From 116152964521ef7fc940f5eeeff8bc96a35f2d9b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 18 Jun 2026 20:55:08 -0700 Subject: [PATCH] Add ACP replay harness and session lifecycle support - Add replay agent and fixture-driven ACP transcript testing - Support session lifecycle, auth methods, and session resume/fork flows - Expand orchestration V2 adapter coverage and debug tooling --- apps/server/scripts/acp-mock-agent.ts | 87 +- apps/server/scripts/acp-replay-agent.ts | 285 ++ .../AcpRegistryOrchestratorV2.live.test.ts | 170 + .../Adapters/AcpAdapterV2.test.ts | 358 +++ .../Adapters/AcpAdapterV2.testkit.ts | 187 ++ .../orchestration-v2/Adapters/AcpAdapterV2.ts | 2203 +++++++++++++ .../Adapters/AcpRegistryAdapterV2.test.ts | 157 + .../Adapters/AcpRegistryAdapterV2.testkit.ts | 89 + .../Adapters/AcpRegistryAdapterV2.ts | 158 + .../Adapters/GrokAdapterV2.test.ts | 111 + .../Adapters/GrokAdapterV2.testkit.ts | 76 + .../Adapters/GrokAdapterV2.ts | 210 ++ .../Adapters/OpenCodeAdapterV2.test.ts | 184 ++ .../Adapters/OpenCodeAdapterV2.testkit.ts | 385 +++ .../Adapters/OpenCodeAdapterV2.ts | 2743 +++++++++++++++++ .../orchestration-v2/CommandPolicy.test.ts | 34 + .../GrokOrchestratorV2.live.test.ts | 158 + .../builtInProviderAdapterDrivers.ts | 23 +- .../src/orchestration-v2/runtimeLayer.ts | 4 + ...rchestratorReplayFixtures.contract.test.ts | 10 +- ...estratorReplayFixtures.integration.test.ts | 18 + .../testkit/ProviderReplayHarness.ts | 2 +- .../acp_elicitation/grok_transcript.ndjson | 11 + .../testkit/fixtures/index.ts | 175 ++ .../fixtures/message_steering/grok_output.ts | 54 + .../message_steering/grok_transcript.ndjson | 14 + .../multi_turn/grok_transcript.ndjson | 12 + .../fixtures/opencode_subagent/input.ts | 7 + .../opencode_transcript.ndjson | 30 + .../fixtures/opencode_subagent/output.ts | 71 + .../fixtures/plan_questions/codex_output.ts | 10 +- .../plan_questions/grok_transcript.ndjson | 11 + .../testkit/fixtures/plan_questions/input.ts | 1 + .../plan_questions/opencode_output.ts | 26 + .../plan_questions/opencode_transcript.ndjson | 23 + .../queued_turn/grok_transcript.ndjson | 12 + .../testkit/fixtures/shared.ts | 18 + .../fixtures/simple/grok_transcript.ndjson | 12 + .../simple/opencode_transcript.ndjson | 19 + .../testkit/fixtures/todo_list/grok_output.ts | 49 + .../fixtures/todo_list/grok_transcript.ndjson | 16 + .../grok_transcript.ndjson | 15 + .../grok_transcript.ndjson | 13 + .../turn_interrupt/grok_transcript.ndjson | 9 + .../turn_interrupt/opencode_transcript.ndjson | 14 + .../provider/acp/AcpJsonRpcConnection.test.ts | 150 +- .../provider/acp/AcpRegistrySupport.test.ts | 263 ++ .../src/provider/acp/AcpRegistrySupport.ts | 633 ++++ .../src/provider/acp/AcpRuntimeModel.ts | 1 + .../src/provider/acp/AcpSessionRuntime.ts | 257 +- .../src/provider/acp/GrokAcpCliProbe.test.ts | 19 + .../server/src/provider/acp/GrokAcpSupport.ts | 5 +- .../src/provider/acp/XAiAcpExtension.ts | 11 + .../settings/AddProviderInstanceDialog.tsx | 7 +- .../settings/ProviderSettingsForm.test.ts | 12 + .../settings/SettingsPanels.browser.tsx | 29 + .../components/settings/SettingsPanels.tsx | 13 +- .../components/settings/providerDriverMeta.ts | 21 +- .../src/orchestrationV2DebugProviders.test.ts | 82 + apps/web/src/orchestrationV2DebugProviders.ts | 88 + .../web/src/routes/debug.orchestration-v2.tsx | 10 +- .../orchestrator-mcp-server.md | 39 +- docs/orchestration-v2/testing-strategy.md | 21 +- packages/contracts/src/model.ts | 3 + packages/contracts/src/settings.ts | 50 + 65 files changed, 9914 insertions(+), 74 deletions(-) create mode 100644 apps/server/scripts/acp-replay-agent.ts create mode 100644 apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts create mode 100644 apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/acp_elicitation/grok_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/message_steering/grok_output.ts create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/message_steering/grok_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/grok_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/input.ts create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/opencode_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/output.ts create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/grok_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/opencode_output.ts create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/opencode_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/grok_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/simple/grok_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/simple/opencode_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/todo_list/grok_output.ts create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/todo_list/grok_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only/grok_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/grok_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/grok_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/opencode_transcript.ndjson create mode 100644 apps/server/src/provider/acp/AcpRegistrySupport.test.ts create mode 100644 apps/server/src/provider/acp/AcpRegistrySupport.ts create mode 100644 apps/web/src/orchestrationV2DebugProviders.test.ts create mode 100644 apps/web/src/orchestrationV2DebugProviders.ts diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 2b5da74eef..9e2dc9d6c0 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -23,6 +23,9 @@ const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1"; const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1"; const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT; const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0"); +const supportsSessionLifecycle = process.env.T3_ACP_SESSION_LIFECYCLE === "1"; +const advertisedAuthMethodId = process.env.T3_ACP_AUTH_METHOD_ID?.trim(); +const requiresAuthentication = process.env.T3_ACP_REQUIRE_AUTH === "1"; const permissionOptionIds = { allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once", allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always", @@ -36,6 +39,7 @@ let parameterizedModelPicker = false; let currentReasoning = "medium"; let currentContext = "272k"; let currentFast = false; +let authenticated = !requiresAuthentication; const cancelledSessions = new Set(); function logExit(reason: string): void { @@ -268,19 +272,56 @@ const program = Effect.gen(function* () { request.clientCapabilities?._meta?.parameterizedModelPicker === true; return { protocolVersion: 1, - agentCapabilities: { loadSession: true }, + agentCapabilities: { + loadSession: true, + ...(supportsSessionLifecycle + ? { + sessionCapabilities: { + list: {}, + fork: {}, + resume: {}, + close: {}, + }, + } + : {}), + }, + ...(advertisedAuthMethodId + ? { + authMethods: [ + { + id: advertisedAuthMethodId, + name: "Mock agent authentication", + }, + ], + } + : {}), }; }), ); - yield* agent.handleAuthenticate(() => Effect.succeed({})); + yield* agent.handleAuthenticate((request) => + Effect.gen(function* () { + if (advertisedAuthMethodId && request.methodId !== advertisedAuthMethodId) { + return yield* AcpError.AcpRequestError.invalidParams( + `Unknown mock authentication method: ${request.methodId}`, + ); + } + authenticated = true; + return {}; + }), + ); yield* agent.handleCreateSession(() => - Effect.succeed({ - sessionId, - modes: modeState(), - models: modelState(), - configOptions: configOptions(), + Effect.gen(function* () { + if (!authenticated) { + return yield* AcpError.AcpRequestError.authRequired(); + } + return { + sessionId, + modes: modeState(), + models: modelState(), + configOptions: configOptions(), + }; }), ); @@ -302,6 +343,38 @@ const program = Effect.gen(function* () { ), ); + yield* agent.handleListSessions((request) => + Effect.succeed({ + sessions: [ + { + sessionId, + cwd: request.cwd ?? process.cwd(), + title: "Mock session", + updatedAt: "1970-01-01T00:00:00.000Z", + }, + ], + }), + ); + + yield* agent.handleForkSession((request) => + Effect.succeed({ + sessionId: `${request.sessionId}-fork`, + modes: modeState(), + models: modelState(), + configOptions: configOptions(), + }), + ); + + yield* agent.handleResumeSession(() => + Effect.succeed({ + modes: modeState(), + models: modelState(), + configOptions: configOptions(), + }), + ); + + yield* agent.handleCloseSession(() => Effect.succeed({})); + yield* agent.handleSetSessionModel((request) => Effect.gen(function* () { if (!grokAcpModels.some((model) => model.modelId === request.modelId)) { diff --git a/apps/server/scripts/acp-replay-agent.ts b/apps/server/scripts/acp-replay-agent.ts new file mode 100644 index 0000000000..f0cd0da1da --- /dev/null +++ b/apps/server/scripts/acp-replay-agent.ts @@ -0,0 +1,285 @@ +#!/usr/bin/env node +// @effect-diagnostics nodeBuiltinImport:off +import { writeFileSync } from "node:fs"; +import { createInterface } from "node:readline"; + +interface ReplayEntry { + readonly type: "emit_inbound" | "expect_outbound" | "runtime_exit"; + readonly label?: string; + readonly frame?: unknown; + readonly status?: "success" | "error" | "cancelled"; + readonly error?: unknown; +} + +interface ReplayTranscript { + readonly scenario: string; + readonly entries: ReadonlyArray; +} + +interface LogicalFrame { + readonly kind: "notification" | "request" | "response"; + readonly method: string; + readonly params?: unknown; + readonly result?: unknown; + readonly error?: unknown; +} + +interface JsonRpcMessage { + readonly jsonrpc?: string; + readonly id?: string | number | null; + readonly method?: string; + readonly params?: unknown; + readonly result?: unknown; + readonly error?: unknown; + readonly headers?: ReadonlyArray; +} + +const encodedTranscript = process.env.T3_ACP_REPLAY_TRANSCRIPT; +const statusPath = process.env.T3_ACP_REPLAY_STATUS_PATH; +const replayWorkspace = process.env.T3_ACP_REPLAY_WORKSPACE ?? process.cwd(); + +if (encodedTranscript === undefined || statusPath === undefined) { + process.stderr.write("ACP replay requires transcript and status environment variables.\n"); + process.exit(2); +} + +const replayStatusPath = statusPath; +const transcript = JSON.parse( + Buffer.from(encodedTranscript, "base64").toString("utf8"), +) as ReplayTranscript; +let cursor = 0; +let stopped = false; +let nextAgentRequestId = 1; +const pendingClientRequestIds = new Map(); +const pendingAgentRequestMethods = new Map(); + +function writeStatus(failure?: unknown): void { + writeFileSync( + replayStatusPath, + JSON.stringify({ + scenario: transcript.scenario, + cursor, + total: transcript.entries.length, + ...(failure === undefined ? {} : { failure }), + }), + "utf8", + ); +} + +function stableStringify(value: unknown): string { + if (Array.isArray(value)) { + return `[${value.map(stableStringify).join(",")}]`; + } + if (typeof value === "object" && value !== null) { + const record = value as Record; + return `{${Object.keys(record) + .toSorted() + .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`) + .join(",")}}`; + } + return JSON.stringify(value); +} + +function expandExpectedString(value: string): string { + return value.replaceAll("", replayWorkspace); +} + +function matchesExpected(expected: unknown, actual: unknown): boolean { + if (expected === "") return true; + if (typeof expected === "string" && typeof actual === "string") { + const expanded = expandExpectedString(expected); + if (!expanded.includes("")) return expanded === actual; + const parts = expanded.split(""); + let offset = 0; + for (const part of parts) { + const index = actual.indexOf(part, offset); + if (index === -1) return false; + offset = index + part.length; + } + return true; + } + if (Array.isArray(expected)) { + return ( + Array.isArray(actual) && + expected.length === actual.length && + expected.every((entry, index) => matchesExpected(entry, actual[index])) + ); + } + if (typeof expected === "object" && expected !== null) { + if (typeof actual !== "object" || actual === null || Array.isArray(actual)) return false; + const expectedRecord = expected as Record; + const actualRecord = actual as Record; + const expectedKeys = Object.keys(expectedRecord).toSorted(); + const actualKeys = Object.keys(actualRecord).toSorted(); + return ( + stableStringify(expectedKeys) === stableStringify(actualKeys) && + expectedKeys.every((key) => matchesExpected(expectedRecord[key], actualRecord[key])) + ); + } + return Object.is(expected, actual); +} + +function stopWithFailure(detail: string, actual?: unknown): void { + if (stopped) return; + stopped = true; + const entry = transcript.entries[cursor]; + const failure = { + detail, + cursor, + expected: entry, + ...(actual === undefined ? {} : { actual }), + }; + writeStatus(failure); + process.stderr.write(`ACP replay mismatch: ${JSON.stringify(failure)}\n`); + process.exitCode = 1; + process.stdin.pause(); +} + +function advance(): void { + cursor += 1; + writeStatus(); +} + +function send(message: JsonRpcMessage): void { + process.stdout.write(`${JSON.stringify(message)}\n`); +} + +function pendingClientRequestId(method: string): string | number | undefined { + return pendingClientRequestIds.get(method); +} + +function logicalIncoming(message: JsonRpcMessage): LogicalFrame | undefined { + if (typeof message.method === "string") { + return { + kind: + message.id === undefined || message.id === null || message.id === "" + ? "notification" + : "request", + method: message.method, + ...(message.params === undefined ? {} : { params: message.params }), + }; + } + if (message.id === undefined || message.id === null) return undefined; + const method = pendingAgentRequestMethods.get(String(message.id)); + if (method === undefined) return undefined; + return { + kind: "response", + method, + ...(message.result === undefined ? {} : { result: message.result }), + ...(message.error === undefined ? {} : { error: message.error }), + }; +} + +function emitInbound(frame: LogicalFrame): void { + switch (frame.kind) { + case "notification": + send({ + jsonrpc: "2.0", + method: frame.method, + ...(frame.params === undefined ? {} : { params: frame.params }), + }); + return; + case "request": { + const id = nextAgentRequestId; + nextAgentRequestId += 1; + pendingAgentRequestMethods.set(String(id), frame.method); + send({ + jsonrpc: "2.0", + id, + method: frame.method, + ...(frame.params === undefined ? {} : { params: frame.params }), + headers: [], + }); + return; + } + case "response": { + const id = pendingClientRequestId(frame.method); + if (id === undefined) { + stopWithFailure(`No pending client request for ${frame.method}`, frame); + return; + } + pendingClientRequestIds.delete(frame.method); + send({ + jsonrpc: "2.0", + id, + ...(frame.result === undefined ? {} : { result: frame.result }), + ...(frame.error === undefined ? {} : { error: frame.error }), + }); + } + } +} + +function flushInbound(): void { + while (!stopped) { + const entry = transcript.entries[cursor]; + if (entry === undefined || entry.type === "expect_outbound") return; + if (entry.type === "runtime_exit") { + if (entry.status !== "success") { + stopWithFailure(`Recorded runtime exit was ${entry.status ?? "unknown"}`, entry.error); + return; + } + advance(); + continue; + } + const frame = entry.frame as LogicalFrame; + if ( + typeof frame !== "object" || + frame === null || + !["notification", "request", "response"].includes(frame.kind) || + typeof frame.method !== "string" + ) { + stopWithFailure("Invalid emit_inbound logical ACP frame", entry.frame); + return; + } + emitInbound(frame); + if (stopped) return; + advance(); + } +} + +function handleMessage(message: JsonRpcMessage): void { + if (stopped) return; + const actual = logicalIncoming(message); + if (actual === undefined) { + stopWithFailure("Could not identify outbound ACP frame", message); + return; + } + const entry = transcript.entries[cursor]; + if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) { + if (actual.kind === "request" && message.id !== undefined && message.id !== null) { + send({ + jsonrpc: "2.0", + id: message.id, + error: { code: -32603, message: "ACP replay frame mismatch" }, + }); + } + stopWithFailure("Unexpected outbound ACP frame", actual); + return; + } + if (actual.kind === "request" && message.id !== undefined && message.id !== null) { + pendingClientRequestIds.set(actual.method, message.id); + } else if (actual.kind === "response" && message.id !== undefined && message.id !== null) { + pendingAgentRequestMethods.delete(String(message.id)); + } + advance(); + flushInbound(); +} + +writeStatus(); +flushInbound(); + +const input = createInterface({ input: process.stdin, crlfDelay: Infinity }); +input.on("line", (line) => { + if (stopped || line.trim().length === 0) return; + try { + handleMessage(JSON.parse(line) as JsonRpcMessage); + } catch (cause) { + stopWithFailure("Failed to decode outbound ACP JSON-RPC", String(cause)); + } +}); + +input.on("close", () => { + if (!stopped && cursor !== transcript.entries.length) { + stopWithFailure("ACP replay input closed before transcript completion"); + } +}); diff --git a/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts b/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts new file mode 100644 index 0000000000..59437ef3fa --- /dev/null +++ b/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts @@ -0,0 +1,170 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + CommandId, + type ModelSelection, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { describe } from "vite-plus/test"; + +import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts"; +import { ServerConfig } from "../config.ts"; +import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; +import { OrchestratorV2 } from "./Orchestrator.ts"; +import { OrchestrationV2LayerLive } from "./runtimeLayer.ts"; + +const liveAgentId = process.env.T3_ACP_REGISTRY_LIVE_AGENT_ID?.trim() || "devin"; +const liveCommandPath = process.env.T3_ACP_REGISTRY_LIVE_COMMAND?.trim(); +const liveInstanceId = ProviderInstanceId.make("acpRegistry_live"); +const liveModelSelection = { + instanceId: liveInstanceId, + model: "default", +} satisfies ModelSelection; + +const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-acp-registry-v2-live-", +}); + +const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe( + Layer.provide(VcsProcess.layer), + Layer.provide(serverConfigLayer), + Layer.provide(NodeServices.layer), +); + +const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(vcsDriverRegistryLayer)); + +const liveLayer = OrchestrationV2LayerLive.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(checkpointStoreLayer), + Layer.provide(serverConfigLayer), + Layer.provide( + ServerSettingsService.layerTest({ + providerInstances: { + [liveInstanceId]: { + driver: ProviderDriverKind.make("acpRegistry"), + displayName: `ACP Registry: ${liveAgentId}`, + enabled: true, + config: { + agentId: liveAgentId, + ...(liveCommandPath ? { commandPath: liveCommandPath } : {}), + }, + }, + }, + }), + ), + Layer.provide(NodeServices.layer), +); + +const waitForIdle = Effect.fn("AcpRegistryOrchestratorV2Live.waitForIdle")(function* ( + threadId: ThreadId, + expectedRunCount: number, +) { + const orchestrator = yield* OrchestratorV2; + for (let attempt = 0; attempt < 900; attempt += 1) { + const projection = yield* orchestrator.getThreadProjection(threadId); + if ( + projection.runs.length >= expectedRunCount && + projection.runs.every( + (run) => !["queued", "starting", "running", "waiting"].includes(run.status), + ) + ) { + return projection; + } + yield* Effect.sleep("500 millis"); + } + return yield* Effect.die(new Error(`Timed out waiting for ACP Registry thread ${threadId}.`)); +}); + +describe.runIf(process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")( + "ACP Registry V2 live orchestrator", + () => { + it.live( + "runs and resumes a real registry agent through the production V2 harness", + () => + Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + const projectId = ProjectId.make("project:acp-registry-live"); + const threadId = ThreadId.make("thread:acp-registry-live"); + const marker = "ACP_REGISTRY_LIVE_7H3Q"; + + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("command:acp-registry-live:create"), + threadId, + projectId, + title: `ACP Registry live: ${liveAgentId}`, + modelSelection: liveModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* Console.log( + `ACP Registry thread created for '${liveAgentId}'; dispatching first prompt.`, + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("command:acp-registry-live:first"), + threadId, + messageId: MessageId.make("message:acp-registry-live:first"), + text: `Remember this opaque marker. Respond with exactly: ${marker}`, + attachments: [], + modelSelection: liveModelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const firstProjection = yield* waitForIdle(threadId, 1); + const firstAssistant = firstProjection.messages.findLast( + (message) => message.role === "assistant", + )?.text; + + assert.deepEqual( + firstProjection.runs.map((run) => [run.provider, run.status]), + [[liveInstanceId, "completed"]], + ); + assert.include(firstAssistant ?? "", marker); + + yield* Console.log("First ACP turn completed; dispatching continuation prompt."); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("command:acp-registry-live:second"), + threadId, + messageId: MessageId.make("message:acp-registry-live:second"), + text: "Return the opaque marker from the previous turn. Respond with only the marker.", + attachments: [], + modelSelection: liveModelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const finalProjection = yield* waitForIdle(threadId, 2); + const finalAssistant = finalProjection.messages.findLast( + (message) => message.role === "assistant", + )?.text; + + assert.deepEqual( + finalProjection.runs.map((run) => [run.provider, run.status]), + [ + [liveInstanceId, "completed"], + [liveInstanceId, "completed"], + ], + ); + assert.include(finalAssistant ?? "", marker); + assert.deepEqual(finalProjection.providerSessions.length, 2); + assert.isAtLeast(finalProjection.providerThreads.length, 1); + assert.deepEqual( + finalProjection.providerTurns.map((turn) => turn.status), + ["completed", "completed"], + ); + }).pipe(Effect.provide(liveLayer), Effect.scoped), + 480_000, + ); + }, +); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts new file mode 100644 index 0000000000..c594228d96 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -0,0 +1,358 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { + MessageId, + NodeId, + ProjectId, + ProviderInstanceId, + ProviderSessionId, + RunAttemptId, + RunId, + ThreadId, + type OrchestrationV2ProviderThread, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { ServerConfig } from "../../config.ts"; +import { AcpSessionRuntime } from "../../provider/acp/AcpSessionRuntime.ts"; +import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts"; +import { + ProviderAdapterV2RuntimePolicy, + type ProviderAdapterV2TurnInput, +} from "../ProviderAdapter.ts"; +import { + AcpProviderCapabilitiesV2, + makeAcpAdapterV2, + type AcpAdapterV2Flavor, +} from "./AcpAdapterV2.ts"; + +const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-acp-v2-adapter-", +}).pipe(Layer.provide(NodeServices.layer)); + +const testLayer = Layer.mergeAll(NodeServices.layer, idAllocatorLayer, serverConfigLayer); + +function makeMockRuntime(input: { + readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; + readonly mockAgentPath: string; + readonly environment?: Readonly>; +}): AcpAdapterV2Flavor["makeRuntime"] { + return (runtimeInput) => + Effect.gen(function* () { + const context = yield* Layer.build( + AcpSessionRuntime.layer({ + ...runtimeInput, + spawn: { + command: process.execPath, + args: [input.mockAgentPath], + cwd: runtimeInput.cwd, + env: { T3_ACP_SESSION_LIFECYCLE: "1", ...input.environment }, + }, + authMethodId: "test", + }).pipe( + Layer.provide( + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner), + ), + ), + ); + return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(context)); + }); +} + +function makeTurnInput(input: { + readonly threadId: ThreadId; + readonly providerThread: OrchestrationV2ProviderThread; + readonly instanceId: ProviderInstanceId; + readonly runtimePolicy: ProviderAdapterV2RuntimePolicy; + readonly now: DateTime.Utc; + readonly ordinal?: number; +}): ProviderAdapterV2TurnInput { + const ordinal = input.ordinal ?? 1; + const suffix = `${input.threadId}:${ordinal}`; + const modelSelection = { instanceId: input.instanceId, model: "default" } as const; + return { + appThread: { + id: input.threadId, + projectId: ProjectId.make(`project:${input.threadId}`), + title: "ACP adapter test", + defaultProvider: "acp-test", + modelSelection, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: input.providerThread.id, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: input.threadId, + }, + forkedFrom: null, + createdAt: input.now, + updatedAt: input.now, + archivedAt: null, + deletedAt: null, + }, + threadId: input.threadId, + runId: RunId.make(`run:${suffix}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt:${suffix}`), + rootNodeId: NodeId.make(`node:${suffix}`), + providerThread: input.providerThread, + message: { + messageId: MessageId.make(`message:${suffix}`), + text: "test prompt", + attachments: [], + }, + modelSelection, + runtimePolicy: input.runtimePolicy, + }; +} + +describe("AcpAdapterV2", () => { + it.effect("negotiates and executes optional native session forks through the ACP runtime", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const makeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath }); + + const instanceId = ProviderInstanceId.make("acp-test"); + const adapter = makeAcpAdapterV2({ + instanceId, + flavor: { + provider: "acp-test", + capabilities: AcpProviderCapabilitiesV2, + makeRuntime, + }, + fileSystem, + idAllocator, + serverConfig, + }); + const sourceThreadId = ThreadId.make("thread-acp-native-fork-source"); + const targetThreadId = ThreadId.make("thread-acp-native-fork-target"); + const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId: sourceThreadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-native-fork"), + modelSelection, + runtimePolicy, + }); + + assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread); + assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot); + + const sourceProviderThread = yield* runtime.ensureThread({ + threadId: sourceThreadId, + modelSelection, + runtimePolicy, + }); + const forkedProviderThread = yield* runtime.forkThread({ + sourceProviderThread, + targetThreadId, + }); + + assert.equal(sourceProviderThread.nativeThreadRef?.nativeId, "mock-session-1"); + assert.equal(forkedProviderThread.nativeThreadRef?.nativeId, "mock-session-1-fork"); + assert.equal(forkedProviderThread.appThreadId, targetThreadId); + assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id); + }).pipe(Effect.provide(testLayer), Effect.scoped), + ); + + it.effect("cancels pending permission requests while interrupting an ACP turn", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const instanceId = ProviderInstanceId.make("acp-test"); + const adapter = makeAcpAdapterV2({ + instanceId, + flavor: { + provider: "acp-test", + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, + }), + }, + fileSystem, + idAllocator, + serverConfig, + }); + const threadId = ThreadId.make("thread-acp-cancel-permission"); + const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-cancel-permission"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), + ); + + const pendingRequest = Option.getOrThrow( + yield* runtime.events.pipe( + Stream.filter( + (event) => + event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", + ), + Stream.runHead, + ), + ); + if ( + pendingRequest.type !== "runtime_request.updated" || + pendingRequest.runtimeRequest.providerTurnId === null + ) { + return yield* Effect.die("Expected a pending ACP permission request with a provider turn"); + } + + yield* runtime.interruptTurn({ + providerThread, + providerTurnId: pendingRequest.runtimeRequest.providerTurnId, + }); + + const cancelledRequest = Option.getOrThrow( + yield* runtime.events.pipe( + Stream.filter( + (event) => + event.type === "runtime_request.updated" && + event.runtimeRequest.id === pendingRequest.runtimeRequest.id && + event.runtimeRequest.status === "cancelled", + ), + Stream.runHead, + ), + ); + assert.equal(cancelledRequest.type, "runtime_request.updated"); + }).pipe(Effect.provide(testLayer), Effect.scoped), + ); + + it.effect("does not release an ACP turn when cancellation is not acknowledged", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const instanceId = ProviderInstanceId.make("acp-test"); + const adapter = makeAcpAdapterV2({ + instanceId, + flavor: { + provider: "acp-test", + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: { T3_ACP_PROMPT_DELAY_MS: "5000" }, + }), + }, + fileSystem, + idAllocator, + serverConfig, + }); + const threadId = ThreadId.make("thread-acp-cancel-timeout"); + const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-cancel-timeout"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const firstTurn = makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + }); + yield* runtime.startTurn(firstTurn); + yield* runtime.rawEvents.pipe( + Stream.filter( + (event) => event.direction === "outgoing" && event.method === "session/prompt", + ), + Stream.runHead, + ); + const providerTurnId = idAllocator.derive.providerTurn({ + provider: "acp-test", + nativeTurnId: "mock-session-1:turn:1", + }); + const interruptFiber = yield* runtime + .interruptTurn({ providerThread, providerTurnId }) + .pipe(Effect.flip, Effect.forkScoped); + yield* runtime.rawEvents.pipe( + Stream.filter( + (event) => event.direction === "outgoing" && event.method === "session/cancel", + ), + Stream.runHead, + ); + yield* TestClock.adjust("10 seconds"); + const interruptError = yield* Fiber.join(interruptFiber); + assert.equal(interruptError._tag, "ProviderAdapterInterruptError"); + + const secondTurnError = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal: 2, + }), + ) + .pipe(Effect.flip); + assert.equal(secondTurnError._tag, "ProviderAdapterTurnStartError"); + }).pipe(Effect.provide(testLayer), Effect.scoped), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts new file mode 100644 index 0000000000..f93281d4bc --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts @@ -0,0 +1,187 @@ +import { + ProviderKind, + ProviderReplayEntry, + type ProviderReplayTranscript, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; +import { ChildProcessSpawner } from "effect/unstable/process"; +import * as EffectAcpErrors from "effect-acp/errors"; + +import { + AcpSessionRuntime, + type AcpSessionRuntimeShape, +} from "../../provider/acp/AcpSessionRuntime.ts"; +import { ACP_PROTOCOL, type AcpAdapterV2RuntimeInput } from "./AcpAdapterV2.ts"; + +export const AcpReplayTranscript = Schema.Struct({ + provider: ProviderKind, + protocol: Schema.Literal(ACP_PROTOCOL), + version: Schema.String, + scenario: Schema.String, + metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + entries: Schema.Array(ProviderReplayEntry), +}); +export type AcpReplayTranscript = typeof AcpReplayTranscript.Type; + +const decodeAcpReplayTranscriptSchema = Schema.decodeUnknownEffect(AcpReplayTranscript); + +export class AcpReplayTranscriptDecodeError extends Schema.TaggedErrorClass()( + "AcpReplayTranscriptDecodeError", + { + expectedProvider: ProviderKind, + provider: Schema.optional(Schema.String), + protocol: Schema.optional(Schema.String), + scenario: Schema.optional(Schema.String), + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Failed to decode ${this.expectedProvider} ACP replay transcript for scenario ${this.scenario ?? ""}.`; + } +} + +const isAcpReplayTranscriptDecodeError = Schema.is(AcpReplayTranscriptDecodeError); + +function metadataFromTranscript(transcript: ProviderReplayTranscript): { + readonly provider?: string; + readonly protocol?: string; + readonly scenario?: string; +} { + return { + provider: transcript.provider, + protocol: transcript.protocol, + scenario: transcript.scenario, + }; +} + +export function decodeAcpReplayTranscript( + transcript: ProviderReplayTranscript, + expectedProvider: ProviderKind, + options: { readonly retargetProvider?: boolean } = {}, +): Effect.Effect { + const candidate = options.retargetProvider + ? { ...transcript, provider: expectedProvider } + : transcript; + return decodeAcpReplayTranscriptSchema(candidate).pipe( + Effect.filterOrFail( + (decoded) => decoded.provider === expectedProvider, + () => + new AcpReplayTranscriptDecodeError({ + expectedProvider, + ...metadataFromTranscript(transcript), + cause: `Expected provider ${expectedProvider}, received ${transcript.provider}`, + }), + ), + Effect.mapError((cause) => + isAcpReplayTranscriptDecodeError(cause) + ? cause + : new AcpReplayTranscriptDecodeError({ + expectedProvider, + ...metadataFromTranscript(transcript), + cause, + }), + ), + ); +} + +interface ReplayStatus { + readonly cursor: number; + readonly total: number; + readonly failure?: unknown; +} + +function decodeReplayStatus(raw: string): ReplayStatus { + const value: unknown = JSON.parse(raw); + if ( + typeof value !== "object" || + value === null || + typeof Reflect.get(value, "cursor") !== "number" || + typeof Reflect.get(value, "total") !== "number" + ) { + throw new Error("ACP replay status is malformed."); + } + return value as ReplayStatus; +} + +export function makeAcpReplayCompletenessAssertion( + fileSystem: FileSystem.FileSystem, + statusPath: string, + transcript: AcpReplayTranscript, +): Effect.Effect { + return fileSystem.readFileString(statusPath).pipe( + Effect.mapError( + (cause) => + new EffectAcpErrors.AcpTransportError({ + detail: `Failed to read ACP replay status for ${transcript.scenario}`, + cause, + }), + ), + Effect.flatMap((raw) => + Effect.try({ + try: () => decodeReplayStatus(raw), + catch: (cause) => + new EffectAcpErrors.AcpTransportError({ + detail: `Failed to decode ACP replay status for ${transcript.scenario}`, + cause, + }), + }), + ), + Effect.flatMap((status) => { + if ( + status.failure === undefined && + status.cursor === transcript.entries.length && + status.total === transcript.entries.length + ) { + return Effect.void; + } + return Effect.fail( + new EffectAcpErrors.AcpTransportError({ + detail: `ACP replay did not consume all frames for ${transcript.scenario}`, + cause: status, + }), + ); + }), + ); +} + +export function makeAcpReplayRuntime(input: { + readonly transcript: AcpReplayTranscript; + readonly statusPath: string; + readonly scriptPath: string; + readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; +}): ( + runtimeInput: AcpAdapterV2RuntimeInput, +) => Effect.Effect { + const encodedTranscript = Buffer.from(JSON.stringify(input.transcript), "utf8").toString( + "base64", + ); + return (runtimeInput) => + Effect.gen(function* () { + const context = yield* Layer.build( + AcpSessionRuntime.layer({ + ...runtimeInput, + spawn: { + command: process.execPath, + args: [input.scriptPath], + cwd: runtimeInput.cwd, + env: { + ...process.env, + T3_ACP_REPLAY_TRANSCRIPT: encodedTranscript, + T3_ACP_REPLAY_STATUS_PATH: input.statusPath, + T3_ACP_REPLAY_WORKSPACE: runtimeInput.cwd, + }, + }, + authMethodId: "replay", + }).pipe( + Layer.provide( + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner), + ), + ), + ); + return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(context)); + }); +} diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts new file mode 100644 index 0000000000..45ce8582f2 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts @@ -0,0 +1,2203 @@ +import { + type ChatAttachment, + type ModelSelection, + type OrchestrationV2ConversationMessage, + type OrchestrationV2ExecutionNode, + type OrchestrationV2PlanArtifact, + type OrchestrationV2PlanStep, + type OrchestrationV2ProviderCapabilities, + type OrchestrationV2ProviderSession, + type OrchestrationV2ProviderThread, + type OrchestrationV2ProviderTurn, + type OrchestrationV2RawProviderEvent, + type OrchestrationV2RuntimeRequest, + type OrchestrationV2TurnItem, + type OrchestrationV2UserInputQuestion, + type ProviderApprovalDecision, + type ProviderInstanceId, + type ProviderKind, + type ProviderRequestKind, + type ProviderUserInputAnswers, + type RuntimeRequestId, + type ThreadId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; +import * as EffectAcpErrors from "effect-acp/errors"; +import type * as EffectAcpProtocol from "effect-acp/protocol"; +import type * as EffectAcpSchema from "effect-acp/schema"; + +import { resolveAttachmentPath } from "../../attachmentStore.ts"; +import { type ServerConfigShape } from "../../config.ts"; +import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; +import { + mergeToolCallState, + parsePermissionRequest, + parseSessionUpdateEvent, + type AcpPlanUpdate, + type AcpToolCallState, +} from "../../provider/acp/AcpRuntimeModel.ts"; +import type { + AcpSessionRuntimeOptions, + AcpSessionRuntimeShape, + AcpSessionRuntimeStartResult, +} from "../../provider/acp/AcpSessionRuntime.ts"; +import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts"; +import { + ProviderAdapterEnsureThreadError, + ProviderAdapterForkThreadError, + ProviderAdapterInterruptError, + ProviderAdapterOpenSessionError, + ProviderAdapterProtocolError, + ProviderAdapterReadThreadSnapshotError, + ProviderAdapterResumeThreadError, + ProviderAdapterRollbackThreadError, + ProviderAdapterRuntimeRequestResponseError, + ProviderAdapterSteerRunUnsupportedError, + ProviderAdapterTurnStartError, + ProviderAdapterV2, + type ProviderAdapterV2EnsureThreadInput, + type ProviderAdapterV2Event, + type ProviderAdapterV2InterruptInput, + type ProviderAdapterV2OpenSessionInput, + type ProviderAdapterV2RuntimePolicy, + type ProviderAdapterV2SessionRuntime, + type ProviderAdapterV2Shape, + type ProviderAdapterV2TurnInput, +} from "../ProviderAdapter.ts"; + +export const ACP_PROTOCOL = "acp.ndjson-jsonrpc" as const; + +export interface AcpAdapterV2RuntimeInput { + readonly cwd: string; + readonly mcpServers: ReadonlyArray; + readonly clientCapabilities: EffectAcpSchema.InitializeRequest["clientCapabilities"]; + readonly clientInfo: AcpSessionRuntimeOptions["clientInfo"]; + readonly protocolLogging: NonNullable; +} + +export interface AcpAdapterV2UserInputRequest { + readonly nativeItemId: string; + readonly nativeRequestId: string; + readonly questions: ReadonlyArray; +} + +export interface AcpAdapterV2ExtensionContext { + readonly runtime: AcpSessionRuntimeShape; + readonly requestUserInput: ( + input: AcpAdapterV2UserInputRequest, + ) => Effect.Effect; +} + +export interface AcpAdapterV2Flavor { + readonly provider: ProviderKind; + readonly capabilities: OrchestrationV2ProviderCapabilities; + readonly makeRuntime: ( + input: AcpAdapterV2RuntimeInput, + ) => Effect.Effect; + readonly resolveModelId?: (selection: ModelSelection) => string | undefined; + readonly registerExtensions?: ( + context: AcpAdapterV2ExtensionContext, + ) => Effect.Effect; + readonly assertComplete?: Effect.Effect; +} + +export interface AcpAdapterV2Options { + readonly instanceId: ProviderInstanceId; + readonly flavor: AcpAdapterV2Flavor; + readonly fileSystem: FileSystem.FileSystem; + readonly idAllocator: IdAllocatorV2Shape; + readonly serverConfig: ServerConfigShape; +} + +export const AcpProviderCapabilitiesV2 = { + sessions: { + supportsMultipleProviderThreadsPerSession: false, + supportsModelSwitchInSession: false, + supportsProviderSwitchingViaHandoff: true, + supportsRuntimeModeSwitchInSession: false, + pendingRequestsSurviveRestart: false, + }, + threads: { + canCreateEmptyThread: true, + canReadThreadSnapshot: false, + canRollbackThread: false, + canForkThread: false, + canForkFromTurn: false, + canForkFromSubagentThread: false, + exposesNativeThreadId: true, + }, + turns: { + exposesNativeTurnId: false, + emitsTurnStarted: true, + emitsTurnCompleted: true, + supportsInterrupt: true, + supportsActiveSteering: false, + supportsSteeringByInterruptRestart: true, + supportsQueuedMessages: true, + terminalStatusQuality: "strong", + }, + streaming: { + streamsAssistantText: true, + streamsReasoning: true, + streamsToolOutput: true, + streamsPlanText: false, + emitsMessageCompleted: true, + }, + tools: { + exposesToolItemIds: true, + emitsToolStarted: true, + emitsToolCompleted: true, + emitsToolOutput: true, + supportsMcpTools: false, + supportsDynamicToolCallbacks: false, + }, + approvals: { + supportsCommandApproval: true, + supportsFileReadApproval: true, + supportsFileChangeApproval: true, + supportsApplyPatchApproval: false, + approvalsHaveNativeRequestIds: false, + approvalCallbacksAreLiveOnly: true, + approvalsCanOriginateFromSubagents: false, + }, + planning: { + emitsPlanUpdated: true, + emitsTodoList: true, + emitsProposedPlan: false, + supportsStructuredQuestions: true, + planDeltasHaveItemIds: false, + }, + subagents: { + supportsSubagents: false, + exposesSubagentThreadIds: false, + emitsSubagentLifecycle: false, + canWaitForSubagents: false, + canCloseSubagents: false, + canForkSubagentThread: false, + }, + context: { + acceptsSystemContext: false, + acceptsDeveloperContext: false, + acceptsSyntheticUserContext: true, + canGenerateSummaries: true, + canConsumeHandoffSummaries: true, + supportsDeltaHandoff: true, + supportsFullThreadHandoff: true, + maxRecommendedHandoffChars: null, + }, + checkpointing: { + appCanCheckpointFilesystem: true, + supportsNestedCheckpointScopes: true, + providerCanRollbackConversation: false, + providerRollbackReturnsSnapshot: false, + providerCanReadConversationSnapshot: false, + }, + identity: { + nativeThreadIds: "strong", + nativeTurnIds: "weak", + nativeItemIds: "weak", + nativeRequestIds: "weak", + }, +} satisfies OrchestrationV2ProviderCapabilities; + +function negotiatedCapabilities( + base: OrchestrationV2ProviderCapabilities, + started: AcpSessionRuntimeStartResult, +): OrchestrationV2ProviderCapabilities { + const agent = started.initializeResult.agentCapabilities ?? {}; + const session = agent.sessionCapabilities; + const setup = started.sessionSetupResult; + const hasModelConfig = + setup.configOptions?.some((option) => option.category === "model") === true; + const hasModeConfig = setup.configOptions?.some((option) => option.category === "mode") === true; + const supportsMcp = agent.mcpCapabilities?.http === true || agent.mcpCapabilities?.sse === true; + const canLoad = agent.loadSession === true; + const canFork = session?.fork != null; + return { + ...base, + sessions: { + ...base.sessions, + supportsModelSwitchInSession: setup.models != null || hasModelConfig, + supportsRuntimeModeSwitchInSession: setup.modes != null || hasModeConfig, + }, + threads: { + ...base.threads, + canReadThreadSnapshot: canLoad, + canForkThread: canFork, + canForkFromTurn: false, + }, + tools: { + ...base.tools, + supportsMcpTools: supportsMcp, + }, + checkpointing: { + ...base.checkpointing, + providerCanReadConversationSnapshot: canLoad, + }, + }; +} + +function acpMcpServers(threadId: ThreadId): ReadonlyArray { + const session = McpProviderSession.readMcpProviderSession(threadId); + if (session === undefined) { + return []; + } + return [ + { + type: "http", + name: "t3-code", + url: session.endpoint, + headers: [ + { + name: "Authorization", + value: session.authorizationHeader, + }, + ], + }, + ]; +} + +function nativeThreadId(provider: ProviderKind, thread: OrchestrationV2ProviderThread): string { + const id = thread.nativeThreadRef?.nativeId; + if (id === null || id === undefined || id.trim().length === 0) { + throw new ProviderAdapterProtocolError({ + provider, + detail: `Provider thread ${thread.id} is missing its ACP session id`, + }); + } + return id; +} + +function makeProviderThread(input: { + readonly provider: ProviderKind; + readonly idAllocator: IdAllocatorV2Shape; + readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"]; + readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"]; + readonly nativeThreadId: string; + readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"]; + readonly forkedFrom?: OrchestrationV2ProviderThread["forkedFrom"]; + readonly now: DateTime.Utc; +}): OrchestrationV2ProviderThread { + return { + id: input.idAllocator.derive.providerThread({ + provider: input.provider, + nativeThreadId: input.nativeThreadId, + }), + provider: input.provider, + providerSessionId: input.providerSessionId, + appThreadId: input.appThreadId, + ownerNodeId: input.ownerNodeId ?? null, + nativeThreadRef: { + provider: input.provider, + nativeId: input.nativeThreadId, + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: input.forkedFrom ?? null, + createdAt: input.now, + updatedAt: input.now, + }; +} + +function unknownRecord(value: unknown): Record | undefined { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Record) + : undefined; +} + +function nonEmptyText(value: unknown, fallback: string): string { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : fallback; +} + +function textFromUnknown(value: unknown): string | undefined { + if (typeof value === "string") { + return value; + } + if (Array.isArray(value)) { + const parts = value.flatMap((entry) => { + const text = textFromUnknown(entry); + return text === undefined || text.length === 0 ? [] : [text]; + }); + return parts.length === 0 ? undefined : parts.join("\n"); + } + const record = unknownRecord(value); + if (record === undefined) { + return undefined; + } + for (const key of ["stdout", "stderr", "output", "content", "text", "message"]) { + const text = textFromUnknown(record[key]); + if (text !== undefined && text.length > 0) { + return text; + } + } + return undefined; +} + +function commandExitCode(value: unknown): number | undefined { + const record = unknownRecord(value); + for (const key of ["exitCode", "exit_code", "code"]) { + const candidate = record?.[key]; + if (typeof candidate === "number" && Number.isInteger(candidate)) { + return candidate; + } + } + return undefined; +} + +function pathFromToolCall(toolCall: AcpToolCallState): string | undefined { + const locations = toolCall.data.locations; + if (Array.isArray(locations)) { + for (const location of locations) { + const path = unknownRecord(location)?.path; + if (typeof path === "string" && path.trim().length > 0) { + return path.trim(); + } + } + } + const rawInput = unknownRecord(toolCall.data.rawInput); + for (const key of ["path", "filePath", "file_path", "url", "query", "pattern"]) { + const candidate = rawInput?.[key]; + if (typeof candidate === "string" && candidate.trim().length > 0) { + return candidate.trim(); + } + } + return undefined; +} + +function providerRequestKind(kind: string | "unknown"): ProviderRequestKind { + switch (kind) { + case "execute": + return "command"; + case "read": + case "search": + case "fetch": + return "file-read"; + case "edit": + case "delete": + case "move": + return "file-change"; + default: + return "command"; + } +} + +function toolStatus( + status: AcpToolCallState["status"], +): "pending" | "running" | "completed" | "failed" { + switch (status) { + case "completed": + return "completed"; + case "failed": + return "failed"; + case "pending": + return "pending"; + default: + return "running"; + } +} + +function nodeStatus(status: ReturnType): OrchestrationV2ExecutionNode["status"] { + return status === "pending" ? "running" : status; +} + +function completedAtForStatus( + status: ReturnType, + now: DateTime.Utc, +): DateTime.Utc | null { + return status === "completed" || status === "failed" ? now : null; +} + +function selectPermissionOptionId( + request: EffectAcpSchema.RequestPermissionRequest, + decision: Exclude, +): string | undefined { + const kind = + decision === "acceptForSession" + ? "allow_always" + : decision === "accept" + ? "allow_once" + : "reject_once"; + return request.options.find((option) => option.kind === kind)?.optionId.trim() || undefined; +} + +function selectAutoApprovedPermissionOption( + request: EffectAcpSchema.RequestPermissionRequest, +): string | undefined { + return ( + selectPermissionOptionId(request, "acceptForSession") ?? + selectPermissionOptionId(request, "accept") + ); +} + +export type AcpPermissionDisposition = "allow" | "ask" | "deny"; + +export function acpPermissionDisposition( + runtimePolicy: ProviderAdapterV2RuntimePolicy, + request: EffectAcpSchema.RequestPermissionRequest, +): AcpPermissionDisposition { + const approvalPolicy = runtimePolicy.approvalPolicy; + const requiresApproval = + approvalPolicy === undefined + ? runtimePolicy.runtimeMode === "approval-required" + : approvalPolicy !== "never"; + if (requiresApproval) { + return "ask"; + } + + const sandboxPolicy = unknownRecord(runtimePolicy.sandboxPolicy); + const sandboxType = sandboxPolicy?.type; + const toolKind = request.toolCall.kind ?? "other"; + switch (sandboxType) { + case "readOnly": + return toolKind === "read" || toolKind === "search" || toolKind === "think" + ? "allow" + : "deny"; + case "workspaceWrite": + return toolKind === "read" || + toolKind === "search" || + toolKind === "think" || + toolKind === "edit" || + toolKind === "delete" || + toolKind === "move" + ? "allow" + : "deny"; + case "dangerFullAccess": + case "externalSandbox": + return "allow"; + case undefined: + return runtimePolicy.runtimeMode === "approval-required" ? "deny" : "allow"; + default: + return "deny"; + } +} + +function jsonRpcId(value: unknown): string | number | null { + return (typeof value === "string" && value.length > 0) || typeof value === "number" + ? value + : null; +} + +function elicitationContent( + answers: ProviderUserInputAnswers, +): Record { + const content: Record = {}; + for (const [key, value] of Object.entries(answers)) { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + content[key] = value; + } else if (Array.isArray(value)) { + content[key] = value.filter((entry): entry is string => typeof entry === "string"); + } + } + return content; +} + +function rawJsonRpcMessages(payload: unknown): ReadonlyArray> { + if (typeof payload !== "string") { + return []; + } + const messages: Array> = []; + for (const line of payload.split("\n")) { + const trimmed = line.trim(); + if (trimmed.length === 0) continue; + try { + const decoded: unknown = JSON.parse(trimmed); + if (Array.isArray(decoded)) { + for (const entry of decoded) { + const record = unknownRecord(entry); + if (record !== undefined) messages.push(record); + } + } else { + const record = unknownRecord(decoded); + if (record !== undefined) messages.push(record); + } + } catch { + messages.push({ raw: trimmed }); + } + } + return messages; +} + +interface ActiveTextSegment { + readonly nativeItemId: string; + readonly startedAt: DateTime.Utc; + text: string; +} + +interface ActiveTextStream { + current: ActiveTextSegment | null; + nextSegment: number; +} + +interface ActiveAcpTurn { + readonly input: ProviderAdapterV2TurnInput; + readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; + readonly nativeTurnId: string; + readonly startedAt: DateTime.Utc; + readonly completed: Deferred.Deferred; + readonly assistant: ActiveTextStream; + readonly reasoning: ActiveTextStream; + readonly tools: Map; + readonly toolStartedAt: Map; + plan: { + readonly id: OrchestrationV2PlanArtifact["id"]; + readonly startedAt: DateTime.Utc; + } | null; + interrupted: boolean; + finalized: boolean; +} + +type PendingRuntimeRequest = { + readonly requestId: RuntimeRequestId; + readonly runtimeRequest: OrchestrationV2RuntimeRequest; + readonly node: OrchestrationV2ExecutionNode; + readonly turnItem: OrchestrationV2TurnItem; +} & ( + | { + readonly type: "approval"; + readonly decision: Deferred.Deferred; + } + | { + readonly type: "user_input"; + readonly answers: Deferred.Deferred; + } +); + +interface SnapshotMessageState { + readonly order: Array; + readonly messages: Map; + loadingRole: "user" | "assistant" | null; + loadingIndex: number; +} + +interface RawProtocolState { + readonly pendingMethods: Map; + sequence: number; +} + +function requestKey(direction: "incoming" | "outgoing", id: string | number): string { + return `${direction}:${String(id)}`; +} + +function oppositeDirection(direction: "incoming" | "outgoing"): "incoming" | "outgoing" { + return direction === "incoming" ? "outgoing" : "incoming"; +} + +export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV2Shape { + const { flavor, fileSystem, idAllocator, serverConfig } = options; + const provider = flavor.provider; + + return ProviderAdapterV2.of({ + instanceId: options.instanceId, + provider, + getCapabilities: () => Effect.succeed(flavor.capabilities), + openSession: Effect.fn("AcpAdapterV2.openSession")( + function* (input: ProviderAdapterV2OpenSessionInput) { + const sessionScope = yield* Effect.scope; + const events = yield* Queue.unbounded(); + const rawEvents = yield* Queue.unbounded(); + const rawState = yield* Ref.make({ + pendingMethods: new Map(), + sequence: 0, + }); + const activeTurn = yield* Ref.make(null); + const activeSessionId = yield* Ref.make(null); + const pendingRuntimeRequests = yield* Ref.make(new Map()); + const nextElicitationOrdinal = yield* Ref.make(0); + const itemOrdinals = yield* Ref.make(new Map()); + const nextItemOrdinalsByTurn = yield* Ref.make(new Map()); + const providerTurns = yield* Ref.make(new Map()); + const snapshot = yield* Ref.make({ + order: [], + messages: new Map(), + loadingRole: null, + loadingIndex: 0, + }); + + const emitProviderEvent = (event: ProviderAdapterV2Event) => + Queue.offer(events, event).pipe(Effect.asVoid); + + const protocolLogger = ( + event: EffectAcpProtocol.AcpProtocolLogEvent, + ): Effect.Effect => + Effect.gen(function* () { + if (event.stage !== "raw") return; + for (const message of rawJsonRpcMessages(event.payload)) { + const methodValue = message.method; + const id = jsonRpcId(message.id); + let method = typeof methodValue === "string" ? methodValue : null; + let messageKind: OrchestrationV2RawProviderEvent["messageKind"]; + if (method !== null) { + messageKind = id === null ? "notification" : "request"; + } else if ("error" in message) { + messageKind = "error"; + } else { + messageKind = "response"; + } + const state = yield* Ref.get(rawState); + if (method !== null && id !== null) { + state.pendingMethods.set(requestKey(event.direction, id), method); + } else if (id !== null) { + method = + state.pendingMethods.get(requestKey(oppositeDirection(event.direction), id)) ?? + null; + state.pendingMethods.delete(requestKey(oppositeDirection(event.direction), id)); + } + state.sequence += 1; + const now = yield* DateTime.now; + const rawEventId = yield* idAllocator.allocate.rawEvent({ + providerSessionId: input.providerSessionId, + method, + }); + yield* Queue.offer(rawEvents, { + id: rawEventId, + provider, + providerSessionId: input.providerSessionId, + sequence: state.sequence, + direction: event.direction, + messageKind, + method, + jsonRpcId: id, + payload: message, + observedAt: now, + }); + } + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.acp-raw-event-failed", { + provider, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ); + + const runtime = yield* flavor.makeRuntime({ + cwd: input.runtimePolicy.cwd ?? process.cwd(), + mcpServers: acpMcpServers(input.threadId), + clientCapabilities: { + fs: { readTextFile: false, writeTextFile: false }, + terminal: false, + elicitation: { form: {} }, + }, + clientInfo: { name: "t3-code", version: "0.0.0" }, + protocolLogging: { + logIncoming: true, + logOutgoing: true, + logger: protocolLogger, + }, + }); + + const resolveItemOrdinal = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + nativeItemId: string, + ) { + const existing = (yield* Ref.get(itemOrdinals)).get(nativeItemId); + if (existing !== undefined) return existing; + const nextWithinTurn = yield* Ref.modify(nextItemOrdinalsByTurn, (current) => { + const next = (current.get(context.nativeTurnId) ?? 0) + 1; + const updated = new Map(current); + updated.set(context.nativeTurnId, next); + return [next, updated] as const; + }); + const ordinal = context.input.runOrdinal * 100 + nextWithinTurn; + yield* Ref.update(itemOrdinals, (current) => { + const updated = new Map(current); + updated.set(nativeItemId, ordinal); + return updated; + }); + return ordinal; + }); + + const rememberSnapshotMessage = (message: OrchestrationV2ConversationMessage) => + Ref.update(snapshot, (current) => { + const key = String(message.id); + const exists = current.messages.has(key); + const messages = new Map(current.messages); + messages.set(key, message); + return { + ...current, + order: exists ? current.order : [...current.order, key], + messages, + }; + }); + + const emitTextSegment = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + kind: "assistant" | "reasoning", + completed: boolean, + ) { + const stream = kind === "assistant" ? context.assistant : context.reasoning; + const segment = stream.current; + if (segment === null || segment.text.length === 0) return; + const now = yield* DateTime.now; + const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId); + const nodeId = idAllocator.derive.nodeFromProviderItem({ + provider, + nativeItemId: segment.nativeItemId, + }); + const turnItemId = idAllocator.derive.turnItemFromProviderItem({ + provider, + nativeItemId: segment.nativeItemId, + }); + const nativeItemRef = { + provider, + nativeId: segment.nativeItemId, + strength: "weak" as const, + }; + yield* emitProviderEvent({ + type: "node.updated", + provider, + node: { + id: nodeId, + threadId: context.input.threadId, + runId: context.input.runId, + parentNodeId: context.input.rootNodeId, + rootNodeId: context.input.rootNodeId, + kind: kind === "assistant" ? "assistant_message" : "reasoning", + status: completed ? "completed" : "running", + countsForRun: false, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: segment.startedAt, + completedAt: completed ? now : null, + }, + }); + if (kind === "assistant") { + const messageId = idAllocator.derive.messageFromProviderItem({ + provider, + nativeItemId: segment.nativeItemId, + }); + const message: OrchestrationV2ConversationMessage = { + id: messageId, + threadId: context.input.threadId, + runId: context.input.runId, + nodeId, + role: "assistant", + text: segment.text, + attachments: [], + streaming: !completed, + createdAt: segment.startedAt, + updatedAt: now, + }; + yield* emitProviderEvent({ type: "message.updated", provider, message }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider, + turnItem: { + id: turnItemId, + threadId: context.input.threadId, + runId: context.input.runId, + nodeId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + parentItemId: null, + ordinal, + status: completed ? "completed" : "running", + title: null, + startedAt: segment.startedAt, + completedAt: completed ? now : null, + updatedAt: now, + type: "assistant_message", + messageId, + text: segment.text, + streaming: !completed, + }, + }); + if (completed) yield* rememberSnapshotMessage(message); + return; + } + yield* emitProviderEvent({ + type: "turn_item.updated", + provider, + turnItem: { + id: turnItemId, + threadId: context.input.threadId, + runId: context.input.runId, + nodeId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + parentItemId: null, + ordinal, + status: completed ? "completed" : "running", + title: null, + startedAt: segment.startedAt, + completedAt: completed ? now : null, + updatedAt: now, + type: "reasoning", + text: segment.text, + streaming: !completed, + }, + }); + }); + + const closeTextStream = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + kind: "assistant" | "reasoning", + ) { + const stream = kind === "assistant" ? context.assistant : context.reasoning; + if (stream.current === null) return; + yield* emitTextSegment(context, kind, true); + stream.current = null; + }); + + const closeTextStreams = Effect.fnUntraced(function* (context: ActiveAcpTurn) { + yield* closeTextStream(context, "reasoning"); + yield* closeTextStream(context, "assistant"); + }); + + const appendText = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + kind: "assistant" | "reasoning", + text: string, + ) { + if (text.length === 0) return; + const other = kind === "assistant" ? "reasoning" : "assistant"; + yield* closeTextStream(context, other); + const stream = kind === "assistant" ? context.assistant : context.reasoning; + if (stream.current === null) { + const now = yield* DateTime.now; + stream.current = { + nativeItemId: `${context.nativeTurnId}:${kind}:${stream.nextSegment}`, + startedAt: now, + text: "", + }; + stream.nextSegment += 1; + } + stream.current.text += text; + yield* emitTextSegment(context, kind, false); + }); + + const emitTool = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + incoming: AcpToolCallState, + ) { + yield* closeTextStreams(context); + const previous = context.tools.get(incoming.toolCallId); + const toolCall = mergeToolCallState(previous, incoming); + context.tools.set(toolCall.toolCallId, toolCall); + const status = toolStatus(toolCall.status); + const now = yield* DateTime.now; + const nativeItemId = `${nativeThreadId(provider, context.input.providerThread)}:tool:${toolCall.toolCallId}`; + const ordinal = yield* resolveItemOrdinal(context, nativeItemId); + const nodeId = idAllocator.derive.nodeFromProviderItem({ provider, nativeItemId }); + const turnItemId = idAllocator.derive.turnItemFromProviderItem({ + provider, + nativeItemId, + }); + const nativeItemRef = { + provider, + nativeId: toolCall.toolCallId, + strength: "strong" as const, + }; + const startedAt = context.toolStartedAt.get(toolCall.toolCallId) ?? now; + context.toolStartedAt.set(toolCall.toolCallId, startedAt); + const completedAt = completedAtForStatus(status, now); + const title = toolCall.title ?? null; + yield* emitProviderEvent({ + type: "node.updated", + provider, + node: { + id: nodeId, + threadId: context.input.threadId, + runId: context.input.runId, + parentNodeId: context.input.rootNodeId, + rootNodeId: context.input.rootNodeId, + kind: "tool_call", + status: nodeStatus(status), + countsForRun: true, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt, + completedAt, + }, + }); + + const base = { + id: turnItemId, + threadId: context.input.threadId, + runId: context.input.runId, + nodeId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + parentItemId: null, + ordinal, + status, + title, + startedAt, + completedAt, + updatedAt: now, + } as const; + const rawInput = toolCall.data.rawInput; + const rawOutput = toolCall.data.rawOutput ?? toolCall.data.content; + const path = pathFromToolCall(toolCall); + let turnItem: OrchestrationV2TurnItem; + switch (toolCall.kind) { + case "read": + case "search": + turnItem = { + ...base, + type: "file_search", + ...(path === undefined ? {} : { pattern: path }), + ...(path === undefined + ? {} + : { + results: [ + { + fileName: path, + ...(textFromUnknown(rawOutput) === undefined + ? {} + : { preview: textFromUnknown(rawOutput) }), + }, + ], + }), + }; + break; + case "execute": + turnItem = { + ...base, + type: "command_execution", + input: toolCall.command ?? toolCall.title ?? "Command", + ...(textFromUnknown(rawOutput) === undefined + ? {} + : { output: textFromUnknown(rawOutput) }), + ...(commandExitCode(rawOutput) === undefined + ? {} + : { exitCode: commandExitCode(rawOutput) }), + }; + break; + case "edit": + case "delete": + case "move": + turnItem = { + ...base, + type: "file_change", + fileName: path ?? toolCall.title ?? "File change", + ...(textFromUnknown(rawOutput) === undefined + ? {} + : { diffStr: textFromUnknown(rawOutput) }), + }; + break; + case "fetch": + turnItem = { + ...base, + type: "web_search", + ...(path === undefined ? {} : { patterns: [path] }), + ...(path === undefined + ? {} + : { + results: [ + { + url: path, + ...(textFromUnknown(rawOutput) === undefined + ? {} + : { snippet: textFromUnknown(rawOutput) }), + }, + ], + }), + }; + break; + default: + turnItem = { + ...base, + type: "dynamic_tool", + toolName: toolCall.title ?? toolCall.kind ?? null, + input: rawInput ?? {}, + ...(rawOutput === undefined ? {} : { output: rawOutput }), + }; + } + yield* emitProviderEvent({ type: "turn_item.updated", provider, turnItem }); + }); + + const emitPlan = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + update: AcpPlanUpdate, + ) { + yield* closeTextStreams(context); + const nativeItemId = `${context.nativeTurnId}:plan`; + const ordinal = yield* resolveItemOrdinal(context, nativeItemId); + const now = yield* DateTime.now; + const nodeId = idAllocator.derive.nodeFromProviderItem({ provider, nativeItemId }); + const turnItemId = idAllocator.derive.turnItemFromProviderItem({ + provider, + nativeItemId, + }); + if (context.plan === null) { + context.plan = { + id: yield* idAllocator.allocate.plan({ + threadId: context.input.threadId, + runId: context.input.runId, + provider, + }), + startedAt: now, + }; + } + const planId = context.plan.id; + const steps: ReadonlyArray = update.plan.map((step, index) => ({ + id: `acp-step-${index + 1}`, + text: nonEmptyText(step.step, `Step ${index + 1}`), + status: + step.status === "inProgress" + ? "running" + : step.status === "completed" + ? "completed" + : "pending", + })); + const completed = steps.length > 0 && steps.every((step) => step.status === "completed"); + const nativeItemRef = { provider, nativeId: nativeItemId, strength: "weak" as const }; + const plan: OrchestrationV2PlanArtifact = { + id: planId, + threadId: context.input.threadId, + runId: context.input.runId, + nodeId, + status: completed ? "completed" : "active", + kind: "todo_list", + steps, + ...(update.explanation == null ? {} : { explanation: update.explanation }), + }; + yield* emitProviderEvent({ + type: "node.updated", + provider, + node: { + id: nodeId, + threadId: context.input.threadId, + runId: context.input.runId, + parentNodeId: context.input.rootNodeId, + rootNodeId: context.input.rootNodeId, + kind: "todo_list", + status: completed ? "completed" : "running", + countsForRun: false, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: context.plan.startedAt, + completedAt: completed ? now : null, + }, + }); + yield* emitProviderEvent({ type: "plan.updated", provider, plan }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider, + turnItem: { + id: turnItemId, + threadId: context.input.threadId, + runId: context.input.runId, + nodeId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + parentItemId: null, + ordinal, + status: completed ? "completed" : "running", + title: null, + startedAt: context.plan.startedAt, + completedAt: completed ? now : null, + updatedAt: now, + type: "todo_list", + planId, + steps, + ...(update.explanation == null ? {} : { explanation: update.explanation }), + }, + }); + }); + + const appendLoadedHistory = ( + notification: EffectAcpSchema.SessionNotification, + role: "user" | "assistant", + text: string, + ) => + Effect.gen(function* () { + if (text.length === 0) return; + const now = yield* DateTime.now; + yield* Ref.update(snapshot, (current) => { + const startsNew = current.loadingRole !== role; + const loadingIndex = startsNew ? current.loadingIndex + 1 : current.loadingIndex; + const nativeItemId = `${notification.sessionId}:history:${role}:${loadingIndex}`; + const messageId = idAllocator.derive.messageFromProviderItem({ + provider, + nativeItemId, + }); + const key = String(messageId); + const previous = current.messages.get(key); + const messages = new Map(current.messages); + messages.set(key, { + id: messageId, + threadId: input.threadId, + runId: null, + nodeId: null, + role, + text: `${previous?.text ?? ""}${text}`, + attachments: [], + streaming: false, + createdAt: previous?.createdAt ?? now, + updatedAt: now, + }); + return { + order: current.order.includes(key) ? current.order : [...current.order, key], + messages, + loadingRole: role, + loadingIndex, + }; + }); + }); + + const handleSessionUpdate = Effect.fnUntraced(function* ( + notification: EffectAcpSchema.SessionNotification, + ) { + const context = yield* Ref.get(activeTurn); + const update = notification.update; + if (context === null) { + if ( + (update.sessionUpdate === "user_message_chunk" || + update.sessionUpdate === "agent_message_chunk") && + update.content.type === "text" + ) { + yield* appendLoadedHistory( + notification, + update.sessionUpdate === "user_message_chunk" ? "user" : "assistant", + update.content.text, + ); + } else if ( + update.sessionUpdate === "tool_call" || + update.sessionUpdate === "tool_call_update" || + update.sessionUpdate === "plan" + ) { + yield* Ref.update(snapshot, (current) => ({ ...current, loadingRole: null })); + } + return; + } + if (context.finalized) return; + if (notification.sessionId !== (yield* Ref.get(activeSessionId))) return; + switch (update.sessionUpdate) { + case "agent_message_chunk": + if (update.content.type === "text") { + yield* appendText(context, "assistant", update.content.text); + } + return; + case "agent_thought_chunk": + if (update.content.type === "text") { + yield* appendText(context, "reasoning", update.content.text); + } + return; + default: { + const parsed = parseSessionUpdateEvent(notification); + for (const event of parsed.events) { + if (event._tag === "ToolCallUpdated") { + yield* emitTool(context, event.toolCall); + } else if (event._tag === "PlanUpdated") { + yield* emitPlan(context, event.payload); + } + } + } + } + }); + + yield* runtime.handleSessionUpdate((notification) => + handleSessionUpdate(notification).pipe( + Effect.mapError( + (cause) => + new EffectAcpErrors.AcpTransportError({ + detail: "Failed to project an ACP session update", + cause, + }), + ), + ), + ); + + const activeContext = Effect.gen(function* () { + const context = yield* Ref.get(activeTurn); + if (context === null) { + return yield* new EffectAcpErrors.AcpTransportError({ + detail: "ACP agent requested input without an active turn", + cause: "No active ACP turn", + }); + } + return context; + }); + + const emitApprovalRequest = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + params: EffectAcpSchema.RequestPermissionRequest, + ) { + yield* closeTextStreams(context); + const parsed = parsePermissionRequest(params); + const nativeRequestId = params.toolCall.toolCallId; + const requestId = yield* idAllocator.allocate.runtimeRequest({ + provider, + providerTurnId: context.providerTurnId, + nativeRequestId, + }); + const decision = yield* Deferred.make(); + const now = yield* DateTime.now; + const nodeId = idAllocator.derive.approvalNode({ requestId }); + const requestKind = providerRequestKind(parsed.kind); + const nativeItemRef = { provider, nativeId: nativeRequestId, strength: "weak" as const }; + const ordinal = yield* resolveItemOrdinal( + context, + `${context.nativeTurnId}:approval:${nativeRequestId}`, + ); + const runtimeRequest: OrchestrationV2RuntimeRequest = { + id: requestId, + nodeId, + providerTurnId: context.providerTurnId, + nativeRequestRef: nativeItemRef, + kind: requestKind, + status: "pending", + responseCapability: { + type: "live", + providerSessionId: input.providerSessionId, + }, + createdAt: now, + resolvedAt: null, + }; + const node: OrchestrationV2ExecutionNode = { + id: nodeId, + threadId: context.input.threadId, + runId: context.input.runId, + parentNodeId: context.input.rootNodeId, + rootNodeId: context.input.rootNodeId, + kind: "approval_request", + status: "waiting", + countsForRun: false, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + runtimeRequestId: requestId, + checkpointScopeId: null, + startedAt: now, + completedAt: null, + }; + const turnItem: OrchestrationV2TurnItem = { + id: idAllocator.derive.approvalTurnItem({ requestId }), + threadId: context.input.threadId, + runId: context.input.runId, + nodeId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + parentItemId: null, + ordinal, + status: "waiting", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + type: "approval_request", + requestId, + requestKind, + ...(parsed.detail === undefined ? {} : { prompt: parsed.detail }), + }; + yield* Ref.update(pendingRuntimeRequests, (current) => { + const updated = new Map(current); + updated.set(String(requestId), { + type: "approval", + requestId, + decision, + runtimeRequest, + node, + turnItem, + }); + return updated; + }); + yield* emitProviderEvent({ + type: "node.updated", + provider, + node, + }); + yield* emitProviderEvent({ + type: "runtime_request.updated", + provider, + threadId: context.input.threadId, + runtimeRequest, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider, + turnItem, + }); + const resolved = yield* Deferred.await(decision).pipe( + Effect.ensuring( + Ref.update(pendingRuntimeRequests, (current) => { + const updated = new Map(current); + updated.delete(String(requestId)); + return updated; + }), + ), + ); + return resolved; + }); + + yield* runtime.handleRequestPermission((params) => + Effect.gen(function* () { + const context = yield* activeContext; + const disposition = acpPermissionDisposition(context.input.runtimePolicy, params); + if (disposition === "allow") { + const optionId = selectAutoApprovedPermissionOption(params); + return optionId === undefined + ? ({ outcome: { outcome: "cancelled" } } as const) + : ({ outcome: { outcome: "selected", optionId } } as const); + } + if (disposition === "deny") { + const optionId = selectPermissionOptionId(params, "decline"); + return optionId === undefined + ? ({ outcome: { outcome: "cancelled" } } as const) + : ({ outcome: { outcome: "selected", optionId } } as const); + } + const decision = yield* emitApprovalRequest(context, params); + if (decision === "cancel") { + return { outcome: { outcome: "cancelled" } } as const; + } + const optionId = selectPermissionOptionId(params, decision); + return optionId === undefined + ? ({ outcome: { outcome: "cancelled" } } as const) + : ({ outcome: { outcome: "selected", optionId } } as const); + }).pipe( + Effect.mapError( + (cause) => + new EffectAcpErrors.AcpTransportError({ + detail: "Failed to handle an ACP permission request", + cause, + }), + ), + ), + ); + + const requestUserInputInternal = Effect.fnUntraced(function* ( + request: AcpAdapterV2UserInputRequest, + ) { + const context = yield* activeContext; + yield* closeTextStreams(context); + const requestId = yield* idAllocator.allocate.runtimeRequest({ + provider, + providerTurnId: context.providerTurnId, + nativeRequestId: request.nativeRequestId, + }); + const answers = yield* Deferred.make(); + const now = yield* DateTime.now; + const nodeId = idAllocator.derive.nodeFromProviderItem({ + provider, + nativeItemId: request.nativeItemId, + }); + const turnItemId = idAllocator.derive.turnItemFromProviderItem({ + provider, + nativeItemId: request.nativeItemId, + }); + const nativeItemRef = { + provider, + nativeId: request.nativeItemId, + strength: "weak" as const, + }; + const ordinal = yield* resolveItemOrdinal(context, request.nativeItemId); + const runtimeRequest: OrchestrationV2RuntimeRequest = { + id: requestId, + nodeId, + providerTurnId: context.providerTurnId, + nativeRequestRef: { + provider, + nativeId: request.nativeRequestId, + strength: "weak", + }, + kind: "user_input", + status: "pending", + responseCapability: { + type: "live", + providerSessionId: input.providerSessionId, + }, + createdAt: now, + resolvedAt: null, + }; + const node: OrchestrationV2ExecutionNode = { + id: nodeId, + threadId: context.input.threadId, + runId: context.input.runId, + parentNodeId: context.input.rootNodeId, + rootNodeId: context.input.rootNodeId, + kind: "user_input_request", + status: "waiting", + countsForRun: false, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + runtimeRequestId: requestId, + checkpointScopeId: null, + startedAt: now, + completedAt: null, + }; + const turnItem: OrchestrationV2TurnItem = { + id: turnItemId, + threadId: context.input.threadId, + runId: context.input.runId, + nodeId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef, + parentItemId: null, + ordinal, + status: "waiting", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + type: "user_input_request", + requestId, + questions: [...request.questions], + }; + yield* Ref.update(pendingRuntimeRequests, (current) => { + const updated = new Map(current); + updated.set(String(requestId), { + type: "user_input", + requestId, + answers, + runtimeRequest, + node, + turnItem, + }); + return updated; + }); + yield* emitProviderEvent({ + type: "node.updated", + provider, + node, + }); + yield* emitProviderEvent({ + type: "runtime_request.updated", + provider, + threadId: context.input.threadId, + runtimeRequest, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider, + turnItem, + }); + return yield* Deferred.await(answers).pipe( + Effect.ensuring( + Ref.update(pendingRuntimeRequests, (current) => { + const updated = new Map(current); + updated.delete(String(requestId)); + return updated; + }), + ), + ); + }); + + const requestUserInput = (request: AcpAdapterV2UserInputRequest) => + requestUserInputInternal(request).pipe( + Effect.mapError( + (cause) => + new EffectAcpErrors.AcpTransportError({ + detail: "Failed to handle ACP user input request", + cause, + }), + ), + ); + + const cancelPendingRuntimeRequests = Effect.fnUntraced(function* () { + const requests = [...(yield* Ref.get(pendingRuntimeRequests)).values()]; + if (requests.length === 0) return; + + const now = yield* DateTime.now; + yield* Effect.forEach( + requests, + (request) => + Effect.gen(function* () { + const cancelled = yield* request.type === "approval" + ? Deferred.succeed(request.decision, "cancel") + : Deferred.succeed(request.answers, null); + if (!cancelled) return; + + yield* emitProviderEvent({ + type: "runtime_request.updated", + provider, + threadId: request.node.threadId, + runtimeRequest: { + ...request.runtimeRequest, + status: "cancelled", + resolvedAt: now, + }, + }); + yield* emitProviderEvent({ + type: "node.updated", + provider, + node: { + ...request.node, + status: "cancelled", + completedAt: now, + }, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider, + turnItem: { + ...request.turnItem, + status: "cancelled", + completedAt: now, + updatedAt: now, + }, + }); + }), + { concurrency: 1, discard: true }, + ); + }); + + yield* runtime.handleElicitation((params) => + Effect.gen(function* () { + if (params.mode === "url") { + return { action: { action: "decline" } } as const; + } + const questions = Object.entries(params.requestedSchema.properties ?? {}).map( + ([id, property], index): OrchestrationV2UserInputQuestion => { + const record = unknownRecord(property); + const enumValues = Array.isArray(record?.enum) + ? record.enum.filter((value): value is string => typeof value === "string") + : []; + const options = + enumValues.length > 0 + ? enumValues.map((value) => ({ label: value, description: value })) + : record?.type === "boolean" + ? [ + { label: "true", description: "Yes" }, + { label: "false", description: "No" }, + ] + : []; + return { + id, + header: nonEmptyText(record?.title, `Question ${index + 1}`), + question: nonEmptyText(record?.description, params.message), + options, + }; + }, + ); + const ordinal = yield* Ref.getAndUpdate( + nextElicitationOrdinal, + (current) => current + 1, + ); + const nativeRequestId = `${params.sessionId}:elicitation:${ordinal}`; + const answers = yield* requestUserInput({ + nativeItemId: nativeRequestId, + nativeRequestId, + questions, + }); + return answers === null + ? ({ action: { action: "cancel" } } as const) + : ({ action: { action: "accept", content: elicitationContent(answers) } } as const); + }), + ); + + if (flavor.registerExtensions !== undefined) { + yield* flavor.registerExtensions({ runtime, requestUserInput }); + } + + const started = yield* runtime.start(); + yield* Ref.set(activeSessionId, started.sessionId); + const capabilities = negotiatedCapabilities(flavor.capabilities, started); + const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true; + const canResumeSession = + started.initializeResult.agentCapabilities?.sessionCapabilities?.resume != null; + const supportsImagePrompts = + started.initializeResult.agentCapabilities?.promptCapabilities?.image === true; + + const activateSession = Effect.fnUntraced(function* (sessionId: string) { + if (canLoadSession) { + return yield* runtime.loadSession(sessionId); + } + if (canResumeSession) { + return yield* runtime.resumeSession(sessionId); + } + return yield* new ProviderAdapterProtocolError({ + provider, + detail: `ACP driver cannot load or resume session ${sessionId}`, + }); + }); + + const configureSession = Effect.fnUntraced(function* ( + startResult: AcpSessionRuntimeStartResult, + modelSelection: ModelSelection, + runtimePolicy: ProviderAdapterV2RuntimePolicy, + ) { + const requestedModel = flavor.resolveModelId?.(modelSelection) ?? modelSelection.model; + if ( + requestedModel.length > 0 && + requestedModel !== "auto" && + requestedModel !== "default" + ) { + const currentModel = startResult.sessionSetupResult.models?.currentModelId; + if (currentModel !== requestedModel) { + if (startResult.sessionSetupResult.models != null) { + yield* runtime.setSessionModel(requestedModel); + } else if ( + startResult.sessionSetupResult.configOptions?.some( + (option) => option.category === "model", + ) === true + ) { + yield* runtime.setModel(requestedModel); + } + } + } + const configOptions = yield* runtime.getConfigOptions; + for (const selection of modelSelection.options ?? []) { + if (configOptions.some((option) => option.id === selection.id)) { + yield* runtime.setConfigOption(selection.id, selection.value); + } + } + const modeState = yield* runtime.getModeState; + if (runtimePolicy.interactionMode === "plan" && modeState !== undefined) { + const planMode = modeState.availableModes.find( + (mode) => mode.id === "plan" || mode.id === "architect", + ); + if (planMode !== undefined) yield* runtime.setMode(planMode.id); + } + }); + + yield* configureSession(started, input.modelSelection, input.runtimePolicy); + const createdAt = yield* DateTime.now; + const providerSession: OrchestrationV2ProviderSession = { + id: input.providerSessionId, + provider, + status: "ready", + cwd: input.runtimePolicy.cwd ?? process.cwd(), + model: input.modelSelection.model, + capabilities, + createdAt, + updatedAt: createdAt, + lastError: null, + }; + + const providerTurnPayload = ( + context: ActiveAcpTurn, + status: OrchestrationV2ProviderTurn["status"], + completedAt: DateTime.Utc | null, + ): OrchestrationV2ProviderTurn => ({ + id: context.providerTurnId, + providerThreadId: context.input.providerThread.id, + nodeId: context.input.rootNodeId, + runAttemptId: context.input.attemptId, + nativeTurnRef: { + provider, + nativeId: context.nativeTurnId, + strength: "weak", + }, + ordinal: context.input.providerTurnOrdinal, + status, + startedAt: context.startedAt, + completedAt, + }); + + const finalizeTurn = Effect.fnUntraced(function* ( + context: ActiveAcpTurn, + status: "completed" | "interrupted" | "failed" | "cancelled", + ) { + if (context.finalized) return; + context.finalized = true; + yield* closeTextStreams(context); + const now = yield* DateTime.now; + const turn = providerTurnPayload(context, status, now); + yield* Ref.update(providerTurns, (current) => { + const updated = new Map(current); + updated.set(String(turn.id), turn); + return updated; + }); + yield* emitProviderEvent({ + type: "provider_turn.updated", + provider, + threadId: context.input.threadId, + providerTurn: turn, + }); + yield* emitProviderEvent({ + type: "provider_thread.updated", + provider, + providerThread: { + ...context.input.providerThread, + providerSessionId: input.providerSessionId, + status: "idle", + lastRunOrdinal: context.input.runOrdinal, + firstRunOrdinal: + context.input.providerThread.firstRunOrdinal ?? context.input.runOrdinal, + updatedAt: now, + }, + }); + yield* emitProviderEvent({ + type: "turn.terminal", + provider, + providerTurnId: context.providerTurnId, + status, + }); + yield* Ref.set(activeTurn, null); + yield* Deferred.succeed(context.completed, undefined).pipe(Effect.ignore); + }); + + const resolvePromptParts = Effect.fnUntraced(function* ( + turnInput: ProviderAdapterV2TurnInput, + ) { + const prompt: Array = []; + if (turnInput.message.text.length > 0) { + prompt.push({ type: "text", text: turnInput.message.text }); + } + if (turnInput.message.attachments.length > 0 && !supportsImagePrompts) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: "ACP driver did not negotiate image prompt support", + }); + } + for (const attachment of turnInput.message.attachments) { + const path = resolveAttachmentPath({ + attachmentsDir: serverConfig.attachmentsDir, + attachment: attachment as ChatAttachment, + }); + if (path === null) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: `Invalid attachment id '${attachment.id}'`, + }); + } + const bytes = yield* fileSystem.readFile(path).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterProtocolError({ + provider, + detail: `Failed to read attachment '${attachment.id}'`, + payload: cause, + }), + ), + ); + prompt.push({ + type: "image", + data: Buffer.from(bytes).toString("base64"), + mimeType: attachment.mimeType, + }); + } + if (prompt.length === 0) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: "ACP turn requires non-empty text or attachments", + }); + } + return prompt; + }); + + const startTurn = Effect.fn("AcpAdapterV2.startTurn")( + function* (turnInput: ProviderAdapterV2TurnInput) { + const existing = yield* Ref.get(activeTurn); + if (existing !== null) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: `ACP provider turn ${existing.providerTurnId} is still active`, + }); + } + const requestedSessionId = nativeThreadId(provider, turnInput.providerThread); + if ((yield* Ref.get(activeSessionId)) !== requestedSessionId) { + const activated = yield* activateSession(requestedSessionId); + yield* Ref.set(activeSessionId, activated.sessionId); + yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy); + } + const prompt = yield* resolvePromptParts(turnInput); + const startedAt = yield* DateTime.now; + const nativeTurnId = `${requestedSessionId}:turn:${turnInput.providerTurnOrdinal}`; + const providerTurnId = idAllocator.derive.providerTurn({ provider, nativeTurnId }); + const completed = yield* Deferred.make(); + const context: ActiveAcpTurn = { + input: turnInput, + providerTurnId, + nativeTurnId, + startedAt, + completed, + assistant: { current: null, nextSegment: 0 }, + reasoning: { current: null, nextSegment: 0 }, + tools: new Map(), + toolStartedAt: new Map(), + plan: null, + interrupted: false, + finalized: false, + }; + yield* Ref.set(activeTurn, context); + const runningTurn = providerTurnPayload(context, "running", null); + yield* Ref.update(providerTurns, (current) => { + const updated = new Map(current); + updated.set(String(runningTurn.id), runningTurn); + return updated; + }); + yield* emitProviderEvent({ + type: "provider_turn.updated", + provider, + threadId: turnInput.threadId, + providerTurn: runningTurn, + }); + yield* emitProviderEvent({ + type: "provider_thread.updated", + provider, + providerThread: { + ...turnInput.providerThread, + providerSessionId: input.providerSessionId, + status: "active", + updatedAt: startedAt, + }, + }); + yield* rememberSnapshotMessage({ + id: turnInput.message.messageId, + threadId: turnInput.threadId, + runId: turnInput.runId, + nodeId: turnInput.rootNodeId, + role: "user", + text: turnInput.message.text, + attachments: [...turnInput.message.attachments], + streaming: false, + createdAt: startedAt, + updatedAt: startedAt, + }); + yield* runtime.prompt({ prompt }).pipe( + Effect.flatMap((result) => { + const status = + result.stopReason === "cancelled" + ? context.interrupted + ? "interrupted" + : "cancelled" + : "completed"; + return finalizeTurn(context, status); + }), + Effect.catchCause((cause) => + finalizeTurn(context, context.interrupted ? "interrupted" : "failed").pipe( + Effect.andThen( + Effect.logWarning("orchestration-v2.acp-prompt-failed", { + provider, + providerSessionId: input.providerSessionId, + providerThreadId: turnInput.providerThread.id, + providerTurnId, + cause, + }), + ), + ), + ), + Effect.forkIn(sessionScope), + ); + }, + (effect, turnInput) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterTurnStartError({ + provider, + threadId: turnInput.threadId, + providerThreadId: turnInput.providerThread.id, + runId: turnInput.runId, + cause, + }), + ), + ), + ); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const requests = [...(yield* Ref.get(pendingRuntimeRequests)).values()]; + yield* Effect.forEach( + requests, + (request) => + request.type === "approval" + ? Deferred.succeed(request.decision, "cancel").pipe(Effect.ignore) + : Deferred.succeed(request.answers, null).pipe(Effect.ignore), + { discard: true }, + ); + const sessionCapabilities = + started.initializeResult.agentCapabilities?.sessionCapabilities; + if (sessionCapabilities?.close != null) { + yield* runtime.closeSession().pipe(Effect.ignore); + } + if (flavor.assertComplete !== undefined) { + yield* flavor.assertComplete.pipe(Effect.orDie); + } + }), + ); + + const sessionRuntime: ProviderAdapterV2SessionRuntime = { + instanceId: options.instanceId, + provider, + providerSessionId: input.providerSessionId, + providerSession, + rawEvents: Stream.fromEffectRepeat(Queue.take(rawEvents)), + events: Stream.fromEffectRepeat(Queue.take(events)), + ensureThread: Effect.fn("AcpAdapterV2.ensureThread")( + function* (threadInput: ProviderAdapterV2EnsureThreadInput) { + const now = yield* DateTime.now; + const sessionId = yield* Ref.get(activeSessionId); + if (sessionId === null) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: "ACP runtime did not produce a session id", + }); + } + return makeProviderThread({ + provider, + idAllocator, + appThreadId: threadInput.threadId, + providerSessionId: input.providerSessionId, + nativeThreadId: sessionId, + now, + }); + }, + (effect, threadInput) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterEnsureThreadError({ + provider, + threadId: threadInput.threadId, + cause, + }), + ), + ), + ), + resumeThread: Effect.fn("AcpAdapterV2.resumeThread")( + function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) { + const sessionId = nativeThreadId(provider, threadInput.providerThread); + if ((yield* Ref.get(activeSessionId)) !== sessionId) { + yield* Ref.set(snapshot, { + order: [], + messages: new Map(), + loadingRole: null, + loadingIndex: 0, + }); + const activated = yield* activateSession(sessionId); + yield* Ref.set(activeSessionId, activated.sessionId); + yield* configureSession(activated, input.modelSelection, input.runtimePolicy); + } + const now = yield* DateTime.now; + return { + ...threadInput.providerThread, + providerSessionId: input.providerSessionId, + status: "idle" as const, + updatedAt: now, + }; + }, + (effect, threadInput) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterResumeThreadError({ + provider, + providerSessionId: input.providerSessionId, + providerThreadId: threadInput.providerThread.id, + cause, + }), + ), + ), + ), + startTurn, + steerTurn: (turnInput) => + Effect.fail( + new ProviderAdapterSteerRunUnsupportedError({ + provider, + providerThreadId: turnInput.providerThread.id, + }), + ), + interruptTurn: Effect.fn("AcpAdapterV2.interruptTurn")( + function* (turnInput: ProviderAdapterV2InterruptInput) { + const context = yield* Ref.get(activeTurn); + if (context?.providerTurnId !== turnInput.providerTurnId) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: `ACP provider turn ${turnInput.providerTurnId} is not active`, + }); + } + context.interrupted = true; + yield* runtime.cancel.pipe(Effect.ensuring(cancelPendingRuntimeRequests())); + const stopped = yield* Deferred.await(context.completed).pipe( + Effect.timeoutOption("10 seconds"), + ); + if (Option.isNone(stopped)) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: `ACP provider turn ${turnInput.providerTurnId} did not acknowledge cancellation before the interrupt timeout`, + }); + } + }, + (effect, turnInput) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterInterruptError({ + provider, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + cause, + }), + ), + ), + ), + respondToRuntimeRequest: (requestInput) => + Effect.gen(function* () { + const pending = (yield* Ref.get(pendingRuntimeRequests)).get( + String(requestInput.requestId), + ); + if (pending === undefined) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: `No pending ACP runtime request ${requestInput.requestId}`, + }); + } + if (pending.type === "user_input") { + yield* Deferred.succeed(pending.answers, requestInput.answers ?? null); + return; + } + if (requestInput.decision === undefined) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: `ACP approval request ${requestInput.requestId} requires a decision`, + }); + } + yield* Deferred.succeed(pending.decision, requestInput.decision); + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRuntimeRequestResponseError({ + provider, + requestId: requestInput.requestId, + cause, + }), + ), + ), + readThreadSnapshot: Effect.fn("AcpAdapterV2.readThreadSnapshot")( + function* (snapshotInput) { + const sessionId = nativeThreadId(provider, snapshotInput.providerThread); + if ((yield* Ref.get(activeSessionId)) !== sessionId) { + if (!capabilities.threads.canReadThreadSnapshot) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: "ACP driver does not support session/load snapshots", + }); + } + yield* Ref.set(snapshot, { + order: [], + messages: new Map(), + loadingRole: null, + loadingIndex: 0, + }); + const activated = yield* runtime.loadSession(sessionId); + yield* Ref.set(activeSessionId, activated.sessionId); + } + const state = yield* Ref.get(snapshot); + const now = yield* DateTime.now; + return { + providerThread: { + ...snapshotInput.providerThread, + providerSessionId: input.providerSessionId, + status: "idle" as const, + updatedAt: now, + }, + providerTurns: [...(yield* Ref.get(providerTurns)).values()], + messages: state.order.flatMap((key) => { + const message = state.messages.get(key); + return message === undefined ? [] : [message]; + }), + runtimeRequests: [], + providerPayload: { protocol: ACP_PROTOCOL, sessionId }, + }; + }, + (effect, snapshotInput) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterReadThreadSnapshotError({ + provider, + providerThreadId: snapshotInput.providerThread.id, + cause, + }), + ), + ), + ), + rollbackThread: (rollbackInput) => + Effect.fail( + new ProviderAdapterRollbackThreadError({ + provider, + providerThreadId: rollbackInput.providerThread.id, + checkpointId: rollbackInput.target.checkpointId, + cause: "ACP does not define conversation rollback.", + }), + ), + forkThread: Effect.fn("AcpAdapterV2.forkThread")( + function* (forkInput) { + if (!capabilities.threads.canForkThread) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: "ACP driver did not negotiate session/fork", + }); + } + if (forkInput.providerTurnId !== undefined) { + return yield* new ProviderAdapterProtocolError({ + provider, + detail: "ACP session/fork can only fork the current session head", + }); + } + const sourceSessionId = nativeThreadId(provider, forkInput.sourceProviderThread); + const forked = yield* runtime.forkSession(sourceSessionId); + yield* Ref.set(activeSessionId, forked.sessionId); + const now = yield* DateTime.now; + return makeProviderThread({ + provider, + idAllocator, + appThreadId: forkInput.targetThreadId, + providerSessionId: input.providerSessionId, + nativeThreadId: forked.sessionId, + ...(forkInput.ownerNodeId === undefined + ? {} + : { ownerNodeId: forkInput.ownerNodeId }), + forkedFrom: { + providerThreadId: forkInput.sourceProviderThread.id, + ...(forkInput.providerTurnId === undefined + ? {} + : { providerTurnId: forkInput.providerTurnId }), + }, + now, + }); + }, + (effect, forkInput) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterForkThreadError({ + provider, + providerThreadId: forkInput.sourceProviderThread.id, + cause, + }), + ), + ), + ), + }; + return sessionRuntime; + }, + (effect, input) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterOpenSessionError({ + provider, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ), + ), + }); +} + +export type AcpAdapterV2Env = FileSystem.FileSystem | IdAllocatorV2; diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts new file mode 100644 index 0000000000..40d86f6086 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -0,0 +1,157 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientResponse } from "effect/unstable/http"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { ServerConfig } from "../../config.ts"; +import { makeAcpRegistryResolver } from "../../provider/acp/AcpRegistrySupport.ts"; +import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts"; +import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts"; +import { BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2 } from "../builtInProviderAdapterDrivers.ts"; +import { + ACP_REGISTRY_DRIVER_KIND, + AcpRegistryAdapterV2Driver, + makeAcpRegistryAdapterV2, +} from "./AcpRegistryAdapterV2.ts"; + +const registryUrl = "https://registry.test/registry.json"; +const decodeAcpRegistryAdapterSettings = Schema.decodeUnknownEffect( + AcpRegistryAdapterV2Driver.configSchema, +); + +const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-acp-registry-v2-adapter-", +}).pipe(Layer.provide(NodeServices.layer)); + +const registryLayer = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ + version: "1.0.0", + agents: [ + { + id: "fixture-agent", + name: "Fixture Agent", + version: "1.0.0", + description: "ACP V2 adapter fixture", + distribution: { + binary: { + "darwin-aarch64": { + archive: "https://registry.test/unused", + cmd: "fixture-agent", + args: [], + }, + "linux-x86_64": { + archive: "https://registry.test/unused", + cmd: "fixture-agent", + args: [], + }, + }, + }, + }, + ], + }), + ), + ), + ), +); + +const testLayer = Layer.mergeAll( + NodeServices.layer, + idAllocatorLayer, + serverConfigLayer, + registryLayer, +); + +describe("AcpRegistryAdapterV2", () => { + it("is registered as a generic provider driver with schema defaults", () => { + assert.isTrue(BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2.has(ACP_REGISTRY_DRIVER_KIND)); + assert.equal(AcpRegistryAdapterV2Driver.driverKind, ACP_REGISTRY_DRIVER_KIND); + assert.deepEqual(AcpRegistryAdapterV2Driver.defaultConfig(), { + enabled: true, + agentId: "", + commandPath: "", + authMethodId: "", + distribution: "auto", + customModels: [], + }); + }); + + it.effect("opens a real ACP child process resolved from registry configuration", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const resolver = yield* makeAcpRegistryResolver({ + cacheDir: serverConfig.providerStatusCacheDir, + registryUrl, + }); + const settings = yield* decodeAcpRegistryAdapterSettings({ + agentId: "fixture-agent", + commandPath: process.execPath, + authMethodId: "test", + }); + const instanceId = ProviderInstanceId.make("acp-registry-fixture"); + const adapter = makeAcpRegistryAdapterV2({ + instanceId, + settings, + environment: { + T3_ACP_SESSION_LIFECYCLE: "1", + }, + childProcessSpawner, + fileSystem, + idAllocator, + resolver: { + resolve: (configuredSettings, cwd, environment) => + resolver.resolve(configuredSettings, cwd, environment).pipe( + Effect.map((resolved) => ({ + ...resolved, + spawn: { + ...resolved.spawn, + args: [mockAgentPath], + }, + })), + ), + }, + serverConfig, + }); + const threadId = ThreadId.make("thread-acp-registry-fixture"); + const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-registry-fixture"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + + assert.equal(runtime.providerSession.provider, "acpRegistry"); + assert.equal(providerThread.nativeThreadRef?.nativeId, "mock-session-1"); + assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot); + assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread); + }).pipe(Effect.provide(testLayer), Effect.scoped), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts new file mode 100644 index 0000000000..6564a1bc6b --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts @@ -0,0 +1,89 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { AcpRegistrySettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { ServerConfig } from "../../config.ts"; +import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts"; +import { makeLayerEffect as makeProviderAdapterRegistryLayerEffect } from "../ProviderAdapterRegistry.ts"; +import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts"; +import { makeReplayServerConfig } from "../testkit/ProviderReplayHarness.ts"; +import { + type AcpReplayTranscript, + AcpReplayTranscriptDecodeError, + decodeAcpReplayTranscript, + makeAcpReplayCompletenessAssertion, + makeAcpReplayRuntime, +} from "./AcpAdapterV2.testkit.ts"; +import { + ACP_REGISTRY_DEFAULT_INSTANCE_ID, + ACP_REGISTRY_PROVIDER, + makeAcpRegistryAdapterV2, +} from "./AcpRegistryAdapterV2.ts"; + +const REPLAY_SETTINGS = Schema.decodeUnknownSync(AcpRegistrySettings)({ + agentId: "replay-agent", + authMethodId: "replay", +}); + +export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: AcpReplayTranscript) { + const serverConfigLayer = Layer.effect( + ServerConfig, + makeReplayServerConfig(`acp-registry-${transcript.scenario}`).pipe(Effect.orDie), + ).pipe(Layer.provide(NodeServices.layer)); + + return makeProviderAdapterRegistryLayerEffect( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocatorV2; + const serverConfig = yield* ServerConfig; + const replayDir = yield* fileSystem + .makeTempDirectory({ + prefix: `t3-orchestration-v2-acp-registry-replay-${transcript.scenario}-`, + }) + .pipe(Effect.orDie); + const statusPath = path.join(replayDir, "status.json"); + const scriptPath = yield* path + .fromFileUrl(new URL("../../../scripts/acp-replay-agent.ts", import.meta.url)) + .pipe(Effect.orDie); + const adapter = makeAcpRegistryAdapterV2({ + instanceId: ACP_REGISTRY_DEFAULT_INSTANCE_ID, + settings: REPLAY_SETTINGS, + environment: {}, + childProcessSpawner, + fileSystem, + idAllocator, + resolver: { + resolve: () => Effect.die("ACP registry resolver must not run during replay"), + }, + serverConfig, + makeRuntime: makeAcpReplayRuntime({ + transcript, + statusPath, + scriptPath, + childProcessSpawner, + }), + assertComplete: makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript), + }); + return [adapter]; + }), + ).pipe(Layer.provide(Layer.mergeAll(serverConfigLayer, NodeServices.layer, idAllocatorLayer))); +} + +export const AcpRegistryOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness< + AcpReplayTranscript, + AcpReplayTranscriptDecodeError +> = { + provider: ACP_REGISTRY_PROVIDER, + decodeTranscript: (transcript) => + decodeAcpReplayTranscript(transcript, ACP_REGISTRY_PROVIDER, { + retargetProvider: true, + }), + makeProviderAdapterRegistryLayer: makeAcpRegistryProviderAdapterRegistryReplayLayer, +}; diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts new file mode 100644 index 0000000000..d792da49b6 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts @@ -0,0 +1,158 @@ +import { + AcpRegistrySettings, + defaultInstanceIdForDriver, + ProviderDriverKind, +} from "@t3tools/contracts"; +import { HostProcessEnvironment } from "@t3tools/shared/hostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; +import { HttpClient } from "effect/unstable/http"; +import { ChildProcessSpawner } from "effect/unstable/process"; +import * as EffectAcpErrors from "effect-acp/errors"; + +import { ServerConfig } from "../../config.ts"; +import { + makeAcpRegistryResolver, + type AcpRegistryResolverShape, +} from "../../provider/acp/AcpRegistrySupport.ts"; +import { + AcpSessionRuntime, + type AcpSessionRuntimeShape, +} from "../../provider/acp/AcpSessionRuntime.ts"; +import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts"; +import { IdAllocatorV2 } from "../IdAllocator.ts"; +import { + ProviderAdapterDriverCreateError, + type ProviderAdapterDriver, + type ProviderAdapterDriverCreateInput, +} from "../ProviderAdapterDriver.ts"; +import { + AcpProviderCapabilitiesV2, + makeAcpAdapterV2, + type AcpAdapterV2Flavor, + type AcpAdapterV2RuntimeInput, +} from "./AcpAdapterV2.ts"; + +export const ACP_REGISTRY_PROVIDER = "acpRegistry" as const; +export const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make(ACP_REGISTRY_PROVIDER); +export const ACP_REGISTRY_DEFAULT_INSTANCE_ID = + defaultInstanceIdForDriver(ACP_REGISTRY_DRIVER_KIND); + +const DEFAULT_ACP_REGISTRY_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({}); + +export interface AcpRegistryAdapterV2Options { + readonly instanceId: Parameters[0]["instanceId"]; + readonly settings: AcpRegistrySettings; + readonly environment: NodeJS.ProcessEnv; + readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; + readonly fileSystem: FileSystem.FileSystem; + readonly idAllocator: IdAllocatorV2["Service"]; + readonly resolver: AcpRegistryResolverShape; + readonly serverConfig: ServerConfig["Service"]; + readonly makeRuntime?: ( + input: AcpAdapterV2RuntimeInput, + ) => Effect.Effect; + readonly assertComplete?: Effect.Effect; +} + +function makeAcpRegistryRuntime(options: AcpRegistryAdapterV2Options) { + return ( + input: AcpAdapterV2RuntimeInput, + ): Effect.Effect => + Effect.gen(function* () { + const resolved = yield* options.resolver + .resolve(options.settings, input.cwd, options.environment) + .pipe( + Effect.mapError( + (cause) => + new EffectAcpErrors.AcpSpawnError({ + command: options.settings.agentId || ACP_REGISTRY_PROVIDER, + cause, + }), + ), + ); + const context = yield* Layer.build( + AcpSessionRuntime.layer({ + ...input, + spawn: resolved.spawn, + ...(options.settings.authMethodId ? { authMethodId: options.settings.authMethodId } : {}), + }).pipe( + Layer.provide( + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, options.childProcessSpawner), + ), + ), + ); + return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(context)); + }); +} + +export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) { + const flavor: AcpAdapterV2Flavor = { + provider: ACP_REGISTRY_PROVIDER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(options), + ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }), + }; + return makeAcpAdapterV2({ + instanceId: options.instanceId, + flavor, + fileSystem: options.fileSystem, + idAllocator: options.idAllocator, + serverConfig: options.serverConfig, + }); +} + +export type AcpRegistryAdapterV2DriverEnv = + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | HttpClient.HttpClient + | IdAllocatorV2 + | Path.Path + | ServerConfig; + +export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver< + AcpRegistrySettings, + AcpRegistryAdapterV2DriverEnv +> = { + driverKind: ACP_REGISTRY_DRIVER_KIND, + configSchema: AcpRegistrySettings, + defaultConfig: (): AcpRegistrySettings => DEFAULT_ACP_REGISTRY_SETTINGS, + create: Effect.fn("AcpRegistryAdapterV2Driver.create")( + function* (input: ProviderAdapterDriverCreateInput) { + const hostEnvironment = yield* HostProcessEnvironment; + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const serverConfig = yield* ServerConfig; + const resolver = yield* makeAcpRegistryResolver({ + cacheDir: serverConfig.providerStatusCacheDir, + }); + return makeAcpRegistryAdapterV2({ + instanceId: input.instanceId, + settings: { ...input.config, enabled: input.enabled }, + environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment), + childProcessSpawner, + fileSystem, + idAllocator, + resolver, + serverConfig, + }); + }, + (effect, input) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterDriverCreateError({ + driver: ACP_REGISTRY_DRIVER_KIND, + instanceId: input.instanceId, + detail: "Failed to create ACP Registry adapter.", + cause, + }), + ), + ), + ), +}; diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts new file mode 100644 index 0000000000..0697ec85b4 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts @@ -0,0 +1,111 @@ +import { assert, describe, it } from "@effect/vitest"; +import type * as EffectAcpSchema from "effect-acp/schema"; + +import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts"; +import { AcpProviderCapabilitiesV2, acpPermissionDisposition } from "./AcpAdapterV2.ts"; +import { GrokProviderCapabilitiesV2 } from "./GrokAdapterV2.ts"; + +function permissionRequest( + kind: EffectAcpSchema.ToolKind, +): EffectAcpSchema.RequestPermissionRequest { + return { + sessionId: "session-1", + options: [ + { optionId: "allow-once", name: "Allow once", kind: "allow_once" }, + { optionId: "allow-always", name: "Allow always", kind: "allow_always" }, + { optionId: "reject-once", name: "Reject", kind: "reject_once" }, + ], + toolCall: { + toolCallId: "tool-1", + title: "Test tool", + kind, + }, + }; +} + +function runtimePolicy(input: { + readonly runtimeMode: "approval-required" | "auto-accept-edits" | "full-access"; + readonly approvalPolicy?: unknown; + readonly sandboxPolicy?: unknown; +}) { + return ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: input.runtimeMode, + interactionMode: "default", + cwd: "/workspace", + ...(input.approvalPolicy === undefined ? {} : { approvalPolicy: input.approvalPolicy }), + ...(input.sandboxPolicy === undefined ? {} : { sandboxPolicy: input.sandboxPolicy }), + }); +} + +describe("GrokAdapterV2 capabilities", () => { + it("keeps optional protocol features conservative until a flavor or handshake confirms them", () => { + assert.isFalse(AcpProviderCapabilitiesV2.sessions.supportsModelSwitchInSession); + assert.isFalse(AcpProviderCapabilitiesV2.sessions.supportsRuntimeModeSwitchInSession); + assert.isFalse(AcpProviderCapabilitiesV2.threads.canReadThreadSnapshot); + assert.isFalse(AcpProviderCapabilitiesV2.tools.supportsMcpTools); + }); + + it("leaves non-native features available to orchestrator fallbacks", () => { + assert.isFalse(GrokProviderCapabilitiesV2.threads.canForkThread); + assert.isFalse(GrokProviderCapabilitiesV2.subagents.supportsSubagents); + assert.isFalse(GrokProviderCapabilitiesV2.turns.supportsActiveSteering); + assert.isTrue(GrokProviderCapabilitiesV2.turns.supportsInterrupt); + assert.isTrue(GrokProviderCapabilitiesV2.turns.supportsSteeringByInterruptRestart); + assert.isTrue(GrokProviderCapabilitiesV2.context.supportsFullThreadHandoff); + }); + + it("declares the optional ACP features verified by the Grok handshake", () => { + assert.isTrue(GrokProviderCapabilitiesV2.sessions.supportsModelSwitchInSession); + assert.isTrue(GrokProviderCapabilitiesV2.threads.canReadThreadSnapshot); + assert.isTrue(GrokProviderCapabilitiesV2.tools.supportsMcpTools); + assert.isTrue(GrokProviderCapabilitiesV2.checkpointing.providerCanReadConversationSnapshot); + }); +}); + +describe("ACP permission policy", () => { + it("honors explicit on-request approval over full-access runtime mode", () => { + assert.equal( + acpPermissionDisposition( + runtimePolicy({ + runtimeMode: "full-access", + approvalPolicy: "on-request", + sandboxPolicy: { type: "readOnly" }, + }), + permissionRequest("execute"), + ), + "ask", + ); + }); + + it("rejects mutating escalation under a non-interactive read-only policy", () => { + const policy = runtimePolicy({ + runtimeMode: "full-access", + approvalPolicy: "never", + sandboxPolicy: { type: "readOnly" }, + }); + assert.equal(acpPermissionDisposition(policy, permissionRequest("execute")), "deny"); + assert.equal(acpPermissionDisposition(policy, permissionRequest("edit")), "deny"); + assert.equal(acpPermissionDisposition(policy, permissionRequest("read")), "allow"); + }); + + it("auto-approves requests only when the resolved policy permits them", () => { + assert.equal( + acpPermissionDisposition( + runtimePolicy({ + runtimeMode: "full-access", + approvalPolicy: "never", + sandboxPolicy: { type: "dangerFullAccess" }, + }), + permissionRequest("execute"), + ), + "allow", + ); + assert.equal( + acpPermissionDisposition( + runtimePolicy({ runtimeMode: "approval-required" }), + permissionRequest("read"), + ), + "ask", + ); + }); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts new file mode 100644 index 0000000000..ec8bbf3501 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts @@ -0,0 +1,76 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { GrokSettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { ServerConfig } from "../../config.ts"; +import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts"; +import { makeLayerEffect as makeProviderAdapterRegistryLayerEffect } from "../ProviderAdapterRegistry.ts"; +import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts"; +import { makeReplayServerConfig } from "../testkit/ProviderReplayHarness.ts"; +import { + type AcpReplayTranscript, + AcpReplayTranscriptDecodeError, + decodeAcpReplayTranscript, + makeAcpReplayCompletenessAssertion, + makeAcpReplayRuntime, +} from "./AcpAdapterV2.testkit.ts"; +import { GROK_DEFAULT_INSTANCE_ID, GROK_PROVIDER, makeGrokAdapterV2 } from "./GrokAdapterV2.ts"; + +const DEFAULT_GROK_SETTINGS = Schema.decodeUnknownSync(GrokSettings)({}); + +export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplayTranscript) { + const serverConfigLayer = Layer.effect( + ServerConfig, + makeReplayServerConfig(`grok-${transcript.scenario}`).pipe(Effect.orDie), + ).pipe(Layer.provide(NodeServices.layer)); + + return makeProviderAdapterRegistryLayerEffect( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocatorV2; + const serverConfig = yield* ServerConfig; + const replayDir = yield* fileSystem + .makeTempDirectory({ + prefix: `t3-orchestration-v2-grok-replay-${transcript.scenario}-`, + }) + .pipe(Effect.orDie); + const statusPath = path.join(replayDir, "status.json"); + const scriptPath = yield* path + .fromFileUrl(new URL("../../../scripts/acp-replay-agent.ts", import.meta.url)) + .pipe(Effect.orDie); + const adapter = makeGrokAdapterV2({ + instanceId: GROK_DEFAULT_INSTANCE_ID, + settings: DEFAULT_GROK_SETTINGS, + environment: {}, + childProcessSpawner, + fileSystem, + idAllocator, + serverConfig, + makeRuntime: makeAcpReplayRuntime({ + transcript, + statusPath, + scriptPath, + childProcessSpawner, + }), + assertComplete: makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript), + }); + return [adapter]; + }), + ).pipe(Layer.provide(Layer.mergeAll(serverConfigLayer, NodeServices.layer, idAllocatorLayer))); +} + +export const GrokOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness< + AcpReplayTranscript, + AcpReplayTranscriptDecodeError +> = { + provider: GROK_PROVIDER, + decodeTranscript: (transcript) => decodeAcpReplayTranscript(transcript, GROK_PROVIDER), + makeProviderAdapterRegistryLayer: makeGrokProviderAdapterRegistryReplayLayer, +}; diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts new file mode 100644 index 0000000000..4bb0f1ef5f --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts @@ -0,0 +1,210 @@ +import { HostProcessEnvironment } from "@t3tools/shared/hostProcess"; +import { + defaultInstanceIdForDriver, + GrokSettings, + ProviderDriverKind, + type OrchestrationV2ProviderCapabilities, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; +import { ChildProcessSpawner } from "effect/unstable/process"; +import type * as EffectAcpErrors from "effect-acp/errors"; + +import { ServerConfig } from "../../config.ts"; +import { + makeGrokAcpRuntime, + resolveGrokAcpBaseModelId, +} from "../../provider/acp/GrokAcpSupport.ts"; +import { + extractXAiAskUserQuestionIdentity, + extractXAiAskUserQuestions, + makeXAiAskUserQuestionCancelledResponse, + makeXAiAskUserQuestionResponse, + XAiAskUserQuestionRequest, +} from "../../provider/acp/XAiAcpExtension.ts"; +import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts"; +import type { AcpSessionRuntimeShape } from "../../provider/acp/AcpSessionRuntime.ts"; +import { IdAllocatorV2 } from "../IdAllocator.ts"; +import { ProviderAdapterV2 } from "../ProviderAdapter.ts"; +import { + ProviderAdapterDriverCreateError, + type ProviderAdapterDriver, + type ProviderAdapterDriverCreateInput, +} from "../ProviderAdapterDriver.ts"; +import { + AcpProviderCapabilitiesV2, + makeAcpAdapterV2, + type AcpAdapterV2Flavor, + type AcpAdapterV2RuntimeInput, +} from "./AcpAdapterV2.ts"; + +export const GROK_PROVIDER = "grok" as const; +export const GROK_DRIVER_KIND = ProviderDriverKind.make(GROK_PROVIDER); +export const GROK_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(GROK_DRIVER_KIND); +const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({}); + +export const GrokProviderCapabilitiesV2 = { + ...AcpProviderCapabilitiesV2, + sessions: { + ...AcpProviderCapabilitiesV2.sessions, + supportsModelSwitchInSession: true, + supportsRuntimeModeSwitchInSession: false, + }, + threads: { + ...AcpProviderCapabilitiesV2.threads, + canReadThreadSnapshot: true, + canForkThread: false, + canForkFromTurn: false, + }, + subagents: { + ...AcpProviderCapabilitiesV2.subagents, + supportsSubagents: false, + }, + tools: { + ...AcpProviderCapabilitiesV2.tools, + supportsMcpTools: true, + }, + checkpointing: { + ...AcpProviderCapabilitiesV2.checkpointing, + providerCanReadConversationSnapshot: true, + }, +} satisfies OrchestrationV2ProviderCapabilities; + +export interface GrokAdapterV2Options { + readonly instanceId: Parameters[0]["instanceId"]; + readonly settings: GrokSettings; + readonly environment: NodeJS.ProcessEnv; + readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; + readonly fileSystem: FileSystem.FileSystem; + readonly idAllocator: IdAllocatorV2["Service"]; + readonly serverConfig: ServerConfig["Service"]; + readonly makeRuntime?: ( + input: AcpAdapterV2RuntimeInput, + ) => Effect.Effect; + readonly assertComplete?: Effect.Effect; +} + +export const registerGrokAcpExtensions: NonNullable = ({ + runtime, + requestUserInput, +}) => + Effect.forEach( + ["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const, + (method) => + runtime.handleExtRequest(method, XAiAskUserQuestionRequest, (params) => { + const identity = extractXAiAskUserQuestionIdentity(params); + const questions = extractXAiAskUserQuestions(params).map((question) => ({ + id: question.id, + header: question.header, + question: question.question, + options: [...question.options], + })); + return requestUserInput({ + nativeItemId: `${identity.sessionId}:xai-question:${identity.toolCallId}`, + nativeRequestId: identity.toolCallId, + questions, + }).pipe( + Effect.map((answers) => + answers === null + ? makeXAiAskUserQuestionCancelledResponse() + : makeXAiAskUserQuestionResponse(params, answers), + ), + ); + }), + { discard: true }, + ); + +export function makeGrokAdapterV2(options: GrokAdapterV2Options) { + const flavor: AcpAdapterV2Flavor = { + provider: GROK_PROVIDER, + capabilities: GrokProviderCapabilitiesV2, + resolveModelId: (selection) => resolveGrokAcpBaseModelId(selection.model), + makeRuntime: + options.makeRuntime ?? + ((input) => + makeGrokAcpRuntime({ + ...input, + grokSettings: options.settings, + environment: options.environment, + childProcessSpawner: options.childProcessSpawner, + })), + registerExtensions: registerGrokAcpExtensions, + ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }), + }; + return makeAcpAdapterV2({ + instanceId: options.instanceId, + flavor, + fileSystem: options.fileSystem, + idAllocator: options.idAllocator, + serverConfig: options.serverConfig, + }); +} + +export type GrokAdapterV2DriverEnv = + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | IdAllocatorV2 + | ServerConfig; + +export const GrokAdapterV2Driver: ProviderAdapterDriver = { + driverKind: GROK_DRIVER_KIND, + configSchema: GrokSettings, + defaultConfig: (): GrokSettings => DEFAULT_GROK_SETTINGS, + create: Effect.fn("GrokAdapterV2Driver.create")( + function* (input: ProviderAdapterDriverCreateInput) { + const hostEnvironment = yield* HostProcessEnvironment; + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const serverConfig = yield* ServerConfig; + return makeGrokAdapterV2({ + instanceId: input.instanceId, + settings: { ...input.config, enabled: input.enabled }, + environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment), + childProcessSpawner, + fileSystem, + idAllocator, + serverConfig, + }); + }, + (effect, input) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterDriverCreateError({ + driver: GROK_DRIVER_KIND, + instanceId: input.instanceId, + detail: "Failed to create Grok ACP adapter.", + cause, + }), + ), + ), + ), +}; + +export const layer: Layer.Layer< + ProviderAdapterV2, + never, + ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | IdAllocatorV2 | ServerConfig +> = Layer.effect( + ProviderAdapterV2, + Effect.gen(function* () { + const hostEnvironment = yield* HostProcessEnvironment; + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const serverConfig = yield* ServerConfig; + return makeGrokAdapterV2({ + instanceId: GROK_DEFAULT_INSTANCE_ID, + settings: DEFAULT_GROK_SETTINGS, + environment: hostEnvironment, + childProcessSpawner, + fileSystem, + idAllocator, + serverConfig, + }); + }), +); diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts new file mode 100644 index 0000000000..222e24aa07 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts @@ -0,0 +1,184 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + NodeId, + ProviderThreadId, + ProviderTurnId, + type OrchestrationV2ProviderTurn, +} from "@t3tools/contracts"; + +import { + openCodeBoundaryAfterProviderTurn, + openCodeChildPermissionRules, + openCodePermissionRules, + openCodePermissionRequestKind, + openCodeToolProjectionKind, + OpenCodeProviderCapabilitiesV2, +} from "./OpenCodeAdapterV2.ts"; +import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts"; + +function runtimePolicy( + runtimeMode: ProviderAdapterV2RuntimePolicy["runtimeMode"], + override: Partial = {}, +): ProviderAdapterV2RuntimePolicy { + return ProviderAdapterV2RuntimePolicy.make({ + runtimeMode, + interactionMode: "default", + cwd: null, + ...override, + }); +} + +function permissionAction(rules: ReturnType, permission: string) { + return rules.findLast((rule) => rule.permission === "*" || rule.permission === permission) + ?.action; +} + +function providerTurn(input: { + readonly id: string; + readonly ordinal: number; + readonly nativeId: string | null; +}): OrchestrationV2ProviderTurn { + return { + id: ProviderTurnId.make(input.id), + providerThreadId: ProviderThreadId.make("provider-thread:opencode-test"), + nodeId: NodeId.make(`node:${input.id}`), + runAttemptId: null, + nativeTurnRef: + input.nativeId === null + ? null + : { provider: "opencode", nativeId: input.nativeId, strength: "weak" }, + ordinal: input.ordinal, + status: "completed", + startedAt: null, + completedAt: null, + }; +} + +describe("OpenCodeAdapterV2", () => { + it("advertises the identity strengths exposed by the SDK boundary", () => { + assert.equal(OpenCodeProviderCapabilitiesV2.identity.nativeThreadIds, "strong"); + assert.equal(OpenCodeProviderCapabilitiesV2.identity.nativeTurnIds, "weak"); + assert.equal(OpenCodeProviderCapabilitiesV2.identity.nativeItemIds, "strong"); + assert.equal(OpenCodeProviderCapabilitiesV2.identity.nativeRequestIds, "strong"); + assert.isTrue(OpenCodeProviderCapabilitiesV2.threads.canForkFromTurn); + assert.isTrue(OpenCodeProviderCapabilitiesV2.turns.supportsActiveSteering); + assert.equal(OpenCodeProviderCapabilitiesV2.turns.terminalStatusQuality, "strong"); + assert.isFalse(OpenCodeProviderCapabilitiesV2.subagents.canCloseSubagents); + }); + + it("maps native permission families to orchestration request kinds", () => { + assert.equal(openCodePermissionRequestKind("bash"), "command"); + assert.equal(openCodePermissionRequestKind("read"), "file-read"); + assert.equal(openCodePermissionRequestKind("grep"), "file-read"); + assert.equal(openCodePermissionRequestKind("external_directory"), "file-read"); + assert.equal(openCodePermissionRequestKind("external_directory", "edit"), "file-change"); + assert.equal(openCodePermissionRequestKind("edit"), "file-change"); + assert.equal(openCodePermissionRequestKind("apply_patch"), "file-change"); + }); + + it("maps OpenCode tools to semantic turn-item families", () => { + assert.equal(openCodeToolProjectionKind("bash"), "command_execution"); + assert.equal(openCodeToolProjectionKind("edit"), "file_change"); + assert.equal(openCodeToolProjectionKind("read"), "file_search"); + assert.equal(openCodeToolProjectionKind("lsp"), "file_search"); + assert.equal(openCodeToolProjectionKind("websearch"), "web_search"); + assert.equal(openCodeToolProjectionKind("codesearch"), "web_search"); + assert.equal(openCodeToolProjectionKind("custom_tool"), "dynamic_tool"); + }); + + it("maps runtime modes to safe OpenCode permission rules", () => { + const approvalRequired = openCodePermissionRules(runtimePolicy("approval-required")); + assert.equal(permissionAction(approvalRequired, "read"), "allow"); + assert.equal(permissionAction(approvalRequired, "edit"), "ask"); + assert.equal(permissionAction(approvalRequired, "bash"), "ask"); + assert.equal(permissionAction(approvalRequired, "doom_loop"), "ask"); + assert.equal(permissionAction(approvalRequired, "unknown_plugin_tool"), "ask"); + assert.equal(permissionAction(approvalRequired, "question"), "allow"); + + const autoAcceptEdits = openCodePermissionRules(runtimePolicy("auto-accept-edits")); + assert.equal(permissionAction(autoAcceptEdits, "edit"), "allow"); + assert.equal(permissionAction(autoAcceptEdits, "bash"), "ask"); + + const fullAccess = openCodePermissionRules(runtimePolicy("full-access")); + assert.equal(permissionAction(fullAccess, "bash"), "allow"); + assert.equal(permissionAction(fullAccess, "edit"), "allow"); + + const granularApproval = openCodePermissionRules( + runtimePolicy("full-access", { + approvalPolicy: { granular: { request_permissions: true } }, + }), + ); + assert.equal(permissionAction(granularApproval, "bash"), "ask"); + assert.equal(permissionAction(granularApproval, "read"), "allow"); + }); + + it("enforces non-interactive sandbox policy through OpenCode permissions", () => { + const readOnly = openCodePermissionRules( + runtimePolicy("full-access", { + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }), + ); + assert.equal(permissionAction(readOnly, "read"), "allow"); + assert.equal(permissionAction(readOnly, "edit"), "deny"); + assert.equal(permissionAction(readOnly, "bash"), "deny"); + assert.equal(permissionAction(readOnly, "webfetch"), "deny"); + assert.equal(permissionAction(readOnly, "doom_loop"), "deny"); + assert.equal(permissionAction(readOnly, "unknown_plugin_tool"), "deny"); + assert.equal(permissionAction(readOnly, "external_directory"), "allow"); + + const workspaceWrite = openCodePermissionRules( + runtimePolicy("auto-accept-edits", { + approvalPolicy: "never", + sandboxPolicy: { + type: "workspaceWrite", + writableRoots: ["/tmp/opencode-workspace"], + networkAccess: true, + }, + }), + ); + assert.equal(permissionAction(workspaceWrite, "edit"), "allow"); + assert.equal(permissionAction(workspaceWrite, "bash"), "deny"); + assert.equal(permissionAction(workspaceWrite, "webfetch"), "allow"); + assert.deepInclude(workspaceWrite, { + permission: "external_directory", + pattern: "/tmp/opencode-workspace/*", + action: "allow", + }); + }); + + it("preserves OpenCode's recursion guard on task-created child sessions", () => { + const childRules = openCodeChildPermissionRules(runtimePolicy("full-access"), [ + { permission: "task", pattern: "*", action: "deny" }, + ]); + + assert.equal(permissionAction(childRules, "read"), "allow"); + assert.equal(permissionAction(childRules, "bash"), "allow"); + assert.equal(permissionAction(childRules, "task"), "deny"); + + const approvalRequiredPolicy = runtimePolicy("approval-required"); + const parentRules = openCodePermissionRules(approvalRequiredPolicy); + const childApprovalRules = openCodeChildPermissionRules(approvalRequiredPolicy, [ + ...parentRules.filter((rule) => rule.action === "deny"), + { permission: "task", pattern: "*", action: "deny" }, + ]); + assert.equal(permissionAction(childApprovalRules, "bash"), "ask"); + assert.equal(permissionAction(childApprovalRules, "task"), "deny"); + }); + + it("uses the next native user message as the exclusive fork and revert boundary", () => { + const first = providerTurn({ id: "turn:first", ordinal: 1, nativeId: "msg-user-1" }); + const synthetic = providerTurn({ id: "turn:synthetic", ordinal: 2, nativeId: null }); + const third = providerTurn({ id: "turn:third", ordinal: 3, nativeId: "msg-user-3" }); + + assert.equal( + openCodeBoundaryAfterProviderTurn([third, first, synthetic], first.id), + "msg-user-3", + ); + assert.isUndefined(openCodeBoundaryAfterProviderTurn([first, synthetic, third], third.id)); + }); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts new file mode 100644 index 0000000000..312c49153f --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts @@ -0,0 +1,385 @@ +import type { Event as OpenCodeEvent, OpencodeClient } from "@opencode-ai/sdk/v2"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { ProviderReplayEntry, type ProviderReplayTranscript } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Duration from "effect/Duration"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { ServerConfig } from "../../config.ts"; +import { + OpenCodeRuntime, + OpenCodeRuntimeError, + type OpenCodeRuntimeShape, +} from "../../provider/opencodeRuntime.ts"; +import { layer as idAllocatorLayer } from "../IdAllocator.ts"; +import { ProviderAdapterDriverCreateError } from "../ProviderAdapterDriver.ts"; +import { makeDriverLayer as makeProviderAdapterRegistryDriverLayer } from "../ProviderAdapterRegistry.ts"; +import { + makeReplayServerConfig, + type OrchestratorV2ProviderReplayHarness, +} from "../testkit/ProviderReplayHarness.ts"; +import { + OPENCODE_DEFAULT_INSTANCE_ID, + OPENCODE_DRIVER_KIND, + OPENCODE_PROVIDER, + OpenCodeAdapterV2Driver, +} from "./OpenCodeAdapterV2.ts"; + +export const OPENCODE_SDK_REPLAY_PROTOCOL = "opencode-sdk.sse" as const; + +const OpenCodeSdkReplayTranscript = Schema.Struct({ + provider: Schema.Literal(OPENCODE_PROVIDER), + protocol: Schema.Literal(OPENCODE_SDK_REPLAY_PROTOCOL), + version: Schema.String, + scenario: Schema.String, + metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + entries: Schema.Array(ProviderReplayEntry), +}); +export type OpenCodeSdkReplayTranscript = typeof OpenCodeSdkReplayTranscript.Type; +const decodeOpenCodeSdkReplayTranscript = Schema.decodeUnknownEffect(OpenCodeSdkReplayTranscript); + +export class OpenCodeReplayTranscriptDecodeError extends Schema.TaggedErrorClass()( + "OpenCodeReplayTranscriptDecodeError", + { + provider: Schema.optional(Schema.String), + protocol: Schema.optional(Schema.String), + scenario: Schema.optional(Schema.String), + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Failed to decode OpenCode replay transcript for scenario ${this.scenario ?? ""}.`; + } +} + +export class OpenCodeReplayMismatchError extends Schema.TaggedErrorClass()( + "OpenCodeReplayMismatchError", + { + scenario: Schema.String, + cursor: Schema.Number, + expected: Schema.Unknown, + actual: Schema.Unknown, + }, +) { + override get message(): string { + return `OpenCode replay frame mismatch at cursor ${this.cursor} in scenario ${this.scenario}.`; + } +} + +export class OpenCodeReplayIncompleteError extends Schema.TaggedErrorClass()( + "OpenCodeReplayIncompleteError", + { + scenario: Schema.String, + cursor: Schema.Number, + remaining: Schema.Number, + }, +) { + override get message(): string { + return `OpenCode replay ended with ${this.remaining} unconsumed entries in scenario ${this.scenario}.`; + } +} + +export const OpenCodeReplayError = Schema.Union([ + OpenCodeReplayTranscriptDecodeError, + OpenCodeReplayMismatchError, + OpenCodeReplayIncompleteError, +]); +export type OpenCodeReplayError = typeof OpenCodeReplayError.Type; +export const OpenCodeOrchestratorReplayHarnessError = Schema.Union([ + OpenCodeReplayError, + ProviderAdapterDriverCreateError, +]); +export type OpenCodeOrchestratorReplayHarnessError = + typeof OpenCodeOrchestratorReplayHarnessError.Type; + +function replayValueMatches(expected: unknown, actual: unknown): boolean { + if (expected === "" || expected === "") return true; + if (Array.isArray(expected)) { + return ( + Array.isArray(actual) && + expected.length === actual.length && + expected.every((entry, index) => replayValueMatches(entry, actual[index])) + ); + } + if (typeof expected === "object" && expected !== null) { + if (typeof actual !== "object" || actual === null) return false; + return Object.entries(expected).every(([key, value]) => + replayValueMatches(value, (actual as Record)[key]), + ); + } + return Object.is(expected, actual); +} + +function frameRecord(frame: unknown): Record | null { + return typeof frame === "object" && frame !== null ? (frame as Record) : null; +} + +class OpenCodeReplayController { + private cursor = 0; + private readonly waiters = new Set<() => void>(); + private failure: unknown = null; + private readonly transcript: OpenCodeSdkReplayTranscript; + + constructor(transcript: OpenCodeSdkReplayTranscript) { + this.transcript = transcript; + } + + async expectOutbound(actual: unknown): Promise { + try { + const entry = this.transcript.entries[this.cursor]; + if (entry?.type !== "expect_outbound" || !replayValueMatches(entry.frame, actual)) { + throw new OpenCodeReplayMismatchError({ + scenario: this.transcript.scenario, + cursor: this.cursor, + expected: entry?.type === "expect_outbound" ? entry.frame : (entry ?? null), + actual, + }); + } + this.advance(); + } catch (cause) { + this.fail(cause); + throw cause; + } + } + + async response(operation: string): Promise { + while (true) { + this.throwFailure(); + const entry = this.transcript.entries[this.cursor]; + if (entry?.type === "emit_inbound") { + const frame = frameRecord(entry.frame); + if (frame?.type === "sdk.response" && frame.operation === operation) { + if (entry.afterMs !== undefined && entry.afterMs > 0) { + await Effect.runPromise(Effect.sleep(Duration.millis(entry.afterMs))); + } + const data = frame.data; + this.advance(); + return data; + } + } + if (entry?.type === "runtime_exit") { + const mismatch = new OpenCodeReplayMismatchError({ + scenario: this.transcript.scenario, + cursor: this.cursor, + expected: { type: "sdk.response", operation }, + actual: entry, + }); + this.fail(mismatch); + throw mismatch; + } + await this.changed(); + } + } + + async *events(signal?: AbortSignal): AsyncIterable { + while (true) { + if (signal?.aborted === true) return; + this.throwFailure(); + const entry = this.transcript.entries[this.cursor]; + if (entry?.type === "emit_inbound") { + const frame = frameRecord(entry.frame); + if (frame?.type === "sdk.event") { + if (entry.afterMs !== undefined && entry.afterMs > 0) { + await Effect.runPromise(Effect.sleep(Duration.millis(entry.afterMs))); + } + const event = frame.event as OpenCodeEvent; + this.advance(); + yield event; + continue; + } + } + if (entry?.type === "runtime_exit") { + this.advance(); + if (entry.status === "success") return; + const mismatch = new OpenCodeReplayMismatchError({ + scenario: this.transcript.scenario, + cursor: this.cursor - 1, + expected: { status: "success" }, + actual: entry, + }); + this.fail(mismatch); + throw mismatch; + } + await this.changed(signal); + } + } + + assertComplete(): void { + while (this.transcript.entries[this.cursor]?.type === "runtime_exit") { + const exit = this.transcript.entries[this.cursor]; + if (exit?.type !== "runtime_exit" || exit.status !== "success") break; + this.cursor += 1; + } + this.throwFailure(); + if (this.cursor !== this.transcript.entries.length) { + throw new OpenCodeReplayIncompleteError({ + scenario: this.transcript.scenario, + cursor: this.cursor, + remaining: this.transcript.entries.length - this.cursor, + }); + } + } + + private advance(): void { + this.cursor += 1; + for (const waiter of this.waiters) waiter(); + this.waiters.clear(); + } + + private fail(cause: unknown): void { + this.failure = cause; + for (const waiter of this.waiters) waiter(); + this.waiters.clear(); + } + + private throwFailure(): void { + if (this.failure !== null) throw this.failure; + } + + private changed(signal?: AbortSignal): Promise { + if (signal?.aborted === true) return Promise.resolve(); + return new Promise((resolve) => { + const done = () => { + signal?.removeEventListener("abort", done); + this.waiters.delete(done); + resolve(); + }; + this.waiters.add(done); + signal?.addEventListener("abort", done, { once: true }); + }); + } +} + +function makeReplayClient(controller: OpenCodeReplayController): OpencodeClient { + const request = async (operation: string, input: unknown) => { + await controller.expectOutbound({ type: operation, input }); + return { data: await controller.response(operation) }; + }; + return { + event: { + subscribe: async (_input?: unknown, options?: { readonly signal?: AbortSignal }) => { + await controller.expectOutbound({ type: "event.subscribe" }); + return { stream: controller.events(options?.signal) }; + }, + }, + session: { + create: (input: unknown) => request("session.create", input), + get: (input: unknown) => request("session.get", input), + update: (input: unknown) => request("session.update", input), + messages: (input: unknown) => request("session.messages", input), + promptAsync: (input: unknown) => request("session.promptAsync", input), + abort: (input: unknown) => request("session.abort", input), + revert: (input: unknown) => request("session.revert", input), + unrevert: (input: unknown) => request("session.unrevert", input), + fork: (input: unknown) => request("session.fork", input), + }, + permission: { + reply: (input: unknown) => request("permission.reply", input), + }, + question: { + reply: (input: unknown) => request("question.reply", input), + }, + mcp: { + add: (input: unknown) => request("mcp.add", input), + }, + } as unknown as OpencodeClient; +} + +function makeOpenCodeReplayRuntimeLayer(transcript: OpenCodeSdkReplayTranscript) { + return Layer.effect( + OpenCodeRuntime, + Effect.gen(function* () { + const controller = new OpenCodeReplayController(transcript); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + controller.assertComplete(); + }), + ); + const client = makeReplayClient(controller); + return OpenCodeRuntime.of({ + startOpenCodeServerProcess: () => + Effect.fail( + new OpenCodeRuntimeError({ + operation: "startOpenCodeServerProcess", + detail: "OpenCode replay uses an external in-memory SDK boundary.", + }), + ), + connectToOpenCodeServer: () => + Effect.succeed({ + url: "replay://opencode", + exitCode: null, + external: true, + }), + runOpenCodeCommand: () => + Effect.fail( + new OpenCodeRuntimeError({ + operation: "runOpenCodeCommand", + detail: "OpenCode replay does not execute commands.", + }), + ), + createOpenCodeSdkClient: () => client, + loadOpenCodeInventory: () => + Effect.fail( + new OpenCodeRuntimeError({ + operation: "loadOpenCodeInventory", + detail: "OpenCode replay does not load inventory.", + }), + ), + } satisfies OpenCodeRuntimeShape); + }), + ); +} + +export function makeOpenCodeProviderAdapterRegistryReplayLayer( + transcript: OpenCodeSdkReplayTranscript, +) { + const serverConfigLayer = Layer.effect( + ServerConfig, + makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie), + ).pipe(Layer.provide(NodeServices.layer)); + return makeProviderAdapterRegistryDriverLayer({ + drivers: [OpenCodeAdapterV2Driver], + configMap: { + [OPENCODE_DEFAULT_INSTANCE_ID]: { + driver: OPENCODE_DRIVER_KIND, + config: { serverUrl: "replay://opencode" }, + }, + }, + }).pipe( + Layer.provide( + Layer.mergeAll( + makeOpenCodeReplayRuntimeLayer(transcript), + serverConfigLayer, + NodeServices.layer, + idAllocatorLayer, + ), + ), + ); +} + +function transcriptMetadata(transcript: ProviderReplayTranscript) { + return { + provider: transcript.provider, + protocol: transcript.protocol, + scenario: transcript.scenario, + }; +} + +export const OpenCodeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness< + OpenCodeSdkReplayTranscript, + OpenCodeOrchestratorReplayHarnessError +> = { + provider: OPENCODE_PROVIDER, + decodeTranscript: (transcript) => + decodeOpenCodeSdkReplayTranscript(transcript).pipe( + Effect.mapError( + (cause) => + new OpenCodeReplayTranscriptDecodeError({ + ...transcriptMetadata(transcript), + cause, + }), + ), + ), + makeProviderAdapterRegistryLayer: makeOpenCodeProviderAdapterRegistryReplayLayer, +}; diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts new file mode 100644 index 0000000000..f06b801a39 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts @@ -0,0 +1,2743 @@ +import type { + Event as OpenCodeEvent, + Message as OpenCodeMessage, + Part as OpenCodePart, + PermissionRequest, + PermissionRuleset, + QuestionRequest, + Session as OpenCodeSession, + Todo as OpenCodeTodo, + ToolPart, +} from "@opencode-ai/sdk/v2"; +import { HostProcessEnvironment } from "@t3tools/shared/hostProcess"; +import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; +import { + defaultInstanceIdForDriver, + type ModelSelection, + type OpenCodeSettings, + type OrchestrationV2AppThread, + type OrchestrationV2ConversationMessage, + type OrchestrationV2ExecutionNode, + type OrchestrationV2PlanStep, + type OrchestrationV2ProviderCapabilities, + type OrchestrationV2ProviderRef, + type OrchestrationV2ProviderSession, + type OrchestrationV2ProviderThread, + type OrchestrationV2ProviderTurn, + type OrchestrationV2RawProviderEvent, + type OrchestrationV2RuntimeRequest, + type OrchestrationV2Subagent, + type OrchestrationV2TurnItem, + OpenCodeSettings as OpenCodeSettingsSchema, + type PlanId, + ProviderDriverKind, + type ProviderInstanceId, + type ProviderRequestKind, + type RuntimeRequestId, + type ThreadId, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import { resolveAttachmentPath } from "../../attachmentStore.ts"; +import { ServerConfig, type ServerConfigShape } from "../../config.ts"; +import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; +import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts"; +import { + OpenCodeRuntime, + OpenCodeRuntimeError, + openCodeQuestionId, + openCodeRuntimeErrorDetail, + parseOpenCodeModelSlug, + runOpenCodeSdk, + toOpenCodeFileParts, + toOpenCodePermissionReply, + toOpenCodeQuestionAnswers, + type OpenCodeRuntimeShape, +} from "../../provider/opencodeRuntime.ts"; +import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts"; +import { + ProviderAdapterEnsureThreadError, + ProviderAdapterForkThreadError, + ProviderAdapterInterruptError, + ProviderAdapterOpenSessionError, + ProviderAdapterProtocolError, + ProviderAdapterReadThreadSnapshotError, + ProviderAdapterResumeThreadError, + ProviderAdapterRollbackThreadError, + ProviderAdapterRuntimeRequestResponseError, + ProviderAdapterSteerRunError, + ProviderAdapterTurnStartError, + ProviderAdapterV2, + type ProviderAdapterV2Event, + type ProviderAdapterV2OpenSessionInput, + type ProviderAdapterV2SessionRuntime, + type ProviderAdapterV2Shape, + type ProviderAdapterV2RuntimePolicy, + type ProviderAdapterV2TurnInput, +} from "../ProviderAdapter.ts"; +import { + ProviderAdapterDriverCreateError, + type ProviderAdapterDriver, + type ProviderAdapterDriverCreateInput, +} from "../ProviderAdapterDriver.ts"; +import { makeSubagentChildThread, subagentThreadTitle } from "../SubagentProjection.ts"; + +export const OPENCODE_PROVIDER = "opencode" as const; +export const OPENCODE_DRIVER_KIND = ProviderDriverKind.make(OPENCODE_PROVIDER); +export const OPENCODE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(OPENCODE_DRIVER_KIND); +const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettingsSchema)({}); + +/** + * OpenCode's session, message, part, and interaction-request identifiers are + * durable. It does not expose a first-class turn object: the initiating user + * message is the best native turn correlation point, and session idle is the + * authoritative terminal signal. + */ +export const OpenCodeProviderCapabilitiesV2 = { + sessions: { + supportsMultipleProviderThreadsPerSession: true, + supportsModelSwitchInSession: true, + supportsProviderSwitchingViaHandoff: true, + supportsRuntimeModeSwitchInSession: false, + pendingRequestsSurviveRestart: false, + }, + threads: { + canCreateEmptyThread: true, + canReadThreadSnapshot: true, + canRollbackThread: true, + canForkThread: true, + canForkFromTurn: true, + canForkFromSubagentThread: true, + exposesNativeThreadId: true, + }, + turns: { + exposesNativeTurnId: false, + emitsTurnStarted: true, + emitsTurnCompleted: true, + supportsInterrupt: true, + supportsActiveSteering: true, + supportsSteeringByInterruptRestart: true, + supportsQueuedMessages: true, + terminalStatusQuality: "strong", + }, + streaming: { + streamsAssistantText: true, + streamsReasoning: true, + streamsToolOutput: true, + streamsPlanText: false, + emitsMessageCompleted: true, + }, + tools: { + exposesToolItemIds: true, + emitsToolStarted: true, + emitsToolCompleted: true, + emitsToolOutput: true, + supportsMcpTools: true, + supportsDynamicToolCallbacks: false, + }, + approvals: { + supportsCommandApproval: true, + supportsFileReadApproval: true, + supportsFileChangeApproval: true, + supportsApplyPatchApproval: true, + approvalsHaveNativeRequestIds: true, + approvalCallbacksAreLiveOnly: true, + approvalsCanOriginateFromSubagents: true, + }, + planning: { + emitsPlanUpdated: true, + emitsTodoList: true, + emitsProposedPlan: false, + supportsStructuredQuestions: true, + planDeltasHaveItemIds: false, + }, + subagents: { + supportsSubagents: true, + exposesSubagentThreadIds: true, + emitsSubagentLifecycle: true, + canWaitForSubagents: true, + canCloseSubagents: false, + canForkSubagentThread: true, + }, + context: { + acceptsSystemContext: false, + acceptsDeveloperContext: false, + acceptsSyntheticUserContext: true, + canGenerateSummaries: true, + canConsumeHandoffSummaries: true, + supportsDeltaHandoff: true, + supportsFullThreadHandoff: true, + maxRecommendedHandoffChars: null, + }, + checkpointing: { + appCanCheckpointFilesystem: true, + supportsNestedCheckpointScopes: true, + providerCanRollbackConversation: true, + providerRollbackReturnsSnapshot: true, + providerCanReadConversationSnapshot: true, + }, + identity: { + nativeThreadIds: "strong", + nativeTurnIds: "weak", + nativeItemIds: "strong", + nativeRequestIds: "strong", + }, +} satisfies OrchestrationV2ProviderCapabilities; + +type TerminalTurnStatus = Extract< + OrchestrationV2ProviderTurn["status"], + "completed" | "interrupted" | "failed" | "cancelled" +>; + +interface ActiveOpenCodeTurn { + readonly isRoot: boolean; + readonly threadId: ThreadId; + readonly runId: ProviderAdapterV2TurnInput["runId"] | null; + readonly rootNodeId: ProviderAdapterV2TurnInput["rootNodeId"]; + readonly appThread: OrchestrationV2AppThread; + readonly modelSelection: ModelSelection; + readonly runtimePolicy: ProviderAdapterV2RuntimePolicy; + readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; + readonly providerTurnOrdinal: number; + readonly runAttemptId: OrchestrationV2ProviderTurn["runAttemptId"]; + readonly startedAt: DateTime.Utc; + readonly itemOrdinals: Map; + readonly parts: Map; + readonly partIdsByMessage: Map>; + readonly providerTurn: OrchestrationV2ProviderTurn; + nextItemOrdinal: number; + nativeUserMessageId: string | null; + interrupted: boolean; + finalized: boolean; + planId: PlanId | null; +} + +interface OpenCodeSubagentContext { + readonly nativeItemId: string; + readonly nodeId: OrchestrationV2Subagent["id"]; + readonly parentTurn: ActiveOpenCodeTurn; + readonly prompt: string; + readonly title: string | null; + readonly startedAt: DateTime.Utc; + childSessionId: string | null; + childThreadId: ThreadId | null; + childProviderThreadId: OrchestrationV2ProviderThread["id"] | null; + model: string | null; + result: string | null; +} + +interface OpenCodeThreadState { + readonly nativeSessionId: string; + providerThread: OrchestrationV2ProviderThread; + appThread: OrchestrationV2AppThread | null; + activeTurn: ActiveOpenCodeTurn | null; + readonly providerTurns: Map; + readonly messages: Map; + readonly runtimeRequests: Map; + readonly messageRoles: Map; + readonly userMessageIds: Array; + parentSubagent: OpenCodeSubagentContext | null; + nextChildTurnOrdinal: number; +} + +interface PendingOpenCodeRequest { + readonly requestId: RuntimeRequestId; + readonly nativeRequestId: string; + readonly turn: ActiveOpenCodeTurn; + readonly state: OpenCodeThreadState; + readonly nodeId: OrchestrationV2ExecutionNode["id"]; + readonly turnItemId: OrchestrationV2TurnItem["id"]; + readonly requestKind: OpenCodePermissionRequestKind | "user_input"; + readonly createdAt: DateTime.Utc; + readonly permission?: PermissionRequest; + readonly question?: QuestionRequest; +} + +export interface OpenCodeAdapterV2Options { + readonly instanceId: ProviderInstanceId; + readonly settings: OpenCodeSettings; + readonly environment: NodeJS.ProcessEnv; + readonly runtime: OpenCodeRuntimeShape; + readonly idAllocator: IdAllocatorV2Shape; + readonly serverConfig: ServerConfigShape; +} + +function protocolError(detail: string, payload?: unknown): ProviderAdapterProtocolError { + return new ProviderAdapterProtocolError({ + provider: OPENCODE_PROVIDER, + detail, + ...(payload === undefined ? {} : { payload }), + }); +} + +function nativeThreadId(providerThread: OrchestrationV2ProviderThread): string { + const nativeId = providerThread.nativeThreadRef?.nativeId; + if (nativeId === null || nativeId === undefined) { + throw protocolError(`Provider thread ${providerThread.id} has no OpenCode session id`); + } + return nativeId; +} + +function dateTimeFromEpoch(value: number | undefined, fallback: DateTime.Utc): DateTime.Utc { + if (value === undefined) return fallback; + return Option.getOrElse(DateTime.make(value), () => fallback); +} + +function nonEmptyString(value: unknown): string | undefined { + return typeof value === "string" && value.trim().length > 0 ? value : undefined; +} + +function recordValue(input: unknown, key: string): unknown { + return typeof input === "object" && input !== null && key in input + ? (input as Record)[key] + : undefined; +} + +function recordString(input: unknown, ...keys: ReadonlyArray): string | undefined { + for (const key of keys) { + const value = nonEmptyString(recordValue(input, key)); + if (value !== undefined) return value; + } + return undefined; +} + +function recordNumber(input: unknown, ...keys: ReadonlyArray): number | undefined { + for (const key of keys) { + const value = recordValue(input, key); + if (typeof value === "number" && Number.isFinite(value)) return value; + } + return undefined; +} + +function stableJson(value: unknown): string { + if (typeof value === "string") return value; + try { + return JSON.stringify(value, null, 2); + } catch { + return String(value); + } +} + +function sdkResponseForRawLog(value: unknown): unknown { + if (typeof value !== "object" || value === null) return value; + if ("data" in value) return { data: (value as { readonly data?: unknown }).data ?? null }; + if ("stream" in value) return { subscribed: true }; + return value; +} + +type OpenCodePermissionRequestKind = Extract< + ProviderRequestKind, + "command" | "file-read" | "file-change" +>; + +export function openCodePermissionRequestKind( + permission: string, + toolName?: string, +): OpenCodePermissionRequestKind { + const normalized = permission.toLowerCase(); + const normalizedTool = toolName?.toLowerCase() ?? ""; + if ( + normalized === "edit" || + normalized.includes("write") || + normalized.includes("patch") || + normalizedTool.includes("edit") || + normalizedTool.includes("write") || + normalizedTool.includes("patch") + ) { + return "file-change"; + } + if ( + normalized === "read" || + normalized === "glob" || + normalized === "grep" || + normalized === "lsp" || + normalized === "external_directory" || + normalizedTool === "read" || + normalizedTool.includes("glob") || + normalizedTool.includes("grep") || + normalizedTool.includes("search") + ) { + return "file-read"; + } + return "command"; +} + +export function openCodeToolProjectionKind( + toolName: string, +): "command_execution" | "file_change" | "file_search" | "web_search" | "dynamic_tool" { + const normalized = toolName.toLowerCase(); + if (normalized.includes("bash") || normalized.includes("shell")) { + return "command_execution"; + } + if (normalized.includes("edit") || normalized.includes("write") || normalized.includes("patch")) { + return "file_change"; + } + if (normalized.includes("web") || normalized === "codesearch" || normalized === "code_search") { + return "web_search"; + } + if ( + normalized === "read" || + normalized.includes("glob") || + normalized.includes("grep") || + normalized.includes("search") || + normalized.includes("lsp") + ) { + return "file_search"; + } + return "dynamic_tool"; +} + +const OPENCODE_ALWAYS_ALLOWED_PERMISSIONS = [ + "question", + "read", + "glob", + "grep", + "lsp", + "todowrite", + "task", + "skill", +] as const; + +const OPENCODE_RESTRICTED_PERMISSIONS = [ + "bash", + "edit", + "webfetch", + "websearch", + "codesearch", + "external_directory", + "doom_loop", +] as const; + +/** + * OpenCode does not provide an OS sandbox, so permission rules are also the + * enforcement boundary for non-interactive policies. Read/planning tools are + * safe by default; edits are auto-approved only for workspace-write modes, + * while shell/network/external access remains gated unless policy explicitly + * allows it. + */ +export function openCodePermissionRules( + runtimePolicy: ProviderAdapterV2RuntimePolicy, +): PermissionRuleset { + const sandboxPolicy = recordValue(runtimePolicy, "sandboxPolicy"); + const sandboxType = recordString(sandboxPolicy, "type"); + const rawApprovalPolicy = runtimePolicy.approvalPolicy; + const approvalPolicy = nonEmptyString(rawApprovalPolicy); + const requiresApproval = + approvalPolicy === undefined + ? (typeof rawApprovalPolicy === "object" && rawApprovalPolicy !== null) || + runtimePolicy.runtimeMode !== "full-access" + : approvalPolicy !== "never"; + const externallySandboxed = sandboxType === "externalSandbox"; + const dangerFullAccess = sandboxType === "dangerFullAccess"; + const implicitFullAccess = + sandboxType === undefined && runtimePolicy.runtimeMode === "full-access"; + + if (!requiresApproval && (externallySandboxed || dangerFullAccess || implicitFullAccess)) { + return [{ permission: "*", pattern: "*", action: "allow" }]; + } + + // Task sessions initially inherit only parent deny rules. Seed explicit + // denies before the effective ask/allow overrides so a child is safe during + // the short interval before emitSubagent installs its complete policy. + const rules: PermissionRuleset = [ + { permission: "*", pattern: "*", action: "deny" }, + ...OPENCODE_RESTRICTED_PERMISSIONS.map((permission) => ({ + permission, + pattern: "*", + action: "deny" as const, + })), + ]; + + if (requiresApproval) { + rules.push({ permission: "*", pattern: "*", action: "ask" }); + for (const permission of OPENCODE_RESTRICTED_PERMISSIONS) { + rules.push({ permission, pattern: "*", action: "ask" }); + } + } + + rules.push( + ...OPENCODE_ALWAYS_ALLOWED_PERMISSIONS.map((permission) => ({ + permission, + pattern: "*", + action: "allow" as const, + })), + ); + + if (runtimePolicy.runtimeMode === "auto-accept-edits" || sandboxType === "workspaceWrite") { + rules.push({ permission: "edit", pattern: "*", action: "allow" }); + } + + if (!requiresApproval && recordValue(sandboxPolicy, "networkAccess") === true) { + for (const permission of ["webfetch", "websearch", "codesearch"] as const) { + rules.push({ permission, pattern: "*", action: "allow" }); + } + } + + if (!requiresApproval && sandboxType === "readOnly") { + const access = recordValue(sandboxPolicy, "access"); + if (recordString(access, "type") === "fullAccess") { + rules.push({ permission: "external_directory", pattern: "*", action: "allow" }); + } + } + + if (!requiresApproval && sandboxType === "workspaceWrite") { + const writableRoots = recordValue(sandboxPolicy, "writableRoots"); + if (Array.isArray(writableRoots)) { + for (const root of writableRoots) { + if (typeof root === "string" && root.trim().length > 0) { + rules.push({ + permission: "external_directory", + pattern: `${root.replace(/\/$/, "")}/*`, + action: "allow", + }); + } + } + } + } + + return rules; +} + +function permissionRuleEquals( + left: PermissionRuleset[number], + right: PermissionRuleset[number], +): boolean { + return ( + left.permission === right.permission && + left.pattern === right.pattern && + left.action === right.action + ); +} + +/** + * OpenCode task sessions inherit only the parent's deny/external-directory + * rules and then add agent-specific restrictions such as disabling nested + * tasks. Install the complete parent policy while retaining only rules that + * were added specifically for the selected child agent. + */ +export function openCodeChildPermissionRules( + runtimePolicy: ProviderAdapterV2RuntimePolicy, + nativeChildRules: PermissionRuleset, +): PermissionRuleset { + const parentRules = openCodePermissionRules(runtimePolicy); + const inheritedRules = parentRules.filter( + (rule) => rule.permission === "external_directory" || rule.action === "deny", + ); + const childSpecificRules = nativeChildRules.filter( + (childRule) => + !inheritedRules.some((inheritedRule) => permissionRuleEquals(childRule, inheritedRule)), + ); + return [...parentRules, ...childSpecificRules]; +} + +/** + * OpenCode's fork/revert boundary is exclusive. To retain the selected app + * turn, address the next native user message; omitting a boundary retains the + * current head when the selected turn is already last. + */ +export function openCodeBoundaryAfterProviderTurn( + providerTurns: ReadonlyArray, + selectedProviderTurnId: OrchestrationV2ProviderTurn["id"], +): string | undefined { + const selected = providerTurns.find((turn) => turn.id === selectedProviderTurnId); + if (selected === undefined) return undefined; + return providerTurns + .filter((turn) => turn.ordinal > selected.ordinal) + .toSorted((left, right) => left.ordinal - right.ordinal) + .map((turn) => turn.nativeTurnRef?.nativeId) + .find((nativeId): nativeId is string => nativeId !== null && nativeId !== undefined); +} + +function toolStatus(part: ToolPart): { + readonly node: OrchestrationV2ExecutionNode["status"]; + readonly item: OrchestrationV2TurnItem["status"]; +} { + switch (part.state.status) { + case "pending": + return { node: "pending", item: "pending" }; + case "running": + return { node: "running", item: "running" }; + case "completed": + return { node: "completed", item: "completed" }; + case "error": + return { node: "failed", item: "failed" }; + } +} + +function toolInput(part: ToolPart): Record { + return part.state.input; +} + +function toolOutput(part: ToolPart): string | undefined { + if (part.state.status === "completed") return part.state.output; + if (part.state.status === "error") return part.state.error; + return undefined; +} + +function toolStartedAt(part: ToolPart, now: DateTime.Utc): DateTime.Utc { + return dateTimeFromEpoch( + part.state.status === "pending" ? undefined : part.state.time.start, + now, + ); +} + +function toolCompletedAt(part: ToolPart, now: DateTime.Utc): DateTime.Utc | null { + return part.state.status === "completed" || part.state.status === "error" + ? dateTimeFromEpoch(part.state.time.end, now) + : null; +} + +function toolTitle(part: ToolPart): string | null { + return part.state.status === "running" || part.state.status === "completed" + ? (part.state.title ?? null) + : null; +} + +function toolModel(part: ToolPart): string | null { + const metadata = + part.state.status === "running" || + part.state.status === "completed" || + part.state.status === "error" + ? part.state.metadata + : undefined; + const model = recordValue(metadata, "model"); + const providerId = recordString(model, "providerID", "providerId"); + const modelId = recordString(model, "modelID", "modelId", "id"); + return providerId !== undefined && modelId !== undefined ? `${providerId}/${modelId}` : null; +} + +function taskSessionId(part: ToolPart): string | null { + const metadata = + part.state.status === "running" || + part.state.status === "completed" || + part.state.status === "error" + ? part.state.metadata + : undefined; + return recordString(metadata, "sessionId", "sessionID") ?? null; +} + +function makeProviderThread(input: { + readonly idAllocator: IdAllocatorV2Shape; + readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"]; + readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"]; + readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"]; + readonly nativeSession: OpenCodeSession; + readonly forkedFrom?: OrchestrationV2ProviderThread["forkedFrom"]; + readonly now: DateTime.Utc; +}): OrchestrationV2ProviderThread { + const createdAt = dateTimeFromEpoch(input.nativeSession.time.created, input.now); + return { + id: input.idAllocator.derive.providerThread({ + provider: OPENCODE_PROVIDER, + nativeThreadId: input.nativeSession.id, + }), + provider: OPENCODE_PROVIDER, + providerSessionId: input.providerSessionId, + appThreadId: input.appThreadId, + ownerNodeId: input.ownerNodeId ?? null, + nativeThreadRef: { + provider: OPENCODE_PROVIDER, + nativeId: input.nativeSession.id, + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: input.forkedFrom ?? null, + createdAt, + updatedAt: dateTimeFromEpoch(input.nativeSession.time.updated, input.now), + }; +} + +function providerRef(nativeId: string, strength: "strong" | "weak" = "strong") { + return { + provider: OPENCODE_PROVIDER, + nativeId, + strength, + } satisfies OrchestrationV2ProviderRef; +} + +function openCodeErrorMessage(event: Extract): string { + const error = event.properties.error; + if (error === undefined) return "OpenCode session failed without an error payload."; + return recordString(error.data, "message") ?? error.name; +} + +function terminalStatusForError( + event: Extract, + turn: ActiveOpenCodeTurn, +): TerminalTurnStatus { + return turn.interrupted || isMessageAbortedError(event) ? "interrupted" : "failed"; +} + +function isMessageAbortedError(event: Extract): boolean { + return event.properties.error?.name === "MessageAbortedError"; +} + +function unwrapData(operation: string, result: { readonly data?: A }): NonNullable { + if (result.data === undefined) { + throw new OpenCodeRuntimeError({ + operation, + detail: `OpenCode ${operation} returned no response payload.`, + }); + } + return result.data as NonNullable; +} + +export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): ProviderAdapterV2Shape { + const { idAllocator, runtime, serverConfig } = options; + + return ProviderAdapterV2.of({ + instanceId: options.instanceId, + provider: OPENCODE_PROVIDER, + getCapabilities: () => Effect.succeed(OpenCodeProviderCapabilitiesV2), + openSession: Effect.fn("OpenCodeAdapterV2.openSession")( + function* (input: ProviderAdapterV2OpenSessionInput) { + const scope = yield* Effect.scope; + const cwd = input.runtimePolicy.cwd ?? serverConfig.cwd; + const connection = yield* runtime.connectToOpenCodeServer({ + binaryPath: options.settings.binaryPath, + serverUrl: options.settings.serverUrl, + environment: options.environment, + }); + const client = runtime.createOpenCodeSdkClient({ + baseUrl: connection.url, + directory: cwd, + ...(connection.external && options.settings.serverPassword + ? { serverPassword: options.settings.serverPassword } + : {}), + }); + + const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId); + if (mcpSession !== undefined && !connection.external) { + yield* runOpenCodeSdk("mcp.add", () => + client.mcp.add({ + name: "t3-code", + config: { + type: "remote", + url: mcpSession.endpoint, + headers: { Authorization: mcpSession.authorizationHeader }, + oauth: false, + }, + }), + ); + } + + const now = yield* DateTime.now; + let sessionEntity: OrchestrationV2ProviderSession = { + id: input.providerSessionId, + provider: OPENCODE_PROVIDER, + status: "ready", + cwd, + model: input.modelSelection.model, + capabilities: OpenCodeProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }; + const events = yield* Queue.unbounded(); + const rawEvents = yield* Queue.unbounded(); + const rawSequence = yield* Ref.make(0); + const threads = new Map(); + const pendingRequests = new Map(); + const pendingRequestsByNativeId = new Map(); + const subagentsByNativeItemId = new Map(); + const subagentsByChildSessionId = new Map(); + const abortController = new AbortController(); + + const emitProviderEvent = (event: ProviderAdapterV2Event) => + Queue.offer(events, event).pipe(Effect.asVoid); + + const emitRawEvent = (raw: { + readonly direction: "incoming" | "outgoing"; + readonly messageKind: OrchestrationV2RawProviderEvent["messageKind"]; + readonly method: string; + readonly payload: unknown; + }): Effect.Effect => + Effect.gen(function* () { + const sequence = yield* Ref.updateAndGet(rawSequence, (value) => value + 1); + const observedAt = yield* DateTime.now; + const rawEventId = yield* idAllocator.allocate.rawEvent({ + providerSessionId: input.providerSessionId, + method: raw.method, + }); + yield* Queue.offer(rawEvents, { + id: rawEventId, + provider: OPENCODE_PROVIDER, + providerSessionId: input.providerSessionId, + sequence, + direction: raw.direction, + messageKind: raw.messageKind, + method: raw.method, + jsonRpcId: null, + payload: raw.payload, + observedAt, + }); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.opencode-raw-event-failed", { + providerSessionId: input.providerSessionId, + cause, + }), + ), + ); + + const sdkCall = ( + method: string, + payload: unknown, + call: () => Promise, + ): Effect.Effect => + emitRawEvent({ + direction: "outgoing", + messageKind: "request", + method, + payload, + }).pipe( + Effect.andThen(runOpenCodeSdk(method, call)), + Effect.tap((response) => + emitRawEvent({ + direction: "incoming", + messageKind: "response", + method, + payload: sdkResponseForRawLog(response), + }), + ), + ); + + const updateProviderSession = ( + status: OrchestrationV2ProviderSession["status"], + lastError: string | null = sessionEntity.lastError, + ) => + Effect.gen(function* () { + const updatedAt = yield* DateTime.now; + sessionEntity = { ...sessionEntity, status, lastError, updatedAt }; + yield* emitProviderEvent({ + type: "provider_session.updated", + provider: OPENCODE_PROVIDER, + providerSession: sessionEntity, + }); + }); + + const updateProviderThread = ( + state: OpenCodeThreadState, + patch: Partial, + ) => + Effect.gen(function* () { + const updatedAt = yield* DateTime.now; + state.providerThread = { ...state.providerThread, ...patch, updatedAt }; + yield* emitProviderEvent({ + type: "provider_thread.updated", + provider: OPENCODE_PROVIDER, + providerThread: state.providerThread, + }); + }); + + const itemOrdinal = (turn: ActiveOpenCodeTurn, nativeItemId: string): number => { + const existing = turn.itemOrdinals.get(nativeItemId); + if (existing !== undefined) return existing; + const ordinal = turn.nextItemOrdinal++; + turn.itemOrdinals.set(nativeItemId, ordinal); + return ordinal; + }; + + const emitProviderTurn = ( + state: OpenCodeThreadState, + turn: ActiveOpenCodeTurn, + status: OrchestrationV2ProviderTurn["status"], + completedAt: DateTime.Utc | null, + ) => { + const providerTurn: OrchestrationV2ProviderTurn = { + ...turn.providerTurn, + nativeTurnRef: + turn.nativeUserMessageId === null + ? turn.providerTurn.nativeTurnRef + : providerRef(turn.nativeUserMessageId, "weak"), + status, + completedAt, + }; + Object.assign(turn.providerTurn, providerTurn); + state.providerTurns.set(String(providerTurn.id), providerTurn); + return emitProviderEvent({ + type: "provider_turn.updated", + provider: OPENCODE_PROVIDER, + threadId: turn.threadId, + providerTurn, + }); + }; + + const emitTextPart = Effect.fnUntraced(function* ( + state: OpenCodeThreadState, + turn: ActiveOpenCodeTurn, + part: Extract, + forceCompleted = false, + ) { + if (part.type === "text" && (part.ignored === true || part.synthetic === true)) return; + if (part.text.length === 0) return; + const emittedAt = yield* DateTime.now; + const isCompleted = forceCompleted || part.time?.end !== undefined; + const startedAt = dateTimeFromEpoch(part.time?.start, emittedAt); + const completedAt = isCompleted ? dateTimeFromEpoch(part.time?.end, emittedAt) : null; + const nativeItemRef = providerRef(part.id); + const nodeId = idAllocator.derive.nodeFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: part.id, + }); + const turnItemId = idAllocator.derive.turnItemFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: part.id, + }); + const ordinal = itemOrdinal(turn, part.id); + yield* emitProviderEvent({ + type: "node.updated", + provider: OPENCODE_PROVIDER, + node: { + id: nodeId, + threadId: turn.threadId, + runId: turn.runId, + parentNodeId: turn.rootNodeId, + rootNodeId: turn.rootNodeId, + kind: part.type === "text" ? "assistant_message" : "reasoning", + status: isCompleted ? "completed" : "running", + countsForRun: false, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt, + completedAt, + }, + }); + if (part.type === "text") { + const messageId = idAllocator.derive.messageFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: part.id, + }); + const message: OrchestrationV2ConversationMessage = { + id: messageId, + threadId: turn.threadId, + runId: turn.runId, + nodeId, + role: "assistant", + text: part.text, + attachments: [], + streaming: !isCompleted, + createdAt: startedAt, + updatedAt: emittedAt, + }; + state.messages.set(String(message.id), message); + yield* emitProviderEvent({ + type: "message.updated", + provider: OPENCODE_PROVIDER, + message, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider: OPENCODE_PROVIDER, + turnItem: { + id: turnItemId, + threadId: turn.threadId, + runId: turn.runId, + nodeId, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef, + parentItemId: null, + ordinal, + status: isCompleted ? "completed" : "running", + title: null, + startedAt, + completedAt, + updatedAt: emittedAt, + type: "assistant_message", + messageId, + text: part.text, + streaming: !isCompleted, + }, + }); + return; + } + yield* emitProviderEvent({ + type: "turn_item.updated", + provider: OPENCODE_PROVIDER, + turnItem: { + id: turnItemId, + threadId: turn.threadId, + runId: turn.runId, + nodeId, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef, + parentItemId: null, + ordinal, + status: isCompleted ? "completed" : "running", + title: null, + startedAt, + completedAt, + updatedAt: emittedAt, + type: "reasoning", + text: part.text, + streaming: !isCompleted, + }, + }); + }); + + const emitSubagent = Effect.fnUntraced(function* ( + state: OpenCodeThreadState, + turn: ActiveOpenCodeTurn, + part: ToolPart, + ) { + const now = yield* DateTime.now; + const nativeItemRef = providerRef(part.id); + const nodeId = idAllocator.derive.nodeFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: part.id, + }); + const turnItemId = idAllocator.derive.turnItemFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: part.id, + }); + const input = toolInput(part); + const prompt = recordString(input, "prompt") ?? ""; + const title = toolTitle(part) ?? recordString(input, "description") ?? null; + let context = subagentsByNativeItemId.get(part.id); + if (context === undefined) { + context = { + nativeItemId: part.id, + nodeId, + parentTurn: turn, + prompt, + title, + startedAt: toolStartedAt(part, now), + childSessionId: null, + childThreadId: null, + childProviderThreadId: null, + model: null, + result: null, + }; + subagentsByNativeItemId.set(part.id, context); + } + context.model = toolModel(part) ?? context.model; + const childSessionId = taskSessionId(part); + if (childSessionId !== null && context.childSessionId === null) { + context.childSessionId = childSessionId; + context.childThreadId = idAllocator.derive.threadFromProviderThread({ + provider: OPENCODE_PROVIDER, + nativeThreadId: childSessionId, + }); + context.childProviderThreadId = idAllocator.derive.providerThread({ + provider: OPENCODE_PROVIDER, + nativeThreadId: childSessionId, + }); + subagentsByChildSessionId.set(childSessionId, context); + const childModelSelection: ModelSelection = { + instanceId: options.instanceId, + model: context.model ?? turn.modelSelection.model, + }; + const childThread = makeSubagentChildThread({ + parentThread: turn.appThread, + childThreadId: context.childThreadId, + parentNodeId: nodeId, + activeProviderThreadId: context.childProviderThreadId, + providerInstanceId: options.instanceId, + modelSelection: childModelSelection, + title: subagentThreadTitle({ + parentTitle: turn.appThread.title, + title, + prompt, + ordinal: itemOrdinal(turn, part.id), + }), + now, + }); + const childProviderThread: OrchestrationV2ProviderThread = { + id: context.childProviderThreadId, + provider: OPENCODE_PROVIDER, + providerSessionId: inputProviderSessionId, + appThreadId: context.childThreadId, + ownerNodeId: nodeId, + nativeThreadRef: providerRef(childSessionId), + nativeConversationHeadRef: null, + status: "active", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }; + const childSessionResponse = yield* sdkCall( + "session.get", + { sessionID: childSessionId }, + () => client.session.get({ sessionID: childSessionId }), + ); + const nativeChildSession = unwrapData("session.get", childSessionResponse); + const childPermission = openCodeChildPermissionRules( + turn.runtimePolicy, + nativeChildSession.permission ?? [], + ); + yield* sdkCall( + "session.update", + { sessionID: childSessionId, permission: childPermission }, + () => + client.session.update({ + sessionID: childSessionId, + permission: childPermission, + }), + ); + threads.set(childSessionId, { + nativeSessionId: childSessionId, + providerThread: childProviderThread, + appThread: childThread, + activeTurn: null, + providerTurns: new Map(), + messages: new Map(), + runtimeRequests: new Map(), + messageRoles: new Map(), + userMessageIds: [], + parentSubagent: context, + nextChildTurnOrdinal: 1, + }); + yield* emitProviderEvent({ + type: "app_thread.created", + provider: OPENCODE_PROVIDER, + appThread: childThread, + }); + yield* emitProviderEvent({ + type: "provider_thread.updated", + provider: OPENCODE_PROVIDER, + providerThread: childProviderThread, + }); + } + const output = toolOutput(part); + if (part.state.status === "completed" && output !== undefined) context.result = output; + const status = toolStatus(part); + const completedAt = toolCompletedAt(part, now); + const subagentStatus: OrchestrationV2Subagent["status"] = + status.item === "failed" + ? "failed" + : status.item === "completed" + ? "completed" + : status.item === "pending" + ? "pending" + : "running"; + const subagent: OrchestrationV2Subagent = { + id: nodeId, + threadId: turn.threadId, + runId: turn.runId, + parentNodeId: turn.rootNodeId, + origin: "provider_native", + createdBy: "agent", + provider: OPENCODE_PROVIDER, + providerThreadId: context.childProviderThreadId, + childThreadId: context.childThreadId, + nativeTaskRef: nativeItemRef, + prompt, + title, + model: context.model, + status: subagentStatus, + result: context.result, + startedAt: context.startedAt, + completedAt, + updatedAt: now, + }; + yield* emitProviderEvent({ + type: "node.updated", + provider: OPENCODE_PROVIDER, + node: { + id: nodeId, + threadId: turn.threadId, + runId: turn.runId, + parentNodeId: turn.rootNodeId, + rootNodeId: turn.rootNodeId, + kind: "subagent", + status: status.node, + countsForRun: false, + providerThreadId: context.childProviderThreadId ?? state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: context.startedAt, + completedAt, + }, + }); + yield* emitProviderEvent({ + type: "subagent.updated", + provider: OPENCODE_PROVIDER, + subagent, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider: OPENCODE_PROVIDER, + turnItem: { + id: turnItemId, + threadId: turn.threadId, + runId: turn.runId, + nodeId, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef, + parentItemId: null, + ordinal: itemOrdinal(turn, part.id), + status: status.item, + title, + startedAt: context.startedAt, + completedAt, + updatedAt: now, + type: "subagent", + subagentId: nodeId, + origin: "provider_native", + provider: OPENCODE_PROVIDER, + childThreadId: context.childThreadId, + prompt, + result: context.result, + }, + }); + }); + + const emitToolPart = Effect.fnUntraced(function* ( + state: OpenCodeThreadState, + turn: ActiveOpenCodeTurn, + part: ToolPart, + ) { + const normalizedTool = part.tool.toLowerCase(); + if (normalizedTool === "task") { + yield* emitSubagent(state, turn, part); + return; + } + // question.asked carries the respondable semantic item. Projecting + // the implementation tool as well would duplicate it in the UI. + if (normalizedTool === "question") return; + const now = yield* DateTime.now; + const status = toolStatus(part); + const startedAt = toolStartedAt(part, now); + const completedAt = toolCompletedAt(part, now); + const nativeItemRef = providerRef(part.id); + const nodeId = idAllocator.derive.nodeFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: part.id, + }); + const turnItemId = idAllocator.derive.turnItemFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: part.id, + }); + const base = { + id: turnItemId, + threadId: turn.threadId, + runId: turn.runId, + nodeId, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef, + parentItemId: null, + ordinal: itemOrdinal(turn, part.id), + status: status.item, + title: toolTitle(part), + startedAt, + completedAt, + updatedAt: now, + } satisfies Pick< + OrchestrationV2TurnItem, + | "id" + | "threadId" + | "runId" + | "nodeId" + | "providerThreadId" + | "providerTurnId" + | "nativeItemRef" + | "parentItemId" + | "ordinal" + | "status" + | "title" + | "startedAt" + | "completedAt" + | "updatedAt" + >; + const input = toolInput(part); + const output = toolOutput(part); + const projectionKind = openCodeToolProjectionKind(part.tool); + let turnItem: OrchestrationV2TurnItem; + if (projectionKind === "command_execution") { + turnItem = { + ...base, + type: "command_execution", + input: recordString(input, "command", "cmd") ?? stableJson(input), + ...(output === undefined ? {} : { output }), + ...(recordNumber( + part.state.status === "completed" ? part.state.metadata : undefined, + "exit", + "exitCode", + ) === undefined + ? {} + : { + exitCode: recordNumber( + part.state.status === "completed" ? part.state.metadata : undefined, + "exit", + "exitCode", + )!, + }), + }; + } else if (projectionKind === "file_change") { + turnItem = { + ...base, + type: "file_change", + fileName: recordString(input, "filePath", "path", "file") ?? part.tool, + ...(recordString(input, "oldString", "oldText") === undefined + ? {} + : { oldStr: recordString(input, "oldString", "oldText")! }), + ...(recordString(input, "newString", "content", "newText") === undefined + ? {} + : { newStr: recordString(input, "newString", "content", "newText")! }), + ...(recordString( + part.state.status === "completed" ? part.state.metadata : undefined, + "diff", + "patch", + ) === undefined + ? {} + : { + diffStr: recordString( + part.state.status === "completed" ? part.state.metadata : undefined, + "diff", + "patch", + )!, + }), + }; + } else if (projectionKind === "file_search") { + turnItem = { + ...base, + type: "file_search", + ...(recordString(input, "pattern", "query", "path", "filePath") === undefined + ? {} + : { pattern: recordString(input, "pattern", "query", "path", "filePath")! }), + }; + } else if (projectionKind === "web_search") { + const pattern = recordString(input, "query", "url", "pattern"); + turnItem = { + ...base, + type: "web_search", + ...(pattern === undefined ? {} : { patterns: [pattern] }), + }; + } else { + turnItem = { + ...base, + type: "dynamic_tool", + toolName: part.tool, + input, + ...(output === undefined ? {} : { output }), + }; + } + yield* emitProviderEvent({ + type: "node.updated", + provider: OPENCODE_PROVIDER, + node: { + id: nodeId, + threadId: turn.threadId, + runId: turn.runId, + parentNodeId: turn.rootNodeId, + rootNodeId: turn.rootNodeId, + kind: "tool_call", + status: status.node, + countsForRun: false, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt, + completedAt, + }, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider: OPENCODE_PROVIDER, + turnItem, + }); + }); + + const emitTodo = Effect.fnUntraced(function* ( + state: OpenCodeThreadState, + turn: ActiveOpenCodeTurn, + todos: ReadonlyArray, + ) { + const now = yield* DateTime.now; + if (turn.planId === null) { + turn.planId = yield* idAllocator.allocate.plan({ + threadId: turn.threadId, + ...(turn.runId === null ? {} : { runId: turn.runId }), + provider: OPENCODE_PROVIDER, + }); + } + const planId = turn.planId; + const nativeItemId = `${state.nativeSessionId}:todo:${turn.providerTurnId}`; + const nodeId = idAllocator.derive.nodeFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId, + }); + const turnItemId = idAllocator.derive.turnItemFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId, + }); + const steps: Array = todos.map((todo, index) => ({ + id: `${nativeItemId}:${index + 1}`, + text: todo.content.trim() || `Todo ${index + 1}`, + status: + todo.status === "completed" + ? "completed" + : todo.status === "in_progress" + ? "running" + : "pending", + })); + const completed = steps.length > 0 && steps.every((step) => step.status === "completed"); + yield* emitProviderEvent({ + type: "node.updated", + provider: OPENCODE_PROVIDER, + node: { + id: nodeId, + threadId: turn.threadId, + runId: turn.runId, + parentNodeId: turn.rootNodeId, + rootNodeId: turn.rootNodeId, + kind: "todo_list", + status: completed ? "completed" : "running", + countsForRun: false, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef: providerRef(nativeItemId, "weak"), + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: turn.startedAt, + completedAt: completed ? now : null, + }, + }); + yield* emitProviderEvent({ + type: "plan.updated", + provider: OPENCODE_PROVIDER, + plan: { + id: planId, + threadId: turn.threadId, + runId: turn.runId, + nodeId, + status: completed ? "completed" : "active", + kind: "todo_list", + steps, + }, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider: OPENCODE_PROVIDER, + turnItem: { + id: turnItemId, + threadId: turn.threadId, + runId: turn.runId, + nodeId, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef: providerRef(nativeItemId, "weak"), + parentItemId: null, + ordinal: itemOrdinal(turn, nativeItemId), + status: completed ? "completed" : "running", + title: "Todo list", + startedAt: turn.startedAt, + completedAt: completed ? now : null, + updatedAt: now, + type: "todo_list", + planId, + steps, + }, + }); + }); + + const requestQuestions = (request: QuestionRequest) => + request.questions.map((question, index) => ({ + id: openCodeQuestionId(index, question), + header: question.header.trim() || `Question ${index + 1}`, + question: question.question.trim() || question.header.trim() || `Question ${index + 1}`, + options: question.options.map((option) => ({ + label: option.label.trim() || "Option", + description: option.description.trim() || option.label.trim() || "Option", + })), + })); + + const runtimeRequestTurnItem = ( + pending: PendingOpenCodeRequest, + status: OrchestrationV2TurnItem["status"], + completedAt: DateTime.Utc | null, + updatedAt: DateTime.Utc, + ): OrchestrationV2TurnItem => { + const base = { + id: pending.turnItemId, + threadId: pending.turn.threadId, + runId: pending.turn.runId, + nodeId: pending.nodeId, + providerThreadId: pending.state.providerThread.id, + providerTurnId: pending.turn.providerTurnId, + nativeItemRef: providerRef(pending.nativeRequestId), + parentItemId: null, + ordinal: itemOrdinal(pending.turn, pending.nativeRequestId), + status, + startedAt: pending.createdAt, + completedAt, + updatedAt, + }; + if (pending.question !== undefined) { + return { + ...base, + title: "User input", + type: "user_input_request", + requestId: pending.requestId, + questions: requestQuestions(pending.question), + }; + } + const permission = pending.permission; + if (permission === undefined) { + throw protocolError(`OpenCode request ${pending.requestId} has no native payload`); + } + return { + ...base, + title: permission.permission, + type: "approval_request", + requestId: pending.requestId, + requestKind: pending.requestKind === "user_input" ? "command" : pending.requestKind, + prompt: + permission.patterns.length === 0 + ? permission.permission + : permission.patterns.join("\n"), + }; + }; + + const emitRuntimeRequest = Effect.fnUntraced(function* ( + state: OpenCodeThreadState, + turn: ActiveOpenCodeTurn, + nativeRequestId: string, + request: + | { readonly type: "permission"; readonly value: PermissionRequest } + | { readonly type: "question"; readonly value: QuestionRequest }, + ) { + if (pendingRequestsByNativeId.has(nativeRequestId)) return; + const now = yield* DateTime.now; + const requestId = yield* idAllocator.allocate.runtimeRequest({ + provider: OPENCODE_PROVIDER, + providerTurnId: turn.providerTurnId, + nativeRequestId, + }); + const nodeId = idAllocator.derive.approvalNode({ requestId }); + const turnItemId = idAllocator.derive.approvalTurnItem({ requestId }); + const permissionToolName = + request.type === "permission" && request.value.tool !== undefined + ? Array.from(turn.parts.values()).find( + (part): part is ToolPart => + part.type === "tool" && part.callID === request.value.tool?.callID, + )?.tool + : undefined; + const permissionRequestKind = + request.type === "permission" + ? openCodePermissionRequestKind(request.value.permission, permissionToolName) + : undefined; + const requestKind: OrchestrationV2RuntimeRequest["kind"] = + permissionRequestKind ?? "user_input"; + const pending: PendingOpenCodeRequest = { + requestId, + nativeRequestId, + turn, + state, + nodeId, + turnItemId, + requestKind, + createdAt: now, + ...(request.type === "permission" + ? { permission: request.value } + : { question: request.value }), + }; + pendingRequests.set(String(requestId), pending); + pendingRequestsByNativeId.set(nativeRequestId, pending); + const runtimeRequest: OrchestrationV2RuntimeRequest = { + id: requestId, + nodeId, + providerTurnId: turn.providerTurnId, + nativeRequestRef: providerRef(nativeRequestId), + kind: requestKind, + status: "pending", + responseCapability: { + type: "live", + providerSessionId: inputProviderSessionId, + }, + createdAt: now, + resolvedAt: null, + }; + state.runtimeRequests.set(String(requestId), runtimeRequest); + yield* emitProviderEvent({ + type: "node.updated", + provider: OPENCODE_PROVIDER, + node: { + id: nodeId, + threadId: turn.threadId, + runId: turn.runId, + parentNodeId: turn.rootNodeId, + rootNodeId: turn.rootNodeId, + kind: request.type === "question" ? "user_input_request" : "approval_request", + status: "waiting", + countsForRun: false, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef: providerRef(nativeRequestId), + runtimeRequestId: requestId, + checkpointScopeId: null, + startedAt: now, + completedAt: null, + }, + }); + yield* emitProviderEvent({ + type: "runtime_request.updated", + provider: OPENCODE_PROVIDER, + threadId: turn.threadId, + runtimeRequest, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider: OPENCODE_PROVIDER, + turnItem: runtimeRequestTurnItem(pending, "waiting", null, now), + }); + yield* updateProviderSession("waiting", null); + }); + + const resolveRuntimeRequest = Effect.fnUntraced(function* ( + nativeRequestId: string, + status: "resolved" | "cancelled", + ) { + const pending = pendingRequestsByNativeId.get(nativeRequestId); + if (pending === undefined) return; + const now = yield* DateTime.now; + const current = pending.state.runtimeRequests.get(String(pending.requestId)); + if (current !== undefined) { + const resolved: OrchestrationV2RuntimeRequest = { + ...current, + status, + resolvedAt: now, + }; + pending.state.runtimeRequests.set(String(pending.requestId), resolved); + yield* emitProviderEvent({ + type: "runtime_request.updated", + provider: OPENCODE_PROVIDER, + threadId: pending.turn.threadId, + runtimeRequest: resolved, + }); + } + yield* emitProviderEvent({ + type: "node.updated", + provider: OPENCODE_PROVIDER, + node: { + id: pending.nodeId, + threadId: pending.turn.threadId, + runId: pending.turn.runId, + parentNodeId: pending.turn.rootNodeId, + rootNodeId: pending.turn.rootNodeId, + kind: pending.question === undefined ? "approval_request" : "user_input_request", + status: status === "resolved" ? "completed" : "cancelled", + countsForRun: false, + providerThreadId: pending.state.providerThread.id, + providerTurnId: pending.turn.providerTurnId, + nativeItemRef: providerRef(nativeRequestId), + runtimeRequestId: pending.requestId, + checkpointScopeId: null, + startedAt: pending.createdAt, + completedAt: now, + }, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider: OPENCODE_PROVIDER, + turnItem: runtimeRequestTurnItem( + pending, + status === "resolved" ? "completed" : "cancelled", + now, + now, + ), + }); + pendingRequests.delete(String(pending.requestId)); + pendingRequestsByNativeId.delete(nativeRequestId); + const hasOtherPending = Array.from(pendingRequests.values()).some( + (candidate) => candidate.turn.isRoot, + ); + if (!hasOtherPending) yield* updateProviderSession("running", null); + }); + + const finalizeTurn = Effect.fnUntraced(function* ( + state: OpenCodeThreadState, + turn: ActiveOpenCodeTurn, + status: TerminalTurnStatus, + ) { + if (turn.finalized) return; + turn.finalized = true; + const completedAt = yield* DateTime.now; + for (const part of turn.parts.values()) { + if (part.type === "text" || part.type === "reasoning") { + yield* emitTextPart(state, turn, part, true); + } + } + for (const pending of Array.from(pendingRequests.values())) { + if (pending.turn.providerTurnId === turn.providerTurnId) { + yield* resolveRuntimeRequest(pending.nativeRequestId, "cancelled"); + } + } + yield* emitProviderTurn(state, turn, status, completedAt); + yield* updateProviderThread(state, { + status: status === "failed" ? "error" : "idle", + nativeConversationHeadRef: + turn.nativeUserMessageId === null + ? state.providerThread.nativeConversationHeadRef + : providerRef(turn.nativeUserMessageId, "weak"), + }); + state.activeTurn = null; + if (!turn.isRoot) { + yield* emitProviderEvent({ + type: "node.updated", + provider: OPENCODE_PROVIDER, + node: { + id: turn.rootNodeId, + threadId: turn.threadId, + runId: null, + parentNodeId: null, + rootNodeId: turn.rootNodeId, + kind: "root_turn", + status, + countsForRun: false, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef: providerRef(state.nativeSessionId), + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: turn.startedAt, + completedAt, + }, + }); + return; + } + const anotherTurnIsActive = Array.from(threads.values()).some( + (candidate) => candidate.activeTurn?.isRoot === true, + ); + yield* updateProviderSession( + anotherTurnIsActive ? "running" : status === "failed" ? "error" : "ready", + status === "failed" ? sessionEntity.lastError : null, + ); + yield* emitProviderEvent({ + type: "turn.terminal", + provider: OPENCODE_PROVIDER, + providerTurnId: turn.providerTurnId, + status, + }); + }); + + const createChildTurn = Effect.fnUntraced(function* ( + state: OpenCodeThreadState, + message: Extract, + ) { + if (state.appThread === null || state.parentSubagent === null) return null; + const now = yield* DateTime.now; + const startedAt = dateTimeFromEpoch(message.time.created, now); + const rootNodeId = idAllocator.derive.nodeFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: `${state.nativeSessionId}:root:${message.id}`, + }); + const providerTurnId = idAllocator.derive.providerTurn({ + provider: OPENCODE_PROVIDER, + nativeTurnId: message.id, + }); + const providerTurn: OrchestrationV2ProviderTurn = { + id: providerTurnId, + providerThreadId: state.providerThread.id, + nodeId: rootNodeId, + runAttemptId: null, + nativeTurnRef: providerRef(message.id, "weak"), + ordinal: state.nextChildTurnOrdinal++, + status: "running", + startedAt, + completedAt: null, + }; + const turn: ActiveOpenCodeTurn = { + isRoot: false, + threadId: state.appThread.id, + runId: null, + rootNodeId, + appThread: state.appThread, + modelSelection: state.appThread.modelSelection, + runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy, + providerTurnId, + providerTurnOrdinal: providerTurn.ordinal, + runAttemptId: null, + startedAt, + itemOrdinals: new Map(), + parts: new Map(), + partIdsByMessage: new Map(), + providerTurn, + nextItemOrdinal: 1, + nativeUserMessageId: message.id, + interrupted: false, + finalized: false, + planId: null, + }; + state.activeTurn = turn; + state.providerTurns.set(String(providerTurnId), providerTurn); + yield* emitProviderEvent({ + type: "node.updated", + provider: OPENCODE_PROVIDER, + node: { + id: rootNodeId, + threadId: turn.threadId, + runId: null, + parentNodeId: null, + rootNodeId, + kind: "root_turn", + status: "running", + countsForRun: false, + providerThreadId: state.providerThread.id, + providerTurnId, + nativeItemRef: providerRef(message.id, "weak"), + runtimeRequestId: null, + checkpointScopeId: null, + startedAt, + completedAt: null, + }, + }); + yield* emitProviderTurn(state, turn, "running", null); + return turn; + }); + + const projectChildUserPart = Effect.fnUntraced(function* ( + state: OpenCodeThreadState, + turn: ActiveOpenCodeTurn, + part: Extract, + ) { + const now = yield* DateTime.now; + const messageId = idAllocator.derive.messageFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: part.messageID, + }); + const turnItemId = idAllocator.derive.turnItemFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: part.messageID, + }); + const projected: OrchestrationV2ConversationMessage = { + id: messageId, + threadId: turn.threadId, + runId: null, + nodeId: turn.rootNodeId, + role: "user", + text: part.text, + attachments: [], + streaming: false, + createdAt: turn.startedAt, + updatedAt: now, + }; + state.messages.set(String(messageId), projected); + yield* emitProviderEvent({ + type: "message.updated", + provider: OPENCODE_PROVIDER, + message: projected, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + provider: OPENCODE_PROVIDER, + turnItem: { + id: turnItemId, + threadId: turn.threadId, + runId: null, + nodeId: turn.rootNodeId, + providerThreadId: state.providerThread.id, + providerTurnId: turn.providerTurnId, + nativeItemRef: providerRef(part.messageID), + parentItemId: null, + ordinal: itemOrdinal(turn, part.messageID), + status: "completed", + title: null, + startedAt: projected.createdAt, + completedAt: now, + updatedAt: now, + type: "user_message", + messageId, + inputIntent: "turn_start", + text: part.text, + attachments: [], + }, + }); + }); + + const handleMessageUpdated = Effect.fnUntraced(function* ( + event: Extract, + ) { + const state = threads.get(event.properties.sessionID); + if (state === undefined) return; + const message = event.properties.info; + state.messageRoles.set(message.id, message.role); + if (message.role !== "user") return; + const isNewUserMessage = !state.userMessageIds.includes(message.id); + if (isNewUserMessage) state.userMessageIds.push(message.id); + let turn = state.activeTurn; + if (turn === null && state.parentSubagent !== null && isNewUserMessage) { + turn = yield* createChildTurn(state, message); + } + if (turn !== null && turn.nativeUserMessageId === null) { + turn.nativeUserMessageId = message.id; + yield* emitProviderTurn(state, turn, "running", null); + } + }); + + const handlePartUpdated = Effect.fnUntraced(function* ( + event: Extract, + ) { + const part = event.properties.part; + const state = threads.get(part.sessionID); + const turn = state?.activeTurn; + if (state === undefined || turn === null || turn === undefined || turn.finalized) return; + if (part.type === "text" && state.messageRoles.get(part.messageID) === "user") { + if (!turn.isRoot) yield* projectChildUserPart(state, turn, part); + return; + } + turn.parts.set(part.id, part); + const ids = turn.partIdsByMessage.get(part.messageID) ?? new Set(); + ids.add(part.id); + turn.partIdsByMessage.set(part.messageID, ids); + switch (part.type) { + case "text": + case "reasoning": + yield* emitTextPart(state, turn, part); + return; + case "tool": + yield* emitToolPart(state, turn, part); + return; + default: + return; + } + }); + + const handlePartDelta = Effect.fnUntraced(function* ( + event: Extract, + ) { + if (event.properties.field !== "text") return; + const state = threads.get(event.properties.sessionID); + const turn = state?.activeTurn; + const current = turn?.parts.get(event.properties.partID); + if ( + state === undefined || + turn === null || + turn === undefined || + current === undefined || + (current.type !== "text" && current.type !== "reasoning") + ) { + return; + } + const updated = { ...current, text: current.text + event.properties.delta }; + turn.parts.set(updated.id, updated); + yield* emitTextPart(state, turn, updated); + }); + + const handleAssistantCompleted = Effect.fnUntraced(function* ( + event: Extract, + ) { + const message = event.properties.info; + if (message.role !== "assistant" || message.time.completed === undefined) return; + const state = threads.get(message.sessionID); + const turn = state?.activeTurn; + if (state === undefined || turn === null || turn === undefined) return; + for (const partId of turn.partIdsByMessage.get(message.id) ?? []) { + const part = turn.parts.get(partId); + if (part?.type === "text" || part?.type === "reasoning") { + yield* emitTextPart(state, turn, part, true); + } + } + }); + + const handleEvent = Effect.fnUntraced(function* (event: OpenCodeEvent) { + yield* emitRawEvent({ + direction: "incoming", + messageKind: "notification", + method: event.type, + payload: event, + }); + switch (event.type) { + case "message.updated": + yield* handleMessageUpdated(event); + yield* handleAssistantCompleted(event); + return; + case "message.part.updated": + yield* handlePartUpdated(event); + return; + case "message.part.delta": + yield* handlePartDelta(event); + return; + case "todo.updated": { + const state = threads.get(event.properties.sessionID); + if (state?.activeTurn !== null && state?.activeTurn !== undefined) { + yield* emitTodo(state, state.activeTurn, event.properties.todos); + } + return; + } + case "permission.asked": { + const state = threads.get(event.properties.sessionID); + if (state?.activeTurn !== null && state?.activeTurn !== undefined) { + yield* emitRuntimeRequest(state, state.activeTurn, event.properties.id, { + type: "permission", + value: event.properties, + }); + } + return; + } + case "question.asked": { + const state = threads.get(event.properties.sessionID); + if (state?.activeTurn !== null && state?.activeTurn !== undefined) { + yield* emitRuntimeRequest(state, state.activeTurn, event.properties.id, { + type: "question", + value: event.properties, + }); + } + return; + } + case "permission.replied": + yield* resolveRuntimeRequest(event.properties.requestID, "resolved"); + return; + case "question.replied": + yield* resolveRuntimeRequest(event.properties.requestID, "resolved"); + return; + case "question.rejected": + yield* resolveRuntimeRequest(event.properties.requestID, "cancelled"); + return; + case "session.status": { + const state = threads.get(event.properties.sessionID); + if (state === undefined) return; + if (event.properties.status.type === "busy") { + yield* updateProviderThread(state, { status: "active" }); + return; + } + if (event.properties.status.type === "idle" && state.activeTurn !== null) { + yield* finalizeTurn( + state, + state.activeTurn, + state.activeTurn.interrupted ? "interrupted" : "completed", + ); + } + return; + } + case "session.idle": { + const state = threads.get(event.properties.sessionID); + if (state?.activeTurn !== null && state?.activeTurn !== undefined) { + yield* finalizeTurn( + state, + state.activeTurn, + state.activeTurn.interrupted ? "interrupted" : "completed", + ); + } + return; + } + case "session.error": { + const states = + event.properties.sessionID === undefined + ? Array.from(threads.values()).filter((state) => state.activeTurn !== null) + : [threads.get(event.properties.sessionID)].filter( + (state): state is OpenCodeThreadState => state !== undefined, + ); + const message = openCodeErrorMessage(event); + if ( + !isMessageAbortedError(event) && + (event.properties.sessionID === undefined || + states.some((state) => state.parentSubagent === null)) + ) { + yield* updateProviderSession("error", message); + } + for (const state of states) { + if (state.activeTurn !== null) { + yield* finalizeTurn( + state, + state.activeTurn, + terminalStatusForError(event, state.activeTurn), + ); + } + } + return; + } + default: + return; + } + }); + + const inputProviderSessionId = input.providerSessionId; + + const subscription = yield* sdkCall("event.subscribe", {}, () => + client.event.subscribe(undefined, { signal: abortController.signal }), + ); + yield* Scope.addFinalizer( + scope, + Effect.sync(() => abortController.abort()), + ); + yield* Stream.fromAsyncIterable( + subscription.stream, + (cause) => + new OpenCodeRuntimeError({ + operation: "event.subscribe", + detail: openCodeRuntimeErrorDetail(cause), + cause, + }), + ).pipe( + Stream.runForEach(handleEvent), + Effect.exit, + Effect.flatMap((exit) => + Effect.gen(function* () { + if (abortController.signal.aborted || Exit.isSuccess(exit)) return; + const detail = openCodeRuntimeErrorDetail(Cause.squash(exit.cause)); + yield* updateProviderSession("error", detail); + for (const state of threads.values()) { + if (state.activeTurn !== null) + yield* finalizeTurn(state, state.activeTurn, "failed"); + } + }), + ), + Effect.forkIn(scope), + ); + + if (!connection.external && connection.exitCode !== null) { + yield* connection.exitCode.pipe( + Effect.flatMap((code) => + abortController.signal.aborted + ? Effect.void + : Effect.gen(function* () { + const detail = `OpenCode server exited unexpectedly (${code}).`; + yield* updateProviderSession("error", detail); + for (const state of threads.values()) { + if (state.activeTurn !== null) { + yield* finalizeTurn(state, state.activeTurn, "failed"); + } + } + }), + ), + Effect.forkIn(scope), + ); + } + + const registerThread = ( + nativeSession: OpenCodeSession, + providerThread: OrchestrationV2ProviderThread, + appThread: OrchestrationV2AppThread | null, + ): OpenCodeThreadState => { + const existing = threads.get(nativeSession.id); + if (existing !== undefined) { + existing.providerThread = providerThread; + if (appThread !== null) existing.appThread = appThread; + return existing; + } + const state: OpenCodeThreadState = { + nativeSessionId: nativeSession.id, + providerThread, + appThread, + activeTurn: null, + providerTurns: new Map(), + messages: new Map(), + runtimeRequests: new Map(), + messageRoles: new Map(), + userMessageIds: [], + parentSubagent: subagentsByChildSessionId.get(nativeSession.id) ?? null, + nextChildTurnOrdinal: 1, + }; + threads.set(nativeSession.id, state); + return state; + }; + + const resolvePromptParts = (turnInput: ProviderAdapterV2TurnInput) => { + const text = turnInput.message.text.trim(); + const files = toOpenCodeFileParts({ + attachments: turnInput.message.attachments, + resolveAttachmentPath: (attachment) => + resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }), + }); + if (text.length === 0 && files.length === 0) { + throw protocolError("OpenCode turns require text or at least one valid attachment"); + } + return [...(text.length === 0 ? [] : [{ type: "text" as const, text }]), ...files]; + }; + + const readSnapshot = Effect.fnUntraced(function* ( + providerThread: OrchestrationV2ProviderThread, + ) { + const sessionId = nativeThreadId(providerThread); + const response = yield* sdkCall("session.messages", { sessionID: sessionId }, () => + client.session.messages({ sessionID: sessionId }), + ); + const nativeMessages = unwrapData("session.messages", response); + const state = threads.get(sessionId); + const snapshotNow = yield* DateTime.now; + const messages: Array = nativeMessages.flatMap( + ({ info, parts }) => { + const text = parts + .filter( + (part): part is Extract => part.type === "text", + ) + .filter((part) => part.ignored !== true && part.synthetic !== true) + .map((part) => part.text) + .join("\n"); + if (text.length === 0) return []; + const createdAt = dateTimeFromEpoch(info.time.created, snapshotNow); + return [ + { + id: idAllocator.derive.messageFromProviderItem({ + provider: OPENCODE_PROVIDER, + nativeItemId: info.id, + }), + threadId: providerThread.appThreadId ?? input.threadId, + runId: null, + nodeId: null, + role: info.role, + text, + attachments: [], + streaming: false, + createdAt, + updatedAt: + info.role === "assistant" + ? dateTimeFromEpoch(info.time.completed, createdAt) + : createdAt, + }, + ]; + }, + ); + const lastUser = nativeMessages.findLast(({ info }) => info.role === "user")?.info.id; + return { + providerThread: { + ...providerThread, + providerSessionId: input.providerSessionId, + nativeConversationHeadRef: + lastUser === undefined ? null : providerRef(lastUser, "weak"), + status: "idle" as const, + updatedAt: snapshotNow, + }, + providerTurns: state === undefined ? [] : [...state.providerTurns.values()], + messages, + runtimeRequests: state === undefined ? [] : [...state.runtimeRequests.values()], + providerPayload: nativeMessages, + }; + }); + + const runtimeSession: ProviderAdapterV2SessionRuntime = { + instanceId: options.instanceId, + provider: OPENCODE_PROVIDER, + providerSessionId: input.providerSessionId, + providerSession: sessionEntity, + rawEvents: Stream.fromEffectRepeat(Queue.take(rawEvents)), + events: Stream.fromEffectRepeat(Queue.take(events)), + ensureThread: (threadInput) => + Effect.gen(function* () { + if (threadInput.existingProviderThread !== undefined) { + return yield* runtimeSession.resumeThread({ + providerThread: threadInput.existingProviderThread, + }); + } + const response = yield* sdkCall( + "session.create", + { + title: `T3 Code ${threadInput.threadId}`, + permission: openCodePermissionRules(threadInput.runtimePolicy), + }, + () => + client.session.create({ + title: `T3 Code ${threadInput.threadId}`, + permission: openCodePermissionRules(threadInput.runtimePolicy), + }), + ); + const nativeSession = unwrapData("session.create", response); + const createdAt = yield* DateTime.now; + const providerThread = makeProviderThread({ + idAllocator, + providerSessionId: input.providerSessionId, + appThreadId: threadInput.threadId, + nativeSession, + now: createdAt, + }); + registerThread(nativeSession, providerThread, null); + return providerThread; + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterEnsureThreadError({ + provider: OPENCODE_PROVIDER, + threadId: threadInput.threadId, + cause, + }), + ), + ), + resumeThread: (threadInput) => + Effect.gen(function* () { + const sessionId = nativeThreadId(threadInput.providerThread); + const response = yield* sdkCall("session.get", { sessionID: sessionId }, () => + client.session.get({ sessionID: sessionId }), + ); + const nativeSession = unwrapData("session.get", response); + const resumedAt = yield* DateTime.now; + const providerThread = { + ...threadInput.providerThread, + providerSessionId: input.providerSessionId, + status: "idle" as const, + updatedAt: dateTimeFromEpoch(nativeSession.time.updated, resumedAt), + }; + registerThread(nativeSession, providerThread, null); + return providerThread; + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterResumeThreadError({ + provider: OPENCODE_PROVIDER, + providerSessionId: input.providerSessionId, + providerThreadId: threadInput.providerThread.id, + cause, + }), + ), + ), + startTurn: (turnInput) => + Effect.gen(function* () { + const sessionId = nativeThreadId(turnInput.providerThread); + const state = threads.get(sessionId); + if (state === undefined) { + return yield* protocolError(`OpenCode session ${sessionId} is not registered`); + } + if (state.activeTurn !== null) { + return yield* protocolError( + `OpenCode provider thread ${turnInput.providerThread.id} already has an active turn`, + ); + } + const parsedModel = parseOpenCodeModelSlug(turnInput.modelSelection.model); + if (parsedModel === null) { + return yield* protocolError( + `OpenCode model '${turnInput.modelSelection.model}' must use provider/model format`, + ); + } + const parts = resolvePromptParts(turnInput); + const startedAt = yield* DateTime.now; + const syntheticNativeTurnId = `${sessionId}:attempt:${turnInput.attemptId}`; + const providerTurnId = idAllocator.derive.providerTurn({ + provider: OPENCODE_PROVIDER, + nativeTurnId: syntheticNativeTurnId, + }); + const providerTurn: OrchestrationV2ProviderTurn = { + id: providerTurnId, + providerThreadId: turnInput.providerThread.id, + nodeId: turnInput.rootNodeId, + runAttemptId: turnInput.attemptId, + nativeTurnRef: providerRef(syntheticNativeTurnId, "weak"), + ordinal: turnInput.providerTurnOrdinal, + status: "running", + startedAt, + completedAt: null, + }; + const turn: ActiveOpenCodeTurn = { + isRoot: true, + threadId: turnInput.threadId, + runId: turnInput.runId, + rootNodeId: turnInput.rootNodeId, + appThread: turnInput.appThread, + modelSelection: turnInput.modelSelection, + runtimePolicy: turnInput.runtimePolicy, + providerTurnId, + providerTurnOrdinal: turnInput.providerTurnOrdinal, + runAttemptId: turnInput.attemptId, + startedAt, + itemOrdinals: new Map(), + parts: new Map(), + partIdsByMessage: new Map(), + providerTurn, + nextItemOrdinal: 100, + nativeUserMessageId: null, + interrupted: false, + finalized: false, + planId: null, + }; + state.appThread = turnInput.appThread; + state.activeTurn = turn; + state.providerTurns.set(String(providerTurnId), providerTurn); + yield* emitProviderTurn(state, turn, "running", null); + yield* updateProviderThread(state, { + status: "active", + firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal, + lastRunOrdinal: turnInput.runOrdinal, + }); + yield* updateProviderSession("running", null); + const agent = + getModelSelectionStringOptionValue(turnInput.modelSelection, "agent") ?? + (turnInput.runtimePolicy.interactionMode === "plan" ? "plan" : undefined); + const variant = getModelSelectionStringOptionValue( + turnInput.modelSelection, + "variant", + ); + yield* sdkCall( + "session.promptAsync", + { + sessionID: sessionId, + model: parsedModel, + ...(agent === undefined ? {} : { agent }), + ...(variant === undefined ? {} : { variant }), + parts, + }, + () => + client.session.promptAsync({ + sessionID: sessionId, + model: parsedModel, + ...(agent === undefined ? {} : { agent }), + ...(variant === undefined ? {} : { variant }), + parts, + }), + ).pipe(Effect.tapError(() => finalizeTurn(state, turn, "failed"))); + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterTurnStartError({ + provider: OPENCODE_PROVIDER, + threadId: turnInput.threadId, + providerThreadId: turnInput.providerThread.id, + runId: turnInput.runId, + cause, + }), + ), + ), + steerTurn: (steerInput) => + Effect.gen(function* () { + const sessionId = nativeThreadId(steerInput.providerThread); + const state = threads.get(sessionId); + const turn = state?.activeTurn; + if ( + turn === undefined || + turn === null || + turn.providerTurnId !== steerInput.providerTurnId + ) { + return yield* protocolError( + `OpenCode turn ${steerInput.providerTurnId} is not active`, + ); + } + const parsedModel = parseOpenCodeModelSlug(turn.modelSelection.model); + if (parsedModel === null) { + return yield* protocolError( + `OpenCode model '${turn.modelSelection.model}' must use provider/model format`, + ); + } + const text = steerInput.message.text.trim(); + const files = toOpenCodeFileParts({ + attachments: steerInput.message.attachments, + resolveAttachmentPath: (attachment) => + resolveAttachmentPath({ + attachmentsDir: serverConfig.attachmentsDir, + attachment, + }), + }); + if (text.length === 0 && files.length === 0) { + return yield* protocolError("OpenCode steering requires text or an attachment"); + } + const parts = [ + ...(text.length === 0 ? [] : [{ type: "text" as const, text }]), + ...files, + ]; + yield* sdkCall( + "session.promptAsync", + { sessionID: sessionId, model: parsedModel, parts }, + () => + client.session.promptAsync({ + sessionID: sessionId, + model: parsedModel, + parts, + }), + ); + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterSteerRunError({ + provider: OPENCODE_PROVIDER, + providerThreadId: steerInput.providerThread.id, + providerTurnId: steerInput.providerTurnId, + cause, + }), + ), + ), + interruptTurn: (interruptInput) => + Effect.gen(function* () { + const sessionId = nativeThreadId(interruptInput.providerThread); + const state = threads.get(sessionId); + const turn = state?.activeTurn; + if ( + turn === undefined || + turn === null || + turn.providerTurnId !== interruptInput.providerTurnId + ) { + return yield* protocolError( + `OpenCode turn ${interruptInput.providerTurnId} is not active`, + ); + } + turn.interrupted = true; + yield* sdkCall("session.abort", { sessionID: sessionId }, () => + client.session.abort({ sessionID: sessionId }), + ).pipe(Effect.tapError(() => Effect.sync(() => (turn.interrupted = false)))); + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterInterruptError({ + provider: OPENCODE_PROVIDER, + providerThreadId: interruptInput.providerThread.id, + providerTurnId: interruptInput.providerTurnId, + cause, + }), + ), + ), + respondToRuntimeRequest: (requestInput) => + Effect.gen(function* () { + const pending = pendingRequests.get(String(requestInput.requestId)); + if (pending === undefined) { + return yield* protocolError( + `No pending OpenCode request ${requestInput.requestId}`, + ); + } + if (pending.question !== undefined) { + if (requestInput.answers === undefined) { + return yield* protocolError( + `OpenCode question request ${requestInput.requestId} requires answers`, + ); + } + const answers = toOpenCodeQuestionAnswers(pending.question, requestInput.answers); + yield* sdkCall( + "question.reply", + { requestID: pending.nativeRequestId, answers }, + () => + client.question.reply({ + requestID: pending.nativeRequestId, + answers, + }), + ); + return; + } + if (requestInput.decision === undefined) { + return yield* protocolError( + `OpenCode approval request ${requestInput.requestId} requires a decision`, + ); + } + const reply = toOpenCodePermissionReply(requestInput.decision); + yield* sdkCall( + "permission.reply", + { requestID: pending.nativeRequestId, reply }, + () => + client.permission.reply({ + requestID: pending.nativeRequestId, + reply, + }), + ); + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRuntimeRequestResponseError({ + provider: OPENCODE_PROVIDER, + requestId: requestInput.requestId, + cause, + }), + ), + ), + readThreadSnapshot: (snapshotInput) => + readSnapshot(snapshotInput.providerThread).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterReadThreadSnapshotError({ + provider: OPENCODE_PROVIDER, + providerThreadId: snapshotInput.providerThread.id, + cause, + }), + ), + ), + rollbackThread: (rollbackInput) => + Effect.gen(function* () { + const sessionId = nativeThreadId(rollbackInput.providerThread); + const state = threads.get(sessionId); + if (state?.activeTurn !== null && state?.activeTurn !== undefined) { + return yield* protocolError( + `Cannot roll back OpenCode thread ${rollbackInput.providerThread.id} while a turn is active`, + ); + } + const response = yield* sdkCall("session.messages", { sessionID: sessionId }, () => + client.session.messages({ sessionID: sessionId }), + ); + const messages = unwrapData("session.messages", response); + let boundaryMessageId: string | undefined; + if (rollbackInput.target.type === "thread_start") { + boundaryMessageId = messages.find(({ info }) => info.role === "user")?.info.id; + } else { + boundaryMessageId = openCodeBoundaryAfterProviderTurn( + rollbackInput.providerThreadTurns, + rollbackInput.target.providerTurn.id, + ); + } + if (boundaryMessageId !== undefined) { + yield* sdkCall( + "session.revert", + { sessionID: sessionId, messageID: boundaryMessageId }, + () => + client.session.revert({ sessionID: sessionId, messageID: boundaryMessageId }), + ); + } + const snapshot = yield* readSnapshot(rollbackInput.providerThread); + return { + ...snapshot, + providerThread: { + ...snapshot.providerThread, + nativeConversationHeadRef: + rollbackInput.target.type === "provider_turn" + ? rollbackInput.target.providerTurn.nativeTurnRef + : null, + }, + }; + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRollbackThreadError({ + provider: OPENCODE_PROVIDER, + providerThreadId: rollbackInput.providerThread.id, + checkpointId: rollbackInput.target.checkpointId, + cause, + }), + ), + ), + forkThread: (forkInput) => + Effect.gen(function* () { + const sourceSessionId = nativeThreadId(forkInput.sourceProviderThread); + const sourceState = threads.get(sourceSessionId); + if (sourceState?.activeTurn !== null && sourceState?.activeTurn !== undefined) { + return yield* protocolError( + `Cannot fork OpenCode thread ${forkInput.sourceProviderThread.id} while a turn is active`, + ); + } + let boundaryMessageId: string | undefined; + if (forkInput.providerTurnId !== undefined) { + const sourceTurns = forkInput.sourceProviderTurns ?? []; + const selected = sourceTurns.find((turn) => turn.id === forkInput.providerTurnId); + if (selected === undefined) { + return yield* protocolError( + `OpenCode fork boundary turn ${forkInput.providerTurnId} was not found`, + ); + } + boundaryMessageId = openCodeBoundaryAfterProviderTurn(sourceTurns, selected.id); + } + const response = yield* sdkCall( + "session.fork", + { + sessionID: sourceSessionId, + ...(boundaryMessageId === undefined ? {} : { messageID: boundaryMessageId }), + }, + () => + client.session.fork({ + sessionID: sourceSessionId, + ...(boundaryMessageId === undefined ? {} : { messageID: boundaryMessageId }), + }), + ); + const nativeSession = unwrapData("session.fork", response); + const forkedAt = yield* DateTime.now; + const providerThread = makeProviderThread({ + idAllocator, + providerSessionId: input.providerSessionId, + appThreadId: forkInput.targetThreadId, + ...(forkInput.ownerNodeId === undefined + ? {} + : { ownerNodeId: forkInput.ownerNodeId }), + nativeSession, + forkedFrom: { + providerThreadId: forkInput.sourceProviderThread.id, + ...(forkInput.providerTurnId === undefined + ? {} + : { providerTurnId: forkInput.providerTurnId }), + }, + now: forkedAt, + }); + registerThread(nativeSession, providerThread, null); + return providerThread; + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterForkThreadError({ + provider: OPENCODE_PROVIDER, + providerThreadId: forkInput.sourceProviderThread.id, + cause, + }), + ), + ), + }; + + return runtimeSession; + }, + (effect, input) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterOpenSessionError({ + provider: OPENCODE_PROVIDER, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ), + ), + }); +} + +export type OpenCodeAdapterV2DriverEnv = OpenCodeRuntime | IdAllocatorV2 | ServerConfig; + +export const OpenCodeAdapterV2Driver: ProviderAdapterDriver< + OpenCodeSettings, + OpenCodeAdapterV2DriverEnv +> = { + driverKind: OPENCODE_DRIVER_KIND, + configSchema: OpenCodeSettingsSchema, + defaultConfig: (): OpenCodeSettings => DEFAULT_OPENCODE_SETTINGS, + create: Effect.fn("OpenCodeAdapterV2Driver.create")( + function* (input: ProviderAdapterDriverCreateInput) { + const hostEnvironment = yield* HostProcessEnvironment; + const openCodeRuntime = yield* OpenCodeRuntime; + const idAllocator = yield* IdAllocatorV2; + const serverConfig = yield* ServerConfig; + return makeOpenCodeAdapterV2({ + instanceId: input.instanceId, + settings: { ...input.config, enabled: input.enabled }, + environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment), + runtime: openCodeRuntime, + idAllocator, + serverConfig, + }); + }, + (effect, input) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapterDriverCreateError({ + driver: OPENCODE_DRIVER_KIND, + instanceId: input.instanceId, + detail: "Failed to create OpenCode v2 adapter.", + cause, + }), + ), + ), + ), +}; + +export const layer: Layer.Layer = + Layer.effect( + ProviderAdapterV2, + Effect.gen(function* () { + const hostEnvironment = yield* HostProcessEnvironment; + const openCodeRuntime = yield* OpenCodeRuntime; + const idAllocator = yield* IdAllocatorV2; + const serverConfig = yield* ServerConfig; + return makeOpenCodeAdapterV2({ + instanceId: OPENCODE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_OPENCODE_SETTINGS, + environment: hostEnvironment, + runtime: openCodeRuntime, + idAllocator, + serverConfig, + }); + }), + ); diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts index 10a8a25c04..4dc99f2b00 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import { CursorProviderCapabilitiesV2 } from "./Adapters/CursorAdapterV2.ts"; +import { GrokProviderCapabilitiesV2 } from "./Adapters/GrokAdapterV2.ts"; import { CommandPolicyCapabilityUnsupportedError, CommandPolicyV2, @@ -62,6 +63,21 @@ layer("CommandPolicyV2", (it) => { }), ); + it.effect("uses interrupt-and-restart steering for Grok ACP", () => + Effect.gen(function* () { + const policy = yield* CommandPolicyV2; + + const result = yield* policy.decideSteeringExecution({ + commandId, + threadId, + provider: "grok", + capabilities: GrokProviderCapabilitiesV2, + }); + + assert.equal(result, "interrupt_restart"); + }), + ); + it.effect("honors an explicit interrupt-and-restart request", () => Effect.gen(function* () { const policy = yield* CommandPolicyV2; @@ -165,6 +181,24 @@ layer("CommandPolicyV2", (it) => { }), ); + it.effect("falls back to portable context when Grok ACP cannot fork natively", () => + Effect.gen(function* () { + const policy = yield* CommandPolicyV2; + + const result = yield* policy.decideForkExecution({ + commandId, + threadId, + provider: "grok", + capabilities: GrokProviderCapabilitiesV2, + sameProvider: true, + hasStrongNativeSource: true, + fromSpecificTurn: true, + }); + + assert.equal(result, "portable_context"); + }), + ); + it.effect("returns a typed error when neither native nor portable fork is available", () => Effect.gen(function* () { const policy = yield* CommandPolicyV2; diff --git a/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts b/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts new file mode 100644 index 0000000000..b965e8d0f9 --- /dev/null +++ b/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts @@ -0,0 +1,158 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + type OrchestrationV2ThreadProjection, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { describe } from "vite-plus/test"; + +import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts"; +import { ServerConfig } from "../config.ts"; +import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; +import { OrchestratorV2 } from "./Orchestrator.ts"; +import { OrchestrationV2LayerLive } from "./runtimeLayer.ts"; +import { GROK_MODEL_SELECTION } from "./testkit/fixtures/shared.ts"; + +const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-grok-v2-live-", +}); + +const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe( + Layer.provide(VcsProcess.layer), + Layer.provide(serverConfigLayer), + Layer.provide(NodeServices.layer), +); + +const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(vcsDriverRegistryLayer)); + +const liveLayer = OrchestrationV2LayerLive.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(checkpointStoreLayer), + Layer.provide(serverConfigLayer), + Layer.provide( + ServerSettingsService.layerTest({ + providers: { + grok: { enabled: true }, + }, + }), + ), + Layer.provide(NodeServices.layer), +); + +const waitForIdle = Effect.fn("GrokOrchestratorV2Live.waitForIdle")(function* (threadId: ThreadId) { + const orchestrator = yield* OrchestratorV2; + for (let attempt = 0; attempt < 600; attempt += 1) { + const projection = yield* orchestrator.getThreadProjection(threadId); + if ( + projection.runs.length > 0 && + projection.runs.every( + (run) => !["queued", "starting", "running", "waiting"].includes(run.status), + ) + ) { + return projection; + } + yield* Effect.sleep("500 millis"); + } + return yield* Effect.die(new Error(`Timed out waiting for Grok thread ${threadId}.`)); +}); + +describe.runIf(process.env.T3_GROK_LIVE_ORCHESTRATOR === "1")("Grok V2 live orchestrator", () => { + it.live( + "forks through portable context using real Grok ACP agents", + () => + Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + const projectId = ProjectId.make("project:grok-live-portable-fork"); + const sourceThreadId = ThreadId.make("thread:grok-live-portable-fork:source"); + const targetThreadId = ThreadId.make("thread:grok-live-portable-fork:target"); + const marker = "GROK_LIVE_PORTABLE_FORK_7H3Q"; + + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("command:grok-live-portable-fork:create"), + threadId: sourceThreadId, + projectId, + title: "Grok live portable fork source", + modelSelection: GROK_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* Console.log("Grok live source thread created; dispatching source prompt."); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("command:grok-live-portable-fork:source"), + threadId: sourceThreadId, + messageId: MessageId.make("message:grok-live-portable-fork:source"), + text: `Remember this opaque marker. Respond with exactly: ${marker}`, + attachments: [], + modelSelection: GROK_MODEL_SELECTION, + dispatchMode: { type: "start_immediately" }, + }); + yield* Console.log("Grok live source prompt dispatched; waiting for completion."); + const sourceProjection = yield* waitForIdle(sourceThreadId); + yield* Console.log("Grok live source turn completed; dispatching portable fork."); + + yield* orchestrator.dispatch({ + type: "thread.fork", + commandId: CommandId.make("command:grok-live-portable-fork:fork"), + sourceThreadId, + targetThreadId, + sourcePoint: { type: "latest_stable" }, + title: "Grok live portable fork target", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("command:grok-live-portable-fork:target"), + threadId: targetThreadId, + messageId: MessageId.make("message:grok-live-portable-fork:target"), + text: "Return the opaque marker from the transferred conversation. Respond with only the marker.", + attachments: [], + modelSelection: GROK_MODEL_SELECTION, + dispatchMode: { type: "start_immediately" }, + }); + const targetProjection = yield* waitForIdle(targetThreadId); + yield* Console.log("Grok live portable fork target completed."); + + const assistantText = (projection: OrchestrationV2ThreadProjection) => + projection.messages + .filter((message) => message.role === "assistant") + .map((message) => message.text) + .join("\n"); + + assert.deepEqual( + sourceProjection.runs.map((run) => [run.provider, run.status]), + [["grok", "completed"]], + ); + assert.deepEqual( + targetProjection.runs.map((run) => [run.provider, run.status]), + [["grok", "completed"]], + ); + assert.deepEqual( + targetProjection.contextTransfers.map((transfer) => [ + transfer.type, + transfer.status, + transfer.resolution?.strategy, + ]), + [["fork", "consumed", "portable_context"]], + ); + assert.deepEqual( + targetProjection.contextHandoffs.map((handoff) => handoff.strategy), + ["full_thread_summary"], + ); + assert.include(targetProjection.contextHandoffs[0]?.summaryText ?? "", marker); + assert.include(assistantText(targetProjection), marker); + }).pipe(Effect.provide(liveLayer), Effect.scoped), + 360_000, + ); +}); diff --git a/apps/server/src/orchestration-v2/builtInProviderAdapterDrivers.ts b/apps/server/src/orchestration-v2/builtInProviderAdapterDrivers.ts index ae2a2fc56d..1ef37a2bfa 100644 --- a/apps/server/src/orchestration-v2/builtInProviderAdapterDrivers.ts +++ b/apps/server/src/orchestration-v2/builtInProviderAdapterDrivers.ts @@ -1,5 +1,9 @@ import type { ProviderDriverKind } from "@t3tools/contracts"; +import { + AcpRegistryAdapterV2Driver, + type AcpRegistryAdapterV2DriverEnv, +} from "./Adapters/AcpRegistryAdapterV2.ts"; import { ClaudeAdapterV2Driver, type ClaudeAdapterV2DriverEnv, @@ -9,16 +13,31 @@ import { CursorAdapterV2Driver, type CursorAdapterV2DriverEnv, } from "./Adapters/CursorAdapterV2.ts"; +import { GrokAdapterV2Driver, type GrokAdapterV2DriverEnv } from "./Adapters/GrokAdapterV2.ts"; +import { + OpenCodeAdapterV2Driver, + type OpenCodeAdapterV2DriverEnv, +} from "./Adapters/OpenCodeAdapterV2.ts"; import type { AnyProviderAdapterDriver } from "./ProviderAdapterDriver.ts"; export type BuiltInProviderAdapterDriversV2Env = + | AcpRegistryAdapterV2DriverEnv | ClaudeAdapterV2DriverEnv | CodexAdapterV2DriverEnv - | CursorAdapterV2DriverEnv; + | CursorAdapterV2DriverEnv + | GrokAdapterV2DriverEnv + | OpenCodeAdapterV2DriverEnv; export const BUILT_IN_PROVIDER_ADAPTER_DRIVERS_V2: ReadonlyArray< AnyProviderAdapterDriver -> = [CodexAdapterV2Driver, ClaudeAdapterV2Driver, CursorAdapterV2Driver]; +> = [ + CodexAdapterV2Driver, + ClaudeAdapterV2Driver, + CursorAdapterV2Driver, + OpenCodeAdapterV2Driver, + GrokAdapterV2Driver, + AcpRegistryAdapterV2Driver, +]; export const BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2: ReadonlySet = new Set( BUILT_IN_PROVIDER_ADAPTER_DRIVERS_V2.map((driver) => driver.driverKind), diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 1e972fe45c..55616d9529 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -1,5 +1,7 @@ import * as Layer from "effect/Layer"; +import { FetchHttpClient } from "effect/unstable/http"; +import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts"; import { claudeAgentSdkQueryRunnerLiveLayer } from "./Adapters/ClaudeAdapterV2.ts"; import { codexAppServerClientFactoryFromSettingsLayer } from "./Adapters/CodexAdapterV2.ts"; import { cursorAgentSdkRunnerLiveLayer } from "./Adapters/CursorAgentSdk.ts"; @@ -40,6 +42,8 @@ const providerAdapterRegistryProvided = providerAdapterRegistryLayerFromSettings Layer.provide(codexAppServerClientFactoryFromSettingsLayer), Layer.provide(claudeAgentSdkQueryRunnerLiveLayer), Layer.provide(cursorAgentSdkRunnerLiveLayer), + Layer.provide(OpenCodeRuntimeLive), + Layer.provide(FetchHttpClient.layer), Layer.provide(idAllocatorLayer), ); diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts index 1a170c95b3..3839d6c4bc 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts @@ -49,7 +49,15 @@ describe("orchestrator replay fixture contract", () => { const firstCommand = materialized.commands[0]; assert.equal(transcript.scenario, fixture.name); - assert.equal(transcript.provider, provider.provider); + if (provider.provider === "acpRegistry") { + assert.include( + ["acpRegistry", "grok"], + transcript.provider, + "ACP Registry may retarget protocol-standard Grok ACP evidence", + ); + } else { + assert.equal(transcript.provider, provider.provider); + } assert.equal(provider.modelSelection.instanceId, provider.provider); assert.isDefined(materialized.projectionThreadIds[0]); assert.equal(firstCommand?.type, "thread.create"); diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts index 457c68d7c6..ebebfb67f3 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts @@ -7,6 +7,9 @@ import * as FileSystem from "effect/FileSystem"; import { ClaudeOrchestratorReplayHarness } from "../Adapters/ClaudeAdapterV2.testkit.ts"; import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts"; import { CursorOrchestratorReplayHarness } from "../Adapters/CursorAdapterV2.testkit.ts"; +import { AcpRegistryOrchestratorReplayHarness } from "../Adapters/AcpRegistryAdapterV2.testkit.ts"; +import { GrokOrchestratorReplayHarness } from "../Adapters/GrokAdapterV2.testkit.ts"; +import { OpenCodeOrchestratorReplayHarness } from "../Adapters/OpenCodeAdapterV2.testkit.ts"; import { layer as idAllocatorLayer } from "../IdAllocator.ts"; import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts"; import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts"; @@ -118,6 +121,21 @@ function runFixtureProviderWithRegisteredHarness(input: { ...input, harness: CursorOrchestratorReplayHarness, }).pipe(Effect.mapError(normalizeTestError), Effect.scoped); + case "grok": + return runFixtureProvider({ + ...input, + harness: GrokOrchestratorReplayHarness, + }).pipe(Effect.mapError(normalizeTestError), Effect.scoped); + case "acpRegistry": + return runFixtureProvider({ + ...input, + harness: AcpRegistryOrchestratorReplayHarness, + }).pipe(Effect.mapError(normalizeTestError), Effect.scoped); + case "opencode": + return runFixtureProvider({ + ...input, + harness: OpenCodeOrchestratorReplayHarness, + }).pipe(Effect.mapError(normalizeTestError), Effect.scoped); default: return Effect.die( new Error(`No replay harness registered for provider ${input.provider.provider}.`), diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 9bbcddfbee..11668ad9ac 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -41,7 +41,7 @@ import { type OrchestratorV2ScenarioResult, } from "./OrchestratorScenario.ts"; -function makeReplayServerConfig( +export function makeReplayServerConfig( scenario: string, ): Effect.Effect< ServerConfigShape, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/acp_elicitation/grok_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/acp_elicitation/grok_transcript.ndjson new file mode 100644 index 0000000000..674723056c --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/acp_elicitation/grok_transcript.ndjson @@ -0,0 +1,11 @@ +{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"acp_elicitation","metadata":{"generatedBy":"protocol-semantic-fixture","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"generic-acp-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}} +{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete"}]}}} +{"type":"emit_inbound","label":"elicitation.request","frame":{"kind":"request","method":"session/elicitation","params":{"sessionId":"grok-replay-session-1","mode":"form","message":"Choose the fixture preference.","requestedSchema":{"type":"object","title":"Fixture preference","properties":{"schema_vs_ui_flexibility":{"type":"string","title":"Fixture","description":"Should this fixture prefer strict schemas or UI flexibility?","enum":["Strict schemas (Recommended)","UI flexibility"]}},"required":["schema_vs_ui_flexibility"]}}}} +{"type":"expect_outbound","label":"elicitation.response","frame":{"kind":"response","method":"session/elicitation","result":{"action":{"action":"accept","content":{"schema_vs_ui_flexibility":"Strict schemas (Recommended)"}}}}} +{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"plan questions fixture complete"}}}}} +{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts index 9f2cff4a09..13569cfc3f 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts @@ -1,11 +1,15 @@ import { assertClaudeMessageSteeringOutput } from "./message_steering/claude_output.ts"; import { assertMessageSteeringOutput } from "./message_steering/codex_output.ts"; import { assertCursorMessageSteeringOutput } from "./message_steering/cursor_output.ts"; +import { assertGrokMessageSteeringOutput } from "./message_steering/grok_output.ts"; import { messageSteeringInput } from "./message_steering/input.ts"; import { assertMultiTurnClaudeOutput } from "./multi_turn/claude_output.ts"; import { assertMultiTurnOutput } from "./multi_turn/codex_output.ts"; import { multiTurnInput } from "./multi_turn/input.ts"; +import { openCodeSubagentInput } from "./opencode_subagent/input.ts"; +import { assertOpenCodeSubagentOutput } from "./opencode_subagent/output.ts"; import { assertPlanQuestionsOutput } from "./plan_questions/codex_output.ts"; +import { assertOpenCodePlanQuestionsOutput } from "./plan_questions/opencode_output.ts"; import { planQuestionsInput } from "./plan_questions/input.ts"; import { assertProposedPlanOutput } from "./proposed_plan/codex_output.ts"; import { assertProposedPlanCursorOutput } from "./proposed_plan/cursor_output.ts"; @@ -26,6 +30,7 @@ import { assertThreadRollbackOutput } from "./thread_rollback/codex_output.ts"; import { threadRollbackInput } from "./thread_rollback/input.ts"; import { assertTodoListOutput } from "./todo_list/codex_output.ts"; import { assertTodoListCursorOutput } from "./todo_list/cursor_output.ts"; +import { assertTodoListGrokOutput } from "./todo_list/grok_output.ts"; import { todoListInput } from "./todo_list/input.ts"; import { assertToolCallReadOnlyClaudeOutput } from "./tool_call_read_only/claude_output.ts"; import { assertToolCallReadOnlyCursorOutput } from "./tool_call_read_only/cursor_output.ts"; @@ -52,9 +57,12 @@ import { assertClaudeWebSearchOutput } from "./web_search/claude_output.ts"; import { assertWebSearchOutput } from "./web_search/codex_output.ts"; import { webSearchInput } from "./web_search/input.ts"; import { + ACP_REGISTRY_MODEL_SELECTION, CLAUDE_MODEL_SELECTION, CODEX_MODEL_SELECTION, CURSOR_MODEL_SELECTION, + GROK_MODEL_SELECTION, + OPENCODE_MODEL_SELECTION, READ_ONLY_NEVER_POLICY, READ_ONLY_ON_REQUEST_POLICY, RESTRICTED_GRANULAR_POLICY, @@ -63,6 +71,26 @@ import { } from "./shared.ts"; export const ORCHESTRATOR_REPLAY_FIXTURES = [ + { + name: "acp_elicitation", + buildInput: planQuestionsInput, + providers: [ + { + provider: "grok", + transcriptFile: new URL("./acp_elicitation/grok_transcript.ndjson", import.meta.url), + modelSelection: GROK_MODEL_SELECTION, + runtimePolicyOverride: READ_ONLY_NEVER_POLICY, + assertOutput: assertPlanQuestionsOutput, + }, + { + provider: "acpRegistry", + transcriptFile: new URL("./acp_elicitation/grok_transcript.ndjson", import.meta.url), + modelSelection: ACP_REGISTRY_MODEL_SELECTION, + runtimePolicyOverride: READ_ONLY_NEVER_POLICY, + assertOutput: assertPlanQuestionsOutput, + }, + ], + }, { name: "simple", buildInput: simpleInput, @@ -85,6 +113,24 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ modelSelection: CURSOR_MODEL_SELECTION, assertOutput: assertSimpleOutput, }, + { + provider: "grok", + transcriptFile: new URL("./simple/grok_transcript.ndjson", import.meta.url), + modelSelection: GROK_MODEL_SELECTION, + assertOutput: assertSimpleOutput, + }, + { + provider: "acpRegistry", + transcriptFile: new URL("./simple/grok_transcript.ndjson", import.meta.url), + modelSelection: ACP_REGISTRY_MODEL_SELECTION, + assertOutput: assertSimpleOutput, + }, + { + provider: "opencode", + transcriptFile: new URL("./simple/opencode_transcript.ndjson", import.meta.url), + modelSelection: OPENCODE_MODEL_SELECTION, + assertOutput: assertSimpleOutput, + }, ], }, { @@ -105,6 +151,20 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertToolCallReadOnlyCursorOutput, }, + { + provider: "grok", + transcriptFile: new URL("./tool_call_read_only/grok_transcript.ndjson", import.meta.url), + modelSelection: GROK_MODEL_SELECTION, + runtimePolicyOverride: READ_ONLY_NEVER_POLICY, + assertOutput: assertToolCallReadOnlyCursorOutput, + }, + { + provider: "acpRegistry", + transcriptFile: new URL("./tool_call_read_only/grok_transcript.ndjson", import.meta.url), + modelSelection: ACP_REGISTRY_MODEL_SELECTION, + runtimePolicyOverride: READ_ONLY_NEVER_POLICY, + assertOutput: assertToolCallReadOnlyCursorOutput, + }, ], }, { @@ -131,6 +191,26 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ runtimePolicyOverride: READ_ONLY_ON_REQUEST_POLICY, assertOutput: assertToolCallReadOnlyOnRequestClaudeOutput, }, + { + provider: "grok", + transcriptFile: new URL( + "./tool_call_read_only_on_request/grok_transcript.ndjson", + import.meta.url, + ), + modelSelection: GROK_MODEL_SELECTION, + runtimePolicyOverride: READ_ONLY_ON_REQUEST_POLICY, + assertOutput: assertToolCallReadOnlyOnRequestOutput, + }, + { + provider: "acpRegistry", + transcriptFile: new URL( + "./tool_call_read_only_on_request/grok_transcript.ndjson", + import.meta.url, + ), + modelSelection: ACP_REGISTRY_MODEL_SELECTION, + runtimePolicyOverride: READ_ONLY_ON_REQUEST_POLICY, + assertOutput: assertToolCallReadOnlyOnRequestOutput, + }, ], }, { @@ -223,6 +303,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ }, ], }, + { + name: "opencode_subagent", + buildInput: openCodeSubagentInput, + providers: [ + { + provider: "opencode", + transcriptFile: new URL("./opencode_subagent/opencode_transcript.ndjson", import.meta.url), + modelSelection: OPENCODE_MODEL_SELECTION, + assertOutput: assertOpenCodeSubagentOutput, + }, + ], + }, { name: "multi_turn", buildInput: multiTurnInput, @@ -245,6 +337,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ modelSelection: CURSOR_MODEL_SELECTION, assertOutput: assertMultiTurnOutput, }, + { + provider: "grok", + transcriptFile: new URL("./multi_turn/grok_transcript.ndjson", import.meta.url), + modelSelection: GROK_MODEL_SELECTION, + assertOutput: assertMultiTurnOutput, + }, + { + provider: "acpRegistry", + transcriptFile: new URL("./multi_turn/grok_transcript.ndjson", import.meta.url), + modelSelection: ACP_REGISTRY_MODEL_SELECTION, + assertOutput: assertMultiTurnOutput, + }, ], }, { @@ -281,6 +385,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ modelSelection: CURSOR_MODEL_SELECTION, assertOutput: assertQueuedTurnOutput, }, + { + provider: "grok", + transcriptFile: new URL("./queued_turn/grok_transcript.ndjson", import.meta.url), + modelSelection: GROK_MODEL_SELECTION, + assertOutput: assertQueuedTurnOutput, + }, + { + provider: "acpRegistry", + transcriptFile: new URL("./queued_turn/grok_transcript.ndjson", import.meta.url), + modelSelection: ACP_REGISTRY_MODEL_SELECTION, + assertOutput: assertQueuedTurnOutput, + }, ], }, { @@ -301,6 +417,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertTodoListCursorOutput, }, + { + provider: "grok", + transcriptFile: new URL("./todo_list/grok_transcript.ndjson", import.meta.url), + modelSelection: GROK_MODEL_SELECTION, + assertOutput: assertTodoListGrokOutput, + }, + { + provider: "acpRegistry", + transcriptFile: new URL("./todo_list/grok_transcript.ndjson", import.meta.url), + modelSelection: ACP_REGISTRY_MODEL_SELECTION, + assertOutput: assertTodoListGrokOutput, + }, ], }, { @@ -332,6 +460,20 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertPlanQuestionsOutput, }, + { + provider: "grok", + transcriptFile: new URL("./plan_questions/grok_transcript.ndjson", import.meta.url), + modelSelection: GROK_MODEL_SELECTION, + runtimePolicyOverride: READ_ONLY_NEVER_POLICY, + assertOutput: assertPlanQuestionsOutput, + }, + { + provider: "opencode", + transcriptFile: new URL("./plan_questions/opencode_transcript.ndjson", import.meta.url), + modelSelection: OPENCODE_MODEL_SELECTION, + runtimePolicyOverride: READ_ONLY_NEVER_POLICY, + assertOutput: assertOpenCodePlanQuestionsOutput, + }, ], }, { @@ -376,6 +518,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ modelSelection: CURSOR_MODEL_SELECTION, assertOutput: assertCursorMessageSteeringOutput, }, + { + provider: "grok", + transcriptFile: new URL("./message_steering/grok_transcript.ndjson", import.meta.url), + modelSelection: GROK_MODEL_SELECTION, + assertOutput: assertGrokMessageSteeringOutput, + }, + { + provider: "acpRegistry", + transcriptFile: new URL("./message_steering/grok_transcript.ndjson", import.meta.url), + modelSelection: ACP_REGISTRY_MODEL_SELECTION, + assertOutput: assertGrokMessageSteeringOutput, + }, ], }, { @@ -396,6 +550,27 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ runtimePolicyOverride: WORKSPACE_NEVER_POLICY, assertOutput: assertTurnInterruptClaudeOutput, }, + { + provider: "grok", + transcriptFile: new URL("./turn_interrupt/grok_transcript.ndjson", import.meta.url), + modelSelection: GROK_MODEL_SELECTION, + runtimePolicyOverride: WORKSPACE_NEVER_POLICY, + assertOutput: assertTurnInterruptOutput, + }, + { + provider: "acpRegistry", + transcriptFile: new URL("./turn_interrupt/grok_transcript.ndjson", import.meta.url), + modelSelection: ACP_REGISTRY_MODEL_SELECTION, + runtimePolicyOverride: WORKSPACE_NEVER_POLICY, + assertOutput: assertTurnInterruptOutput, + }, + { + provider: "opencode", + transcriptFile: new URL("./turn_interrupt/opencode_transcript.ndjson", import.meta.url), + modelSelection: OPENCODE_MODEL_SELECTION, + runtimePolicyOverride: WORKSPACE_NEVER_POLICY, + assertOutput: assertTurnInterruptOutput, + }, ], }, { diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/grok_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/grok_output.ts new file mode 100644 index 0000000000..7fbd5d1f64 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/grok_output.ts @@ -0,0 +1,54 @@ +import { assert } from "@effect/vitest"; +import type { ProviderReplayTranscript } from "@t3tools/contracts"; + +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts"; +import { + assertAssistantTextIncludes, + assertBaseProjection, + assertRuntimeRequestCounts, + assertSemanticProjectionIntegrity, + assertTurnItemTypes, + assertUserMessageInputIntents, + assertUserMessagesInclude, + MESSAGE_STEERING_INITIAL_PROMPT, + MESSAGE_STEERING_STEER_PROMPT, + projectionFor, +} from "../shared.ts"; + +export function assertGrokMessageSteeringOutput( + result: OrchestratorV2ScenarioResult, + transcript: ProviderReplayTranscript, +) { + assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] }); + + const projection = projectionFor(result, transcript.scenario); + assertSemanticProjectionIntegrity(projection); + assertTurnItemTypes(projection, ["user_message", "run_interrupt_result", "assistant_message"]); + assertRuntimeRequestCounts(projection, { total: 0 }); + assertUserMessagesInclude(projection, [ + MESSAGE_STEERING_INITIAL_PROMPT, + MESSAGE_STEERING_STEER_PROMPT, + ]); + assertUserMessageInputIntents(projection, ["turn_start", "steer"]); + assertAssistantTextIncludes(projection, "steering fixture observed"); + + assert.lengthOf(projection.runs, 1, "steering must preserve the app run"); + assert.deepEqual( + projection.attempts.map((attempt) => [attempt.reason, attempt.status]), + [ + ["initial", "superseded"], + ["steering_restart", "completed"], + ], + ); + assert.deepEqual( + projection.providerTurns.map((turn) => turn.status), + ["interrupted", "completed"], + ); + assert.equal(projection.runs[0]?.activeAttemptId, projection.attempts[1]?.id); + assert.equal(projection.runs[0]?.rootNodeId, projection.attempts[1]?.rootNodeId); + assert.notInclude( + projection.visibleTurnItems.map((row) => row.item.type), + "run_interrupt_result", + "restart steering must keep its internal interruption out of visible chat history", + ); +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/grok_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/grok_transcript.ndjson new file mode 100644 index 0000000000..b50308c07f --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/grok_transcript.ndjson @@ -0,0 +1,14 @@ +{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"message_steering","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}} +{"type":"expect_outbound","label":"session.prompt.1","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with exactly: steering fixture initial response"}]}}} +{"type":"emit_inbound","label":"assistant.partial","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ste"}}}}} +{"type":"expect_outbound","label":"session.cancel","frame":{"kind":"notification","method":"session/cancel","params":{"sessionId":"grok-replay-session-1"}}} +{"type":"emit_inbound","label":"prompt.cancelled","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"cancelled"}}} +{"type":"expect_outbound","label":"session.prompt.2","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Actually, respond with exactly: steering fixture observed"}]}}} +{"type":"emit_inbound","label":"assistant.1","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"steering fixture "}}}}} +{"type":"emit_inbound","label":"assistant.2","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"observed"}}}}} +{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/grok_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/grok_transcript.ndjson new file mode 100644 index 0000000000..541d21f79c --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/grok_transcript.ndjson @@ -0,0 +1,12 @@ +{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"multi_turn","metadata":{"generatedBy":"protocol-semantic-fixture","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}} +{"type":"expect_outbound","label":"first.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with exactly: first fixture turn complete"}]}}} +{"type":"emit_inbound","label":"first.assistant","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"first fixture turn complete"}}}}} +{"type":"emit_inbound","label":"first.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"expect_outbound","label":"second.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with exactly: second fixture turn complete"}]}}} +{"type":"emit_inbound","label":"second.assistant","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"second fixture turn complete"}}}}} +{"type":"emit_inbound","label":"second.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/input.ts b/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/input.ts new file mode 100644 index 0000000000..29fdd8910b --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/input.ts @@ -0,0 +1,7 @@ +import { OPENCODE_SUBAGENT_PROMPT, type OrchestratorFixtureInput } from "../shared.ts"; + +export function openCodeSubagentInput(): OrchestratorFixtureInput { + return { + steps: [{ type: "message", text: OPENCODE_SUBAGENT_PROMPT }], + }; +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/opencode_transcript.ndjson new file mode 100644 index 0000000000..f825179964 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/opencode_transcript.ndjson @@ -0,0 +1,30 @@ +{"type":"transcript_start","provider":"opencode","protocol":"opencode-sdk.sse","version":"1.14.39","scenario":"opencode_subagent","metadata":{"source":"authenticated-opencode-sdk-probe","capturedAt":"2026-06-18","nativeSessionId":"ses_1235df8f8ffekByXP7gVnnXA3P","nativeChildSessionId":"ses_1235debc9ffe9MNk00UheV2j0q","model":"openai/gpt-5.4-mini","description":"One real OpenCode task-tool delegation. The session.update boundary records the adapter policy propagation required before projecting buffered child events."}} +{"type":"expect_outbound","label":"event.subscribe","frame":{"type":"event.subscribe"}} +{"type":"expect_outbound","label":"session.create","frame":{"type":"session.create","input":{"title":"","permission":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"type":"sdk.response","operation":"session.create","data":{"id":"ses_1235df8f8ffekByXP7gVnnXA3P","slug":"kind-tiger","version":"1.14.39","projectID":"global","directory":"/private/tmp/t3-opencode-probe","path":"private/tmp/t3-opencode-probe","title":"T3 OpenCode v2 probe","time":{"created":1781818066695,"updated":1781818066695}}}} +{"type":"expect_outbound","label":"session.promptAsync","frame":{"type":"session.promptAsync","input":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"agent":"build","parts":[{"type":"text","text":"Use the task tool exactly once. Delegate to the general subagent with this prompt: Respond exactly CHILD_OK. After the task completes, respond exactly PARENT_OK."}]}}} +{"type":"emit_inbound","label":"session.promptAsync.response","frame":{"type":"sdk.response","operation":"session.promptAsync","data":null}} +{"type":"emit_inbound","label":"root.user","frame":{"type":"sdk.event","event":{"id":"evt_edca20735003a32yj1UtyUpHkU","type":"message.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","info":{"id":"msg_edca20735001Esh39V762TEx7f","role":"user","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","time":{"created":1781818066741},"agent":"build","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}} +{"type":"emit_inbound","label":"root.user.text","frame":{"type":"sdk.event","event":{"id":"evt_edca207360015UIWeYXmKllHo3","type":"message.part.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","part":{"type":"text","text":"Use the task tool exactly once. Delegate to the general subagent with this prompt: Respond exactly CHILD_OK. After the task completes, respond exactly PARENT_OK.","messageID":"msg_edca20735001Esh39V762TEx7f","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","id":"prt_edca20735002U603TIFRMOYd9M"},"time":1781818066742}}}} +{"type":"emit_inbound","label":"root.busy","frame":{"type":"sdk.event","event":{"id":"evt_edca207370013ecC1B3n7HWHF0","type":"session.status","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","status":{"type":"busy"}}}}} +{"type":"emit_inbound","label":"root.assistant.tool-step","frame":{"type":"sdk.event","event":{"id":"evt_edca207380024rQ5C0LdF5jkgv","type":"message.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","info":{"id":"msg_edca20738001L0AkDDqxC8ipdK","parentID":"msg_edca20735001Esh39V762TEx7f","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818066744},"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P"}}}}} +{"type":"emit_inbound","label":"task.pending","frame":{"type":"sdk.event","event":{"id":"evt_edca213fb002A7172u3WxPY2Jy","type":"message.part.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","part":{"id":"prt_edca213fb001pDRIA33EBmsHOT","messageID":"msg_edca20738001L0AkDDqxC8ipdK","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","type":"tool","tool":"task","callID":"call_MMPbMUvLDj12T5aimkDZC8Sl","state":{"status":"pending","input":{},"raw":""}},"time":1781818070011}}}} +{"type":"emit_inbound","label":"task.running","frame":{"type":"sdk.event","event":{"id":"evt_edca21438001pcNOWgyXdKFyaI","type":"message.part.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","part":{"type":"tool","tool":"task","callID":"call_MMPbMUvLDj12T5aimkDZC8Sl","state":{"title":"Return CHILD_OK","metadata":{"sessionId":"ses_1235debc9ffe9MNk00UheV2j0q","model":{"modelID":"gpt-5.4-mini","providerID":"openai"}},"status":"running","input":{"description":"Return CHILD_OK","prompt":"Respond exactly CHILD_OK.","subagent_type":"general","task_id":"","command":"delegate exact response"},"time":{"start":1781818070072}},"id":"prt_edca213fb001pDRIA33EBmsHOT","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","messageID":"msg_edca20738001L0AkDDqxC8ipdK"},"time":1781818070072}}}} +{"type":"expect_outbound","label":"session.get.child-policy","frame":{"type":"session.get","input":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q"}}} +{"type":"emit_inbound","label":"session.get.child-policy.response","frame":{"type":"sdk.response","operation":"session.get","data":{"id":"ses_1235debc9ffe9MNk00UheV2j0q","slug":"tidy-engine","projectID":"global","directory":"/private/tmp/t3-opencode-probe","path":"private/tmp/t3-opencode-probe","parentID":"ses_1235df8f8ffekByXP7gVnnXA3P","title":"Return CHILD_OK (@general subagent)","version":"1.14.39","permission":[{"permission":"task","action":"deny","pattern":"*"}],"time":{"created":1781818070070,"updated":1781818070072}}}} +{"type":"expect_outbound","label":"session.update.child-policy","frame":{"type":"session.update","input":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","permission":""}}} +{"type":"emit_inbound","label":"session.update.child-policy.response","frame":{"type":"sdk.response","operation":"session.update","data":{"id":"ses_1235debc9ffe9MNk00UheV2j0q","permission":[{"permission":"*","pattern":"*","action":"allow"},{"permission":"task","pattern":"*","action":"deny"}]}}} +{"type":"emit_inbound","label":"child.user","frame":{"type":"sdk.event","event":{"id":"evt_edca21439002NEQt3QTkDp4ENI","type":"message.updated","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","info":{"id":"msg_edca21438002r6NiMUSoqNKyyO","role":"user","sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","time":{"created":1781818070073},"tools":{"task":false},"agent":"general","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}} +{"type":"emit_inbound","label":"child.user.text","frame":{"type":"sdk.event","event":{"id":"evt_edca21439003pseKePjnoGiTMW","type":"message.part.updated","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","part":{"type":"text","text":"Respond exactly CHILD_OK.","messageID":"msg_edca21438002r6NiMUSoqNKyyO","sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","id":"prt_edca214390014Naiz0G5HjlDbr"},"time":1781818070073}}}} +{"type":"emit_inbound","label":"child.busy","frame":{"type":"sdk.event","event":{"id":"evt_edca2143c0013lzfo6Odo5FMzE","type":"session.status","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","status":{"type":"busy"}}}}} +{"type":"emit_inbound","label":"child.assistant","frame":{"type":"sdk.event","event":{"id":"evt_edca2143c0033666Mhyl3cAlhK","type":"message.updated","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","info":{"id":"msg_edca2143c002Eu46Ey4Vg2BbuM","parentID":"msg_edca21438002r6NiMUSoqNKyyO","role":"assistant","mode":"general","agent":"general","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818070076},"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q"}}}}} +{"type":"emit_inbound","label":"child.assistant.text","frame":{"type":"sdk.event","event":{"id":"evt_edca21a3f001VbjReH1JvfruIc","type":"message.part.updated","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","part":{"id":"prt_edca21a22001xAMVOfMPeu3Pe5","messageID":"msg_edca2143c002Eu46Ey4Vg2BbuM","sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","type":"text","text":"CHILD_OK","time":{"start":1781818071586,"end":1781818071615},"metadata":{"openai":{"itemId":"msg_08dabd7d4c704130016a3462d793f48196a3764bab4f871b8d","phase":"final_answer"}}},"time":1781818071615}}}} +{"type":"emit_inbound","label":"child.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edca21a5d001RVnmfbE88crcg3","type":"message.updated","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","info":{"id":"msg_edca2143c002Eu46Ey4Vg2BbuM","parentID":"msg_edca21438002r6NiMUSoqNKyyO","role":"assistant","mode":"general","agent":"general","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":7538,"input":7515,"output":9,"reasoning":14,"cache":{"write":0,"read":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818070076,"completed":1781818071645},"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","finish":"stop"}}}}} +{"type":"emit_inbound","label":"child.idle","frame":{"type":"sdk.event","event":{"id":"evt_edca21a5d0033WtPpZQdeaACpg","type":"session.status","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","status":{"type":"idle"}}}}} +{"type":"emit_inbound","label":"task.completed","frame":{"type":"sdk.event","event":{"id":"evt_edca21a5e001nGDHspvGlDIOu3","type":"message.part.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","part":{"type":"tool","tool":"task","callID":"call_MMPbMUvLDj12T5aimkDZC8Sl","state":{"status":"completed","input":{"description":"Return CHILD_OK","prompt":"Respond exactly CHILD_OK.","subagent_type":"general","task_id":"","command":"delegate exact response"},"output":"task_id: ses_1235debc9ffe9MNk00UheV2j0q (for resuming to continue this task if needed)\n\n\nCHILD_OK\n","metadata":{"sessionId":"ses_1235debc9ffe9MNk00UheV2j0q","model":{"modelID":"gpt-5.4-mini","providerID":"openai"},"truncated":false},"title":"Return CHILD_OK","time":{"start":1781818070075,"end":1781818071646}},"metadata":{"openai":{"itemId":"fc_0f59e88787b4bf7e016a3462d5f5d08196893b4fa241992c81"}},"id":"prt_edca213fb001pDRIA33EBmsHOT","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","messageID":"msg_edca20738001L0AkDDqxC8ipdK"},"time":1781818071646}}}} +{"type":"emit_inbound","label":"root.assistant.tool-step.completed","frame":{"type":"sdk.event","event":{"id":"evt_edca21a5f001I6X2xOrOgrkGi4","type":"message.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","info":{"id":"msg_edca20738001L0AkDDqxC8ipdK","parentID":"msg_edca20735001Esh39V762TEx7f","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":10945,"input":10835,"output":43,"reasoning":67,"cache":{"write":0,"read":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818066744,"completed":1781818071647},"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","finish":"tool-calls"}}}}} +{"type":"emit_inbound","label":"root.assistant.final-step","frame":{"type":"sdk.event","event":{"id":"evt_edca21a5f004jTKIwlcQchMbZY","type":"message.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","info":{"id":"msg_edca21a5f003lreMfrQqG0qWIe","parentID":"msg_edca20735001Esh39V762TEx7f","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818071647},"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P"}}}}} +{"type":"emit_inbound","label":"root.assistant.text","frame":{"type":"sdk.event","event":{"id":"evt_edca21e36001X0l8t5UPa1gOe3","type":"message.part.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","part":{"id":"prt_edca21d9e001I40GbbzvlzhQ6Z","messageID":"msg_edca21a5f003lreMfrQqG0qWIe","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","type":"text","text":"PARENT_OK","time":{"start":1781818072478,"end":1781818072630},"metadata":{"openai":{"itemId":"msg_06e59296cb53fc7c016a3462d879288196aead5e9838c741df","phase":"final_answer"}}},"time":1781818072630}}}} +{"type":"emit_inbound","label":"root.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edca21e3800181OyYIBTDTTK3r","type":"message.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","info":{"id":"msg_edca21a5f003lreMfrQqG0qWIe","parentID":"msg_edca20735001Esh39V762TEx7f","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":11007,"input":248,"output":7,"reasoning":0,"cache":{"write":0,"read":10752}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818071647,"completed":1781818072632},"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","finish":"stop"}}}}} +{"type":"emit_inbound","label":"root.idle","frame":{"type":"sdk.event","event":{"id":"evt_edca21e39001lo71BB2Ym4WFC2","type":"session.status","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","status":{"type":"idle"}}}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/output.ts new file mode 100644 index 0000000000..e50f12bad8 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/output.ts @@ -0,0 +1,71 @@ +import { assert } from "@effect/vitest"; +import type { ProviderReplayTranscript } from "@t3tools/contracts"; + +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts"; +import { + assertAssistantTextIncludes, + assertBaseProjection, + assertExecutionNodeKinds, + assertNoExtraAppRunsForProviderChildren, + assertRunProviderTurnCardinality, + assertSemanticProjectionIntegrity, + assertTurnItemTypes, + assertUserMessagesInclude, + OPENCODE_SUBAGENT_PROMPT, + projectionFor, +} from "../shared.ts"; + +export function assertOpenCodeSubagentOutput( + result: OrchestratorV2ScenarioResult, + transcript: ProviderReplayTranscript, +) { + assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] }); + + const projection = projectionFor(result, transcript.scenario); + assertSemanticProjectionIntegrity(projection); + assertExecutionNodeKinds(projection, ["root_turn", "subagent", "assistant_message"]); + assertTurnItemTypes(projection, ["user_message", "subagent", "assistant_message"]); + assertRunProviderTurnCardinality({ projection, rootRunCount: 1 }); + assertNoExtraAppRunsForProviderChildren({ projection, expectedAppRuns: 1 }); + assertUserMessagesInclude(projection, [OPENCODE_SUBAGENT_PROMPT]); + assertAssistantTextIncludes(projection, "PARENT_OK"); + + assert.lengthOf(projection.subagents, 1); + assert.lengthOf(result.shellSnapshot.threads, 2); + const subagent = projection.subagents[0]; + assert.isDefined(subagent); + assert.equal(subagent.origin, "provider_native"); + assert.equal(subagent.createdBy, "agent"); + assert.equal(subagent.provider, "opencode"); + assert.equal(subagent.status, "completed"); + assert.equal(subagent.prompt, "Respond exactly CHILD_OK."); + assert.include(subagent.result ?? "", "CHILD_OK"); + assert.isNotNull(subagent.childThreadId); + assert.isNotNull(subagent.providerThreadId); + assert.isNotNull(subagent.nativeTaskRef); + assert.isNotNull(subagent.completedAt); + if (subagent.childThreadId === null || subagent.providerThreadId === null) { + throw new Error("OpenCode subagent is missing its child thread identity"); + } + + const providerThread = projection.providerThreads.find( + (thread) => thread.id === subagent.providerThreadId, + ); + assert.isDefined(providerThread); + assert.equal(providerThread.appThreadId, subagent.childThreadId); + assert.equal(providerThread.ownerNodeId, subagent.id); + + const childProjection = result.projections.get(subagent.childThreadId); + assert.isDefined(childProjection); + assert.equal(childProjection.thread.lineage.parentThreadId, projection.thread.id); + assert.equal(childProjection.thread.lineage.relationshipToParent, "subagent"); + assert.equal(childProjection.thread.activeProviderThreadId, providerThread.id); + assert.lengthOf(childProjection.runs, 0); + assert.lengthOf(childProjection.providerThreads, 1); + assert.lengthOf(childProjection.providerTurns, 1); + assert.equal(childProjection.providerTurns[0]?.status, "completed"); + assertExecutionNodeKinds(childProjection, ["root_turn", "assistant_message"]); + assertTurnItemTypes(childProjection, ["user_message", "assistant_message"]); + assertUserMessagesInclude(childProjection, ["Respond exactly CHILD_OK."]); + assertAssistantTextIncludes(childProjection, "CHILD_OK"); +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_output.ts index 3f6e1a5313..8b1abc5c4d 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_output.ts @@ -18,7 +18,7 @@ import { projectionFor, } from "../shared.ts"; -export function assertPlanQuestionsOutput( +export function assertPlanQuestionsOutputBase( result: OrchestratorV2ScenarioResult, transcript: ProviderReplayTranscript, ) { @@ -35,7 +35,15 @@ export function assertPlanQuestionsOutput( assertTurnItemTypes(projection, ["user_message", "user_input_request", "assistant_message"]); assertUserMessagesInclude(projection, [PLAN_QUESTIONS_PROMPT]); assertAssistantTextIncludes(projection, "plan questions fixture complete"); +} +export function assertPlanQuestionsOutput( + result: OrchestratorV2ScenarioResult, + transcript: ProviderReplayTranscript, +) { + assertPlanQuestionsOutputBase(result, transcript); + + const projection = projectionFor(result, transcript.scenario); const requestItem = projection.turnItems.find((item) => item.type === "user_input_request"); assert.isDefined(requestItem); assert.equal(requestItem?.questions[0]?.id, "schema_vs_ui_flexibility"); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/grok_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/grok_transcript.ndjson new file mode 100644 index 0000000000..be5d2bb29f --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/grok_transcript.ndjson @@ -0,0 +1,11 @@ +{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"plan_questions","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}} +{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete"}]}}} +{"type":"emit_inbound","label":"question.request","frame":{"kind":"request","method":"_x.ai/ask_user_question","params":{"method":"x.ai/ask_user_question","params":{"sessionId":"grok-replay-session-1","toolCallId":"ask-user-question-tool-call-1","questions":[{"id":"schema_vs_ui_flexibility","question":"For this fixture, should the plan prefer strict schemas or UI flexibility?","multiSelect":null,"options":[{"label":"Strict schemas (Recommended)","description":"Favor precise contracts and validation."},{"label":"UI flexibility","description":"Favor looser fixture shapes."}]}],"mode":"plan"}}}} +{"type":"expect_outbound","label":"question.response","frame":{"kind":"response","method":"_x.ai/ask_user_question","result":{"outcome":"accepted","answers":{"For this fixture, should the plan prefer strict schemas or UI flexibility?":["Strict schemas (Recommended)"]}}}} +{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"plan questions fixture complete"}}}}} +{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/input.ts b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/input.ts index 7c8f06d4e5..a3442ca6f5 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/input.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/input.ts @@ -9,6 +9,7 @@ export function planQuestionsInput(): OrchestratorFixtureInput { type: "answer_next_user_input_request", answers: { schema_vs_ui_flexibility: "Strict schemas (Recommended)", + "question-0-schema-vs-flexibility": "Strict schemas", }, }, ], diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/opencode_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/opencode_output.ts new file mode 100644 index 0000000000..790b74379b --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/opencode_output.ts @@ -0,0 +1,26 @@ +import { assert } from "@effect/vitest"; +import type { ProviderReplayTranscript } from "@t3tools/contracts"; + +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts"; +import { assertPlanQuestionsOutputBase } from "./codex_output.ts"; +import { projectionFor } from "../shared.ts"; + +export function assertOpenCodePlanQuestionsOutput( + result: OrchestratorV2ScenarioResult, + transcript: ProviderReplayTranscript, +) { + // The shared assertions cover the runtime-request lifecycle. OpenCode owns + // its question identifiers, so assert its normalized native header instead + // of Codex's fixture-specific id. + assertPlanQuestionsOutputBase(result, transcript); + const projection = projectionFor(result, transcript.scenario); + const requestItem = projection.turnItems.find((item) => item.type === "user_input_request"); + assert.equal(requestItem?.questions[0]?.id, "question-0-schema-vs-flexibility"); + assert.equal(requestItem?.status, "completed"); + assert.lengthOf( + projection.turnItems.filter( + (item) => item.type === "dynamic_tool" && item.toolName === "question", + ), + 0, + ); +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/opencode_transcript.ndjson new file mode 100644 index 0000000000..c6e7bb8e53 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/opencode_transcript.ndjson @@ -0,0 +1,23 @@ +{"type":"transcript_start","provider":"opencode","protocol":"opencode-sdk.sse","version":"1.14.39","scenario":"plan_questions","metadata":{"source":"authenticated-opencode-sdk-probe","capturedAt":"2026-06-18","nativeSessionId":"ses_12369ea4cffePl0BsyVg3hGlmZ","model":"openai/gpt-5.4-mini","filteredToRelevantEvents":true,"description":"Real structured-question request/reply and continuation across two assistant steps."}} +{"type":"expect_outbound","label":"event.subscribe","frame":{"type":"event.subscribe"}} +{"type":"expect_outbound","label":"session.create","frame":{"type":"session.create","input":{"title":"","permission":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"type":"sdk.response","operation":"session.create","data":{"id":"ses_12369ea4cffePl0BsyVg3hGlmZ","slug":"mighty-harbor","version":"1.14.39","projectID":"global","directory":"/private/tmp/t3-opencode-probe","path":"private/tmp/t3-opencode-probe","title":"T3 OpenCode v2 probe","time":{"created":1781817284019,"updated":1781817284019}}}} +{"type":"expect_outbound","label":"session.promptAsync","frame":{"type":"session.promptAsync","input":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"agent":"build","parts":[{"type":"text","text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete"}]}}} +{"type":"emit_inbound","label":"message.updated.user","frame":{"type":"sdk.event","event":{"id":"evt_edc9615bb003WEUXUNfpZxMZDD","type":"message.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","info":{"id":"msg_edc9615bb001iCnWab1qzSeRA3","role":"user","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","time":{"created":1781817284027},"agent":"build","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}} +{"type":"emit_inbound","label":"message.part.updated.user","frame":{"type":"sdk.event","event":{"id":"evt_edc9615bc001l8KO7edlPViXO0","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"type":"text","text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete","messageID":"msg_edc9615bb001iCnWab1qzSeRA3","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","id":"prt_edc9615bb002fjGpO5oeQE22B9"},"time":1781817284028}}}} +{"type":"emit_inbound","label":"session.promptAsync.response","frame":{"type":"sdk.response","operation":"session.promptAsync","data":null}} +{"type":"emit_inbound","label":"session.status.busy","frame":{"type":"sdk.event","event":{"id":"evt_edc9615bd0012brtruCEXYmNyX","type":"session.status","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","status":{"type":"busy"}}}}} +{"type":"emit_inbound","label":"message.updated.assistant","frame":{"type":"sdk.event","event":{"id":"evt_edc9615bd003GQj8GzeHgoMlZ2","type":"message.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","info":{"id":"msg_edc9615bd002qb49gh9N1krbX2","parentID":"msg_edc9615bb001iCnWab1qzSeRA3","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781817284029},"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ"}}}}} +{"type":"emit_inbound","label":"reasoning.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc96244e001ez77NBs6gJaPZh","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"id":"prt_edc961988001aollEeE48XSJDg","messageID":"msg_edc9615bd002qb49gh9N1krbX2","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","type":"reasoning","text":"Clarifying user input before asking the structured question.","time":{"start":1781817285000,"end":1781817287757}},"time":1781817287757}}}} +{"type":"emit_inbound","label":"question.tool.pending","frame":{"type":"sdk.event","event":{"id":"evt_edc96244e003ljcUzfVu0WTFc2","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"id":"prt_edc96244e002RBYg9ASwc10E8R","messageID":"msg_edc9615bd002qb49gh9N1krbX2","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","type":"tool","tool":"question","callID":"call_XU0dxWGu2ioLZscBtYAIqGfT","state":{"status":"pending","input":{},"raw":""}},"time":1781817287758}}}} +{"type":"emit_inbound","label":"question.asked","frame":{"type":"sdk.event","event":{"id":"evt_edc9624d90022x2I3Rv9S6t1tt","type":"question.asked","properties":{"id":"que_edc9624d9001e2GFKX724Z8b5Z","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","questions":[{"question":"Should this fixture prefer strict schemas or UI flexibility?","header":"Schema vs Flexibility","options":[{"label":"Strict schemas","description":"Prioritize validation and exact structure over visual freedom."},{"label":"UI flexibility","description":"Prioritize adaptable rendering and tolerant input handling."}],"multiple":false}],"tool":{"messageID":"msg_edc9615bd002qb49gh9N1krbX2","callID":"call_XU0dxWGu2ioLZscBtYAIqGfT"}}}}} +{"type":"expect_outbound","label":"question.reply","frame":{"type":"question.reply","input":{"requestID":"que_edc9624d9001e2GFKX724Z8b5Z","answers":[["Strict schemas"]]}}} +{"type":"emit_inbound","label":"question.reply.response","frame":{"type":"sdk.response","operation":"question.reply","data":true}} +{"type":"emit_inbound","label":"question.tool.running","frame":{"type":"sdk.event","event":{"id":"evt_edc9624da001qamTLzcYoY2CPY","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"type":"tool","tool":"question","callID":"call_XU0dxWGu2ioLZscBtYAIqGfT","state":{"status":"running","input":{"questions":[{"question":"Should this fixture prefer strict schemas or UI flexibility?","header":"Schema vs Flexibility","options":[{"label":"Strict schemas","description":"Prioritize validation and exact structure over visual freedom."},{"label":"UI flexibility","description":"Prioritize adaptable rendering and tolerant input handling."}],"multiple":false}]},"raw":"","time":{"start":1781817287898}},"id":"prt_edc96244e002RBYg9ASwc10E8R","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","messageID":"msg_edc9615bd002qb49gh9N1krbX2"},"time":1781817287898}}}} +{"type":"emit_inbound","label":"question.replied","frame":{"type":"sdk.event","event":{"id":"evt_edc9624de001JBbX1qaXzgfeKl","type":"question.replied","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","requestID":"que_edc9624d9001e2GFKX724Z8b5Z","answers":[["Strict schemas"]]}}}} +{"type":"emit_inbound","label":"question.tool.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc9624df001Pw6H7GGa8tCa3V","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"type":"tool","tool":"question","callID":"call_XU0dxWGu2ioLZscBtYAIqGfT","state":{"status":"completed","input":{"questions":[{"question":"Should this fixture prefer strict schemas or UI flexibility?","header":"Schema vs Flexibility","options":[{"label":"Strict schemas","description":"Prioritize validation and exact structure over visual freedom."},{"label":"UI flexibility","description":"Prioritize adaptable rendering and tolerant input handling."}],"multiple":false}]},"output":"User answered: Strict schemas","metadata":{"answers":[["Strict schemas"]],"truncated":false},"title":"Asked 1 question","time":{"start":1781817287898,"end":1781817287903}},"id":"prt_edc96244e002RBYg9ASwc10E8R","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","messageID":"msg_edc9615bd002qb49gh9N1krbX2"},"time":1781817287903}}}} +{"type":"emit_inbound","label":"message.updated.assistant.second-step","frame":{"type":"sdk.event","event":{"id":"evt_edc9624fa002nuPVbTfhxoDpJh","type":"message.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","info":{"id":"msg_edc9624fa0015O6R1rRjuqc4uS","parentID":"msg_edc9615bb001iCnWab1qzSeRA3","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781817287930},"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ"}}}}} +{"type":"emit_inbound","label":"assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc9628b5001owQkxpRhqtRF5N","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"id":"prt_edc962867001us1nuabvajQrgu","messageID":"msg_edc9624fa0015O6R1rRjuqc4uS","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","type":"text","text":"plan questions fixture complete","time":{"start":1781817288807,"end":1781817288885}},"time":1781817288885}}}} +{"type":"emit_inbound","label":"message.updated.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc9628bf002uUONicDkn1X7YA","type":"message.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","info":{"id":"msg_edc9624fa0015O6R1rRjuqc4uS","parentID":"msg_edc9615bb001iCnWab1qzSeRA3","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":11041,"input":281,"output":8,"reasoning":0,"cache":{"write":0,"read":10752}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781817287930,"completed":1781817288895},"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","finish":"stop"}}}}} +{"type":"emit_inbound","label":"session.status.idle","frame":{"type":"sdk.event","event":{"id":"evt_edc9628c00021lW2ZypKwU71AE","type":"session.status","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","status":{"type":"idle"}}}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/grok_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/grok_transcript.ndjson new file mode 100644 index 0000000000..a1bfc238bc --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/grok_transcript.ndjson @@ -0,0 +1,12 @@ +{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"queued_turn","metadata":{"generatedBy":"protocol-semantic-fixture","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}} +{"type":"expect_outbound","label":"first.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with exactly: first fixture turn complete"}]}}} +{"type":"emit_inbound","label":"first.assistant","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"first fixture turn complete"}}}}} +{"type":"emit_inbound","label":"first.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"expect_outbound","label":"queued.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with exactly: second fixture turn complete"}]}}} +{"type":"emit_inbound","label":"queued.assistant","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"second fixture turn complete"}}}}} +{"type":"emit_inbound","label":"queued.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts index c5be6f581a..6dbe7ae448 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts @@ -42,6 +42,8 @@ export const MESSAGE_STEERING_INITIAL_PROMPT = "Respond with exactly: steering fixture initial response"; export const SUBAGENT_PROMPT = "Spawn 2 subagents, one to read package.json and one to read tsconfig.json"; +export const OPENCODE_SUBAGENT_PROMPT = + "Use the task tool exactly once. Delegate to the general subagent with this prompt: Respond exactly CHILD_OK. After the task completes, respond exactly PARENT_OK."; export const SUBAGENT_CONTINUE_PROMPT = "Spawn one subagent and have it reply exactly: initial subagent response"; export const SUBAGENT_CONTINUE_PARENT_PROMPT = @@ -237,6 +239,22 @@ export const CURSOR_MODEL_SELECTION = { model: "composer-2.5", } satisfies ModelSelection; +export const GROK_MODEL_SELECTION = { + instanceId: ProviderInstanceId.make("grok"), + model: "grok-build", +} satisfies ModelSelection; + +export const OPENCODE_MODEL_SELECTION = { + instanceId: ProviderInstanceId.make("opencode"), + model: "openai/gpt-5.4-mini", + options: [{ id: "agent", value: "build" }], +} satisfies ModelSelection; + +export const ACP_REGISTRY_MODEL_SELECTION = { + instanceId: ProviderInstanceId.make("acpRegistry"), + model: "default", +} satisfies ModelSelection; + export const READ_ONLY_ON_REQUEST_POLICY = { approvalPolicy: "on-request", sandboxPolicy: { diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/grok_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/simple/grok_transcript.ndjson new file mode 100644 index 0000000000..15a35708bc --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/grok_transcript.ndjson @@ -0,0 +1,12 @@ +{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"simple","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"},{"modelId":"grok-composer-2.5-fast","name":"Grok Composer 2.5 Fast"}]}}}} +{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with the following text: fixture simple ok"}]}}} +{"type":"emit_inbound","label":"reasoning.1","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"I should "}}}}} +{"type":"emit_inbound","label":"reasoning.2","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"answer exactly."}}}}} +{"type":"emit_inbound","label":"assistant.1","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"fixture simple "}}}}} +{"type":"emit_inbound","label":"assistant.2","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ok"}}}}} +{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/simple/opencode_transcript.ndjson new file mode 100644 index 0000000000..b38d99658b --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/opencode_transcript.ndjson @@ -0,0 +1,19 @@ +{"type":"transcript_start","provider":"opencode","protocol":"opencode-sdk.sse","version":"1.14.39","scenario":"simple","metadata":{"source":"authenticated-opencode-sdk-probe","capturedAt":"2026-06-18","nativeSessionId":"ses_1236c522dffeunHBidt20OIzWc","model":"openai/gpt-5.4-mini","description":"One real OpenCode session and text-only turn, captured at the SDK request/SSE boundary."}} +{"type":"expect_outbound","label":"event.subscribe","frame":{"type":"event.subscribe"}} +{"type":"expect_outbound","label":"session.create","frame":{"type":"session.create","input":{"title":"","permission":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"type":"sdk.response","operation":"session.create","data":{"id":"ses_1236c522dffeunHBidt20OIzWc","slug":"shiny-tiger","version":"1.14.39","projectID":"global","directory":"/private/tmp/t3-opencode-probe","path":"private/tmp/t3-opencode-probe","title":"T3 OpenCode v2 probe","time":{"created":1781817126354,"updated":1781817126354}}}} +{"type":"expect_outbound","label":"session.promptAsync","frame":{"type":"session.promptAsync","input":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"agent":"build","parts":[{"type":"text","text":"Respond with the following text: fixture simple ok"}]}}} +{"type":"emit_inbound","label":"session.promptAsync.response","frame":{"type":"sdk.response","operation":"session.promptAsync","data":null}} +{"type":"emit_inbound","label":"message.updated.user","frame":{"type":"sdk.event","event":{"id":"evt_edc93ade5002giWB7gMKgKTh1N","type":"message.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","info":{"role":"user","time":{"created":1781817126365},"agent":"build","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"id":"msg_edc93addd001jzzrE6lotn7BJj","sessionID":"ses_1236c522dffeunHBidt20OIzWc","summary":{"diffs":[]}}}}}} +{"type":"emit_inbound","label":"session.status.busy","frame":{"type":"sdk.event","event":{"id":"evt_edc93ade80015pjdCBdTty67tQ","type":"session.status","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","status":{"type":"busy"}}}}} +{"type":"emit_inbound","label":"step-start","frame":{"type":"sdk.event","event":{"id":"evt_edc93b29c002bOE0jF6Ngtp9WQ","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b29c001e2RRrSU0wC3EBK","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"step-start"},"time":1781817127580}}}} +{"type":"emit_inbound","label":"reasoning.started","frame":{"type":"sdk.event","event":{"id":"evt_edc93b3ac002IjQHVrdbEr0grF","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b3ac0018TDuhzb5SgaTNW","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"reasoning","text":"","time":{"start":1781817127852},"metadata":{"openai":{"itemId":"rs_0cebf1703d45601c016a345f27cd448193bf5ca8d64792912b","reasoningEncryptedContent":""}}},"time":1781817127852}}}} +{"type":"emit_inbound","label":"reasoning.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5b7001F8JgWVWz3axRi4","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b3ac0018TDuhzb5SgaTNW","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"reasoning","text":"","time":{"start":1781817127852,"end":1781817128375},"metadata":{"openai":{"itemId":"rs_0cebf1703d45601c016a345f27cd448193bf5ca8d64792912b","reasoningEncryptedContent":""}}},"time":1781817128375}}}} +{"type":"emit_inbound","label":"assistant.started","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5b8002b8hqk8j4ycOQDv","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b5b8001T13mKZn2DRRWdH","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"text","text":"","time":{"start":1781817128376},"metadata":{"openai":{"itemId":"msg_0cebf1703d45601c016a345f284b7c819398d57b692541e5a1","phase":"final_answer"}}},"time":1781817128376}}}} +{"type":"emit_inbound","label":"assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5b90010jWiRMyH8CF4tS","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b5b8001T13mKZn2DRRWdH","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"text","text":"fixture simple ok","time":{"start":1781817128376,"end":1781817128377},"metadata":{"openai":{"itemId":"msg_0cebf1703d45601c016a345f284b7c819398d57b692541e5a1","phase":"final_answer"}}},"time":1781817128377}}}} +{"type":"emit_inbound","label":"step-finish","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5d500236244jGWEFb6ac","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b5d5001CPBPBe0mxI1DbU","reason":"stop","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"step-finish","tokens":{"total":10837,"input":571,"output":9,"reasoning":17,"cache":{"write":0,"read":10240}},"cost":0},"time":1781817128405}}}} +{"type":"emit_inbound","label":"message.updated.assistant","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5d6001bMOQP8gbJZ0od6","type":"message.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","info":{"id":"msg_edc93ade1001nkGj5Jt1JAd8nq","parentID":"msg_edc93addd001jzzrE6lotn7BJj","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":10837,"input":571,"output":9,"reasoning":17,"cache":{"write":0,"read":10240}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781817126369},"sessionID":"ses_1236c522dffeunHBidt20OIzWc","finish":"stop"}}}}} +{"type":"emit_inbound","label":"message.updated.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5d7001XXJei8Ixk5qMHN","type":"message.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","info":{"id":"msg_edc93ade1001nkGj5Jt1JAd8nq","parentID":"msg_edc93addd001jzzrE6lotn7BJj","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":10837,"input":571,"output":9,"reasoning":17,"cache":{"write":0,"read":10240}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781817126369,"completed":1781817128407},"sessionID":"ses_1236c522dffeunHBidt20OIzWc","finish":"stop"}}}}} +{"type":"emit_inbound","label":"session.status.busy.finalizing","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5d7002NYE00v0LorwLmf","type":"session.status","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","status":{"type":"busy"}}}}} +{"type":"emit_inbound","label":"session.status.idle","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5d8001wkyQQVJNv3M9vP","type":"session.status","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","status":{"type":"idle"}}}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/grok_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/grok_output.ts new file mode 100644 index 0000000000..d9e778e28d --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/grok_output.ts @@ -0,0 +1,49 @@ +import { assert } from "@effect/vitest"; +import type { ProviderReplayTranscript } from "@t3tools/contracts"; + +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts"; +import { + assertAssistantTextIncludes, + assertBaseProjection, + assertExecutionNodeKinds, + assertSemanticProjectionIntegrity, + assertTurnItemTypes, + assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, + projectionFor, + TODO_LIST_PROMPT, +} from "../shared.ts"; + +export function assertTodoListGrokOutput( + result: OrchestratorV2ScenarioResult, + transcript: ProviderReplayTranscript, +) { + assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] }); + + const projection = projectionFor(result, transcript.scenario); + assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); + assertExecutionNodeKinds(projection, ["root_turn", "todo_list", "tool_call"]); + assertTurnItemTypes(projection, [ + "user_message", + "todo_list", + "file_search", + "assistant_message", + ]); + assertUserMessagesInclude(projection, [TODO_LIST_PROMPT]); + assertAssistantTextIncludes(projection, "todo list fixture complete"); + + const planEvents = result.domainEvents.filter((event) => event.type === "plan.updated"); + assert.lengthOf(planEvents, 2); + assert.lengthOf( + new Set(planEvents.map((event) => (event.type === "plan.updated" ? event.payload.id : null))), + 1, + "ACP plan updates must preserve one plan identity", + ); + const todoLists = projection.plans.filter((plan) => plan.kind === "todo_list"); + assert.isAtLeast(todoLists.length, 1); + assert.deepEqual( + todoLists.at(-1)?.steps.map((step) => step.status), + ["completed", "completed", "completed"], + ); +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/grok_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/grok_transcript.ndjson new file mode 100644 index 0000000000..e726ac5b21 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/grok_transcript.ndjson @@ -0,0 +1,16 @@ +{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"todo_list","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}} +{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Use the update_plan tool to track exactly three steps: inspect package.json, inspect tsconfig.json, report completion. Then read package.json and tsconfig.json, and answer exactly: todo list fixture complete"}]}}} +{"type":"emit_inbound","label":"assistant.progress","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I'll track the three steps and inspect both files."}}}}} +{"type":"emit_inbound","label":"plan.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"plan","entries":[{"content":"Inspect package.json","priority":"high","status":"in_progress"},{"content":"Inspect tsconfig.json","priority":"high","status":"pending"},{"content":"Report completion","priority":"high","status":"pending"}]}}}} +{"type":"emit_inbound","label":"tool.package.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call","toolCallId":"read-package","title":"Read package.json","kind":"read","status":"pending","rawInput":{"path":"package.json"}}}}} +{"type":"emit_inbound","label":"tool.package.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"read-package","status":"completed","rawOutput":{"content":"{\"name\":\"t3\"}"}}}}} +{"type":"emit_inbound","label":"tool.tsconfig.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call","toolCallId":"read-tsconfig","title":"Read tsconfig.json","kind":"read","status":"pending","rawInput":{"path":"tsconfig.json"}}}}} +{"type":"emit_inbound","label":"tool.tsconfig.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"read-tsconfig","status":"completed","rawOutput":{"content":"{\"compilerOptions\":{}}"}}}}} +{"type":"emit_inbound","label":"plan.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"plan","entries":[{"content":"Inspect package.json","priority":"high","status":"completed"},{"content":"Inspect tsconfig.json","priority":"high","status":"completed"},{"content":"Report completion","priority":"high","status":"completed"}]}}}} +{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"todo list fixture complete"}}}}} +{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only/grok_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only/grok_transcript.ndjson new file mode 100644 index 0000000000..e0742029b6 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only/grok_transcript.ndjson @@ -0,0 +1,15 @@ +{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"tool_call_read_only","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}} +{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Read /tmp/claude-replay-tool_call_read_only/package.json and /tmp/claude-replay-tool_call_read_only/tsconfig.json, then answer exactly: read only tool fixture complete"}]}}} +{"type":"emit_inbound","label":"assistant.progress","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Reading both files now.\n"}}}}} +{"type":"emit_inbound","label":"tool.package.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call","toolCallId":"read-package","title":"Read package.json","kind":"read","status":"pending","rawInput":{"path":"/tmp/claude-replay-tool_call_read_only/package.json"}}}}} +{"type":"emit_inbound","label":"tool.package.running","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"read-package","status":"in_progress"}}}} +{"type":"emit_inbound","label":"tool.package.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"read-package","status":"completed","rawOutput":{"content":"{\"name\":\"cursor-read-only-fixture\"}"}}}}} +{"type":"emit_inbound","label":"tool.tsconfig.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call","toolCallId":"read-tsconfig","title":"Read tsconfig.json","kind":"read","status":"pending","rawInput":{"path":"/tmp/claude-replay-tool_call_read_only/tsconfig.json"}}}}} +{"type":"emit_inbound","label":"tool.tsconfig.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"read-tsconfig","status":"completed","rawOutput":{"content":"{\"compilerOptions\":{\"target\":\"ES2022\"}}"}}}}} +{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"read only tool fixture complete"}}}}} +{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/grok_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/grok_transcript.ndjson new file mode 100644 index 0000000000..b3d009f128 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/grok_transcript.ndjson @@ -0,0 +1,13 @@ +{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"tool_call_read_only_on_request","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}} +{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP."}]}}} +{"type":"emit_inbound","label":"tool.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call","toolCallId":"write-probe","title":"Write probe file","kind":"execute","status":"pending","rawInput":{"command":"printf fixture > .codex-probe-write-action.txt"}}}}} +{"type":"emit_inbound","label":"permission.request","frame":{"kind":"request","method":"session/request_permission","params":{"sessionId":"grok-replay-session-1","toolCall":{"toolCallId":"write-probe","title":"Write probe file","kind":"execute","status":"pending","content":[{"type":"content","content":{"type":"text","text":"Write .codex-probe-write-action.txt"}}]},"options":[{"optionId":"allow-once","name":"Allow once","kind":"allow_once"},{"optionId":"allow-always","name":"Allow for session","kind":"allow_always"},{"optionId":"reject-once","name":"Reject","kind":"reject_once"}]}}} +{"type":"expect_outbound","label":"permission.response","frame":{"kind":"response","method":"session/request_permission","result":{"outcome":{"outcome":"selected","optionId":"allow-once"}}}} +{"type":"emit_inbound","label":"tool.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"write-probe","status":"completed","rawOutput":{"exitCode":0,"stdout":"","stderr":""}}}}} +{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Created the requested probe file."}}}}} +{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/grok_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/grok_transcript.ndjson new file mode 100644 index 0000000000..d8496c0a55 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/grok_transcript.ndjson @@ -0,0 +1,9 @@ +{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"turn_interrupt","metadata":{"generatedBy":"protocol-semantic-fixture","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}} +{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally."}]}}} +{"type":"expect_outbound","label":"session.cancel","frame":{"kind":"notification","method":"session/cancel","params":{"sessionId":"grok-replay-session-1"}}} +{"type":"emit_inbound","label":"prompt.cancelled","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"cancelled"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/opencode_transcript.ndjson new file mode 100644 index 0000000000..14ab96d6a9 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/opencode_transcript.ndjson @@ -0,0 +1,14 @@ +{"type":"transcript_start","provider":"opencode","protocol":"opencode-sdk.sse","version":"1.14.39","scenario":"turn_interrupt","metadata":{"source":"authenticated-opencode-sdk-probe","capturedAt":"2026-06-18","nativeSessionId":"ses_123570840ffenLEumkPQfegGCd","model":"openai/gpt-5.4-mini","filteredToRelevantEvents":true,"description":"A real immediate session abort where the authoritative idle notification arrived before the abort HTTP response."}} +{"type":"expect_outbound","label":"event.subscribe","frame":{"type":"event.subscribe"}} +{"type":"expect_outbound","label":"session.create","frame":{"type":"session.create","input":{"title":"","permission":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"type":"sdk.response","operation":"session.create","data":{"id":"ses_123570840ffenLEumkPQfegGCd","slug":"shiny-wolf","version":"1.14.39","projectID":"global","directory":"/private/tmp/t3-opencode-probe","path":"private/tmp/t3-opencode-probe","title":"T3 OpenCode interrupt probe","permission":[{"permission":"bash","pattern":"*","action":"deny"},{"permission":"edit","pattern":"*","action":"deny"},{"permission":"webfetch","pattern":"*","action":"deny"},{"permission":"websearch","pattern":"*","action":"deny"},{"permission":"codesearch","pattern":"*","action":"deny"},{"permission":"external_directory","pattern":"*","action":"deny"},{"permission":"question","pattern":"*","action":"allow"},{"permission":"read","pattern":"*","action":"allow"},{"permission":"glob","pattern":"*","action":"allow"},{"permission":"grep","pattern":"*","action":"allow"},{"permission":"lsp","pattern":"*","action":"allow"},{"permission":"todowrite","pattern":"*","action":"allow"},{"permission":"task","pattern":"*","action":"allow"},{"permission":"skill","pattern":"*","action":"allow"},{"permission":"doom_loop","pattern":"*","action":"allow"},{"permission":"edit","pattern":"*","action":"allow"}],"time":{"created":1781818521535,"updated":1781818521535}}}} +{"type":"expect_outbound","label":"session.promptAsync","frame":{"type":"session.promptAsync","input":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"agent":"build","parts":[{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally."}]}}} +{"type":"emit_inbound","label":"session.promptAsync.response","frame":{"type":"sdk.response","operation":"session.promptAsync","data":null}} +{"type":"expect_outbound","label":"session.abort","frame":{"type":"session.abort","input":{"sessionID":"ses_123570840ffenLEumkPQfegGCd"}}} +{"type":"emit_inbound","label":"message.updated.user","frame":{"type":"sdk.event","event":{"id":"evt_edca8f7ca002yIVK4oYgGErvdA","type":"message.updated","properties":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","info":{"id":"msg_edca8f7c9001w8R30p1SpzPuUJ","role":"user","sessionID":"ses_123570840ffenLEumkPQfegGCd","time":{"created":1781818521545},"agent":"build","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}} +{"type":"emit_inbound","label":"message.part.updated.user","frame":{"type":"sdk.event","event":{"id":"evt_edca8f7ca00377fxNZjgW62lds","type":"message.part.updated","properties":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","part":{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","messageID":"msg_edca8f7c9001w8R30p1SpzPuUJ","sessionID":"ses_123570840ffenLEumkPQfegGCd","id":"prt_edca8f7ca001ugmdiNWtC2964M"},"time":1781818521546}}}} +{"type":"emit_inbound","label":"session.status.busy","frame":{"type":"sdk.event","event":{"id":"evt_edca8f7cc001qWTqVj4Xrui4Sc","type":"session.status","properties":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","status":{"type":"busy"}}}}} +{"type":"emit_inbound","label":"message.updated.assistant","frame":{"type":"sdk.event","event":{"id":"evt_edca8f7cc003brTfV2AHRR2C61","type":"message.updated","properties":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","info":{"id":"msg_edca8f7cc002W56d1gpf5e17kX","parentID":"msg_edca8f7c9001w8R30p1SpzPuUJ","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818521548},"sessionID":"ses_123570840ffenLEumkPQfegGCd"}}}}} +{"type":"emit_inbound","label":"session.status.idle","frame":{"type":"sdk.event","event":{"id":"evt_edca8f7d0001Gjy7U3InhsfliL","type":"session.status","properties":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","status":{"type":"idle"}}}}} +{"type":"emit_inbound","label":"session.abort.response","frame":{"type":"sdk.response","operation":"session.abort","data":true}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index f2e286c589..6a74c9f3c8 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -10,7 +10,11 @@ import * as Effect from "effect/Effect"; import * as Stream from "effect/Stream"; import { describe, expect } from "vite-plus/test"; -import { AcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts"; +import { + AcpSessionRuntime, + selectAcpAgentAuthMethod, + type AcpSessionRequestLogEvent, +} from "./AcpSessionRuntime.ts"; import type * as EffectAcpProtocol from "effect-acp/protocol"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -19,6 +23,17 @@ const mockAgentCommand = "node"; const mockAgentArgs = [mockAgentPath]; describe("AcpSessionRuntime", () => { + it("selects explicit or agent-managed authentication without choosing terminal auth", () => { + const methods = [ + { id: "browser", name: "Browser", type: "terminal" as const }, + { id: "api-key", name: "API key" }, + ]; + + expect(selectAcpAgentAuthMethod(methods)?.id).toBe("api-key"); + expect(selectAcpAgentAuthMethod(methods, "browser")?.id).toBe("browser"); + expect(selectAcpAgentAuthMethod(methods, "missing")).toBeUndefined(); + }); + it.effect("merges custom initialize client capabilities into the ACP handshake", () => { const requestEvents: Array = []; return Effect.gen(function* () { @@ -62,6 +77,82 @@ describe("AcpSessionRuntime", () => { ); }); + it.effect("does not authenticate when an advertised method is not required", () => { + const requestEvents: Array = []; + return Effect.gen(function* () { + const runtime = yield* AcpSessionRuntime; + yield* runtime.start(); + + expect( + requestEvents.filter((event) => event.status === "started").map((event) => event.method), + ).toEqual(["initialize", "session/new"]); + }).pipe( + Effect.provide( + AcpSessionRuntime.layer({ + authMethodId: "test", + spawn: { + command: mockAgentCommand, + args: mockAgentArgs, + env: { T3_ACP_AUTH_METHOD_ID: "test" }, + }, + cwd: process.cwd(), + clientInfo: { name: "t3-test", version: "0.0.0" }, + requestLogger: (event) => + Effect.sync(() => { + requestEvents.push(event); + }), + }), + ), + Effect.scoped, + Effect.provide(NodeServices.layer), + ); + }); + + it.effect("authenticates and retries once after session creation returns auth_required", () => { + const requestEvents: Array = []; + return Effect.gen(function* () { + const runtime = yield* AcpSessionRuntime; + const started = yield* runtime.start(); + + expect(started.sessionId).toBe("mock-session-1"); + expect( + requestEvents.filter((event) => event.status === "started").map((event) => event.method), + ).toEqual(["initialize", "session/new", "authenticate", "session/new"]); + expect( + requestEvents.filter( + (event) => event.method === "session/new" && event.status === "failed", + ), + ).toHaveLength(1); + expect( + requestEvents.filter( + (event) => event.method === "session/new" && event.status === "succeeded", + ), + ).toHaveLength(1); + }).pipe( + Effect.provide( + AcpSessionRuntime.layer({ + authMethodId: "test", + spawn: { + command: mockAgentCommand, + args: mockAgentArgs, + env: { + T3_ACP_AUTH_METHOD_ID: "test", + T3_ACP_REQUIRE_AUTH: "1", + }, + }, + cwd: process.cwd(), + clientInfo: { name: "t3-test", version: "0.0.0" }, + requestLogger: (event) => + Effect.sync(() => { + requestEvents.push(event); + }), + }), + ), + Effect.scoped, + Effect.provide(NodeServices.layer), + ); + }); + it.effect("starts a session, prompts, and emits normalized events against the mock agent", () => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime; @@ -264,6 +355,63 @@ describe("AcpSessionRuntime", () => { ); }); + it.effect("supports negotiated ACP session list, fork, resume, and close methods", () => { + const requestEvents: Array = []; + return Effect.gen(function* () { + const runtime = yield* AcpSessionRuntime; + const started = yield* runtime.start(); + expect(started.initializeResult.agentCapabilities?.sessionCapabilities).toMatchObject({ + list: {}, + fork: {}, + resume: {}, + close: {}, + }); + + const listed = yield* runtime.listSessions(); + expect(listed.sessions.map((session) => session.sessionId)).toEqual(["mock-session-1"]); + + const forked = yield* runtime.forkSession(started.sessionId); + expect(forked.sessionId).toBe("mock-session-1-fork"); + yield* runtime.prompt({ prompt: [{ type: "text", text: "on fork" }] }); + + const resumed = yield* runtime.resumeSession(started.sessionId); + expect(resumed.sessionId).toBe("mock-session-1"); + yield* runtime.closeSession(); + + expect( + requestEvents.find( + (event) => event.method === "session/prompt" && event.status === "started", + )?.payload, + ).toMatchObject({ sessionId: "mock-session-1-fork" }); + expect( + requestEvents.filter((event) => event.status === "started").map((event) => event.method), + ).toEqual( + expect.arrayContaining(["session/list", "session/fork", "session/resume", "session/close"]), + ); + }).pipe( + Effect.provide( + AcpSessionRuntime.layer({ + authMethodId: "test", + spawn: { + command: mockAgentCommand, + args: mockAgentArgs, + env: { + T3_ACP_SESSION_LIFECYCLE: "1", + }, + }, + cwd: process.cwd(), + clientInfo: { name: "t3-test", version: "0.0.0" }, + requestLogger: (event) => + Effect.sync(() => { + requestEvents.push(event); + }), + }), + ), + Effect.scoped, + Effect.provide(NodeServices.layer), + ); + }); + it.effect("skips no-op session config writes when the requested value is already active", () => { const requestEvents: Array = []; return Effect.gen(function* () { diff --git a/apps/server/src/provider/acp/AcpRegistrySupport.test.ts b/apps/server/src/provider/acp/AcpRegistrySupport.test.ts new file mode 100644 index 0000000000..b4363dda71 --- /dev/null +++ b/apps/server/src/provider/acp/AcpRegistrySupport.test.ts @@ -0,0 +1,263 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import { AcpRegistrySettings } from "@t3tools/contracts"; +import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientResponse } from "effect/unstable/http"; + +import { + makeAcpRegistryResolver, + resolveAcpRegistryDistribution, + resolveAcpRegistryPlatformTarget, + type AcpRegistryAgent, +} from "./AcpRegistrySupport.ts"; + +const registryUrl = "https://registry.test/registry.json"; +const archiveUrl = "https://registry.test/example-agent.bin"; +const decodeAcpRegistrySettings = Schema.decodeSync(AcpRegistrySettings); + +function makeAgent(distribution: AcpRegistryAgent["distribution"]): AcpRegistryAgent { + return { + id: "example-agent", + name: "Example Agent", + version: "1.2.3", + description: "ACP Registry test agent", + distribution, + }; +} + +function makeRegistry(agent: AcpRegistryAgent): string { + return JSON.stringify({ version: "1.0.0", agents: [agent] }); +} + +function settings(input: Partial = {}): AcpRegistrySettings { + return decodeAcpRegistrySettings({ + agentId: "example-agent", + ...input, + }); +} + +function resolverLayer(execute: Parameters[0]) { + return Layer.mergeAll( + NodeServices.layer, + Layer.succeed(HostProcessPlatform, "linux"), + Layer.succeed(HostProcessArchitecture, "x64"), + Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute)), + ); +} + +describe("AcpRegistrySupport", () => { + it("maps supported Node platforms to ACP Registry target keys", () => { + expect(resolveAcpRegistryPlatformTarget("darwin", "arm64")).toBe("darwin-aarch64"); + expect(resolveAcpRegistryPlatformTarget("linux", "x64")).toBe("linux-x86_64"); + expect(resolveAcpRegistryPlatformTarget("win32", "arm64")).toBe("windows-aarch64"); + expect(resolveAcpRegistryPlatformTarget("freebsd", "x64")).toBeUndefined(); + expect(resolveAcpRegistryPlatformTarget("linux", "ia32")).toBeUndefined(); + }); + + it("selects the preferred compatible distribution", () => { + const agent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + }, + }, + npx: { + package: "@example/acp@1.2.3", + args: ["--stdio"], + }, + }); + + expect( + resolveAcpRegistryDistribution({ + agent, + preference: "auto", + platformTarget: "linux-x86_64", + }), + ).toMatchObject({ kind: "binary", args: ["acp"] }); + expect( + resolveAcpRegistryDistribution({ + agent, + preference: "npx", + platformTarget: "linux-x86_64", + }), + ).toEqual({ + kind: "npx", + packageName: "@example/acp@1.2.3", + args: ["--stdio"], + env: {}, + }); + expect( + resolveAcpRegistryDistribution({ + agent, + preference: "binary", + platformTarget: "darwin-aarch64", + }), + ).toBeUndefined(); + }); + + it.effect("resolves command overrides while preserving registry args and environment", () => { + const agent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "./bin/example-agent", + args: ["acp", "--stdio"], + env: { REGISTRY_VALUE: "registry", OVERRIDE_ME: "registry" }, + }, + }, + }); + const requests: Array = []; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-override-", + }); + const resolver = yield* makeAcpRegistryResolver({ cacheDir, registryUrl }); + const resolved = yield* resolver.resolve( + settings({ commandPath: "/opt/example-agent" }), + "/workspace", + { HOST_VALUE: "host", OVERRIDE_ME: "host" }, + ); + + expect(resolved.distribution).toBe("binary"); + expect(resolved.spawn).toEqual({ + command: "/opt/example-agent", + args: ["acp", "--stdio"], + cwd: "/workspace", + env: { + HOST_VALUE: "host", + OVERRIDE_ME: "registry", + REGISTRY_VALUE: "registry", + }, + }); + expect(requests).toEqual([registryUrl]); + }).pipe( + Effect.scoped, + Effect.provide( + resolverLayer((request) => { + requests.push(request.url); + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent))), + ); + }), + ), + ); + }); + + it.effect("installs and reuses a registry binary in the managed cache", () => { + const agent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "./bin/example-agent", + args: ["acp"], + }, + }, + }); + const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n"); + const requests: Array = []; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-install-", + }); + const resolver = yield* makeAcpRegistryResolver({ cacheDir, registryUrl }); + const first = yield* resolver.resolve(settings(), "/workspace"); + const second = yield* resolver.resolve(settings(), "/workspace"); + + expect(first.spawn.command).toBe(second.spawn.command); + expect(first.spawn.command).toContain( + "/acp-registry/agents/example-agent/1.2.3/linux-x86_64/bin/example-agent", + ); + expect(yield* fileSystem.readFileString(first.spawn.command)).toBe( + "#!/bin/sh\necho example\n", + ); + expect(requests).toEqual([registryUrl, archiveUrl]); + }).pipe( + Effect.scoped, + Effect.provide( + resolverLayer((request) => { + requests.push(request.url); + const response = + request.url === registryUrl + ? new Response(makeRegistry(agent)) + : new Response(binaryBytes.buffer as ArrayBuffer); + return Effect.succeed(HttpClientResponse.fromWeb(request, response)); + }), + ), + ); + }); + + it.effect("falls back to a valid cached registry index when refresh fails", () => { + const agent = makeAgent({ + npx: { + package: "@example/acp@1.2.3", + args: ["--stdio"], + }, + }); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-cache-", + }); + const registryDirectory = `${cacheDir}/acp-registry`; + yield* fileSystem.makeDirectory(registryDirectory, { recursive: true }); + yield* fileSystem.writeFileString(`${registryDirectory}/registry.json`, makeRegistry(agent)); + const resolver = yield* makeAcpRegistryResolver({ cacheDir, registryUrl }); + const resolved = yield* resolver.resolve(settings(), "/workspace"); + + expect(resolved.spawn).toMatchObject({ + command: "npx", + args: ["--yes", "@example/acp@1.2.3", "--stdio"], + }); + }).pipe( + Effect.scoped, + Effect.provide( + resolverLayer((request) => + Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })), + ), + ), + ), + ); + }); + + it.effect("rejects unsafe command paths before downloading an archive", () => { + const agent = makeAgent({ + binary: { + "linux-x86_64": { + archive: archiveUrl, + cmd: "../outside", + }, + }, + }); + const requests: Array = []; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-invalid-", + }); + const resolver = yield* makeAcpRegistryResolver({ cacheDir, registryUrl }); + const error = yield* resolver.resolve(settings(), "/workspace").pipe(Effect.flip); + + expect(error.reason).toBe("archive_invalid"); + expect(requests).toEqual([registryUrl]); + }).pipe( + Effect.scoped, + Effect.provide( + resolverLayer((request) => { + requests.push(request.url); + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent))), + ); + }), + ), + ); + }); +}); diff --git a/apps/server/src/provider/acp/AcpRegistrySupport.ts b/apps/server/src/provider/acp/AcpRegistrySupport.ts new file mode 100644 index 0000000000..a0107725c0 --- /dev/null +++ b/apps/server/src/provider/acp/AcpRegistrySupport.ts @@ -0,0 +1,633 @@ +import { + type AcpRegistryDistributionPreference, + type AcpRegistrySettings, +} from "@t3tools/contracts"; +import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { collectUint8StreamText } from "../../stream/collectUint8StreamText.ts"; +import type { AcpSpawnInput } from "./AcpSessionRuntime.ts"; + +export const ACP_REGISTRY_URL = + "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json"; + +const AcpRegistryPackageDistribution = Schema.Struct({ + package: Schema.String, + args: Schema.optionalKey(Schema.Array(Schema.String)), + env: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)), +}); + +const AcpRegistryBinaryTarget = Schema.Struct({ + archive: Schema.String, + cmd: Schema.String, + args: Schema.optionalKey(Schema.Array(Schema.String)), + env: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)), +}); + +const AcpRegistryAgent = Schema.Struct({ + id: Schema.String, + name: Schema.String, + version: Schema.String, + description: Schema.String, + distribution: Schema.Struct({ + binary: Schema.optionalKey(Schema.Record(Schema.String, AcpRegistryBinaryTarget)), + npx: Schema.optionalKey(AcpRegistryPackageDistribution), + uvx: Schema.optionalKey(AcpRegistryPackageDistribution), + }), +}); +export type AcpRegistryAgent = typeof AcpRegistryAgent.Type; + +const AcpRegistryIndex = Schema.Struct({ + version: Schema.String, + agents: Schema.Array(AcpRegistryAgent), +}); +export type AcpRegistryIndex = typeof AcpRegistryIndex.Type; + +const decodeRegistryIndex = Schema.decodeUnknownEffect(AcpRegistryIndex); +const decodeJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString); + +export const AcpRegistryErrorReason = Schema.Literals([ + "agent_not_configured", + "agent_not_found", + "archive_invalid", + "download_failed", + "install_failed", + "registry_unavailable", + "unsupported_distribution", + "unsupported_platform", +]); +export type AcpRegistryErrorReason = typeof AcpRegistryErrorReason.Type; + +export class AcpRegistryError extends Schema.TaggedErrorClass()( + "AcpRegistryError", + { + reason: AcpRegistryErrorReason, + detail: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.detail; + } +} + +const isAcpRegistryError = Schema.is(AcpRegistryError); + +export type AcpRegistryPlatformTarget = + | "darwin-aarch64" + | "darwin-x86_64" + | "linux-aarch64" + | "linux-x86_64" + | "windows-aarch64" + | "windows-x86_64"; + +export function resolveAcpRegistryPlatformTarget( + platform: NodeJS.Platform, + architecture: NodeJS.Architecture, +): AcpRegistryPlatformTarget | undefined { + const os = + platform === "darwin" + ? "darwin" + : platform === "linux" + ? "linux" + : platform === "win32" + ? "windows" + : undefined; + const arch = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined; + return os && arch ? (`${os}-${arch}` as AcpRegistryPlatformTarget) : undefined; +} + +export type AcpRegistryDistributionKind = "binary" | "npx" | "uvx"; + +export interface ResolvedAcpRegistryDistribution { + readonly kind: AcpRegistryDistributionKind; + readonly args: ReadonlyArray; + readonly env: Readonly>; + readonly binaryTarget?: typeof AcpRegistryBinaryTarget.Type; + readonly packageName?: string; +} + +export function resolveAcpRegistryDistribution(input: { + readonly agent: AcpRegistryAgent; + readonly preference: AcpRegistryDistributionPreference; + readonly platformTarget: AcpRegistryPlatformTarget | undefined; +}): ResolvedAcpRegistryDistribution | undefined { + const { agent, platformTarget } = input; + const binary = platformTarget ? agent.distribution.binary?.[platformTarget] : undefined; + const candidates: ReadonlyArray = + input.preference === "auto" ? ["binary", "npx", "uvx"] : [input.preference]; + + for (const kind of candidates) { + if (kind === "binary" && binary) { + return { + kind, + args: binary.args ?? [], + env: binary.env ?? {}, + binaryTarget: binary, + }; + } + if (kind === "npx" && agent.distribution.npx) { + return { + kind, + args: agent.distribution.npx.args ?? [], + env: agent.distribution.npx.env ?? {}, + packageName: agent.distribution.npx.package, + }; + } + if (kind === "uvx" && agent.distribution.uvx) { + return { + kind, + args: agent.distribution.uvx.args ?? [], + env: agent.distribution.uvx.env ?? {}, + packageName: agent.distribution.uvx.package, + }; + } + } + return undefined; +} + +export interface ResolvedAcpRegistryAgent { + readonly agent: AcpRegistryAgent; + readonly distribution: AcpRegistryDistributionKind; + readonly spawn: AcpSpawnInput; +} + +export interface AcpRegistryResolverShape { + readonly resolve: ( + settings: AcpRegistrySettings, + cwd: string, + environment?: NodeJS.ProcessEnv, + ) => Effect.Effect; +} + +const INSTALL_LOCK_RETRY_COUNT = 300; +const INSTALL_LOCK_RETRY_DELAY = "100 millis"; +const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000; +const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024; + +function isAlreadyExists(error: PlatformError.PlatformError): boolean { + return error.reason._tag === "AlreadyExists"; +} + +function normalizeRegistryCommandPath(command: string): ReadonlyArray | undefined { + const normalized = command.trim().replaceAll("\\", "/").replace(/^\.\//u, ""); + const segments = normalized.split("/").filter((segment) => segment.length > 0); + if ( + segments.length === 0 || + normalized.startsWith("/") || + /^[a-zA-Z]:/u.test(normalized) || + segments.some((segment) => segment === "." || segment === "..") + ) { + return undefined; + } + return segments; +} + +function validateArchiveEntries(output: string): boolean { + return output + .split(/\r?\n/u) + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0) + .every((entry) => normalizeRegistryCommandPath(entry) !== undefined); +} + +type ArchiveKind = "raw" | "tar_bz2" | "tar_gz" | "zip"; + +function archiveKind(url: string): ArchiveKind { + const pathname = new URL(url).pathname.toLowerCase(); + if (pathname.endsWith(".tar.gz") || pathname.endsWith(".tgz")) return "tar_gz"; + if (pathname.endsWith(".tar.bz2") || pathname.endsWith(".tbz2")) return "tar_bz2"; + if (pathname.endsWith(".zip")) return "zip"; + return "raw"; +} + +function archiveFileName(kind: ArchiveKind): string { + switch (kind) { + case "tar_gz": + return "agent.tar.gz"; + case "tar_bz2": + return "agent.tar.bz2"; + case "zip": + return "agent.zip"; + case "raw": + return "agent.bin"; + } +} + +export const makeAcpRegistryResolver = Effect.fn("AcpRegistryResolver.make")(function* (input: { + readonly cacheDir: string; + readonly registryUrl?: string; +}): Effect.fn.Return< + AcpRegistryResolverShape, + never, + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | HttpClient.HttpClient + | Path.Path +> { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const httpClient = yield* HttpClient.HttpClient; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const platform = yield* HostProcessPlatform; + const architecture = yield* HostProcessArchitecture; + const platformTarget = resolveAcpRegistryPlatformTarget(platform, architecture); + const registryUrl = input.registryUrl ?? ACP_REGISTRY_URL; + const registryDirectory = path.join(input.cacheDir, "acp-registry"); + const registryCachePath = path.join(registryDirectory, "registry.json"); + const installsDirectory = path.join(registryDirectory, "agents"); + const registryRef = yield* Ref.make(undefined); + const registrySemaphore = yield* Semaphore.make(1); + const installSemaphore = yield* Semaphore.make(1); + + const decodeRegistryText = Effect.fn("AcpRegistryResolver.decodeRegistryText")(function* ( + text: string, + ) { + const decoded = yield* decodeJson(text).pipe( + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "registry_unavailable", + detail: "ACP Registry returned invalid JSON.", + cause, + }), + ), + ); + return yield* decodeRegistryIndex(decoded).pipe( + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "registry_unavailable", + detail: "ACP Registry returned an invalid index.", + cause, + }), + ), + ); + }); + + const readCachedRegistry = fileSystem + .readFileString(registryCachePath) + .pipe(Effect.flatMap(decodeRegistryText), Effect.option); + + const writeRegistryCache = (text: string) => + fileSystem + .makeDirectory(registryDirectory, { recursive: true }) + .pipe( + Effect.andThen(fileSystem.writeFileString(`${registryCachePath}.${process.pid}.tmp`, text)), + Effect.andThen( + fileSystem.rename(`${registryCachePath}.${process.pid}.tmp`, registryCachePath), + ), + Effect.ignore, + ); + + const fetchRegistry = Effect.gen(function* () { + const response = yield* httpClient.execute(HttpClientRequest.get(registryUrl)).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "registry_unavailable", + detail: `Could not fetch ACP Registry index from ${registryUrl}.`, + cause, + }), + ), + ); + const text = yield* response.text.pipe( + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "registry_unavailable", + detail: "Could not read ACP Registry response body.", + cause, + }), + ), + ); + const registry = yield* decodeRegistryText(text); + yield* writeRegistryCache(text); + return registry; + }); + + const loadRegistry = registrySemaphore.withPermits(1)( + Effect.gen(function* () { + const memoized = yield* Ref.get(registryRef); + if (memoized !== undefined) return memoized; + const registry = yield* fetchRegistry.pipe( + Effect.catch((networkError) => + readCachedRegistry.pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.fail(networkError), + onSome: Effect.succeed, + }), + ), + ), + ), + ); + yield* Ref.set(registryRef, registry); + return registry; + }), + ); + + const runCommand = Effect.fn("AcpRegistryResolver.runCommand")(function* ( + command: string, + args: ReadonlyArray, + cwd?: string, + ) { + const child = yield* spawner.spawn( + ChildProcess.make(command, args, { + ...(cwd ? { cwd } : {}), + shell: false, + }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectUint8StreamText({ stream: child.stdout }), + collectUint8StreamText({ stream: child.stderr }), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + if (Number(exitCode) !== 0) { + return yield* new AcpRegistryError({ + reason: "install_failed", + detail: `ACP Registry install command '${command}' exited with code ${Number(exitCode)}: ${stderr.text.trim()}`, + }); + } + return stdout.text; + }); + + const acquireInstallLock = Effect.fn("AcpRegistryResolver.acquireInstallLock")(function* ( + lockPath: string, + ) { + for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) { + const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe( + Effect.as(true), + Effect.catch((error) => + isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error), + ), + ); + if (acquired) return; + const now = yield* Clock.currentTimeMillis; + const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option); + const mtime = Option.flatMap(lockInfo, (info) => info.mtime); + if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) { + yield* fileSystem.remove(lockPath, { force: true }); + continue; + } + yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY); + } + return yield* new AcpRegistryError({ + reason: "install_failed", + detail: `Timed out waiting for ACP Registry install lock ${lockPath}.`, + }); + }); + + const assertExecutableInRoot = Effect.fn("AcpRegistryResolver.assertExecutableInRoot")(function* ( + root: string, + executablePath: string, + ) { + const rootRealPath = yield* fileSystem.realPath(root); + const executableRealPath = yield* fileSystem.realPath(executablePath); + const relative = path.relative(rootRealPath, executableRealPath); + if (relative.startsWith("..") || path.isAbsolute(relative)) { + return yield* new AcpRegistryError({ + reason: "archive_invalid", + detail: "ACP Registry archive command resolves outside its installation directory.", + }); + } + return executableRealPath; + }); + + const installBinary = Effect.fn("AcpRegistryResolver.installBinary")(function* ( + agent: AcpRegistryAgent, + target: typeof AcpRegistryBinaryTarget.Type, + ) { + if (platformTarget === undefined) { + return yield* new AcpRegistryError({ + reason: "unsupported_platform", + detail: `ACP Registry does not support platform ${platform}-${architecture}.`, + }); + } + const commandSegments = normalizeRegistryCommandPath(target.cmd); + if (commandSegments === undefined) { + return yield* new AcpRegistryError({ + reason: "archive_invalid", + detail: `ACP Registry agent ${agent.id} declares an unsafe command path '${target.cmd}'.`, + }); + } + const installRoot = path.join(installsDirectory, agent.id, agent.version, platformTarget); + const executablePath = path.join(installRoot, ...commandSegments); + if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) { + return yield* assertExecutableInRoot(installRoot, executablePath).pipe( + Effect.mapError((cause) => + isAcpRegistryError(cause) + ? cause + : new AcpRegistryError({ + reason: "install_failed", + detail: `Could not validate cached ACP Registry agent ${agent.id}.`, + cause, + }), + ), + ); + } + + yield* fileSystem.makeDirectory(path.dirname(installRoot), { recursive: true }).pipe( + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "install_failed", + detail: `Could not create ACP Registry cache for ${agent.id}.`, + cause, + }), + ), + ); + const lockPath = `${installRoot}.lock`; + yield* acquireInstallLock(lockPath).pipe( + Effect.mapError((cause) => + isAcpRegistryError(cause) + ? cause + : new AcpRegistryError({ + reason: "install_failed", + detail: `Could not acquire install lock for ACP Registry agent ${agent.id}.`, + cause, + }), + ), + ); + + return yield* Effect.gen(function* () { + if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) { + return yield* assertExecutableInRoot(installRoot, executablePath); + } + const temporaryRoot = yield* fileSystem.makeTempDirectoryScoped({ + directory: path.dirname(installRoot), + prefix: `.${agent.id}-install-`, + }); + const extractionRoot = path.join(temporaryRoot, "extracted"); + yield* fileSystem.makeDirectory(extractionRoot, { recursive: true }); + const kind = archiveKind(target.archive); + const archivePath = path.join(temporaryRoot, archiveFileName(kind)); + const response = yield* httpClient.execute(HttpClientRequest.get(target.archive)).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "download_failed", + detail: `Could not download ACP Registry agent ${agent.id} ${agent.version}.`, + cause, + }), + ), + ); + const bytes = new Uint8Array( + yield* response.arrayBuffer.pipe( + Effect.mapError( + (cause) => + new AcpRegistryError({ + reason: "download_failed", + detail: `Could not read ACP Registry agent ${agent.id} download.`, + cause, + }), + ), + ), + ); + if (bytes.byteLength > MAX_ARCHIVE_BYTES) { + return yield* new AcpRegistryError({ + reason: "archive_invalid", + detail: `ACP Registry agent ${agent.id} archive exceeds ${MAX_ARCHIVE_BYTES} bytes.`, + }); + } + yield* fileSystem.writeFile(archivePath, bytes); + + if (kind === "raw") { + const targetPath = path.join(extractionRoot, ...commandSegments); + yield* fileSystem.makeDirectory(path.dirname(targetPath), { recursive: true }); + yield* fileSystem.rename(archivePath, targetPath); + } else { + const listArgs = + kind === "tar_gz" + ? ["-tzf", archivePath] + : kind === "tar_bz2" + ? ["-tjf", archivePath] + : platform === "win32" + ? ["-tf", archivePath] + : undefined; + const entries = + listArgs === undefined + ? yield* runCommand("unzip", ["-Z1", archivePath]) + : yield* runCommand("tar", listArgs); + if (!validateArchiveEntries(entries)) { + return yield* new AcpRegistryError({ + reason: "archive_invalid", + detail: `ACP Registry agent ${agent.id} archive contains an unsafe path.`, + }); + } + if (kind === "zip" && platform !== "win32") { + yield* runCommand("unzip", ["-q", archivePath, "-d", extractionRoot]); + } else { + const extractFlag = kind === "tar_gz" ? "-xzf" : kind === "tar_bz2" ? "-xjf" : "-xf"; + yield* runCommand("tar", [extractFlag, archivePath, "-C", extractionRoot]); + } + } + + const stagedExecutable = path.join(extractionRoot, ...commandSegments); + if (!(yield* fileSystem.exists(stagedExecutable).pipe(Effect.orElseSucceed(() => false)))) { + return yield* new AcpRegistryError({ + reason: "archive_invalid", + detail: `ACP Registry archive for ${agent.id} did not contain '${target.cmd}'.`, + }); + } + if (platform !== "win32") yield* fileSystem.chmod(stagedExecutable, 0o755); + yield* assertExecutableInRoot(extractionRoot, stagedExecutable); + yield* fileSystem.remove(installRoot, { recursive: true, force: true }); + yield* fileSystem.rename(extractionRoot, installRoot); + return yield* assertExecutableInRoot(installRoot, executablePath); + }).pipe( + Effect.scoped, + Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)), + Effect.mapError((cause) => + isAcpRegistryError(cause) + ? cause + : new AcpRegistryError({ + reason: "install_failed", + detail: `Could not install ACP Registry agent ${agent.id}.`, + cause, + }), + ), + ); + }); + + const resolve: AcpRegistryResolverShape["resolve"] = (settings, cwd, environment) => + Effect.gen(function* () { + const agentId = settings.agentId.trim(); + if (agentId.length === 0) { + return yield* new AcpRegistryError({ + reason: "agent_not_configured", + detail: "ACP Registry provider requires a registry agent ID.", + }); + } + const registry = yield* loadRegistry; + const agent = registry.agents.find((candidate) => candidate.id === agentId); + if (agent === undefined) { + return yield* new AcpRegistryError({ + reason: "agent_not_found", + detail: `ACP Registry does not contain agent '${agentId}'.`, + }); + } + const distribution = resolveAcpRegistryDistribution({ + agent, + preference: settings.distribution, + platformTarget, + }); + if (distribution === undefined) { + return yield* new AcpRegistryError({ + reason: + platformTarget === undefined ? "unsupported_platform" : "unsupported_distribution", + detail: `ACP Registry agent ${agent.id} has no ${settings.distribution === "auto" ? "compatible" : settings.distribution} distribution for ${platform}-${architecture}.`, + }); + } + + let command: string; + let args: ReadonlyArray; + const commandOverride = settings.commandPath.trim(); + if (commandOverride.length > 0) { + command = commandOverride; + args = distribution.args; + } else if (distribution.kind === "npx") { + command = "npx"; + args = ["--yes", distribution.packageName!, ...distribution.args]; + } else if (distribution.kind === "uvx") { + command = "uvx"; + args = [distribution.packageName!, ...distribution.args]; + } else { + command = yield* installSemaphore.withPermits(1)( + installBinary(agent, distribution.binaryTarget!), + ); + args = distribution.args; + } + + return { + agent, + distribution: distribution.kind, + spawn: { + command, + args, + cwd, + env: { + ...environment, + ...distribution.env, + }, + }, + } satisfies ResolvedAcpRegistryAgent; + }); + + return { resolve }; +}); diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts index 3587d703db..48a3c8b0ea 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -72,6 +72,7 @@ export type AcpParsedSessionEvent = }; type AcpSessionSetupResponse = + | EffectAcpSchema.ForkSessionResponse | EffectAcpSchema.LoadSessionResponse | EffectAcpSchema.NewSessionResponse | EffectAcpSchema.ResumeSessionResponse; diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index b8097f10b7..a170708313 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -47,7 +47,7 @@ export interface AcpSessionRuntimeOptions { readonly name: string; readonly version: string; }; - readonly authMethodId: string; + readonly authMethodId?: string; readonly mcpServers?: ReadonlyArray; readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect; readonly protocolLogging?: { @@ -65,10 +65,26 @@ export interface AcpSessionRequestLogEvent { readonly cause?: Cause.Cause; } +export function selectAcpAgentAuthMethod( + authMethods: ReadonlyArray | undefined, + preferredMethodId?: string, +): EffectAcpSchema.AuthMethod | undefined { + const preferred = preferredMethodId?.trim(); + if (preferred) { + return authMethods?.find((method) => method.id === preferred); + } + return authMethods?.find((method) => !("type" in method)); +} + +function isAcpAuthenticationRequired(error: EffectAcpErrors.AcpError): boolean { + return error._tag === "AcpRequestError" && error.code === -32000; +} + export interface AcpSessionRuntimeStartResult { readonly sessionId: string; readonly initializeResult: EffectAcpSchema.InitializeResponse; readonly sessionSetupResult: + | EffectAcpSchema.ForkSessionResponse | EffectAcpSchema.LoadSessionResponse | EffectAcpSchema.NewSessionResponse | EffectAcpSchema.ResumeSessionResponse; @@ -95,6 +111,21 @@ export interface AcpSessionRuntimeShape { readonly getEvents: () => Stream.Stream; readonly getModeState: Effect.Effect; readonly getConfigOptions: Effect.Effect>; + readonly loadSession: ( + sessionId: string, + ) => Effect.Effect; + readonly resumeSession: ( + sessionId: string, + ) => Effect.Effect; + readonly forkSession: ( + sessionId: string, + ) => Effect.Effect; + readonly listSessions: ( + cursor?: string, + ) => Effect.Effect; + readonly closeSession: ( + sessionId?: string, + ) => Effect.Effect; readonly prompt: ( payload: Omit, ) => Effect.Effect; @@ -327,6 +358,7 @@ const makeAcpSessionRuntime = ( const updateConfigOptions = ( response: | EffectAcpSchema.SetSessionConfigOptionResponse + | EffectAcpSchema.ForkSessionResponse | EffectAcpSchema.LoadSessionResponse | EffectAcpSchema.NewSessionResponse | EffectAcpSchema.ResumeSessionResponse, @@ -337,6 +369,30 @@ const makeAcpSessionRuntime = ( current ? { ...current, currentModeId: modeId } : current, ); + const adoptSession = ( + sessionId: string, + sessionSetupResult: + | EffectAcpSchema.ForkSessionResponse + | EffectAcpSchema.LoadSessionResponse + | EffectAcpSchema.NewSessionResponse + | EffectAcpSchema.ResumeSessionResponse, + ): Effect.Effect => + Effect.gen(function* () { + const current = yield* getStartedState; + const nextState = { + sessionId, + initializeResult: current.initializeResult, + sessionSetupResult, + modelConfigId: extractModelConfigId(sessionSetupResult), + } satisfies AcpStartedState; + yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult)); + yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult)); + yield* Ref.set(toolCallsRef, new Map()); + yield* Ref.set(assistantSegmentRef, { nextSegmentIndex: 0 }); + yield* Ref.set(startStateRef, { _tag: "Started", result: nextState }); + return nextState; + }); + const setConfigOption = ( configId: string, value: string | boolean, @@ -388,35 +444,80 @@ const makeAcpSessionRuntime = ( acp.agent.initialize(initializePayload), ); - const authenticatePayload = { - methodId: options.authMethodId, - } satisfies EffectAcpSchema.AuthenticateRequest; + const authenticateAfterRequired = ( + authRequiredError: EffectAcpErrors.AcpError, + ): Effect.Effect => + Effect.gen(function* () { + const configuredAuthMethodId = options.authMethodId?.trim(); + const authMethod = selectAcpAgentAuthMethod( + initializeResult.authMethods, + configuredAuthMethodId, + ); + if ( + configuredAuthMethodId && + initializeResult.authMethods !== undefined && + authMethod === undefined + ) { + return yield* new EffectAcpErrors.AcpTransportError({ + detail: `ACP agent did not advertise configured authentication method "${configuredAuthMethodId}"`, + cause: { configuredAuthMethodId, authMethods: initializeResult.authMethods }, + }); + } + if (authMethod !== undefined && "type" in authMethod) { + return yield* new EffectAcpErrors.AcpTransportError({ + detail: `ACP authentication method "${authMethod.id}" requires ${authMethod.type} authentication, which cannot run inside a headless provider session`, + cause: authMethod, + }); + } - yield* runLoggedRequest( - "authenticate", - authenticatePayload, - acp.agent.authenticate(authenticatePayload), - ); + const authMethodId = authMethod?.id ?? configuredAuthMethodId; + if (!authMethodId) { + return yield* authRequiredError; + } - let sessionId: string; - let sessionSetupResult: - | EffectAcpSchema.LoadSessionResponse - | EffectAcpSchema.NewSessionResponse - | EffectAcpSchema.ResumeSessionResponse; - if (options.resumeSessionId) { - const loadPayload = { - sessionId: options.resumeSessionId, - cwd: options.cwd, - mcpServers: options.mcpServers ?? [], - } satisfies EffectAcpSchema.LoadSessionRequest; - const resumed = yield* runLoggedRequest( - "session/load", - loadPayload, - acp.agent.loadSession(loadPayload), - ).pipe(Effect.exit); - if (Exit.isSuccess(resumed)) { - sessionId = options.resumeSessionId; - sessionSetupResult = resumed.value; + const authenticatePayload = { + methodId: authMethodId, + } satisfies EffectAcpSchema.AuthenticateRequest; + yield* runLoggedRequest( + "authenticate", + authenticatePayload, + acp.agent.authenticate(authenticatePayload), + ); + }); + + const setupSession = Effect.gen(function* () { + let sessionId: string; + let sessionSetupResult: + | EffectAcpSchema.LoadSessionResponse + | EffectAcpSchema.NewSessionResponse + | EffectAcpSchema.ResumeSessionResponse; + if (options.resumeSessionId) { + const loadPayload = { + sessionId: options.resumeSessionId, + cwd: options.cwd, + mcpServers: options.mcpServers ?? [], + } satisfies EffectAcpSchema.LoadSessionRequest; + const resumed = yield* runLoggedRequest( + "session/load", + loadPayload, + acp.agent.loadSession(loadPayload), + ).pipe(Effect.exit); + if (Exit.isSuccess(resumed)) { + sessionId = options.resumeSessionId; + sessionSetupResult = resumed.value; + } else { + const createPayload = { + cwd: options.cwd, + mcpServers: options.mcpServers ?? [], + } satisfies EffectAcpSchema.NewSessionRequest; + const created = yield* runLoggedRequest( + "session/new", + createPayload, + acp.agent.createSession(createPayload), + ); + sessionId = created.sessionId; + sessionSetupResult = created; + } } else { const createPayload = { cwd: options.cwd, @@ -430,19 +531,17 @@ const makeAcpSessionRuntime = ( sessionId = created.sessionId; sessionSetupResult = created; } - } else { - const createPayload = { - cwd: options.cwd, - mcpServers: options.mcpServers ?? [], - } satisfies EffectAcpSchema.NewSessionRequest; - const created = yield* runLoggedRequest( - "session/new", - createPayload, - acp.agent.createSession(createPayload), - ); - sessionId = created.sessionId; - sessionSetupResult = created; - } + + return { sessionId, sessionSetupResult }; + }); + + const { sessionId, sessionSetupResult } = yield* setupSession.pipe( + Effect.catch((error) => + isAcpAuthenticationRequired(error) + ? authenticateAfterRequired(error).pipe(Effect.andThen(setupSession)) + : Effect.fail(error), + ), + ); yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult)); yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult)); @@ -508,6 +607,82 @@ const makeAcpSessionRuntime = ( getEvents: () => Stream.fromQueue(eventQueue), getModeState: Ref.get(modeStateRef), getConfigOptions: Ref.get(configOptionsRef), + loadSession: (sessionId) => + start.pipe( + Effect.flatMap(() => { + const requestPayload = { + sessionId, + cwd: options.cwd, + mcpServers: options.mcpServers ?? [], + } satisfies EffectAcpSchema.LoadSessionRequest; + return runLoggedRequest( + "session/load", + requestPayload, + acp.agent.loadSession(requestPayload), + ); + }), + Effect.flatMap((response) => adoptSession(sessionId, response)), + ), + resumeSession: (sessionId) => + start.pipe( + Effect.flatMap(() => { + const requestPayload = { + sessionId, + cwd: options.cwd, + mcpServers: options.mcpServers ?? [], + } satisfies EffectAcpSchema.ResumeSessionRequest; + return runLoggedRequest( + "session/resume", + requestPayload, + acp.agent.resumeSession(requestPayload), + ); + }), + Effect.flatMap((response) => adoptSession(sessionId, response)), + ), + forkSession: (sessionId) => + start.pipe( + Effect.flatMap(() => { + const requestPayload = { + sessionId, + cwd: options.cwd, + mcpServers: options.mcpServers ?? [], + } satisfies EffectAcpSchema.ForkSessionRequest; + return runLoggedRequest( + "session/fork", + requestPayload, + acp.agent.forkSession(requestPayload), + ); + }), + Effect.flatMap((response) => adoptSession(response.sessionId, response)), + ), + listSessions: (cursor) => { + const requestPayload = { + cwd: options.cwd, + ...(cursor === undefined ? {} : { cursor }), + } satisfies EffectAcpSchema.ListSessionsRequest; + return start.pipe( + Effect.andThen( + runLoggedRequest( + "session/list", + requestPayload, + acp.agent.listSessions(requestPayload), + ), + ), + ); + }, + closeSession: (sessionId) => + start.pipe( + Effect.flatMap((started) => { + const requestPayload = { + sessionId: sessionId ?? started.sessionId, + } satisfies EffectAcpSchema.CloseSessionRequest; + return runLoggedRequest( + "session/close", + requestPayload, + acp.agent.closeSession(requestPayload), + ); + }), + ), prompt: (payload) => getStartedState.pipe( Effect.flatMap((started) => { diff --git a/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts b/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts index 222fc4a12d..7ca3d72a12 100644 --- a/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts +++ b/apps/server/src/provider/acp/GrokAcpCliProbe.test.ts @@ -66,4 +66,23 @@ describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("Grok ACP CLI probe", () = yield* runtime.setSessionModel(currentModelId); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + + it.effect("switches to another advertised model and completes a prompt", () => + Effect.gen(function* () { + const runtime = yield* makeProbeRuntime; + const started = yield* runtime.start(); + const models = started.sessionSetupResult.models; + const targetModel = models?.availableModels.find( + ({ modelId }) => modelId !== models.currentModelId, + )?.modelId; + expect(targetModel).toBeDefined(); + if (!targetModel) return; + + yield* runtime.setSessionModel(targetModel).pipe(Effect.timeout("20 seconds")); + const result = yield* runtime + .prompt({ prompt: [{ type: "text", text: "Respond with exactly: grok switch ok" }] }) + .pipe(Effect.timeout("60 seconds")); + expect(result.stopReason).toBe("end_turn"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); }); diff --git a/apps/server/src/provider/acp/GrokAcpSupport.ts b/apps/server/src/provider/acp/GrokAcpSupport.ts index 642548832f..1208a1c163 100644 --- a/apps/server/src/provider/acp/GrokAcpSupport.ts +++ b/apps/server/src/provider/acp/GrokAcpSupport.ts @@ -23,10 +23,7 @@ const GROK_DRIVER_KIND = ProviderDriverKind.make("grok"); type GrokAcpRuntimeGrokSettings = Pick; -interface GrokAcpRuntimeInput extends Omit< - AcpSessionRuntimeOptions, - "authMethodId" | "clientCapabilities" | "spawn" -> { +interface GrokAcpRuntimeInput extends Omit { readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined; readonly environment?: NodeJS.ProcessEnv; diff --git a/apps/server/src/provider/acp/XAiAcpExtension.ts b/apps/server/src/provider/acp/XAiAcpExtension.ts index 6c774c7f8d..cc7669fd3c 100644 --- a/apps/server/src/provider/acp/XAiAcpExtension.ts +++ b/apps/server/src/provider/acp/XAiAcpExtension.ts @@ -64,6 +64,17 @@ export function extractXAiAskUserQuestions( })); } +export function extractXAiAskUserQuestionIdentity(params: XAiAskUserQuestionRequest): { + readonly sessionId: string; + readonly toolCallId: string; +} { + const unwrapped = unwrapAskUserQuestionParams(params); + return { + sessionId: unwrapped.sessionId, + toolCallId: unwrapped.toolCallId, + }; +} + interface XAiAskUserQuestionAnnotation { readonly preview?: string; readonly notes?: string; diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index affa35ff26..99a69da10d 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -13,7 +13,7 @@ import { useSettings, useUpdateSettings } from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; import { normalizeProviderAccentColor } from "../../providerInstances"; import { Button } from "../ui/button"; -import { ACPRegistryIcon, Gemini, GithubCopilotIcon, PiAgentIcon, type Icon } from "../Icons"; +import { Gemini, GithubCopilotIcon, PiAgentIcon, type Icon } from "../Icons"; import { Dialog, DialogDescription, @@ -81,11 +81,6 @@ const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [ label: "Gemini", icon: Gemini, }, - { - value: ProviderDriverKind.make("acpRegistry"), - label: "ACP Registry", - icon: ACPRegistryIcon, - }, { value: ProviderDriverKind.make("piAgent"), label: "Pi Agent", diff --git a/apps/web/src/components/settings/ProviderSettingsForm.test.ts b/apps/web/src/components/settings/ProviderSettingsForm.test.ts index 33331c1490..fabf27d05c 100644 --- a/apps/web/src/components/settings/ProviderSettingsForm.test.ts +++ b/apps/web/src/components/settings/ProviderSettingsForm.test.ts @@ -36,6 +36,18 @@ describe("ProviderSettingsForm helpers", () => { }); }); + it("exposes ACP Registry as an instance-only configurable driver", () => { + const acpRegistry = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("acpRegistry")]; + + expect(acpRegistry).toBeDefined(); + expect(acpRegistry?.hasDefaultInstance).toBe(false); + expect(deriveProviderSettingsFields(acpRegistry!).map((field) => field.key)).toEqual([ + "agentId", + "commandPath", + "authMethodId", + ]); + }); + it("preserves unknown config keys while omitting empty configurable fields", () => { const opencode = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("opencode")]; expect(opencode).toBeDefined(); diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index 339c817bd7..cc63f32595 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -1233,6 +1233,35 @@ describe("GeneralSettingsPanel observability", () => { await expect.element(page.getByPlaceholder("Optional")).toBeInTheDocument(); }); + it("renders configured ACP Registry instances without a blank default card", async () => { + const instanceId = ProviderInstanceId.make("acpRegistry_devin"); + setServerConfigSnapshot({ + ...createBaseServerConfig(), + settings: { + ...DEFAULT_SERVER_SETTINGS, + providerInstances: { + [instanceId]: { + driver: ProviderDriverKind.make("acpRegistry"), + displayName: "Devin ACP", + config: { agentId: "devin" }, + }, + }, + }, + }); + + mounted = await render( + + + , + ); + + await expect + .element(page.getByLabelText("Toggle ACP Registry details")) + .not.toBeInTheDocument(); + await page.getByLabelText("Toggle Devin ACP details").click(); + await expect.element(page.getByText("Registry agent ID")).toBeInTheDocument(); + }); + it("runs one-click provider updates from the provider card", async () => { const updateProvider = vi.fn().mockResolvedValue({ providers: [createOutdatedProvider("codex")], diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 76d5d34c35..55570bd68f 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -121,6 +121,7 @@ function withoutProviderInstanceFavorites( const PROVIDER_SETTINGS = DRIVER_OPTIONS.map((definition) => ({ provider: definition.value, + hasDefaultInstance: definition.hasDefaultInstance !== false, })); function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) { @@ -1032,9 +1033,9 @@ export function ProviderSettingsPanel() { } const defaultSlotIdsBySource = new Set( - visibleProviderSettings.map((providerSettings) => - String(defaultInstanceIdForDriver(providerSettings.provider)), - ), + visibleProviderSettings + .filter((providerSettings) => providerSettings.hasDefaultInstance) + .map((providerSettings) => String(defaultInstanceIdForDriver(providerSettings.provider))), ); const rows: InstanceRow[] = []; @@ -1043,6 +1044,12 @@ export function ProviderSettingsPanel() { ); for (const providerSettings of visibleProviderSettings) { + if (!providerSettings.hasDefaultInstance) { + for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) { + rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false }); + } + continue; + } type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers]; const legacyProviders = settings.providers as Record; const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record< diff --git a/apps/web/src/components/settings/providerDriverMeta.ts b/apps/web/src/components/settings/providerDriverMeta.ts index bfee6a8d68..fd4f72e4c3 100644 --- a/apps/web/src/components/settings/providerDriverMeta.ts +++ b/apps/web/src/components/settings/providerDriverMeta.ts @@ -1,4 +1,5 @@ import { + AcpRegistrySettings, ClaudeSettings, CodexSettings, CursorSettings, @@ -7,7 +8,15 @@ import { ProviderDriverKind, } from "@t3tools/contracts"; import type * as Schema from "effect/Schema"; -import { ClaudeAI, CursorIcon, GrokIcon, type Icon, OpenAI, OpenCodeIcon } from "../Icons"; +import { + ACPRegistryIcon, + ClaudeAI, + CursorIcon, + GrokIcon, + type Icon, + OpenAI, + OpenCodeIcon, +} from "../Icons"; type ProviderSettingsSchema = { readonly fields: Readonly>; @@ -24,6 +33,8 @@ export interface ProviderClientDefinition { readonly label: string; readonly icon: Icon; readonly settingsSchema: ProviderSettingsSchema; + /** Whether this driver has a built-in default instance backed by legacy settings. */ + readonly hasDefaultInstance?: boolean; /** * Optional short label rendered as a `variant="warning"` badge next to * the instance title. Used to flag drivers that still ship under an @@ -61,6 +72,14 @@ export const PROVIDER_CLIENT_DEFINITIONS: readonly ProviderClientDefinition[] = badgeLabel: "Early Access", settingsSchema: GrokSettings, }, + { + value: ProviderDriverKind.make("acpRegistry"), + label: "ACP Registry", + icon: ACPRegistryIcon, + badgeLabel: "V2 Preview", + settingsSchema: AcpRegistrySettings, + hasDefaultInstance: false, + }, { value: ProviderDriverKind.make("opencode"), label: "OpenCode", diff --git a/apps/web/src/orchestrationV2DebugProviders.test.ts b/apps/web/src/orchestrationV2DebugProviders.test.ts new file mode 100644 index 0000000000..0df7d258b0 --- /dev/null +++ b/apps/web/src/orchestrationV2DebugProviders.test.ts @@ -0,0 +1,82 @@ +import { + ProviderDriverKind, + ProviderInstanceId, + type ProviderInstanceConfigMap, + type ServerProvider, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { deriveOrchestrationV2DebugProviderSnapshots } from "./orchestrationV2DebugProviders"; + +const acpRegistry = ProviderDriverKind.make("acpRegistry"); +const instanceId = ProviderInstanceId.make("acpRegistry_example"); + +const unavailable: ServerProvider = { + instanceId, + driver: acpRegistry, + displayName: "Example ACP", + enabled: false, + installed: false, + version: null, + status: "error", + auth: { status: "unknown" }, + checkedAt: "2026-01-01T00:00:00.000Z", + availability: "unavailable", + unavailableReason: "Driver is not registered in the V1 runtime.", + models: [], + slashCommands: [], + skills: [], +}; + +describe("deriveOrchestrationV2DebugProviderSnapshots", () => { + it("replaces the V1 unavailable shadow for a configured registry agent", () => { + const providerInstances = { + [instanceId]: { + driver: acpRegistry, + enabled: true, + displayName: "Example ACP", + config: { + agentId: "example-agent", + customModels: ["model-one"], + }, + }, + } satisfies ProviderInstanceConfigMap; + + expect( + deriveOrchestrationV2DebugProviderSnapshots({ + providers: [unavailable], + providerInstances, + }), + ).toEqual([ + expect.objectContaining({ + instanceId, + driver: acpRegistry, + displayName: "Example ACP", + enabled: true, + installed: true, + status: "ready", + availability: "available", + models: [ + expect.objectContaining({ slug: "default", isCustom: false }), + expect.objectContaining({ slug: "model-one", isCustom: true }), + ], + }), + ]); + }); + + it("does not make an incomplete registry instance selectable", () => { + const providerInstances = { + [instanceId]: { + driver: acpRegistry, + config: { agentId: "" }, + }, + } satisfies ProviderInstanceConfigMap; + + expect( + deriveOrchestrationV2DebugProviderSnapshots({ + providers: [unavailable], + providerInstances, + }), + ).toEqual([unavailable]); + }); +}); diff --git a/apps/web/src/orchestrationV2DebugProviders.ts b/apps/web/src/orchestrationV2DebugProviders.ts new file mode 100644 index 0000000000..36994447dd --- /dev/null +++ b/apps/web/src/orchestrationV2DebugProviders.ts @@ -0,0 +1,88 @@ +import { + ProviderDriverKind, + type ProviderInstanceConfigMap, + type ProviderInstanceId, + type ServerProvider, + type ServerProviderModel, +} from "@t3tools/contracts"; + +const ACP_REGISTRY_DRIVER = ProviderDriverKind.make("acpRegistry"); +const DEBUG_CHECKED_AT = "1970-01-01T00:00:00.000Z"; + +function configRecord(config: unknown): Readonly> { + return config !== null && typeof config === "object" && !Array.isArray(config) + ? (config as Readonly>) + : {}; +} + +function configuredModels( + config: Readonly>, +): ReadonlyArray { + const customModels = Array.isArray(config.customModels) + ? config.customModels.filter( + (model): model is string => typeof model === "string" && model.trim().length > 0, + ) + : []; + const slugs = [...new Set(["default", ...customModels.map((model) => model.trim())])]; + return slugs.map((slug) => ({ + slug, + name: slug === "default" ? "Agent default" : slug, + shortName: slug === "default" ? "Default" : slug, + isCustom: slug !== "default", + capabilities: null, + })); +} + +/** + * Add V2-only ACP Registry instances to the orchestration debugger's provider catalog. + * The regular application provider catalog remains V1-owned and is intentionally untouched. + */ +export function deriveOrchestrationV2DebugProviderSnapshots(input: { + readonly providers: ReadonlyArray; + readonly providerInstances: ProviderInstanceConfigMap; +}): ReadonlyArray { + const snapshots = [...input.providers]; + const indexByInstanceId = new Map( + snapshots.map((provider, index) => [provider.instanceId, index]), + ); + + for (const [instanceId, instance] of Object.entries(input.providerInstances)) { + if (instance.driver !== ACP_REGISTRY_DRIVER) continue; + const config = configRecord(instance.config); + const agentId = typeof config.agentId === "string" ? config.agentId.trim() : ""; + if (agentId.length === 0) continue; + const id = instanceId as ProviderInstanceId; + const existingIndex = indexByInstanceId.get(id); + const existing = existingIndex === undefined ? undefined : snapshots[existingIndex]; + const enabled = + instance.enabled ?? (typeof config.enabled === "boolean" ? config.enabled : true); + const snapshot: ServerProvider = { + instanceId: id, + driver: ACP_REGISTRY_DRIVER, + displayName: instance.displayName?.trim() || `ACP: ${agentId}`, + ...(instance.accentColor ? { accentColor: instance.accentColor } : {}), + badgeLabel: "V2 Preview", + showInteractionModeToggle: true, + requiresNewThreadForModelChange: false, + enabled, + installed: true, + version: null, + status: enabled ? "ready" : "disabled", + auth: { status: "unknown" }, + checkedAt: existing?.checkedAt ?? DEBUG_CHECKED_AT, + message: `ACP Registry agent '${agentId}' is resolved when the V2 session starts.`, + availability: "available", + models: configuredModels(config), + slashCommands: [], + skills: [], + }; + if (existingIndex === undefined) { + indexByInstanceId.set(id, snapshots.length); + snapshots.push(snapshot); + } else { + snapshots[existingIndex] = snapshot; + } + } + + return snapshots; +} diff --git a/apps/web/src/routes/debug.orchestration-v2.tsx b/apps/web/src/routes/debug.orchestration-v2.tsx index 63409dab3f..b8835aa2b5 100644 --- a/apps/web/src/routes/debug.orchestration-v2.tsx +++ b/apps/web/src/routes/debug.orchestration-v2.tsx @@ -36,6 +36,7 @@ import { } from "../lib/orchestrationV2Timeline"; import { newCommandId, newMessageId, newProjectId, newThreadId } from "../lib/utils"; import { type AppModelOption, getAppModelOptionsForInstance } from "../modelSelection"; +import { deriveOrchestrationV2DebugProviderSnapshots } from "../orchestrationV2DebugProviders"; import { type ProviderInstanceEntry, deriveProviderInstanceEntries, @@ -1621,7 +1622,14 @@ function OrchestrationV2DebugRoute() { const serverProviders = useServerProviders(); const settings = useSettings(); const keybindings = useServerKeybindings(); - const providerSnapshots = serverProviders.length > 0 ? serverProviders : DEBUG_PROVIDER_SNAPSHOTS; + const providerSnapshots = useMemo( + () => + deriveOrchestrationV2DebugProviderSnapshots({ + providers: serverProviders.length > 0 ? serverProviders : DEBUG_PROVIDER_SNAPSHOTS, + providerInstances: settings.providerInstances, + }), + [serverProviders, settings.providerInstances], + ); const providerInstanceEntries = useMemo>( () => sortProviderInstanceEntries(deriveProviderInstanceEntries(providerSnapshots)), [providerSnapshots], diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 756f113a84..40f32e9e19 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -90,9 +90,40 @@ Cursor receives the same authenticated HTTP MCP endpoint through the SDK's `mcpServers` agent and send options. The adapter passes the authorization header to the SDK but projects only redacted option metadata into protocol diagnostics. +### Grok ACP V2 + +Grok receives the authenticated HTTP MCP endpoint through the ACP +`session/new`, `session/load`, and `session/fork` `mcpServers` field. The shared +ACP adapter owns standard protocol behavior; the Grok flavor adds xAI extension +requests such as structured user questions. + +ACP does not define native subagents or active steering. Grok therefore uses +orchestrator-owned child threads and implements steering through +cancel-and-restart. Its current driver also lacks `session/fork`, so app forks +use portable context transfer. These are orchestrator policies, not +provider-specific MCP tools. + +### ACP Registry V2 + +The `acpRegistry` driver is the generic flavor of the same shared ACP adapter. +Each provider instance names an agent from the official ACP Registry. At +session startup the driver resolves the current platform distribution, uses a +managed binary cache or the declared `npx`/`uvx` package, and then negotiates +standard ACP capabilities during `initialize`. A local executable may override +the managed command without changing the registry-declared arguments or +environment. + +Capabilities such as session loading, session forking, models, modes, and MCP +transport are enabled only when the selected agent advertises them. Missing +features degrade through V2 policy: steering uses interrupt-and-restart, +forking uses portable context when native `session/fork` is unavailable, and +subagents use orchestrator-owned child threads. Registry agents do not receive +provider-specific extensions; those remain in flavors such as Grok. + ### Initial Provider Support -The V2 provider adapters are Codex, Claude Agent SDK, and Cursor Agent SDK. +The V2 provider adapters are Codex, Claude Agent SDK, Cursor Agent SDK, and +Grok plus generic registry agents over ACP. Capability discovery still reports other registered provider instances, but marks them unavailable for orchestration when no V2 adapter exists. This keeps provider selection model-visible without allowing a request that cannot run. @@ -299,6 +330,6 @@ Coverage includes: - inheritance and per-thread provider overrides; and - idempotent retries. -Provider adapter tests separately verify Codex, Claude, and Cursor MCP injection, and -the provider-session manager test verifies that credentials exist before an -adapter opens and are revoked when it closes. +Provider adapter tests separately verify Codex, Claude, Cursor, Grok, and ACP +Registry behavior and MCP injection. The provider-session manager test verifies +that credentials exist before an adapter opens and are revoked when it closes. diff --git a/docs/orchestration-v2/testing-strategy.md b/docs/orchestration-v2/testing-strategy.md index 1906c2e543..7d9185bee4 100644 --- a/docs/orchestration-v2/testing-strategy.md +++ b/docs/orchestration-v2/testing-strategy.md @@ -122,6 +122,14 @@ Claude replay transcript Cursor replay transcript -> Cursor Agent SDK open/send calls and ordered onDelta/run results -> consumed by CursorAdapter + +OpenCode replay transcript + -> OpenCode SDK requests/responses plus ordered SSE events + -> consumed by OpenCodeAdapter + +ACP replay transcript + -> logical JSON-RPC requests/responses/notifications over a strict NDJSON peer + -> consumed by AcpAdapter and a provider flavor (Grok or ACP Registry) ``` Fixtures should preserve raw provider evidence as closely as possible. Expected V2 events or projections are assertions, not fixture input. @@ -131,6 +139,17 @@ call. A transcript should include the `query` prompt/options we sent and then re `SDKMessage` chunks in provider order. This intentionally tests the V2 adapter against real Claude SDK output; it does not test the SDK's own subprocess or transport parser. +ACP fixtures run against a child-process replay peer that validates every outbound frame and +serves recorded inbound frames. This replaces only the external ACP driver transport; the shared +runtime, adapter normalization, orchestration, persistence, and projections remain production code. +The generic ACP Registry harness retargets protocol-standard ACP transcripts; +provider-extension transcripts remain scoped to the flavor that owns the extension. + +OpenCode fixtures replace the SDK client at its HTTP/SSE boundary. They must preserve races between +request responses and SSE events, because user messages and terminal `session.status` events can +arrive before the corresponding `promptAsync` or `abort` response. Subagent fixtures must retain +both parent and child session ids so root-only terminal behavior remains testable. + Provider transcript recorders live with the server orchestration testkit, not with provider client packages. Use `bun run record:codex-replay -- --scenario ` for Codex app-server transcripts and `bun run record:claude-replay -- --scenario ` for Claude Agent SDK transcripts. Use @@ -206,7 +225,7 @@ Testing infrastructure should be built before production rewrites: 2. Effect service definitions. 3. provider runtime transport abstraction. 4. generic replay runtime. -5. Codex, Claude, and Cursor transcript loaders for app-owned provider replay fixtures. +5. Codex, Claude, Cursor, OpenCode, and ACP transcript loaders for app-owned provider replay fixtures. 6. projection reducer tests for core invariants. 7. full command-to-projection integration tests. 8. production layers. diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts index 7788eaace4..627ca2f094 100644 --- a/packages/contracts/src/model.ts +++ b/packages/contracts/src/model.ts @@ -131,6 +131,7 @@ const CODEX_DRIVER_KIND = ProviderDriverKind.make("codex"); const CLAUDE_DRIVER_KIND = ProviderDriverKind.make("claudeAgent"); const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor"); const GROK_DRIVER_KIND = ProviderDriverKind.make("grok"); +const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode"); export const DEFAULT_MODEL = "gpt-5.4"; @@ -141,6 +142,7 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial> [CLAUDE_DRIVER_KIND]: "Claude", [CURSOR_DRIVER_KIND]: "Cursor", [GROK_DRIVER_KIND]: "Grok", + [ACP_REGISTRY_DRIVER_KIND]: "ACP Registry", [OPENCODE_DRIVER_KIND]: "OpenCode", }; diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 6955ab7050..1eb09c9e40 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -305,6 +305,56 @@ export const GrokSettings = makeProviderSettingsSchema( ); export type GrokSettings = typeof GrokSettings.Type; +export const AcpRegistryDistributionPreference = Schema.Literals(["auto", "binary", "npx", "uvx"]); +export type AcpRegistryDistributionPreference = typeof AcpRegistryDistributionPreference.Type; + +export const AcpRegistrySettings = makeProviderSettingsSchema( + { + enabled: Schema.Boolean.pipe( + Schema.withDecodingDefault(Effect.succeed(true)), + Schema.annotateKey({ providerSettingsForm: { hidden: true } }), + ), + agentId: TrimmedString.pipe( + Schema.withDecodingDefault(Effect.succeed("")), + Schema.annotateKey({ + title: "Registry agent ID", + description: "Agent identifier from the official ACP Registry, for example 'devin'.", + providerSettingsForm: { placeholder: "devin", clearWhenEmpty: "persist" }, + }), + ), + commandPath: TrimmedString.pipe( + Schema.withDecodingDefault(Effect.succeed("")), + Schema.annotateKey({ + title: "Executable override", + description: + "Optional local executable to use instead of installing the registry distribution. Registry arguments and environment are still applied.", + providerSettingsForm: { placeholder: "devin", clearWhenEmpty: "omit" }, + }), + ), + authMethodId: TrimmedString.pipe( + Schema.withDecodingDefault(Effect.succeed("")), + Schema.annotateKey({ + title: "Authentication method", + description: + "Optional ACP authentication method ID. By default, the first agent-managed method is selected.", + providerSettingsForm: { placeholder: "auto", clearWhenEmpty: "omit" }, + }), + ), + distribution: AcpRegistryDistributionPreference.pipe( + Schema.withDecodingDefault(Effect.succeed("auto")), + Schema.annotateKey({ providerSettingsForm: { hidden: true } }), + ), + customModels: Schema.Array(Schema.String).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + Schema.annotateKey({ providerSettingsForm: { hidden: true } }), + ), + }, + { + order: ["agentId", "commandPath", "authMethodId"], + }, +); +export type AcpRegistrySettings = typeof AcpRegistrySettings.Type; + export const OpenCodeSettings = makeProviderSettingsSchema( { enabled: Schema.Boolean.pipe(