Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(daemon): support OpenCode CLI v1 and v2 in one harness (#954)
Gustavo Ye8fc1c90c13db
diff --git a/plans/opencode-service-startup.md b/plans/opencode-service-startup.mdnew file mode 100644index 000000000..caa162dda--- /dev/null+++ b/plans/opencode-service-startup.md@@ -0,0 +1,51 @@+# OpenCode startup after model selection++## Features / show case+A bot configured with opencode/space-bunny-free must start the persistent native OpenCode service and reply through the injected Alook CLI. Do not substitute a different model or per-turn runtime. The reported machine uses daemon 0.1.49 and OpenCode v2.0.28 on macOS arm64.++## Designs overview+First reproduce the current daemon launch against the exact official 2.0.28 artifact, using isolated native state. Trace launch arguments, process exit and required HTTP/SSE capabilities before editing. Make the smallest compatibility repair established by reproduction. Keep the existing native process/session authority. A diagnosis-only change cannot close the reported failure.++## New deps+None planned. Native release packages used for private QA are not product dependencies.++## TODOS+- [x] Read both screenshots and verify selected model, daemon/native version and saved audit through scoped read-only D1 queries.+- [x] Verify and reproduce official 2.0.28 native startup; compare the working 1.18.35 control.+- [x] Determine the repair: separate CLI-major compatibility profiles and lanes inside the same OpenCode adapter. Preserve v1 native durable protocol. V2 uses its persisted paginated messages/inbox and new idle records, with common authenticated process/start/stop primitives.+- [x] Modify `src/daemon/agent-driver/src/adapters/opencode/index.ts`, `index.test.ts`, `src/daemon/agent-driver/src/sdk.test.ts`, `recent-context.ts`, `recent-context.test.ts`, and `service-lane.ts`; add `compatibility.ts`, `compatibility.test.ts`, `v2-service-lane.ts`, and `v2-service-lane.test.ts`. Protect existing v1 serve/models arguments; fix v2 readiness, payloads, model variants, pending-input recovery, native tool event/message recovery and terminal correlation. Preserve global recent-project discovery with CLI v2 native `api GET /api/session` rather than its project-scoped `session list`. Update `src/daemon/README.md`, `agent-driver/README.md`, and `agent-driver/RELEASE_NOTES.md` for both major lanes. Do not add a generic event ledger or new dependency.+- [x] Implement and run scoped tests, lint, typecheck, boundary checks and build.+- [x] Commit only after actual affected QA; push one PR and hand exact SHA to Claudette for independent acceptance.+- [ ] Track CI/coverage and preserve failed evidence until delivery. No production release without Gus execution-time confirmation.++### Test cases+- [x] Current reported command fails under 2.0.28 with recorded original native result.+- [x] Corrected native service starts with authenticated loopback and required API, and selected model reaches the native session.+- [x] Existing 1.18.35 native path, persistent reuse, startup cancellation and cleanup remain valid.+- [x] Unsupported/configuration failures retain a meaningful error without leaking credentials.++## QA tests+- [x] Actual bot journey: isolated local test owner creates/binds OpenCode bot with opencode/space-bunny-free; human message reaches daemon wake; native session shows exact selected model; injected CLI pulls/acks and sends the bot-authored reply. Correlate local D1 message, WS wake, daemon timeline and native session history. Preserve session for follow-up.+- [x] Two turns use one persistent native session and bot sends two stored replies; no seed helper acts as the bot.+- [x] Stop only owned native QA processes; no native OpenCode service remains. Preserve isolated synthetic session state and leave owner state/credentials untouched. Local web/queue/ws QA services stay available for independent acceptance.+- [ ] Claudette independently verifies the final committed artifact, exact model and visible bot reply.++## Local QA evidence (2026-10-13)+- Official CLI 2.0.28 rejects the prior `serve --pure` with exit 1. Original evidence is retained separately.+- CLI v2 real bot: one physical open, two native succeeded idle records, two injected CLI pulls and sends, two FSM root ends; exact `opencode/space-bunny-free`. An isolated Chrome context renders both bot-authored replies in the channel.+- CLI v1 1.18.35 real bot: one physical open, two FSM root ends, same selected model, two native durable prompt admissions and two stored bot-authored replies.+- CLI v2 native shell plus forced SSE disconnect: one reconnect, accepted busy input, native tool finishes, final response contains both requested markers, only current root settles. Native interrupt produces `interrupted` idle; `#high` persists as the actual model variant and generates a reply.+- CLI v2 global recent-project query finds the isolated bot project while `session list` from the repository returns zero; keeps read-only global discovery.+- 97 scoped tests pass; agent-driver typecheck/lint/knip/build and import-boundary checks pass. Daemon packed agent-driver isolation test passes.+- No production mutation/release. Exact committed artifact and independent acceptance remain required.++## CI follow-up+Initial CI found zero-bound discovery unnecessarily probing a missing CLI and an old SDK test treating Node as a supported OpenCode major. Zero-project discovery now returns the existing empty result without a version probe; SDK coverage verifies unsupported Node and a supported CLI shim separately.++## Coverage follow-up+Added focused tests for empty discovery with an unavailable CLI, actual override discovery dispatch, interrupt receipt versus native interrupted idle, failed native idle followed by session reuse, and transient recovery 503 without losing accepted input ownership. 141 focused tests and typecheck/lint pass. No production-code change in this follow-up.++## Recovery boundary completion+Complete patch coverage requires malformed native responses and close/admission races. Remove only redundant checks: parent start already verifies physical identity/session before invoking streams; admit owns its own failure cleanup, so beginRoot does not clear a second time. Pass the captured root into admit rather than rereading an impossible missing root. Retain every asynchronous identity/generation fence and durable recovery check. Repeat native QA for this small production simplification.++Final local candidate: 171 focused tests pass with no uncovered statements in the changed OpenCode modules; typecheck/lint/build/boundary/knip pass. After the small simplification, repeat native v1/v2 real-bot journeys, v2 disconnect/busy and interrupt all pass. Final independent QA and CI/Codecov remain merge gates.diff --git a/src/daemon/README.md b/src/daemon/README.mdindex 2314645a0..a49040436 100644--- a/src/daemon/README.md+++ b/src/daemon/README.md@@ -108,10 +108,12 @@ without killing the process.### Persistent service runtime (OpenCode)-OpenCode starts one authenticated, loopback-only v2 service per logical session.-Root prompts and busy steers share the same service and vendor session. Durable-session SSE is replayed by event id and sequence across reconnects; a separate-live stream handles permissions.+OpenCode starts one authenticated, loopback-only service per logical session.+The actual CLI major selects its adapter: v1 retains `--pure` and durable event+replay; v2 uses its native API, persisted inbox/messages, and a new idle record+after all accepted inputs. Root prompts and busy steers share the same service+and vendor session. Live SSE handles permissions and tool progress. Unknown+majors or missing native capabilities fail explicitly.---@@ -123,7 +125,7 @@ live stream handles permissions.| **codex** | persistent session | JSON-RPC 2.0 (`app-server --listen stdio://`) | `safe_boundary_queue` | `initialize` → `thread/start`/`resume` | JSON-RPC notifications || **pi** | persistent session | `@earendil-works/pi-coding-agent` | `steer` | `session.prompt()` | SDK callback || **cursor** | persistent session | ACP JSON-RPC 2.0 (`cursor-agent acp`) | `steer` | `session/prompt` | `session/update` + correlated prompt response |-| **opencode** | persistent session | authenticated HTTP + SSE (`opencode serve --pure`) | `steer` | v2 session prompt API | durable + live SSE |+| **opencode** | persistent session | authenticated HTTP + SSE (`opencode serve`; v1 adds `--pure`) | `steer` | CLI-major session prompt API | native recovery + live SSE |(Exact launch flags live in `agent-driver/src/adapters/<backend>/`.)diff --git a/src/daemon/agent-driver/README.md b/src/daemon/agent-driver/README.mdindex d35645cf6..cc260c526 100644--- a/src/daemon/agent-driver/README.md+++ b/src/daemon/agent-driver/README.md@@ -119,6 +119,14 @@ closes the boundary again. Compaction and review remain closed until theirmatching finished events. Cursor, OpenCode, and Pi steer immediately and do notparticipate in this boundary latch.+OpenCode selects a private compatibility lane from the actual CLI version.+CLI v1 retains its `--pure` launch and durable event admission frontier; CLI v2+recovers native inbox/messages and requires a new idle record after every+accepted input. Both retain one authenticated service/session and the same+public contract. Recent-project discovery stays global: v1 uses session list,+while v2 queries its native session API without a project filter. Unknown CLI+majors and missing required capabilities fail explicitly.+Pi's runtime behavior did not change in this migration. It already kept oneSDK session and used prompt/steer/abort/dispose on that session; contract v1formalizes that existing persistent behavior as an `in_process_sdk`diff --git a/src/daemon/agent-driver/RELEASE_NOTES.md b/src/daemon/agent-driver/RELEASE_NOTES.mdindex 808729420..d7205de47 100644--- a/src/daemon/agent-driver/RELEASE_NOTES.md+++ b/src/daemon/agent-driver/RELEASE_NOTES.md@@ -1,5 +1,17 @@# Release notes+## OpenCode CLI major compatibility++- Select CLI v1 or v2 within the existing OpenCode harness using the actual+ configured command version. Keep v1 launch flags and durable protocol.+- Support v2 readiness, selected model variants, prompt receipts, permissions,+ tool lifecycle, and recovery through persisted native inbox/messages. A new+ idle record after all current inputs owns completion; a live stream or+ streamed assistant response cannot complete the root.+- Preserve global recent-project discovery through the v2 native session API.+- Include scrubbed native exit details in readiness failures. No public SDK+ contract, process authority, dependency, or user configuration change.+## Bounded recent-context discovery- Added `AgentDriverSdk.discoverRecentContext()` with independentdiff --git a/src/daemon/agent-driver/src/adapters/opencode/compatibility.test.ts b/src/daemon/agent-driver/src/adapters/opencode/compatibility.test.tsnew file mode 100644index 000000000..b29823c5c--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/opencode/compatibility.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from "vitest";+import { resolveOpenCodeCompatibility } from "./compatibility.js";++describe("OpenCode CLI major compatibility", () => {+ it.each(["1.17.20", "1.18.35", "opencode v1.19.0", "v1.19.1-beta.2"])("preserves CLI v1 arguments for %s", (version) => {+ expect(resolveOpenCodeCompatibility(version)).toMatchObject({ major: 1, serviceArgs: ["serve", "--pure"], modelArgs: ["models", "--pure"] });+ });++ it.each(["2.0.28", "opencode v2.0.29", "v2.1.0"])("selects CLI v2 arguments for %s", (version) => {+ expect(resolveOpenCodeCompatibility(version)).toMatchObject({ major: 2, serviceArgs: ["serve"], modelArgs: ["models", "--standalone"] });+ });++ it.each([undefined, "", "unknown", "3.0.0", "error: version 2.0.28 failed"])("rejects unrecognized versions without defaulting: %s", (version) => {+ expect(() => resolveOpenCodeCompatibility(version)).toThrow("unrecognized or has an unsupported major");+ });+});diff --git a/src/daemon/agent-driver/src/adapters/opencode/compatibility.ts b/src/daemon/agent-driver/src/adapters/opencode/compatibility.tsnew file mode 100644index 000000000..877983e22--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/opencode/compatibility.ts@@ -0,0 +1,27 @@+export interface OpenCodeCompatibility {+ readonly major: 1 | 2;+ readonly modelArgs: readonly string[];+ readonly serviceArgs: readonly string[];+ readonly sessionListArgs: (maxCount: number) => readonly string[];+}++export const OPEN_CODE_V1: OpenCodeCompatibility = {+ major: 1,+ modelArgs: ["models", "--pure"],+ serviceArgs: ["serve", "--pure"],+ sessionListArgs: (maxCount) => ["session", "list", "--format", "json", "--max-count", String(maxCount), "--pure"],+};++const OPEN_CODE_V2: OpenCodeCompatibility = {+ major: 2,+ modelArgs: ["models", "--standalone"],+ serviceArgs: ["serve"],+ sessionListArgs: (maxCount) => ["api", "--standalone", "GET", `/api/session?parentID=null&order=desc&limit=${maxCount}`],+};++export function resolveOpenCodeCompatibility(version: string | undefined): OpenCodeCompatibility {+ const match = version?.trim().match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:[-+][\w.-]+)?$/i);+ if (match?.[1] === "1") return OPEN_CODE_V1;+ if (match?.[1] === "2") return OPEN_CODE_V2;+ throw new Error("Installed OpenCode CLI version is unrecognized or has an unsupported major version");+}diff --git a/src/daemon/agent-driver/src/adapters/opencode/index.test.ts b/src/daemon/agent-driver/src/adapters/opencode/index.test.tsindex 56997b883..37e01df05 100644--- a/src/daemon/agent-driver/src/adapters/opencode/index.test.ts+++ b/src/daemon/agent-driver/src/adapters/opencode/index.test.ts@@ -5,17 +5,22 @@ import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { fakeLaunchContext, fakePrepared } from "../../testing/adapter-fixture.js";import { OpenCodeDriver } from "./index.js";+import { resolveOpenCodeCompatibility } from "./compatibility.js";+import * as recentContext from "./recent-context.js";+import { OpenCodeV2ServiceLane } from "./v2-service-lane.js";const spawnAgentProcess = vi.hoisted(() => vi.fn());vi.mock("../../internal/killTree.js", async () => ({...(await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js")),spawnAgentProcess,+ killProcessTree: vi.fn(async () => {}),}));const directories: string[] = [];afterEach(() => {vi.restoreAllMocks();+ vi.unstubAllGlobals();for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });});@@ -24,7 +29,29 @@ describe("OpenCodeDriver persistent v2 service", () => {beforeEach(() => {spawnAgentProcess.mockClear();- driver = new OpenCodeDriver();+ driver = new OpenCodeDriver(undefined, () => ({ status: "healthy", version: "1.18.35" }));+ });++ it("keeps empty discovery available when the configured CLI is unavailable", async () => {+ const version = vi.fn(() => ({ status: "unhealthy" as const, lastError: "not_found" }));+ const driver = new OpenCodeDriver(undefined, version);+ await expect(driver.discoverRecentContext({ recentSessionFilesTopK: 2, recentProjectsTopK: 0 })).resolves.toEqual({+ sessionFiles: { capability: "unavailable", items: [] }, recentProjects: [],+ });+ expect(version).not.toHaveBeenCalled();+ expect(driver.probe()).toMatchObject({ status: "unhealthy", lastError: "not_found" });+ expect(() => driver.discoverRecentContext({ recentSessionFilesTopK: 0, recentProjectsTopK: 1 })).toThrow("could not report its version");+ await expect(driver.openLane(fakeLaunchContext("opencode", "/tmp"))).rejects.toThrow("could not report its version");+ });++ it("dispatches recent projects with the actual override's CLI compatibility", async () => {+ const discover = vi.spyOn(recentContext, "discoverOpenCodeRecentContext").mockResolvedValue({+ sessionFiles: { capability: "unavailable", items: [] }, recentProjects: [],+ });+ const driver = new OpenCodeDriver(undefined, () => ({ status: "healthy", version: "2.0.28" }));+ const request = { command: "opencode-custom", recentSessionFilesTopK: 0, recentProjectsTopK: 1 };+ await driver.discoverRecentContext(request);+ expect(discover).toHaveBeenCalledWith(request, { compatibility: resolveOpenCodeCompatibility("2.0.28") });});it("uses models --pure output for a non-fatal startup catalog", () => {@@ -32,7 +59,7 @@ describe("OpenCodeDriver persistent v2 service", () => {ok: true as const,output: "openai/gpt-5\nanthropic/claude-sonnet\n",}));- const result = new OpenCodeDriver(outputProbe).probe(process.execPath);+ const result = new OpenCodeDriver(outputProbe, () => ({ status: "healthy", version: "1.18.35" })).probe(process.execPath);expect(outputProbe).toHaveBeenCalledWith(process.execPath, ["models", "--pure"]);expect(result).toMatchObject({@@ -46,8 +73,57 @@ describe("OpenCodeDriver persistent v2 service", () => {});});+ it("probes the configured CLI major and uses its model catalog arguments", () => {+ const output = vi.fn(() => ({ ok: true as const, output: "opencode/space-bunny-free\n" }));+ const version = vi.fn(() => ({ status: "healthy" as const, version: "opencode v2.0.28" }));+ const result = new OpenCodeDriver(output, version).probe("opencode-v2-custom");+ expect(version).toHaveBeenCalledWith("opencode", {}, "opencode-v2-custom");+ expect(output).toHaveBeenCalledWith("opencode-v2-custom", ["models", "--standalone"]);+ expect(result.status).toBe("healthy");+ });++ it("rejects an unknown CLI major before catalog or service startup", async () => {+ const output = vi.fn();+ const unknown = new OpenCodeDriver(output, () => ({ status: "healthy", version: "3.0.0" }));+ expect(unknown.probe()).toMatchObject({ status: "unhealthy", lastError: "unsupported_opencode_cli_version" });+ await expect(unknown.openLane(fakeLaunchContext("opencode", "/tmp"))).rejects.toThrow("unsupported major");+ expect(output).not.toHaveBeenCalled();+ expect(spawnAgentProcess).not.toHaveBeenCalled();+ });++ it("selects the CLI v2 lane from the actual command override", async () => {+ const version = vi.fn(() => ({ status: "healthy" as const, version: "2.0.28" }));+ const lane = await new OpenCodeDriver(undefined, version).openLane(fakeLaunchContext("opencode", "/tmp", {+ config: { runtimeConfig: { command: "opencode-v2-custom", model: { kind: "default" } } },+ }));+ expect(version).toHaveBeenCalledWith("opencode", {}, "opencode-v2-custom");+ expect(lane).toBeInstanceOf(OpenCodeV2ServiceLane);+ expect(spawnAgentProcess).not.toHaveBeenCalled();+ });++ it("fixes the selected CLI profile for the lane even when a later probe changes", async () => {+ const version = vi.fn().mockReturnValueOnce({ status: "healthy", version: "2.0.28" }).mockReturnValue({ status: "healthy", version: "1.18.35" });+ const driver = new OpenCodeDriver(() => ({ ok: false, error: "unavailable" }), version);+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ version: "3.0.0", pid: 42_999 })));+ const lane = await driver.openLane(fakeLaunchContext("opencode", "/tmp"));+ driver.probe();+ spawnAgentProcess.mockReturnValue(Object.assign(new EventEmitter(), { pid: 42_999, stdout: null, stderr: null, stdin: null, exitCode: null, signalCode: null, kill: vi.fn() }));+ expect(await lane.start({ text: "one", terminalOwner: "msg_root" })).toMatchObject({ ok: false, reason: "incompatible_configuration" });+ expect(spawnAgentProcess.mock.calls[0]?.[1]).toEqual(expect.arrayContaining(["serve", "--hostname"]));+ expect(spawnAgentProcess.mock.calls[0]?.[1]).not.toContain("--pure");+ });++ it("protects CLI v2 service authentication without passing legacy flags", async () => {+ const directory = mkdtempSync(join(tmpdir(), "opencode-v2-spawn-")); directories.push(directory);+ await driver.spawnService(fakeLaunchContext("opencode", directory), 43123, "session-secret", resolveOpenCodeCompatibility("2.0.28"));+ const [, args, options] = spawnAgentProcess.mock.calls[0]!;+ expect(args).toEqual(["serve", "--hostname", "127.0.0.1", "--port", "43123"]);+ expect(options.env.OPENCODE_PASSWORD).toBe("session-secret");+ expect(JSON.stringify(args)).not.toContain("session-secret");+ });+it("keeps runtime health healthy when models --pure fails", () => {- expect(new OpenCodeDriver(() => ({ ok: false, error: "ETIMEDOUT" })).probe(process.execPath))+ expect(new OpenCodeDriver(() => ({ ok: false, error: "ETIMEDOUT" }), () => ({ status: "healthy", version: "1.18.35" })).probe(process.execPath)).toMatchObject({ status: "healthy", reasoning: undefined });});diff --git a/src/daemon/agent-driver/src/adapters/opencode/index.ts b/src/daemon/agent-driver/src/adapters/opencode/index.tsindex 714167fbb..76132a913 100644--- a/src/daemon/agent-driver/src/adapters/opencode/index.ts+++ b/src/daemon/agent-driver/src/adapters/opencode/index.ts@@ -1,9 +1,9 @@/**- * OpenCode driver — persistent v2 service over authenticated loopback HTTP/SSE.+ * OpenCode driver — CLI-major lanes over authenticated loopback HTTP/SSE.*- * One `opencode serve` process owns one logical Alook session. The lane uses- * caller-generated message ids for durable prompt admission and an- * admission-frontier-bound `/api/session/active` query as the terminal owner.+ * One `opencode serve` process owns one logical Alook session. CLI v1 retains+ * its durable event admission frontier. CLI v2 recovers persisted inputs and+ * messages and requires a new native idle record after every accepted input.*/import { randomBytes } from "node:crypto";import type {@@ -29,6 +29,8 @@ import {} from "./service-lane.js";import { legacyOpenCodeApiEnvironment } from "./legacy-auth.js";import { discoverOpenCodeRecentContext } from "./recent-context.js";+import { OPEN_CODE_V1, resolveOpenCodeCompatibility, type OpenCodeCompatibility } from "./compatibility.js";+import { OpenCodeV2ServiceLane } from "./v2-service-lane.js";function createOpenCodeMessageId(): string {return `msg_${randomBytes(16).toString("hex")}`;@@ -46,16 +48,26 @@ export class OpenCodeDriver implements BackendAdapter, OpenCodeServiceProcessFacconstructor(private readonly outputProbe: (command: string, args: string[]) => CommandOutputProbeResult = probeCommandOutput,+ private readonly versionProbe: typeof probeCliRuntime = probeCliRuntime,) {}discoverRecentContext(request: Parameters<typeof discoverOpenCodeRecentContext>[0]) {- return discoverOpenCodeRecentContext(request);+ if (request.recentProjectsTopK === 0) return discoverOpenCodeRecentContext(request);+ const result = this.versionProbe("opencode", {}, request.command);+ if (result.status !== "healthy") throw new Error("Installed OpenCode CLI could not report its version");+ return discoverOpenCodeRecentContext(request, { compatibility: resolveOpenCodeCompatibility(result.version) });}probe(command?: string) {- const result = probeCliRuntime("opencode", {}, command);+ const result = this.versionProbe("opencode", {}, command);if (result.status !== "healthy") return result;- const spec = resolveSpawnSpec("opencode", ["models", "--pure"], command);+ let compatibility: OpenCodeCompatibility;+ try {+ compatibility = resolveOpenCodeCompatibility(result.version);+ } catch {+ return { ...result, status: "unhealthy" as const, lastError: "unsupported_opencode_cli_version" };+ }+ const spec = resolveSpawnSpec("opencode", [...compatibility.modelArgs], command);const output = this.outputProbe(spec.command, spec.args);return {...result,@@ -68,21 +80,34 @@ export class OpenCodeDriver implements BackendAdapter, OpenCodeServiceProcessFac}async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane> {- return new OpenCodeServiceLane(this, ctx, {+ const command = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;+ const result = this.versionProbe("opencode", {}, command);+ if (result.status !== "healthy") throw new Error("Installed OpenCode CLI could not report its version");+ const compatibility = resolveOpenCodeCompatibility(result.version);+ const factory: OpenCodeServiceProcessFactory = {+ spawnService: (launch, port, password) => this.spawnService(launch, port, password, compatibility),+ };+ const Lane = compatibility.major === 1 ? OpenCodeServiceLane : OpenCodeV2ServiceLane;+ return new Lane(factory, ctx, {onRawStdoutLine: options?.onRawStdoutLine,});}- async spawnService(ctx: AdapterLaunchContext, port: number, password: string): Promise<SpawnedProcess> {+ async spawnService(+ ctx: AdapterLaunchContext,+ port: number,+ password: string,+ compatibility: OpenCodeCompatibility = OPEN_CODE_V1,+ ): Promise<SpawnedProcess> {const { spawnEnv } = await prepareCliTransport(ctx, {OPENCODE_SERVER_PASSWORD: password,+ ...(compatibility.major === 2 ? { OPENCODE_PASSWORD: password } : {}),});const fields = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);Object.assign(spawnEnv, await legacyOpenCodeApiEnvironment(spawnEnv, fields.model));const override = fields.command;const args = [- "serve",- "--pure",+ ...compatibility.serviceArgs,"--hostname","127.0.0.1","--port",diff --git a/src/daemon/agent-driver/src/adapters/opencode/recent-context.test.ts b/src/daemon/agent-driver/src/adapters/opencode/recent-context.test.tsindex d064eb8ce..9755d02f0 100644--- a/src/daemon/agent-driver/src/adapters/opencode/recent-context.test.ts+++ b/src/daemon/agent-driver/src/adapters/opencode/recent-context.test.ts@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import type { SpawnedProcessHandle } from "../../internal/adapter.js";import { discoverOpenCodeRecentContext } from "./recent-context.js";import path from "node:path";+import { resolveOpenCodeCompatibility } from "./compatibility.js";const projectPath = (...segments: string[]) => path.join(path.parse(process.cwd()).root, "projects", ...segments);const killTreeMocks = vi.hoisted(() => ({ killProcessTree: vi.fn(async () => {}) }));@@ -103,6 +104,15 @@ describe("OpenCode recent-context discovery", () => {expect(cleanup).toHaveBeenCalledOnce();});+ it("uses the CLI v2 global native API without a current-project filter", async () => {+ const spawn = vi.fn(() => fakeCommandProcess(JSON.stringify({ data: [{ location: { directory: projectPath("v2") }, time: { updated: "2026-01-01T00:00:00Z" } }], cursor: {} })));+ const result = await discoverOpenCodeRecentContext({ recentSessionFilesTopK: 0, recentProjectsTopK: 1, command: "opencode-v2-custom" }, {+ spawn, cleanup: async () => {}, compatibility: resolveOpenCodeCompatibility("2.0.28"),+ });+ expect(spawn.mock.calls[0]?.slice(0, 2)).toEqual(["opencode-v2-custom", ["api", "--standalone", "GET", "/api/session?parentID=null&order=desc&limit=10"]]);+ expect(result.recentProjects).toHaveLength(1);+ });+it("fails closed on invalid JSON", async () => {await expect(discoverOpenCodeRecentContext({recentSessionFilesTopK: 0,diff --git a/src/daemon/agent-driver/src/adapters/opencode/recent-context.ts b/src/daemon/agent-driver/src/adapters/opencode/recent-context.tsindex 2bde01be7..9288d4f4b 100644--- a/src/daemon/agent-driver/src/adapters/opencode/recent-context.ts+++ b/src/daemon/agent-driver/src/adapters/opencode/recent-context.ts@@ -7,11 +7,14 @@ import { spawnAgentProcess } from "../../internal/killTree.js";import { resolveSpawnSpec } from "../../internal/probe.js";import { RecentContextCollector } from "../../internal/recent-context.js";import { asRecord } from "../../internal/utils.js";+import { OPEN_CODE_V1, type OpenCodeCompatibility } from "./compatibility.js";const OPENCODE_DISCOVERY_TIMEOUT_MS = 15_000;const OPENCODE_DISCOVERY_OUTPUT_MAX_BYTES = 4 * 1024 * 1024;-type OpenCodeRecentContextDependencies = DiscoveryProcessDependencies;+interface OpenCodeRecentContextDependencies extends DiscoveryProcessDependencies {+ readonly compatibility?: OpenCodeCompatibility;+}interface CommandOutput {readonly output: string;@@ -56,6 +59,7 @@ export async function discoverOpenCodeRecentContext(): Promise<RecentContextDiscoveryData> {const collector = new RecentContextCollector(request, "unavailable");if (collector.satisfied) return collector.result();+ const compatibility = dependencies.compatibility ?? OPEN_CODE_V1;const startedAt = Date.now();const timeoutMs = dependencies.timeoutMs ?? OPENCODE_DISCOVERY_TIMEOUT_MS;let remainingOutputBytes = dependencies.outputMaxBytes ?? OPENCODE_DISCOVERY_OUTPUT_MAX_BYTES;@@ -65,7 +69,7 @@ export async function discoverOpenCodeRecentContext(if (remainingTimeoutMs <= 0) throw new Error("OpenCode discovery timed out");const spec = resolveSpawnSpec("opencode",- ["session", "list", "--format", "json", "--max-count", String(maxCount), "--pure"],+ [...compatibility.sessionListArgs(maxCount)],request.command,);const commandOutput = await collectCommandOutput(@@ -83,12 +87,14 @@ export async function discoverOpenCodeRecentContext(} catch {throw new Error("OpenCode session listing returned invalid JSON");}+ if (compatibility.major === 2) parsed = asRecord(parsed)?.data;if (!Array.isArray(parsed)) throw new Error("OpenCode session listing returned an invalid response");for (const value of parsed) {const session = asRecord(value);if (!session) continue;- const modifiedAt = session.updated ?? session.updatedAt;- collector.add({ projectPath: session.directory, modifiedAt });+ const modifiedAt = compatibility.major === 2 ? asRecord(session.time)?.updated : session.updated ?? session.updatedAt;+ const projectPath = compatibility.major === 2 ? asRecord(session.location)?.directory : session.directory;+ collector.add({ projectPath, modifiedAt });}if (collector.satisfied || parsed.length < maxCount) break;const nextMaxCount = Math.min(Number.MAX_SAFE_INTEGER, maxCount * 2);diff --git a/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts b/src/daemon/agent-driver/src/adapters/opencode/service-lane.tsindex e1db0d189..28f9acbfb 100644--- a/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts+++ b/src/daemon/agent-driver/src/adapters/opencode/service-lane.ts@@ -17,6 +17,7 @@ import type {import { SettledUsageProjector } from "../../internal/token-usage.js";import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";import { killProcessTree, SESSION_STOP_GRACE_MS } from "../../internal/killTree.js";+import { scrubDriverErrorMessage } from "../../internal/errors.js";const HOST = "127.0.0.1";const START_TIMEOUT_MS = 15_000;@@ -79,10 +80,10 @@ export interface OpenCodeServiceProcessFactory {class OpenCodeIncompatibleError extends Error {}class OpenCodeResetRequiredError extends Error {}class OpenCodePortBindError extends Error {}-class OpenCodeProtocolError extends Error {}+export class OpenCodeProtocolError extends Error {}class OpenCodeStoppedError extends Error {}-class OpenCodeHttpError extends Error {+export class OpenCodeHttpError extends Error {constructor(readonly status: number,operation: string,@@ -91,7 +92,7 @@ class OpenCodeHttpError extends Error {}}-function record(value: unknown): JsonRecord | null {+export function record(value: unknown): JsonRecord | null {return value && typeof value === "object" && !Array.isArray(value)? value as JsonRecord: null;@@ -158,20 +159,20 @@ function codeFromError(value: unknown): string {}export class OpenCodeServiceLane implements RuntimeLane {- private readonly events = new EventEmitter();+ protected readonly events = new EventEmitter();private readonly fetchFn: typeof fetch;private readonly password: string;private readonly requestControllers = new Set<AbortController>();private process: SpawnedProcessHandle | null = null;- private identity: ServiceIdentity | null = null;+ protected identity: ServiceIdentity | null = null;private baseUrl = "";- private sessionId: string | null = null;+ protected sessionId: string | null = null;private stdoutBuffer = "";private stderrBuffer = "";private serviceGeneration = 0;private started = false;- private ready = false;- private stopping = false;+ protected ready = false;+ protected stopping = false;private requestedStopReason?: string;private suppressExit = false;private serviceActivated = false;@@ -183,7 +184,7 @@ export class OpenCodeServiceLane implements RuntimeLane {private durableAbort?: AbortController;private liveAbort?: AbortController;private durableTask?: Promise<void>;- private liveTask?: Promise<void>;+ protected liveTask?: Promise<void>;private durableBootstrapAdmissionUsed = false;private durableGate = makeGate();private liveGate = makeGate();@@ -207,7 +208,7 @@ export class OpenCodeServiceLane implements RuntimeLane {constructor(private readonly factory: OpenCodeServiceProcessFactory,private readonly ctx: AdapterLaunchContext,- private readonly options: OpenCodeServiceLaneOptions = {},+ protected readonly options: OpenCodeServiceLaneOptions = {},) {this.fetchFn = options.fetch ?? fetch;this.password = options.password ?? randomBytes(32).toString("base64url");@@ -491,7 +492,9 @@ export class OpenCodeServiceLane implements RuntimeLane {if (this.processStartError) throw this.processStartError;if (!this.identity || this.identity.generation !== generation || this.isProcessClosed(this.identity.process)) {if (/EADDRINUSE|address already in use/i.test(this.stderrBuffer)) throw new OpenCodePortBindError("OpenCode service port bind raced");- throw new Error("OpenCode service exited before readiness");+ const process = this.identity?.process;+ const detail = scrubDriverErrorMessage(this.stderrBuffer.replaceAll(this.password, "[redacted]"), "no native stderr");+ throw new Error(`OpenCode service exited before readiness (code=${process?.exitCode ?? "unknown"}, signal=${process?.signalCode ?? "none"}): ${detail}`);}try {const healthTimeoutMs = Math.max(1, Math.min(@@ -500,14 +503,14 @@ export class OpenCodeServiceLane implements RuntimeLane {this.options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS,));const { response, body } = await this.fetchJsonWithTimeout(- "/global/health",+ this.healthPath,{ method: "GET" },"health",healthTimeoutMs,);if (response.ok) {const health = record(body);- if (health?.healthy !== true) {+ if (!this.acceptsHealth(health)) {throw new OpenCodeIncompatibleError("Installed OpenCode service did not report healthy status");}await this.verifyOpenApi();@@ -523,11 +526,24 @@ export class OpenCodeServiceLane implements RuntimeLane {}private async verifyOpenApi(): Promise<void> {- const { response, body } = await this.fetchJsonWithTimeout("/doc", { method: "GET" }, "OpenAPI");+ const { response, body } = await this.fetchJsonWithTimeout(this.openApiPath, { method: "GET" }, "OpenAPI");if (!response.ok) throw new OpenCodeIncompatibleError("Installed OpenCode service does not expose its OpenAPI document");const document = record(body);const paths = record(document?.paths);- const required = [+ const required = this.requiredApiPaths;+ if (!paths || required.some((path) => !record(paths[path]))) {+ throw new OpenCodeIncompatibleError("Installed OpenCode service is missing required session capabilities");+ }+ }++ protected get healthPath(): string { return "/global/health"; }++ protected get openApiPath(): string { return "/doc"; }++ protected acceptsHealth(health: JsonRecord | null): boolean { return health?.healthy === true; }++ protected get requiredApiPaths(): readonly string[] {+ return ["/api/session","/api/session/active","/api/session/{sessionID}/prompt",@@ -539,13 +555,14 @@ export class OpenCodeServiceLane implements RuntimeLane {"/api/session/{sessionID}/permission/{requestID}/reply","/api/event",];- if (!paths || required.some((path) => !record(paths[path]))) {- throw new OpenCodeIncompatibleError("Installed OpenCode service is missing required v2 session capabilities");- }+ }++ protected get selectedModel(): JsonRecord | undefined {+ return parseModelRef(resolveLaunchFieldsOrDefault(this.ctx.config.runtimeConfig).model);}private async openSession(resumeId: string | undefined): Promise<void> {- const model = parseModelRef(resolveLaunchFieldsOrDefault(this.ctx.config.runtimeConfig).model);+ const model = this.selectedModel;if (resumeId) {const { response, body } = await this.fetchJsonWithTimeout(`/api/session/${encodeURIComponent(resumeId)}`,@@ -589,11 +606,11 @@ export class OpenCodeServiceLane implements RuntimeLane {this.sessionId = session.id;}- private async primeHistory(): Promise<void> {+ protected async primeHistory(): Promise<void> {await this.catchUpHistory(false);}- private startStreams(): void {+ protected startStreams(): void {const identity = this.identity;if (!identity || !this.sessionId) throw new Error("OpenCode service streams started before session initialization");this.durableTask = this.runDurableStream(identity).catch((error) => this.streamFailure("durable", error));@@ -640,7 +657,7 @@ export class OpenCodeServiceLane implements RuntimeLane {}}- private async runLiveStream(identity: ServiceIdentity): Promise<void> {+ protected async runLiveStream(identity: ServiceIdentity): Promise<void> {while (!this.stopping && this.isIdentity(identity)) {const gate = this.liveGate;const controller = new AbortController();@@ -678,7 +695,7 @@ export class OpenCodeServiceLane implements RuntimeLane {this.protocolFailure(`OpenCode ${kind} stream stopped unexpectedly`, error);}- private async openStream(path: string, lifecycle: AbortController, operation: string): Promise<Response> {+ protected async openStream(path: string, lifecycle: AbortController, operation: string): Promise<Response> {const deadline = new AbortController();const timeout = setTimeout(() => deadline.abort(), this.options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS);timeout.unref?.();@@ -695,7 +712,7 @@ export class OpenCodeServiceLane implements RuntimeLane {}}- private async consumeSse(response: Response, consume: (value: unknown) => Promise<void>): Promise<void> {+ protected async consumeSse(response: Response, consume: (value: unknown) => Promise<void>): Promise<void> {const reader = response.body!.getReader();const decoder = new TextDecoder();let buffer = "";@@ -898,17 +915,17 @@ export class OpenCodeServiceLane implements RuntimeLane {return seq;}- private async handleLiveEvent(value: unknown): Promise<void> {+ protected async handleLiveEvent(value: unknown): Promise<void> {const event = record(value);const data = record(event?.data);- if (event?.type !== "permission.v2.asked" || data?.sessionID !== this.sessionId) return;+ if (event?.type !== this.permissionEventType || data?.sessionID !== this.sessionId) return;if (typeof data.id !== "string" || !/^per/.test(data.id)) {throw new OpenCodeProtocolError("OpenCode emitted a malformed permission request");}await this.replyPermission(data.id);}- private async recoverPendingPermissions(): Promise<void> {+ protected async recoverPendingPermissions(): Promise<void> {if (!this.sessionId) return;const { response, body: responseBody } = await this.fetchJsonWithTimeout(`/api/session/${encodeURIComponent(this.sessionId)}/permission`,@@ -926,14 +943,18 @@ export class OpenCodeServiceLane implements RuntimeLane {}}- private async replyPermission(requestId: string): Promise<void> {+ protected get permissionEventType(): string { return "permission.v2.asked"; }++ protected get permissionReply(): JsonRecord { return { reply: "once" }; }++ protected async replyPermission(requestId: string): Promise<void> {if (this.handledPermissions.has(requestId)) return;const existing = this.permissionFlights.get(requestId);if (existing) return existing;const flight = this.requestNoContent(`/api/session/${encodeURIComponent(this.sessionId!)}/permission/${encodeURIComponent(requestId)}/reply`,"POST",- { reply: "once" },+ this.permissionReply,"permission reply",).catch((error) => {@@ -945,7 +966,7 @@ export class OpenCodeServiceLane implements RuntimeLane {return flight;}- private async beginRoot(input: LaneStartInput): Promise<LaneAdmission> {+ protected async beginRoot(input: LaneStartInput): Promise<LaneAdmission> {const receipt = input.terminalOwner?.startsWith("msg_") ? input.terminalOwner : this.newMessageId();this.activeRoot = {receipt,@@ -1172,7 +1193,7 @@ export class OpenCodeServiceLane implements RuntimeLane {} satisfies AdapterEvent);}- private async requestNoContent(+ protected async requestNoContent(path: string,method: "POST",body: JsonRecord | undefined,@@ -1213,7 +1234,7 @@ export class OpenCodeServiceLane implements RuntimeLane {}}- private async fetchJsonWithTimeout(+ protected async fetchJsonWithTimeout(path: string,init: RequestInit,operation: string,@@ -1258,11 +1279,11 @@ export class OpenCodeServiceLane implements RuntimeLane {return headers;}- private newMessageId(): string {+ protected newMessageId(): string {return `msg_${randomBytes(16).toString("hex")}`;}- private diagnostic(severity: "warning" | "error", message: string): void {+ protected diagnostic(severity: "warning" | "error", message: string): void {this.events.emit("runtime_event", {kind: "runtime_diagnostic",severity,@@ -1271,13 +1292,13 @@ export class OpenCodeServiceLane implements RuntimeLane {} satisfies AdapterEvent);}- private protocolFailure(message: string, _cause?: unknown): void {+ protected protocolFailure(message: string, _cause?: unknown): void {if (this.stopping) return;void this.stop({ reason: "protocol_error", forceAfterMs: 0 });this.events.emit("error", new Error(message));}- private identityMatches(): boolean {+ protected identityMatches(): boolean {const identity = this.identity;const matches = !!identity&& identity.process === this.process@@ -1296,7 +1317,7 @@ export class OpenCodeServiceLane implements RuntimeLane {return matches;}- private isIdentity(identity: ServiceIdentity): boolean {+ protected isIdentity(identity: ServiceIdentity): boolean {return this.identity === identity && this.identityMatches();}@@ -1304,7 +1325,7 @@ export class OpenCodeServiceLane implements RuntimeLane {return proc.exitCode !== null || proc.signalCode !== null;}- private async waitForLiveStream(): Promise<void> {+ protected async waitForLiveStream(): Promise<void> {while (!this.stopping) {const live = this.liveGate;await live.promise;diff --git a/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.ts b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.tsnew file mode 100644index 000000000..6284c0eea--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.ts@@ -0,0 +1,408 @@+import { EventEmitter } from "node:events";+import { PassThrough } from "node:stream";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { AdapterEvent } from "../../internal/adapter.js";+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";+import { OpenCodeV2ServiceLane } from "./v2-service-lane.js";++vi.mock("../../internal/killTree.js", async () => ({+ ...(await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js")),+ killProcessTree: vi.fn(async () => {}),+}));++type Row = Record<string, unknown>;+const paths = [+ "/api/session", "/api/session/active", "/api/session/{sessionID}",+ "/api/session/{sessionID}/prompt", "/api/session/{sessionID}/inbox", "/api/session/{sessionID}/message",+ "/api/session/{sessionID}/message/{messageID}",+ "/api/session/{sessionID}/interrupt", "/api/session/{sessionID}/model", "/api/session/{sessionID}/permission",+ "/api/session/{sessionID}/permission/{requestID}/reply", "/api/event",+];+const lanes: OpenCodeV2ServiceLane[] = [];+afterEach(async () => { for (const lane of lanes.splice(0)) await lane.stop({ reason: "test_cleanup" }); vi.restoreAllMocks(); });++class NativeV2 {+ readonly id = "ses_test";+ readonly inputs: Row[] = [];+ readonly messages: Row[] = [{ id: "msg_old_idle", type: "idle", outcome: "succeeded" }];+ readonly events: AdapterEvent[] = [];+ readonly errors: unknown[] = [];+ active = true;+ model: unknown;+ connections = 0;+ activeFailures = 0;+ interruptQuery?: string;+ stream?: ReadableStreamDefaultController<Uint8Array>;+ permissionBody?: unknown;+ delayPrompt?: Promise<void>;+ beforeInbox?: () => void;+ respond?: (url: URL, init?: RequestInit) => Response | undefined | Promise<Response | undefined>;+ readonly child = Object.assign(new EventEmitter(), {+ pid: 42_199, stdout: new PassThrough(), stderr: new PassThrough(), stdin: null,+ exitCode: null as number | null, signalCode: null as string | null, kill: vi.fn(() => true),+ });++ readonly fetch: typeof fetch = async (input, init) => {+ const url = new URL(String(input));+ const override = await this.respond?.(url, init);+ if (override) return override;+ const json = (value: unknown) => Response.json(value);+ if (url.pathname === "/api/info") return json({ version: "2.0.28", pid: this.child.pid });+ if (url.pathname === "/openapi.json") return json({ paths: Object.fromEntries(paths.map((path) => [path, {}])) });+ if (url.pathname === "/api/session" && init?.method === "POST") {+ this.model = JSON.parse(String(init.body)).model;+ return json({ data: { id: this.id, model: this.model } });+ }+ if (url.pathname === "/api/session/active" && this.activeFailures-- > 0) return new Response(null, { status: 503 });+ if (url.pathname === "/api/session/active") return json({ data: this.active ? { [this.id]: { type: "running" }, ses_child: { type: "running" } } : { ses_child: { type: "running" } } });+ if (url.pathname === "/api/event") {+ this.connections += 1;+ return new Response(new ReadableStream<Uint8Array>({+ start: (controller) => {+ this.stream = controller;+ init?.signal?.addEventListener("abort", () => { try { controller.close(); } catch {} }, { once: true });+ },+ }), { headers: { "content-type": "text/event-stream" } });+ }+ if (url.pathname.endsWith("/permission")) return json({ data: [] });+ if (url.pathname.endsWith("/permission/per_test/reply")) { this.permissionBody = JSON.parse(String(init?.body)); return new Response(null, { status: 204 }); }+ if (url.pathname.endsWith("/message")) {+ const data = [...this.messages].reverse();+ const limit = Number(url.searchParams.get("limit"));+ const offset = Number(url.searchParams.get("cursor")?.slice(7) ?? 0);+ return json({ data: data.slice(offset, offset + limit), cursor: { previous: null, next: offset + limit < data.length ? `cursor_${offset + limit}` : null } });+ }+ if (url.pathname.endsWith("/inbox")) { this.beforeInbox?.(); return json({ data: this.inputs }); }+ if (url.pathname.includes("/message/")) {+ const message = this.messages.find((item) => item.id === url.pathname.split("/").at(-1));+ return message ? json({ data: message }) : new Response(null, { status: 404 });+ }+ if (url.pathname.endsWith("/prompt")) {+ const body = JSON.parse(String(init?.body));+ if (typeof body.text !== "string" || body.prompt !== undefined) return new Response(null, { status: 400 });+ if (this.delayPrompt) await this.delayPrompt;+ const item = { ...body, type: "user", sessionID: this.id };+ this.inputs.push(item);+ return json({ data: item });+ }+ if (url.pathname.endsWith("/interrupt")) { this.interruptQuery = url.search; return json({ interrupted: true }); }+ throw new Error(`Unexpected v2 route ${url.pathname}`);+ };++ lane(model: string | null = "opencode/space-bunny-free") {+ const lane = new OpenCodeV2ServiceLane(+ { spawnService: async () => ({ process: this.child }) },+ fakeLaunchContext("opencode", process.cwd(), { config: { runtimeConfig: { model: model === null ? { kind: "default" } : { kind: "named", name: model } } } }),+ { fetch: this.fetch, allocatePort: async () => 43_123, activePollMs: 2, reconnectDelayMs: 2 },+ );+ lane.on("runtime_event", (event) => this.events.push(event));+ lane.on("error", (error) => this.errors.push(error));+ lanes.push(lane);+ return lane;+ }++ deliver() {+ for (const input of this.inputs.splice(0)) this.messages.push({ ...input, type: "user" });+ }++ finish(id = "msg_new_idle", outcome = "succeeded") {+ this.messages.push({ id, type: "idle", outcome });+ this.active = false;+ }++ emit(type: string, data: Row = {}) {+ this.stream?.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({ type, data: { sessionID: this.id, ...data } })}\n\n`));+ }++ get ends() { return this.events.filter((event) => event.kind === "turn_end"); }+}++describe("OpenCode CLI v2 persisted message authority", () => {+ it.each([{ pid: 1 }, { version: "2.0.28", pid: 0 }, { version: "3.0.0", pid: 1 }])("rejects incompatible native health before admitting inputs: %j", async health => {+ const native = new NativeV2(); native.respond = url => url.pathname === "/api/info" ? Response.json(health) : undefined;+ expect(await native.lane().start({ text: "one", terminalOwner: "msg_root" })).toMatchObject({ ok: false, reason: "incompatible_configuration" });+ expect(native.inputs).toHaveLength(0);+ });++ it("keeps default model selection and complete reasoning, compaction and sparse usage semantics", async () => {+ const native = new NativeV2(); const lane = native.lane(null);+ expect(await lane.send({ mode: "idle", text: "early" })).toMatchObject({ ok: false, reason: "closed" });+ await lane.start({ text: "one", terminalOwner: "msg_root" }); expect(native.model).toBeUndefined();+ expect(await lane.send({ mode: "idle", text: "duplicate" })).toMatchObject({ ok: false, reason: "runtime_busy" });+ native.emit("session.compaction.started"); native.emit("session.compaction.failed");+ native.deliver(); native.messages.push({ id: "msg_reason", type: "assistant", time: { completed: 2 }, content: [{ type: "reasoning", text: "settled reasoning" }, { type: "text", text: "" }] }); native.finish();+ await vi.waitFor(() => expect(native.ends).toHaveLength(1));+ expect(native.events).toEqual(expect.arrayContaining([{ kind: "assistant_reasoning_completed", text: "settled reasoning" }, { kind: "compaction_started" }, { kind: "compaction_finished" }]));+ expect(native.events.some(event => event.kind === "telemetry")).toBe(false);+ expect(await lane.send({ mode: "busy", text: "late" })).toMatchObject({ ok: false, reason: "not_ready" });+ });++ it.each(["http", "receipt"])("rejects a failed %s prompt admission without a terminal receipt", async kind => {+ const native = new NativeV2(); native.respond = url => url.pathname.endsWith("/prompt") ? kind === "http" ? new Response(null, { status: 400 }) : Response.json({ data: {} }) : undefined;+ await expect(native.lane().start({ text: "one", terminalOwner: "msg_root" })).rejects.toThrow(kind === "http" ? "HTTP 400" : "invalid prompt receipt");+ expect(native.ends).toHaveLength(0); expect(native.inputs).toHaveLength(0);+ });++ it.each(["page", "cursor", "http"])("rejects invalid initial native message %s", async kind => {+ const native = new NativeV2(); native.respond = url => url.pathname.endsWith("/message") ? kind === "http" ? new Response(null, { status: 400 }) : Response.json(kind === "page" ? { data: {} } : { data: [], cursor: { next: 42 } }) : undefined;+ await expect(native.lane().start({ text: "one", terminalOwner: "msg_root" })).rejects.toThrow(kind === "http" ? "HTTP 400" : "invalid message");+ expect(native.inputs).toHaveLength(0); expect(native.ends).toHaveLength(0);+ });++ it.each(["boundary", "cursor", "active", "inbox_http", "inbox_shape", "input_http", "input_shape", "idle"])("fails native recovery closed on %s corruption", async kind => {+ const native = new NativeV2(); const lane = native.lane(); await lane.start({ text: "one", terminalOwner: "msg_root" });+ native.active = false;+ if (kind === "boundary") native.messages.splice(0);+ if (kind.startsWith("input")) native.inputs.splice(0);+ if (kind === "idle") { native.deliver(); native.finish("msg_invalid_idle", "unknown"); }+ native.respond = url => {+ if (kind === "cursor" && url.pathname.endsWith("/message")) return Response.json({ data: [], cursor: { next: "repeated" } });+ if (kind === "active" && url.pathname === "/api/session/active") return Response.json({ data: null });+ if (kind.startsWith("inbox") && url.pathname.endsWith("/inbox")) return kind === "inbox_http" ? new Response(null, { status: 400 }) : Response.json({ data: null });+ if (kind.startsWith("input") && url.pathname.includes("/message/")) return kind === "input_http" ? new Response(null, { status: 400 }) : Response.json({ data: { id: url.pathname.split("/").at(-1), type: "assistant" } });+ };+ await vi.waitFor(() => expect(native.errors).toHaveLength(1)); expect(native.ends).toHaveLength(0);+ });++ it("closes the lane when native interruption fails instead of settling the root", async () => {+ const native = new NativeV2(); const lane = native.lane(); await lane.start({ text: "one", terminalOwner: "msg_root" });+ native.respond = url => url.pathname.endsWith("/interrupt") ? new Response(null, { status: 400 }) : undefined;+ await expect(lane.interrupt({ reason: "user_interrupt" })).rejects.toThrow("HTTP 400");+ expect(await lane.send({ mode: "idle", text: "late" })).toMatchObject({ ok: false, reason: "closed" }); expect(native.ends).toHaveLength(0);+ });++ it("fails unexpected stream faults during startup without admitting input", async () => {+ const native = new NativeV2(); const lane = native.lane();+ vi.spyOn(lane as unknown as { runLiveStream: () => Promise<void> }, "runLiveStream").mockRejectedValueOnce(new Error("unexpected native stream fault"));+ await expect(lane.start({ text: "one", terminalOwner: "msg_root" })).rejects.toThrow();+ expect(native.errors).toHaveLength(1); expect(native.inputs).toHaveLength(0); expect(native.ends).toHaveLength(0);+ });++ it("closes admission when physical identity is lost during the baseline snapshot", async () => {+ const native = new NativeV2(); const lane = native.lane(); await lane.start({ text: "one", terminalOwner: "msg_root" }); native.deliver(); native.finish();+ await vi.waitFor(() => expect(native.ends).toHaveLength(1));+ native.respond = url => { if (url.pathname.endsWith("/message")) native.child.exitCode = 1; };+ expect(await lane.send({ mode: "idle", text: "late", terminalOwner: "msg_next" })).toMatchObject({ ok: false, reason: "closed" });+ expect(native.inputs).toHaveLength(0);+ });++ it("fences both queued and returned admissions after the service exits", async () => {+ const native = new NativeV2(); const lane = native.lane(); await lane.start({ text: "one", terminalOwner: "msg_root" });+ let release!: () => void; native.delayPrompt = new Promise<void>(resolve => { release = resolve; });+ const first = lane.send({ mode: "busy", text: "first" }); const second = lane.send({ mode: "busy", text: "second" });+ await new Promise(resolve => setTimeout(resolve, 5)); native.child.exitCode = 1; release();+ expect(await first).toMatchObject({ ok: false, reason: "closed" }); expect(await second).toMatchObject({ ok: false, reason: "closed" }); expect(native.ends).toHaveLength(0);+ });++ it.each(["message", "inbox", "input"])("ignores late %s recovery after stop", async phase => {+ const native = new NativeV2(); const lane = native.lane(); await lane.start({ text: "one", terminalOwner: "msg_root" }); native.active = false;+ if (phase === "input") native.inputs.splice(0);+ native.respond = async url => {+ const target = phase === "message" ? url.pathname.endsWith("/message") : phase === "inbox" ? url.pathname.endsWith("/inbox") : url.pathname.includes("/message/");+ if (!target) return;+ void lane.stop({ reason: "shutdown" });+ if (phase === "message") return Response.json({ data: [], cursor: {} });+ if (phase === "inbox") return Response.json({ data: [] });+ return Response.json({ data: { id: "stale", type: "user" } });+ };+ await vi.waitFor(() => expect(native.events.some(event => event.kind === "runtime_metric" && event.name === "sse_reconnect")).toBe(false));+ await new Promise(resolve => setTimeout(resolve, 20)); expect(native.ends).toHaveLength(0); expect(native.errors).toHaveLength(0);+ });++ it("does not settle stale page results when a new busy input arrives", async () => {+ const native = new NativeV2(); const lane = native.lane(); await lane.start({ text: "one", terminalOwner: "msg_root" }); native.deliver(); native.finish();+ let admitted: Promise<unknown> | undefined;+ native.respond = async url => {+ if (!url.pathname.endsWith("/message") || admitted) return;+ admitted = lane.send({ mode: "busy", text: "new input" }); await admitted;+ };+ await vi.waitFor(() => expect(admitted).toBeDefined()); expect(native.ends).toHaveLength(0);+ native.deliver(); native.finish("msg_next_idle"); await vi.waitFor(() => expect(native.ends).toHaveLength(1));+ });++ it("does not project recovered tools after a root has stopped", async () => {+ const native = new NativeV2(); const lane = native.lane(); await lane.start({ text: "one", terminalOwner: "msg_root" }); native.deliver();+ native.messages.push({ id: "msg_tool", type: "assistant", content: [{ type: "tool", id: "call", name: "shell", state: { status: "running", input: {} } }] });+ native.respond = async url => { if (url.pathname.endsWith("/message")) { void lane.stop({ reason: "shutdown" }); return Response.json({ data: [], cursor: {} }); } };+ native.stream?.close(); await new Promise(resolve => setTimeout(resolve, 20));+ expect(native.events.filter(event => event.kind === "tool_call")).toHaveLength(0); expect(native.ends).toHaveLength(0);+ });++ it("starts a fresh native message history and ignores child, orphan and post-root live signals", async () => {+ const native = new NativeV2(); native.messages.splice(0); const lane = native.lane();+ const admitted = await lane.start({ text: "one", terminalOwner: "host-owner" }); expect(admitted).toMatchObject({ ok: true, receipt: expect.stringMatching(/^msg_/) });+ native.emit("session.step.started"); native.emit("session.step.started", { sessionID: "ses_child" });+ native.emit("session.tool.success", { assistantMessageID: "msg_unseen", id: "orphan" });+ await vi.waitFor(() => expect(native.events.filter(event => event.kind === "internal_progress")).toHaveLength(1));+ native.deliver(); native.finish(); await vi.waitFor(() => expect(native.ends).toHaveLength(1));+ native.emit("session.step.started"); await new Promise(resolve => setTimeout(resolve, 10));+ expect(native.events.filter(event => event.kind === "internal_progress")).toHaveLength(1);+ expect(native.events.filter(event => event.kind === "tool_output")).toHaveLength(0);+ });++ it("discards inactive results after physical service identity is lost", async () => {+ const native = new NativeV2(); const lane = native.lane(); await lane.start({ text: "one", terminalOwner: "msg_root" });+ let observed = false; native.respond = url => { if (url.pathname === "/api/session/active") { observed = true; native.child.exitCode = 1; return Response.json({ data: {} }); } };+ await vi.waitFor(() => expect(observed).toBe(true)); expect(native.ends).toHaveLength(0); expect(native.errors).toHaveLength(0);+ });++ it("ignores a malformed late recovery response after shutdown", async () => {+ const native = new NativeV2(); const lane = native.lane(); await lane.start({ text: "one", terminalOwner: "msg_root" }); native.active = false;+ let observed = false; native.respond = url => { if (url.pathname.endsWith("/message")) { observed = true; void lane.stop({ reason: "shutdown" }); return Response.json({ data: null }); } };+ await vi.waitFor(() => expect(observed).toBe(true)); await new Promise(resolve => setTimeout(resolve, 10));+ expect(native.ends).toHaveLength(0); expect(native.errors).toHaveLength(0);+ });++ it("uses the exact selected model and ignores old idle, child activity and streamed-only output", async () => {+ const native = new NativeV2();+ const lane = native.lane("opencode/space-bunny-free#high");+ expect(await lane.start({ text: "one", terminalOwner: "msg_root" })).toMatchObject({ ok: true, receipt: "msg_root" });+ expect(native.model).toEqual({ providerID: "opencode", id: "space-bunny-free", variant: "high" });+ native.active = false;+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(native.ends).toHaveLength(0);+ native.deliver();+ native.messages.push({ id: "msg_assistant", type: "assistant", time: { streamed: 12 }, content: [{ type: "text", text: "incomplete" }] });+ native.emit("session.step.ended", { finish: "stop" });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(native.ends).toHaveLength(0);+ native.finish();+ await vi.waitFor(() => expect(native.ends).toEqual([{ kind: "turn_end", sessionId: native.id, turnOwner: "msg_root" }]));+ expect(native.errors).toHaveLength(0);+ });++ it("projects actual v2 tool IDs and restores missed running/completed tools after reconnect", async () => {+ const native = new NativeV2(); const lane = native.lane();+ await lane.start({ text: "tools", terminalOwner: "msg_root" }); native.deliver();+ native.emit("session.tool.input.started", { assistantMessageID: "msg_a", id: "call_one", name: "bash" });+ native.emit("session.tool.called", { assistantMessageID: "msg_a", id: "call_one", input: { command: "true" }, executed: true });+ await vi.waitFor(() => expect(native.events.filter(event => event.kind === "tool_call")).toHaveLength(1));+ native.stream?.close();+ native.messages.push({ id: "msg_a", type: "assistant", content: [+ { type: "tool", id: "call_one", name: "bash", state: { status: "completed", input: { command: "true" } } },+ { type: "tool", id: "call_two", name: "bash", state: { status: "running", input: { command: "sleep 1" } } },+ ] });+ await vi.waitFor(() => expect(native.events.filter(event => event.kind === "tool_call")).toHaveLength(2));+ expect(native.events.filter(event => event.kind === "tool_output")).toEqual([{ kind: "tool_output", callId: "msg_a:call_one", name: "bash" }]);+ native.emit("session.tool.success", { assistantMessageID: "msg_a", id: "call_two", executed: true });+ await vi.waitFor(() => expect(native.events.filter(event => event.kind === "tool_output")).toHaveLength(2));+ native.finish(); await vi.waitFor(() => expect(native.ends).toHaveLength(1));+ expect(native.events.filter(event => event.kind === "tool_call")).toHaveLength(2);+ expect(native.errors).toHaveLength(0);+ });++ it("retains busy admission until every input is delivered and followed by a new idle", async () => {+ const native = new NativeV2();+ const lane = native.lane();+ await lane.start({ text: "one", terminalOwner: "msg_root" });+ native.deliver();+ let release!: () => void;+ native.delayPrompt = new Promise<void>((resolve) => { release = resolve; });+ const sending = lane.send({ mode: "busy", text: "two" });+ native.finish("msg_first_idle");+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(native.ends).toHaveLength(0);+ release();+ expect(await sending).toMatchObject({ ok: true, acceptedAs: "steer" });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(native.ends).toHaveLength(0);+ native.deliver();+ native.finish("msg_second_idle");+ await vi.waitFor(() => expect(native.ends).toHaveLength(1));+ expect(native.errors).toHaveLength(0);+ });++ it("recovers a disconnected live stream from persisted messages and reuses the same session", async () => {+ const native = new NativeV2();+ const lane = native.lane();+ await lane.start({ text: "one", terminalOwner: "msg_root" });+ native.stream!.close();+ await vi.waitFor(() => expect(native.connections).toBeGreaterThan(1));+ native.deliver();+ for (let n = 0; n < 110; n++) native.messages.push({ id: `msg_note_${n}`, type: "system" });+ native.messages.push({ id: "msg_answer", type: "assistant", time: { completed: 20 }, content: [{ type: "text", text: "done" }], tokens: { input: 10, output: 2, reasoning: 1, cache: { read: 4, write: 0 } } });+ native.finish();+ await vi.waitFor(() => expect(native.ends).toHaveLength(1));+ expect(native.events.filter((event) => event.kind === "assistant_message_completed")).toEqual([{ kind: "assistant_message_completed", text: "done" }]);+ expect(native.events.filter((event) => event.kind === "telemetry")).toHaveLength(1);+ native.active = true;+ expect(await lane.send({ mode: "idle", text: "second", terminalOwner: "msg_second" })).toMatchObject({ ok: true });+ native.deliver();+ native.finish("msg_second_idle");+ await vi.waitFor(() => expect(native.ends).toHaveLength(2));+ expect(lane.currentSessionId).toBe(native.id);+ expect(native.events.filter((event) => event.kind === "session_init")).toHaveLength(1);+ expect(native.errors).toHaveLength(0);+ });++ it("uses the v2 permission decision and fences callbacks after shutdown", async () => {+ const native = new NativeV2();+ const lane = native.lane();+ await lane.start({ text: "one", terminalOwner: "msg_root" });+ native.emit("permission.asked", { id: "per_test" });+ await vi.waitFor(() => expect(native.permissionBody).toEqual({ decision: "once" }));+ await lane.stop({ reason: "shutdown" });+ native.deliver();+ native.finish();+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(native.ends).toHaveLength(0);+ });++ it("waits for native interrupted idle instead of treating an interrupt receipt as completion", async () => {+ const native = new NativeV2(); const lane = native.lane();+ await lane.start({ text: "one", terminalOwner: "msg_root" });+ expect(await lane.interrupt({ reason: "user_interrupt" })).toBe(true);+ expect(native.interruptQuery).toBe("?resume=false");+ expect(native.ends).toHaveLength(0);+ native.deliver(); native.finish("msg_interrupted", "interrupted");+ await vi.waitFor(() => expect(native.ends).toEqual([{ kind: "turn_end", sessionId: native.id, turnOwner: "msg_root" }]));+ expect(await lane.interrupt({ reason: "user_interrupt" })).toBe(false);+ expect(native.errors).toHaveLength(0);+ });++ it("reports a failed native idle for its root and keeps the persistent lane reusable", async () => {+ const native = new NativeV2(); const lane = native.lane();+ await lane.start({ text: "one", terminalOwner: "msg_root" }); native.deliver();+ native.finish("msg_failure", "failed"); native.messages.at(-1)!.error = { message: "provider unavailable" };+ await vi.waitFor(() => expect(native.ends).toHaveLength(1));+ expect(native.events.filter(event => event.kind === "error")).toEqual([{ kind: "error", code: "opencode.turn_failed", message: "provider unavailable" }]);+ expect(native.errors).toHaveLength(0);+ expect(await lane.send({ mode: "idle", text: "retry", terminalOwner: "msg_retry" })).toMatchObject({ ok: true });+ native.deliver(); native.finish("msg_retry_idle");+ await vi.waitFor(() => expect(native.ends).toHaveLength(2));+ expect(native.ends[1]).toMatchObject({ turnOwner: "msg_retry" });+ });++ it("keeps accepted inputs owned through a temporary native recovery outage", async () => {+ const native = new NativeV2(); const lane = native.lane();+ await lane.start({ text: "one", terminalOwner: "msg_root" }); native.activeFailures = 1;+ await vi.waitFor(() => expect(native.events.some(event => event.kind === "runtime_diagnostic" && event.message.includes("temporarily unavailable"))).toBe(true));+ expect(native.ends).toHaveLength(0); expect(native.errors).toHaveLength(0);+ native.deliver(); native.finish();+ await vi.waitFor(() => expect(native.ends).toHaveLength(1));+ });++ it("fails explicitly if accepted input is absent from both inbox and persisted messages", async () => {+ const native = new NativeV2();+ const lane = native.lane();+ await lane.start({ text: "one", terminalOwner: "msg_root" });+ native.inputs.splice(0);+ native.finish();+ await vi.waitFor(() => expect(native.errors).toHaveLength(1));+ expect(native.ends).toHaveLength(0);+ });++ it("rechecks a persisted input that moved out of inbox after the messages snapshot", async () => {+ const native = new NativeV2();+ const lane = native.lane();+ await lane.start({ text: "one", terminalOwner: "msg_root" });+ native.active = false;+ native.beforeInbox = () => {+ native.beforeInbox = undefined;+ native.deliver();+ native.finish();+ };+ await vi.waitFor(() => expect(native.ends).toHaveLength(1));+ expect(native.errors).toHaveLength(0);+ });+});diff --git a/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.ts b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.tsnew file mode 100644index 000000000..a477d376c--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.ts@@ -0,0 +1,386 @@+import type {+ AdapterEvent,+ LaneAdmission,+ LaneInterruptInput,+ LaneSendInput,+ LaneStartInput,+ LaneStopInput,+} from "../../internal/adapter.js";+import { SettledUsageProjector } from "../../internal/token-usage.js";+import { scrubDriverErrorMessage } from "../../internal/errors.js";+import { resolveOpenCodeCompatibility } from "./compatibility.js";+import {+ OpenCodeHttpError,+ OpenCodeProtocolError,+ OpenCodeServiceLane,+ record,+} from "./service-lane.js";++type JsonRecord = Record<string, unknown>;++interface Root {+ readonly receipt: string;+ readonly baseline: string | null;+ readonly inputs: Set<string>;+ generation: number;+ pending: number;+}++export class OpenCodeV2ServiceLane extends OpenCodeServiceLane {+ private root: Root | null = null;+ private v2AdmissionTail: Promise<void> = Promise.resolve();+ private v2EvaluationTimer?: ReturnType<typeof setTimeout>;+ private v2Evaluating = false;+ private readonly projectedMessages = new Set<string>();+ private readonly liveTools = new Map<string, { name: string; called: boolean }>();+ private readonly settledTools = new Set<string>();+ private readonly usage = new SettledUsageProjector();++ protected override get healthPath(): string { return "/api/info"; }++ protected override get openApiPath(): string { return "/openapi.json"; }++ protected override acceptsHealth(health: JsonRecord | null): boolean {+ if (typeof health?.version !== "string" || !Number.isInteger(health.pid) || Number(health.pid) < 1) return false;+ try { return resolveOpenCodeCompatibility(health.version).major === 2; } catch { return false; }+ }++ protected override get requiredApiPaths(): readonly string[] {+ return [+ "/api/session",+ "/api/session/active",+ "/api/session/{sessionID}",+ "/api/session/{sessionID}/prompt",+ "/api/session/{sessionID}/inbox",+ "/api/session/{sessionID}/message",+ "/api/session/{sessionID}/message/{messageID}",+ "/api/session/{sessionID}/interrupt",+ "/api/session/{sessionID}/model",+ "/api/session/{sessionID}/permission",+ "/api/session/{sessionID}/permission/{requestID}/reply",+ "/api/event",+ ];+ }++ protected override get selectedModel(): JsonRecord | undefined {+ const model = super.selectedModel;+ if (typeof model?.id !== "string") return model;+ const hash = model.id.lastIndexOf("#");+ return hash > 0 && hash < model.id.length - 1+ ? { ...model, id: model.id.slice(0, hash), variant: model.id.slice(hash + 1) }+ : model;+ }++ protected override get permissionEventType(): string { return "permission.asked"; }++ protected override get permissionReply(): JsonRecord { return { decision: "once" }; }++ protected override protocolFailure(message: string, cause?: unknown): void {+ super.protocolFailure(cause === undefined ? message : `${message}: ${scrubDriverErrorMessage(cause)}`);+ }++ protected override async primeHistory(): Promise<void> {}++ protected override startStreams(): void {+ const identity = this.identity!;+ this.liveTask = this.runLiveStream(identity).catch((error: unknown) => {+ if (!this.stopping) this.protocolFailure("OpenCode CLI v2 live stream failed", error);+ });+ }++ protected override async recoverPendingPermissions(): Promise<void> {+ await super.recoverPendingPermissions();+ const root = this.root;+ if (root) for (const message of await this.messagesAfter(root)) this.projectTools(message);+ this.schedule();+ }++ protected override async handleLiveEvent(value: unknown): Promise<void> {+ await super.handleLiveEvent(value);+ const event = record(value);+ const data = record(event?.data);+ if (data?.sessionID !== this.sessionId || !this.root) return;+ switch (event?.type) {+ case "session.step.started":+ this.events.emit("runtime_event", {+ kind: "internal_progress", source: "opencode.service", itemType: "step_started",+ } satisfies AdapterEvent);+ break;+ case "session.tool.input.started": {+ const key = this.toolKey(data.assistantMessageID, data.id);+ if (key && typeof data.name === "string" && !this.liveTools.has(key) && !this.settledTools.has(key)) {+ this.liveTools.set(key, { name: data.name, called: false });+ }+ break;+ }+ case "session.tool.called":+ this.projectTool(data);+ break;+ case "session.tool.success":+ case "session.tool.failed": {+ this.finishTool(this.toolKey(data.assistantMessageID, data.id));+ break;+ }+ case "session.compaction.started":+ this.events.emit("runtime_event", { kind: "compaction_started" } satisfies AdapterEvent);+ break;+ case "session.compaction.failed":+ case "session.compaction.ended":+ this.events.emit("runtime_event", { kind: "compaction_finished" } satisfies AdapterEvent);+ break;+ default:+ break;+ }+ this.schedule();+ }++ override async send(input: LaneSendInput): Promise<LaneAdmission> {+ if (!this.ready || this.stopping || !this.sessionId || !this.identityMatches()) return { ok: false, reason: "closed" };+ if (input.mode === "idle") {+ if (this.root) return { ok: false, reason: "runtime_busy" };+ return this.beginRoot(input);+ }+ const root = this.root;+ if (!root) return { ok: false, reason: "not_ready" };+ return this.admit(input.text, "steer", this.newMessageId(), root);+ }++ protected override async beginRoot(input: LaneStartInput): Promise<LaneAdmission> {+ const page = await this.messagePage(undefined, 1);+ if (this.stopping || !this.identityMatches()) return { ok: false, reason: "closed" };+ const receipt = input.terminalOwner?.startsWith("msg_") ? input.terminalOwner : this.newMessageId();+ const root: Root = {+ receipt,+ baseline: typeof page.data[0]?.id === "string" ? page.data[0].id : null,+ inputs: new Set(), generation: 0, pending: 0,+ };+ this.root = root;+ return this.admit(input.text, "queue", receipt, root);+ }++ private admit(text: string, delivery: "queue" | "steer", id: string, root: Root): Promise<LaneAdmission> {+ root.generation += 1;+ root.pending += 1;+ const run = this.v2AdmissionTail.then(async (): Promise<LaneAdmission> => {+ await this.waitForLiveStream();+ if (this.root !== root || this.stopping || !this.identityMatches()) return { ok: false, reason: "closed" };+ const { response, body } = await this.fetchJsonWithTimeout(+ `/api/session/${encodeURIComponent(this.sessionId!)}/prompt`,+ { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ id, text, delivery, resume: true }) },+ "prompt admission",+ );+ if (!response.ok) throw new OpenCodeHttpError(response.status, "prompt admission");+ const input = record(record(body)?.data);+ if (input?.id !== id || input.sessionID !== this.sessionId || input.type !== "user" || input.delivery !== delivery) {+ throw new OpenCodeProtocolError("OpenCode CLI v2 returned an invalid prompt receipt");+ }+ if (this.root !== root || this.stopping || !this.identityMatches()) return { ok: false, reason: "closed" };+ root.inputs.add(id);+ return { ok: true, acceptedAs: delivery === "steer" ? "steer" : "prompt", receipt: id };+ }).catch((error: unknown) => {+ if (this.root === root && !this.stopping) this.protocolFailure("OpenCode CLI v2 prompt admission failed", error);+ throw error;+ }).finally(() => { root.pending -= 1; this.schedule(); });+ this.v2AdmissionTail = run.then(() => {}, () => {});+ return run;+ }++ private async messagePage(cursor?: string, limit = 100): Promise<{ data: JsonRecord[]; next?: string }> {+ const query = new URLSearchParams({ limit: String(limit), ...(cursor ? { cursor } : { order: "desc" }) });+ const { response, body } = await this.fetchJsonWithTimeout(+ `/api/session/${encodeURIComponent(this.sessionId!)}/message?${query}`,+ { method: "GET" }, "message recovery",+ );+ if (!response.ok) throw new OpenCodeHttpError(response.status, "message recovery");+ const page = record(body);+ const cursors = record(page?.cursor);+ if (!Array.isArray(page?.data) || !cursors || page.data.some((item: unknown) => typeof record(item)?.id !== "string")) {+ throw new OpenCodeProtocolError("OpenCode CLI v2 returned an invalid message page");+ }+ if (cursors.next !== undefined && cursors.next !== null && typeof cursors.next !== "string") throw new OpenCodeProtocolError("OpenCode CLI v2 returned an invalid message cursor");+ return { data: page.data as JsonRecord[], next: typeof cursors.next === "string" ? cursors.next : undefined };+ }++ private async messagesAfter(root: Root): Promise<JsonRecord[]> {+ const messages: JsonRecord[] = [];+ const cursors = new Set<string>();+ let cursor: string | undefined;+ for (;;) {+ const page = await this.messagePage(cursor);+ if (this.root !== root || this.stopping) return [];+ for (const message of page.data) {+ if (message.id === root.baseline) return messages.reverse();+ messages.push(message);+ }+ if (!page.next) {+ if (root.baseline !== null) throw new OpenCodeProtocolError("OpenCode CLI v2 message recovery lost its root boundary");+ return messages.reverse();+ }+ if (cursors.has(page.next)) throw new OpenCodeProtocolError("OpenCode CLI v2 message cursor did not advance");+ cursors.add(page.next);+ cursor = page.next;+ }+ }++ private schedule(): void {+ if (!this.root || this.stopping || this.v2EvaluationTimer || this.v2Evaluating) return;+ this.v2EvaluationTimer = setTimeout(() => {+ this.v2EvaluationTimer = undefined;+ void this.evaluate();+ }, this.options.activePollMs ?? 100);+ this.v2EvaluationTimer.unref?.();+ }++ private async isActive(): Promise<boolean> {+ const { response, body } = await this.fetchJsonWithTimeout("/api/session/active", { method: "GET" }, "active session query");+ if (!response.ok) throw new OpenCodeHttpError(response.status, "active session query");+ const active = record(record(body)?.data);+ if (!active) throw new OpenCodeProtocolError("OpenCode CLI v2 returned invalid active session data");+ return active[this.sessionId!] !== undefined;+ }++ private async evaluate(): Promise<void> {+ const root = this.root;+ const identity = this.identity;+ if (!root || !identity || this.stopping || root.pending > 0 || root.inputs.size === 0 || this.v2Evaluating) return;+ this.v2Evaluating = true;+ const generation = root.generation;+ const current = () => this.root === root && root.generation === generation && root.pending === 0 && this.isIdentity(identity);+ try {+ if (await this.isActive()) return;+ if (!current()) return;+ const messages = await this.messagesAfter(root);+ if (!current()) return;+ let lastInput = -1;+ const delivered = new Set<string>();+ for (const [index, message] of messages.entries()) {+ if (message.type === "user" && typeof message.id === "string" && root.inputs.has(message.id)) {+ delivered.add(message.id);+ lastInput = index;+ }+ }+ const idle = messages.slice(lastInput + 1).reverse().find((message) => message.type === "idle");+ if (delivered.size !== root.inputs.size) {+ const { response, body } = await this.fetchJsonWithTimeout(+ `/api/session/${encodeURIComponent(this.sessionId!)}/inbox`, { method: "GET" }, "pending input recovery",+ );+ if (!response.ok) throw new OpenCodeHttpError(response.status, "pending input recovery");+ const pending = record(body)?.data;+ if (!Array.isArray(pending)) throw new OpenCodeProtocolError("OpenCode CLI v2 returned invalid inbox data");+ if (!current()) return;+ const retained = new Set(pending.map((item: unknown) => record(item)?.id));+ for (const id of root.inputs) {+ if (delivered.has(id) || retained.has(id)) continue;+ const recovered = await this.fetchJsonWithTimeout(+ `/api/session/${encodeURIComponent(this.sessionId!)}/message/${encodeURIComponent(id)}`,+ { method: "GET" }, "accepted input recovery",+ );+ if (!current()) return;+ if (recovered.response.status === 404) throw new OpenCodeProtocolError("OpenCode CLI v2 lost an accepted input from both inbox and messages");+ if (!recovered.response.ok) throw new OpenCodeHttpError(recovered.response.status, "accepted input recovery");+ const message = record(record(recovered.body)?.data);+ if (message?.id !== id || message.type !== "user") throw new OpenCodeProtocolError("OpenCode CLI v2 returned an invalid recovered input");+ }+ return;+ }+ for (const message of messages) { this.projectTools(message); this.projectMessage(message); }+ if (!idle || await this.isActive() || !current()) return;+ if (!["succeeded", "failed", "interrupted"].includes(String(idle.outcome))) {+ throw new OpenCodeProtocolError("OpenCode CLI v2 returned an invalid idle outcome");+ }+ this.root = null;+ if (idle.outcome === "failed") {+ const error = record(idle.error);+ this.events.emit("runtime_event", {+ kind: "error", code: "opencode.turn_failed",+ message: typeof error?.message === "string" ? error.message : "OpenCode CLI v2 execution failed",+ } satisfies AdapterEvent);+ }+ this.events.emit("runtime_event", {+ kind: "turn_end", sessionId: this.sessionId!, turnOwner: root.receipt,+ } satisfies AdapterEvent);+ } catch (error) {+ if (!current() || this.stopping) return;+ if (error instanceof OpenCodeProtocolError || (error instanceof OpenCodeHttpError && error.status < 500)) {+ this.protocolFailure("OpenCode CLI v2 durable message recovery failed", error);+ } else this.diagnostic("warning", "OpenCode CLI v2 message recovery temporarily unavailable; keeping the root active");+ } finally { this.v2Evaluating = false; this.schedule(); }+ }++ private toolKey(messageId: unknown, id: unknown): string | undefined {+ return typeof messageId === "string" && typeof id === "string" ? `${messageId}:${id}` : undefined;+ }++ private projectTool(data: JsonRecord): void {+ const key = this.toolKey(data.assistantMessageID, data.id);+ if (!key || this.settledTools.has(key)) return;+ const tool = this.liveTools.get(key) ?? { name: typeof data.name === "string" ? data.name : "OpenCode tool", called: false };+ if (tool.called) return;+ tool.called = true;+ this.liveTools.set(key, tool);+ this.events.emit("runtime_event", { kind: "tool_call", callId: key, name: tool.name, input: data.input } satisfies AdapterEvent);+ }++ private finishTool(key: string | undefined): void {+ if (!key || this.settledTools.has(key)) return;+ const tool = this.liveTools.get(key);+ if (!tool?.called) return;+ this.liveTools.delete(key);+ this.settledTools.add(key);+ this.events.emit("runtime_event", { kind: "tool_output", callId: key, name: tool.name } satisfies AdapterEvent);+ }++ private projectTools(message: JsonRecord): void {+ if (message.type !== "assistant" || !Array.isArray(message.content) || !this.root || this.stopping) return;+ for (const value of message.content) {+ const tool = record(value);+ const state = record(tool?.state);+ if (tool?.type !== "tool" || !["running", "completed", "error"].includes(String(state?.status))) continue;+ this.projectTool({ assistantMessageID: message.id, id: tool.id, name: tool.name, input: state?.input });+ if (state?.status !== "running") this.finishTool(this.toolKey(message.id, tool.id));+ }+ }++ private projectMessage(message: JsonRecord): void {+ if (message.type !== "assistant" || typeof message.id !== "string" || this.projectedMessages.has(message.id)) return;+ const time = record(message.time);+ if (time?.completed === undefined) return;+ this.projectedMessages.add(message.id);+ if (Array.isArray(message.content)) for (const value of message.content) {+ const content = record(value);+ if (typeof content?.text !== "string" || !content.text) continue;+ if (content.type === "text") this.events.emit("runtime_event", { kind: "assistant_message_completed", text: content.text } satisfies AdapterEvent);+ if (content.type === "reasoning") this.events.emit("runtime_event", { kind: "assistant_reasoning_completed", text: content.text } satisfies AdapterEvent);+ }+ const tokens = record(message.tokens);+ if (!tokens || !this.sessionId) return;+ const cache = record(tokens.cache);+ const identity = { runtime: "opencode", backendSessionId: this.sessionId, providerRecordId: message.id } as const;+ const usage = this.usage.project({+ ...identity, source: "opencode.v2", input: tokens.input, output: tokens.output, reasoning: tokens.reasoning,+ cacheRead: cache?.read, cacheWrite: cache?.write, inputIncludesCache: false, outputIncludesReasoning: false,+ });+ if (usage) this.events.emit("runtime_event", usage);+ this.usage.release(identity);+ }++ override async interrupt(_input: LaneInterruptInput): Promise<boolean> {+ const root = this.root;+ if (!root || !this.ready || this.stopping || !this.identityMatches()) return false;+ root.generation += 1;+ root.pending += 1;+ try {+ await this.requestNoContent(`/api/session/${encodeURIComponent(this.sessionId!)}/interrupt?resume=false`, "POST", undefined, "session interrupt");+ return true;+ } catch (error) {+ if (!this.stopping) void this.stop({ reason: "interrupt_timeout", forceAfterMs: 0 });+ throw error;+ } finally { root.pending -= 1; this.schedule(); }+ }++ override stop(input: LaneStopInput = {}): Promise<void> {+ this.root = null;+ if (this.v2EvaluationTimer) clearTimeout(this.v2EvaluationTimer);+ return super.stop(input);+ }+}diff --git a/src/daemon/agent-driver/src/sdk.test.ts b/src/daemon/agent-driver/src/sdk.test.tsindex d08ade358..e660a0d0e 100644--- a/src/daemon/agent-driver/src/sdk.test.ts+++ b/src/daemon/agent-driver/src/sdk.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import type {@@ -90,10 +90,27 @@ describe("createAgentDriverSdk", () => {const result = await createAgentDriverSdk().probe({ backend, command: process.execPath });expect(result).toMatchObject(backend === "grok"? { status: "unhealthy", error: { code: "grok_acp_process_failed" } }- : { status: "healthy" });+ : backend === "opencode"+ ? { status: "unhealthy", error: { code: "unsupported_opencode_cli_version" } }+ : { status: "healthy" });},);+ it("probes a supported OpenCode CLI through an actual executable override", async () => {+ const directory = mkdtempSync(join(tmpdir(), "opencode-sdk-probe-"));+ const command = join(directory, process.platform === "win32" ? "opencode.cmd" : "opencode");+ try {+ writeFileSync(command, process.platform === "win32"+ ? '@echo off\r\nif "%~1"=="--version" (echo opencode v2.0.28) else (echo opencode/space-bunny-free)\r\n'+ : '#!/usr/bin/env node\nconsole.log(process.argv[2] === "--version" ? "opencode v2.0.28" : "opencode/space-bunny-free");\n');+ if (process.platform !== "win32") chmodSync(command, 0o755);+ await expect(createAgentDriverSdk().probe({ backend: "opencode", command })).resolves.toMatchObject({+ status: "healthy", version: "opencode v2.0.28",+ reasoning: { models: [{ id: "opencode/space-bunny-free" }] },+ });+ } finally { rmSync(directory, { recursive: true, force: true }); }+ });+it("public SDK factory delegates to the built-in logical SDK", () => {expect(createPublicAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity"]);});