From f5f1df8da07823e32ef6901a558a3dfa8cee9141 Mon Sep 17 00:00:00 2001 From: William Wang Date: Mon, 30 Nov 2026 18:33:34 +0800 Subject: [PATCH 1/9] chore: document the ACP V2 face layout and its invariants in AGENTS.md --- AGENTS.md | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 96 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 4538d11..8305bc8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -121,11 +121,35 @@ src/ │ ├── projection-differ.ts Snapshot diff for turn-completion reconciliation │ └── tool-helpers.ts Diff builder, location extractor ├── interaction/ Permission, ExitPlanMode, AskUserQuestion handling +├── v2/ The ACP V2 face (ADR-0039): one app per protocol +│ │ version over the SAME session engine; a connection's +│ │ face is fixed by its initialize (index.ts router) +│ ├── app.ts V2 method surface — shared handlers behind V2 answers +│ ├── initialize.ts Face declaration (only what a product client calls) +│ ├── project.ts V1-shaped client messages → V2 wire (update/request) +│ ├── session.ts new/prompt/cancel/close/set_config_option, holders +│ ├── resume.ts V2 replay contract over the shared load path +│ ├── ops.ts list/archive/unarchive/fork (V2 face completeness) +│ ├── queue.ts v4 conversation tracker — merged per-session state, +│ │ CAS watermark, drain nudge (single queue source) +│ ├── commands.ts v4/command sender — one envelope, CAS retry, typed +│ │ errors carrying upstream reasonCode +│ ├── tools.ts The private `_zcode/*` surface + `_zcode/queue_changed` +│ ├── background.ts V2 background items: terminals, tool calls, subagents +│ ├── child-mirror.ts Subagent child transcript via the child's v4 topic +│ ├── orphan.ts Backend-owned turns through the shared turn loop +│ ├── state.ts V2 state store — phase derived from engine facts, +│ │ state_update snapshots, live compaction lifecycle +│ └── prompt-keys.ts session/prompt idempotency keys (durable JSON store) +├── archive-store.ts Archive flag per backend session (V2 session/list + +│ hub heartbeat + /sessions honor it; durable store) ├── remote/ Remote access (opt-in via ZCODE_ACP_REMOTE=1) │ ├── broadcast.ts ClientRegistry + broadcast proxy (notify fan-out, request first-wins) +│ ├── client-handle.ts Per-connection V2 ClientHandle (face identity, holders) │ ├── config.ts ENV parsing (gate, mandatory token, hub/bridge ports) │ ├── endpoint.ts Loopback ACP endpoint + hub registration heartbeat │ ├── file-endpoint.ts Read-only /fs/list + /fs/file, session-root scoped (ADR-0004) +│ ├── session-archive-endpoint.ts POST archive|unarchive, any-bridge flag flip │ └── hub-server.ts Hub daemon: auth, discovery, byte-level proxy (ACP WS + /fs files), ?probe=1 liveness ├── quota/ GLM Coding Plan usage API client (/quota command) ├── push/ Offline WeCom push (spec: zcode-acp-app @@ -168,6 +192,77 @@ ZCode protocol types into ACP notifications directly — always translate. ## Gotchas +- **The ACP V2 face is a projection, not a second engine (ADR-0039; shipped + 0.98.0)**: one bridge, one session engine, TWO protocol faces routed per + connection by the SDK's protocol router (`buildProtocolRouter`, index.ts — + a connection's face is fixed by its `initialize`; the bundled TUI and + external editors stay on V1, the product clients speak V2). Every shared + handler keeps its V1-shaped signature: a V2 connection is wrapped in a + `ClientHandle` (remote/client-handle.ts) whose `notify`/`request` project + through `v2/project.ts` (update kinds mapped one by one; turn-state + notifications DROPPED — V2 reads `state_update` snapshots from the v2 + state store, whose phase is DERIVED from engine facts at emit time, never + counted at the emit points). Invariants that will bite anyone "simplifying" + either side: + - **`turn.face` gating**: `runEventTurn` settles V2 turns through + `noteV2TurnEnd` on EVERY terminal — early cancel exits included + (`cancelledResult`, session.ts ~4937). A `cancelledResult` call must + STAY a wrapper function that records then returns `turnResult(...)`: + an earlier shape returned `turnResult(...)` directly from inside + `cancelledResult`, and under **bun/JSC** that not-quite-tail-call + self-recursed without growing the stack and wedged the whole bridge + (`_zcode/ping` dead after a mid-stream cancel) — node/V8 never + reproduced it. The cancel-repro probe + (`.zcode/scratch/v2-probes/cancel-repro.mjs`) is the reproducer; run + it under `REPRO_BUN=` when touching any cancel/terminal path. + - **V2 answers `session/prompt` at INSERTION, not at turn end**: the + request resolves with the message id (`_meta.zcode.delivery`), the turn + itself reports through `state_update` snapshots. Probes and clients + must not await the response as "turn finished" (cancel-repro sends the + prompt without awaiting for exactly this reason). + - **v4 `sendText` CANNOT be a draft session's first input** (probe P5 + delivery finding 2): a legacy-created session is a deferred draft + until its first input and the v4 ledger write fails "FOREIGN KEY + constraint failed" — after which the session stays broken for later + `sendText`. The V2 face therefore keeps the legacy `session/send` path + for an idle session with an EMPTY queue and uses v4 `sendText` only + while a turn runs or the queue is non-empty. Legacy `session/send` + during a backend follow-up turn parks as steer (never for V2 + follow-ups); a mid-turn probe send during a REGULAR turn fails -32010. + - **v4 CAS commands need the conversation watermark, and auto-drain is + ONLY re-evaluated from v4 command handlers upstream** (probe journal + `.zcode/scratch/acp-v2-probes-2026-11-29.md`): the tracker (v2/queue.ts) + merges the topic's snapshot + `state.updated` patches per session — + `revision`/`logEpoch` are the CAS watermark, and `queueCommand` waits + for the first snapshot before ANY queue command (upstream rejects a + bare command with `proto.invalidPayload`). After a turn NOT started by + a v4 command ends with a non-empty auto-drain queue, the bridge must + nudge (`setAutoDrain`, CAS, idle-only, debounced) or the queued item + sticks forever. While a turn runs the revision moves constantly → + `status: "stale"` is routine; retry with a refreshed watermark + (bounded, `sendV4Command`). A queue-command RESPONSE carries whatever + the tracker holds when the ACK returns: usually the pre-command view, + but the v4 frame can beat the RPC reply and the response then already + holds the new state (both orders observed live, 2026-11-30). Clients + apply responses and `_zcode/queue_changed` pushes alike, idempotently + (the React App dedupes through `sameQueueView`), and read the push as + the truth — a frame ingested before the ACK is in the response, one + ingested after it pushes after the response. Do not make the response + wait for a frame; and if a deleted queue item ever reappears on a + client, suspect a stale response landing after a newer push — none + was observed. + - **Child sessions speak ONLY v4** (probe P1): `session/subscribe` / + `session/messages` on a subagent child answer "runtime is not ready" + (no protocol record upstream); the child transcript mirror + (v2/child-mirror.ts) rides the child's OWN v4 conversation topic. + Side chats (selection chat) are the mirror opposite: legacy methods + work, the restricted v4 command set rejects CAS commands with + `guard.selectionSideChatRestrictedCommand`. + - **The archive bit is bridge-owned state, not upstream's**: + `src/archive-store.ts` (durable, temp+rename) is honored by the V2 + `session/list` filter, the hub heartbeat and the `/sessions` rows; ANY + bridge can flip it (remote/session-archive-endpoint.ts) because the + bridge that lists a project is seldom the one holding the conversation. - **ZCode backend version drift**: the backend may change event payloads between releases. When diff display or event handling breaks, check the raw backend event with `ZCODE_ACP_DEBUG=1` before changing translator code. @@ -1419,7 +1514,7 @@ suppressed` warn — treat that line as "the id bridge failed again". Do not (`applyModelRequestAuth` merges it into the provider config the signing fetch reads). Parser parity (`cBr`): THREE dot-separated parts that decode as base64url JSON with header `{alg:"HS256", typ:"JWT", - sign_type:"SIGN"}` and payload `{token_use:"project_access", api_key}` +sign_type:"SIGN"}` and payload `{token_use:"project_access", api_key}` (the project-access token; handshake field `accessToken`), OR exactly one dot splitting a non-empty `id.secret` console key (handshake field `apiKey`); a malformed 3-part string does NOT fall through to the From 9884446c81ce99a5d8f464da8cc8560eb9dac65f Mon Sep 17 00:00:00 2001 From: William Wang Date: Tue, 1 Dec 2026 09:09:42 +0800 Subject: [PATCH 2/9] feat: stream background shell output on the V2 face and file background agents as subagents MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - background.ts: a task that carries a childSessionId but no taskKind is a subagent — SubagentSpawned reaches the wire before the task event and was filed as "other" for good; output tails are cumulative snapshots, diffed before they are streamed as terminal_output_chunk; killed, stopped, lost, timed_out and spawn_error settle the task instead of leaving it running - background-tasks.ts: the output tail was forwarded only on the reused launch-card path, which needs _meta.terminal_output (Zed) — every task event now reaches the V2 face, settled per session in event order - tests: 9 new cases in tests/v2-background.test.ts --- src/handlers/background-tasks.ts | 47 ++++- src/v2/background.ts | 91 ++++++++- tests/v2-background.test.ts | 331 ++++++++++++++++++++++++++++++- 3 files changed, 447 insertions(+), 22 deletions(-) diff --git a/src/handlers/background-tasks.ts b/src/handlers/background-tasks.ts index 29f15e1..d4c7958 100644 --- a/src/handlers/background-tasks.ts +++ b/src/handlers/background-tasks.ts @@ -57,6 +57,7 @@ import { noteV2TaskRegistered, noteV2TaskTerminal, noteV2TerminalOutput, + v2TaskOutcome, } from "../v2/background.js"; /** Shape of a `session.updated` payload that reports a background task state. */ @@ -630,19 +631,45 @@ export class BackgroundTaskListener implements EventListener { /** * V2 view of the same task (ADR-0039 B6): announce it in its V2 form on - * first sight, end it when the listener saw a terminal status. Runs after - * the listener tracked the card, so the card id is known. + * first sight, stream its output, end it when the listener saw a terminal + * status. Runs after the listener tracked the card, so the card id is + * known, and strictly in event order: the handlers of two task events may + * settle out of order, and a V2 note landing late would stream an older + * output snapshot over a newer one. */ + private v2Notes: Promise = Promise.resolve(); + private noteV2(p: TaskStatusPayload): void { + if (!this.server.v2) return; + this.v2Notes = this.v2Notes + .then(() => this.settleV2(p)) + .catch((e: unknown) => + warn(` [v2] background note failed: ${e instanceof Error ? e.message : String(e)}`), + ); + } + + private async settleV2(p: TaskStatusPayload): Promise { const task = this.tasks.get(p.taskId); - if (!task || !this.server.v2) return; - const acpStatus = toAcpStatus(p.status); - void noteV2TaskRegistered(this.server, this.zcodeSid, p, task.acpCallId).catch((e: unknown) => - warn(` [v2] background register failed: ${e instanceof Error ? e.message : String(e)}`), + if (!task) return; + await noteV2TaskRegistered(this.server, this.zcodeSid, p, task.acpCallId); + // Every task event carries the output as a cumulative tail (a shell's + // stdout, else stderr); the V2 side diffs it and streams what is new. + // Rides the events rather than the launch-card path below, which only a + // client that declared terminal output ever takes. + await noteV2TerminalOutput( + this.server, + this.zcodeSid, + p.taskId, + p.outputTail ?? p.stdoutTail ?? p.stderrTail, ); - if (acpStatus !== "in_progress") { - void noteV2TaskTerminal(this.server, this.zcodeSid, p.taskId, acpStatus, acpStatus === "failed" ? 1 : 0).catch( - (e: unknown) => warn(` [v2] background settle failed: ${e instanceof Error ? e.message : String(e)}`), + const outcome = v2TaskOutcome(p.status); + if (outcome) { + await noteV2TaskTerminal( + this.server, + this.zcodeSid, + p.taskId, + outcome, + outcome === "completed" ? 0 : 1, ); } } @@ -850,8 +877,6 @@ export class BackgroundTaskListener implements EventListener { toolCallId: task.sourceToolCallId, _meta: { terminal_output: { terminal_id: task.sourceToolCallId, data: delta } }, }); - // The same delta as a V2 terminal chunk (ADR-0039 B6). - void noteV2TerminalOutput(this.server, this.zcodeSid, p.taskId, delta).catch(() => undefined); } } // terminal_exit only fires on a terminal status. A non-terminal (running) diff --git a/src/v2/background.ts b/src/v2/background.ts index 6823722..bf4a943 100644 --- a/src/v2/background.ts +++ b/src/v2/background.ts @@ -34,6 +34,8 @@ export interface BackgroundTask { done?: boolean; /** Last output of a shell task (what a resume replays for it). */ outputTail?: string; + /** The last output snapshot upstream sent for a shell task, diffed against the next. */ + outputSnapshot?: string; mirror?: ChildMirror; /** The mirror's start, shared by everyone who asks for it at the same time. */ mirrorStart?: Promise; @@ -149,6 +151,66 @@ async function publish(server: ZcodeAcpServer, zcodeSid: string): Promise await emitV2State(server, acpSid); } +/** The kind of work a task is, from the listener's `session.updated` payload. */ +function kindOf(payload: { taskKind?: string; childSessionId?: string }): BackgroundTask["kind"] { + if ( + payload.taskKind === "subagent" || + payload.taskKind === "workflow" || + payload.taskKind === "bash" + ) { + return payload.taskKind; + } + // A subagent's spawn event names no taskKind — only the task event that + // follows it does — but it is the one other carrier of a child session id, + // and it reaches the wire FIRST (the child is ready before the Agent call + // returns). Without this the task is filed as "other" for good. + if (!payload.taskKind && payload.childSessionId) return "subagent"; + return "other"; +} + +/** + * The V2 outcome of an upstream task status; undefined while the task is + * still live. Upstream's terminal spellings go beyond failed/cancelled + * (killed, stopped, lost, timed_out, …): anything not known to mean "live" + * ends the item, so no status wording can strand it in the list. + */ +export function v2TaskOutcome( + status: string | undefined, +): "completed" | "failed" | "cancelled" | undefined { + switch (status) { + case undefined: + case "": + case "pending": + case "running": + return undefined; + case "completed": + return "completed"; + case "cancelled": + case "killed": + case "stopped": + return "cancelled"; + default: + return "failed"; + } +} + +/** + * What a cumulative output snapshot adds over the previous one. Upstream's + * tails are bounded windows over a growing stream: once the output outgrows + * the window, the next snapshot no longer extends the last one — it has + * scrolled past it — so the delta is the part after the longest overlap. + */ +export function snapshotDelta(previous: string | undefined, next: string): string { + if (!previous) return next; + if (next.startsWith(previous)) return next.slice(previous.length); + if (previous.endsWith(next)) return ""; + const max = Math.min(previous.length, next.length); + for (let size = max; size > 0; size--) { + if (previous.endsWith(next.slice(0, size))) return next.slice(size); + } + return next; +} + /** * First sighting of a background task on a session a V2 connection holds: * announce it in its V2 form and list it. `payload` is the listener's @@ -171,12 +233,7 @@ export async function noteV2TaskRegistered( tasks.set(zcodeSid, byTask); } if (byTask.has(payload.taskId)) return; - const kind = - payload.taskKind === "subagent" || - payload.taskKind === "workflow" || - payload.taskKind === "bash" - ? payload.taskKind - : "other"; + const kind = kindOf(payload); const task: BackgroundTask = { zcodeSid, taskId: payload.taskId, @@ -207,6 +264,9 @@ export async function noteV2TaskRegistered( title: task.title || "Subagent", capabilities: { cancel: {} }, state: { state: "running" }, + // The listener's task id (a workflow run's is its run id): the one + // link between a V2 item and the task the hub's workflow routes name. + _meta: { zcode: { taskId: task.taskId } }, }); await mirrorFor(server, acpSid, task); } @@ -216,23 +276,32 @@ export async function noteV2TaskRegistered( toolCallId: task.toolCallId, status: "in_progress", capabilities: { cancel: {} }, + _meta: { zcode: { taskId: task.taskId, title: task.title } }, }); } await publish(server, zcodeSid); log(` [v2] background task listed: ${payload.taskId.slice(-12)} (${kind})`); } -/** A shell task produced output (already diffed by the listener). */ +/** + * A shell task's output as upstream last reported it: a CUMULATIVE snapshot + * (`outputTail` / `stdoutTail` / `stderrTail` of a task event), not a delta. + * Only the part newer than the last snapshot goes out as a chunk, and the + * tail a resume replays is kept whether or not a V2 connection is held. + */ export async function noteV2TerminalOutput( server: ZcodeAcpServer, zcodeSid: string, taskId: string, - delta: string, + snapshot: string | undefined, ): Promise { const task = tasks.get(zcodeSid)?.get(taskId); - const acpSid = acpSidOf(server, zcodeSid); - if (!task?.terminalId) return; + if (!task?.terminalId || !snapshot) return; + const delta = snapshotDelta(task.outputSnapshot, snapshot); + task.outputSnapshot = snapshot; + if (!delta) return; task.outputTail = ((task.outputTail ?? "") + delta).slice(-8192); + const acpSid = acpSidOf(server, zcodeSid); if (!acpSid || !server.v2?.held(server, acpSid)) return; await emit(server, acpSid, { sessionUpdate: "terminal_output_chunk", @@ -404,6 +473,7 @@ export async function replayBackground( title: task.title || "Subagent", capabilities: { cancel: {} }, state: { state: task.mirror?.state ?? "running" }, + _meta: { zcode: { taskId: task.taskId, replayed: true } }, }); for (const update of task.mirror?.replayRows() ?? []) send(task.childSessionId, update); if (task.mirror) send(task.childSessionId, task.mirror.stateUpdate()); @@ -413,6 +483,7 @@ export async function replayBackground( toolCallId: task.toolCallId, status: "in_progress", capabilities: { cancel: {} }, + _meta: { zcode: { taskId: task.taskId, title: task.title, replayed: true } }, }); } } diff --git a/tests/v2-background.test.ts b/tests/v2-background.test.ts index c914e76..5285769 100644 --- a/tests/v2-background.test.ts +++ b/tests/v2-background.test.ts @@ -12,7 +12,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { ZcodeBackend } from "../src/backend/client.js"; import type { ZcodeEvent } from "../src/backend/types.js"; import { ZcodeAcpServer } from "../src/server.js"; -import { resetBackgroundForTests } from "../src/v2/background.js"; +import { resetBackgroundForTests, snapshotDelta } from "../src/v2/background.js"; import { ingestV4Frame, resetV4TrackerForTests } from "../src/v2/queue.js"; import { connectV2, type TestClient } from "./v2-helpers.js"; @@ -137,6 +137,128 @@ describe("v2 background shells", () => { expect(terminals.at(-1)).toMatchObject({ terminalId: "call_b", exitStatus: { exitCode: 0 } }); expect(states(client).at(-1)).toMatchObject({ background: [] }); }); + + it("streams a shell's output to a client that declared no terminal-output support (no launch card reused)", async () => { + const { client, ev, push } = await setup(); + // No `terminalSentData` entry: the dispatcher took the plain tool path, so + // the listener mints its own card and the task never rides a launch card. + const chunks = () => + client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "terminal_output_chunk") + .map( + (p) => + [ + String(p.update.terminalId), + Buffer.from(String(p.update.data), "base64").toString("utf8"), + ] as const, + ); + push([ + ev("session.updated", { + taskId: "exec_1", + toolCallId: "call_b", + taskKind: "bash", + status: "running", + description: "npm test", + }), + ]); + await settle(); + const registered = client + .sessionUpdates(SESSION) + .find((p) => p.update.sessionUpdate === "terminal_update")?.update.terminalId as string; + expect(registered).toMatch(/^bg_/); + expect(chunks()).toEqual([]); + + push([ev("session.updated", { taskId: "exec_1", status: "running", stdoutTail: "line 1\n" })]); + await settle(); + expect(chunks()).toEqual([[registered, "line 1\n"]]); + + // Upstream's tails are a bounded window: once the output outgrows it the + // next snapshot has scrolled past the last one instead of extending it. + // Only the part that is new may go out. + const head = "x".repeat(4000); + push([ + ev("session.updated", { taskId: "exec_1", status: "running", stdoutTail: `${head}line 2\n` }), + ]); + await settle(); + expect(chunks().at(-1)).toEqual([registered, `${head}line 2\n`]); + push([ + ev("session.updated", { + taskId: "exec_1", + status: "running", + stdoutTail: "x".repeat(3990) + "line 2\nline 3\n", + }), + ]); + await settle(); + expect(chunks().at(-1)).toEqual([registered, "line 3\n"]); + + push([ + ev("session.updated", { + taskId: "exec_1", + status: "completed", + stdoutTail: "x".repeat(3990) + "line 2\nline 3\ndone\n", + }), + ]); + await settle(); + expect(chunks().at(-1)).toEqual([registered, "done\n"]); + const end = client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "terminal_update") + .at(-1)?.update; + expect(end).toMatchObject({ + terminalId: registered, + exitStatus: { exitCode: 0 }, + capabilities: null, + }); + // Output precedes the exit frame, and nothing was sent twice. + const kinds = client.sessionUpdates(SESSION).map((p) => p.update.sessionUpdate); + expect(kinds.lastIndexOf("terminal_output_chunk")).toBeLessThan( + kinds.lastIndexOf("terminal_update"), + ); + expect( + chunks() + .map(([, text]) => text) + .join(""), + ).toBe("line 1\n" + "x".repeat(4000) + "line 2\nline 3\ndone\n"); + }); + + it("delivers a short shell's output before its exit frame when start and end arrive back to back", async () => { + const { client, ev, push } = await setup(); + push([ + ev("session.updated", { + taskId: "exec_1", + toolCallId: "call_b", + taskKind: "bash", + status: "running", + description: "npm test", + }), + ev("session.updated", { taskId: "exec_1", status: "completed", stdoutTail: "ok\n" }), + ]); + await settle(); + const kinds = client.sessionUpdates(SESSION).map((p) => p.update.sessionUpdate); + expect(kinds.lastIndexOf("terminal_output_chunk")).toBeGreaterThan( + kinds.indexOf("terminal_update"), + ); + expect(kinds.lastIndexOf("terminal_output_chunk")).toBeLessThan( + kinds.lastIndexOf("terminal_update"), + ); + const chunk = client + .sessionUpdates(SESSION) + .find((p) => p.update.sessionUpdate === "terminal_output_chunk"); + expect(Buffer.from(String(chunk?.update.data), "base64").toString("utf8")).toBe("ok\n"); + }); +}); + +describe("snapshotDelta", () => { + it("emits what a cumulative tail adds, across a window that extends, repeats, scrolls or replaces", () => { + expect(snapshotDelta(undefined, "abc")).toBe("abc"); + expect(snapshotDelta("abc", "abcdef")).toBe("def"); + expect(snapshotDelta("abcdef", "abcdef")).toBe(""); + expect(snapshotDelta("abcdef", "cdef")).toBe(""); // the window shrank + // A 4-character window over a stream that grew by two characters. + expect(snapshotDelta("abcd", "cdefgh")).toBe("efgh"); + expect(snapshotDelta("abcd", "wxyz")).toBe("wxyz"); // nothing in common + }); }); describe("v2 subagents", () => { @@ -161,6 +283,7 @@ describe("v2 subagents", () => { title: "research the parser", capabilities: { cancel: {} }, state: { state: "running" }, + _meta: { zcode: { taskId: "agent_kid" } }, }); expect(states(client).at(-1)).toMatchObject({ background: [{ type: "subagent", sessionId: CHILD }], @@ -184,6 +307,161 @@ describe("v2 subagents", () => { }); }); + it("announces a background agent from its spawn event, which names the child session but no task kind", async () => { + const { client, ev, push } = await setup(); + // The wire order upstream (4.0): the child is ready before the Agent call + // returns, so `SubagentSpawned` (a generic session.updated) arrives FIRST + // and the task event with `taskKind` only after it. + const v2Kinds = () => client.sessionUpdates(SESSION).map((p) => p.update.sessionUpdate); + push([ + ev("session.updated", { + agentId: "agent_kid", + taskId: "agent_kid", + executionId: "ex_1", + agentType: "Explore", + background: true, + childSessionId: CHILD, + description: "count the entries", + parentToolCallId: "call_a", + status: "running", + }), + ]); + await settle(); + const sub = client + .sessionUpdates(SESSION) + .find((p) => p.update.sessionUpdate === "subagent_update"); + expect(sub?.update).toMatchObject({ + sessionId: CHILD, + title: "count the entries", + capabilities: { cancel: {} }, + state: { state: "running" }, + _meta: { zcode: { taskId: "agent_kid" } }, + }); + expect(states(client).at(-1)).toMatchObject({ + background: [{ type: "subagent", sessionId: CHILD }], + }); + // A subagent is one item: no stand-in terminal, no tool call beside it. + expect(v2Kinds()).not.toContain("terminal_update"); + expect( + client + .sessionUpdates(SESSION) + .some( + (p) => + p.update.sessionUpdate === "tool_call_update" && + (p.update.capabilities as { cancel?: unknown } | undefined)?.cancel !== undefined, + ), + ).toBe(false); + + // The task event that follows adds nothing: one announcement, still live. + push([ + ev("session.updated", { + taskId: "agent_kid", + toolCallId: "call_a", + toolName: "Agent", + taskKind: "subagent", + childSessionId: CHILD, + cancellable: true, + description: "count the entries", + status: "running", + terminalId: "agent_kid", + }), + ]); + await settle(); + expect( + client.sessionUpdates(SESSION).filter((p) => p.update.sessionUpdate === "subagent_update") + .length, + ).toBe(1); + + push([ + ev("session.updated", { + taskId: "agent_kid", + toolCallId: "call_a", + toolName: "Agent", + taskKind: "subagent", + childSessionId: CHILD, + description: "count the entries", + status: "completed", + outputPath: "/tmp/agents/agent_kid/output.txt", + terminalId: "agent_kid", + }), + ]); + await settle(); + const subs = client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "subagent_update") + .map((p) => p.update); + expect(subs.at(-1)).toMatchObject({ + sessionId: CHILD, + state: { state: "idle", stopReason: "end_turn" }, + }); + expect(states(client).at(-1)).toMatchObject({ background: [] }); + expect(v2Kinds()).not.toContain("terminal_update"); + }); + + it("is announced once when the task event comes before the spawn event", async () => { + const { client, ev, push } = await setup(); + push([ + ev("session.updated", { + taskId: "agent_kid", + toolCallId: "call_a", + toolName: "Agent", + taskKind: "subagent", + childSessionId: CHILD, + description: "count the entries", + status: "running", + }), + ev("session.updated", { + agentId: "agent_kid", + taskId: "agent_kid", + childSessionId: CHILD, + parentToolCallId: "call_a", + status: "running", + }), + ]); + await settle(); + const subs = client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "subagent_update"); + expect(subs.length).toBe(1); + expect(states(client).at(-1)).toMatchObject({ + background: [{ type: "subagent", sessionId: CHILD }], + }); + }); + + it.each([ + ["killed", "cancelled"], + ["stopped", "cancelled"], + ["lost", "error"], + ["failed", "error"], + ] as const)( + "settles an agent the upstream reports as %s with stopReason %s", + async (status, stopReason) => { + const { client, ev, push } = await setup(); + push([ + ev("session.updated", { + agentId: "agent_kid", + taskId: "agent_kid", + childSessionId: CHILD, + status: "running", + }), + ev("session.updated", { + taskId: "agent_kid", + toolCallId: "call_a", + taskKind: "subagent", + childSessionId: CHILD, + status, + }), + ]); + await settle(); + const subs = client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "subagent_update") + .map((p) => p.update); + expect(subs.at(-1)).toMatchObject({ sessionId: CHILD, state: { state: "idle", stopReason } }); + expect(states(client).at(-1)).toMatchObject({ background: [] }); + }, + ); + it("mirrors the child's v4 conversation rows as updates addressed to the child", async () => { const { client, ev, push } = await setup(); push([ @@ -341,6 +619,7 @@ describe("v2 subagents", () => { sessionId: CHILD, capabilities: { cancel: {} }, state: { state: "running" }, + _meta: { zcode: { taskId: "agent_kid", replayed: true } }, }); const updates = joiner.notifications("session/update"); const announceAt = updates.findIndex( @@ -399,6 +678,56 @@ describe("v2 subagents", () => { }); }); +describe("v2 workflow runs", () => { + it("names the listener's task on the registration — live and on replay — so a client can map a run id to its tool call", async () => { + const { server, client, ev, push } = await setup(); + push([ + ev("session.updated", { + taskId: "run_42", + toolCallId: "call_wf", + taskKind: "workflow", + status: "running", + description: "nightly build", + }), + ]); + await settle(); + // The registration is the one `tool_call_update` that carries cancel + // capabilities; its card is whatever the listener tracks the run under + // (the launch card, or a fresh one for a settings-launched run). + const registration = (c: TestClient) => + c + .sessionUpdates(SESSION) + .find( + (p) => + p.update.sessionUpdate === "tool_call_update" && + (p.update.capabilities as { cancel?: unknown } | undefined)?.cancel !== undefined, + ); + const live = registration(client); + expect(live?.update).toMatchObject({ + status: "in_progress", + capabilities: { cancel: {} }, + _meta: { zcode: { taskId: "run_42", title: "nightly build" } }, + }); + expect(states(client).at(-1)).toMatchObject({ + background: [{ type: "tool_call", toolCallId: live?.update.toolCallId }], + }); + + // A late joiner's resume announces the same task under the same name. + const joiner = await connectV2(server); + const response = await joiner.request("session/resume", { + sessionId: SESSION, + cwd: process.env.HOME!, + }); + expect(response.error).toBeUndefined(); + expect(registration(joiner)?.update).toMatchObject({ + toolCallId: live?.update.toolCallId, + status: "in_progress", + capabilities: { cancel: {} }, + _meta: { zcode: { taskId: "run_42", title: "nightly build", replayed: true } }, + }); + }); +}); + describe("v2 per-item cancel", () => { it("terminal/cancel stops the task behind the terminal and answers unknown work with -32602", async () => { const { server, client, ev, push, calls } = await setup(); From 064ca26ace19c2d566c1cd6658acc149874692eb Mon Sep 17 00:00:00 2001 From: William Wang Date: Tue, 1 Dec 2026 10:29:35 +0800 Subject: [PATCH 3/9] feat: stream a background shell's output while it runs by reading its output file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - background.ts: a running background shell publishes nothing on the wire while it runs (the adapter watches output progress for foreground runs alone) and the end event's tail is the HEAD of the output file — the V2 face now tails the task's output file itself (every 500 ms, a 64 KiB catch-up cut to a line start, chunks of at most 256 KiB never split inside a UTF-8 sequence, read to the end before the exit frame) and skips the end tail once the file delivered anything - background-tasks.ts: V2 notes settle per session in event order (settleV2) so two task events cannot land out of order - tests: tests/v2-background.test.ts --- src/handlers/background-tasks.ts | 32 ++-- src/v2/background.ts | 267 ++++++++++++++++++++++++++++++- tests/v2-background.test.ts | 259 +++++++++++++++++++++++++++++- 3 files changed, 541 insertions(+), 17 deletions(-) diff --git a/src/handlers/background-tasks.ts b/src/handlers/background-tasks.ts index d4c7958..70a170a 100644 --- a/src/handlers/background-tasks.ts +++ b/src/handlers/background-tasks.ts @@ -54,9 +54,12 @@ import { echoSteeredInputs, emitSessionTurnState } from "./io.js"; import { dispatchEvent } from "./dispatch.js"; import { isAdoptableTurnStarted, runOrphanTurn } from "../v2/orphan.js"; import { + flushV2OutputFile, + noteV2OutputFile, noteV2TaskRegistered, noteV2TaskTerminal, noteV2TerminalOutput, + streamedFromOutputFile, v2TaskOutcome, } from "../v2/background.js"; @@ -652,17 +655,26 @@ export class BackgroundTaskListener implements EventListener { const task = this.tasks.get(p.taskId); if (!task) return; await noteV2TaskRegistered(this.server, this.zcodeSid, p, task.acpCallId); - // Every task event carries the output as a cumulative tail (a shell's - // stdout, else stderr); the V2 side diffs it and streams what is new. - // Rides the events rather than the launch-card path below, which only a - // client that declared terminal output ever takes. - await noteV2TerminalOutput( - this.server, - this.zcodeSid, - p.taskId, - p.outputTail ?? p.stdoutTail ?? p.stderrTail, - ); + // A running shell's output is in the file every task event names, not on + // the wire (upstream sends it with the end event alone). + noteV2OutputFile(this.server, this.zcodeSid, p.taskId, p.outputPath); const outcome = v2TaskOutcome(p.status); + // The shell's last output goes out before its exit frame. + if (outcome) await flushV2OutputFile(this.zcodeSid, p.taskId); + // A task event also carries the output as a cumulative tail (a shell's + // stdout, else stderr), which the V2 side diffs and streams — the path + // for a shell whose file could not be read; once the file was read, that + // tail is the head of the same output. Rides the events rather than the + // launch-card path below, which only a client that declared terminal + // output ever takes. + if (!streamedFromOutputFile(this.zcodeSid, p.taskId)) { + await noteV2TerminalOutput( + this.server, + this.zcodeSid, + p.taskId, + p.outputTail ?? p.stdoutTail ?? p.stderrTail, + ); + } if (outcome) { await noteV2TaskTerminal( this.server, diff --git a/src/v2/background.ts b/src/v2/background.ts index bf4a943..a0cf847 100644 --- a/src/v2/background.ts +++ b/src/v2/background.ts @@ -10,8 +10,14 @@ * `tool_call_update` with cancel capabilities, `subagent_update` with the * child's mirrored state. Nothing here talks to the backend on its own except * through the existing listener and cancel paths. + * + * A shell's output is the exception, by necessity: upstream puts a background + * shell's output on the wire only with the task's end event, so while the + * shell runs its output is read from the file the child process writes. */ +import { open, type FileHandle } from "node:fs/promises"; + import type { ZcodeAcpServer } from "../server.js"; import { log, warn } from "../utils.js"; import type { ClientHandle } from "../remote/client-handle.js"; @@ -36,17 +42,51 @@ export interface BackgroundTask { outputTail?: string; /** The last output snapshot upstream sent for a shell task, diffed against the next. */ outputSnapshot?: string; + /** Set while a shell task's output file is being read as it grows. */ + tail?: OutputFileTail; mirror?: ChildMirror; /** The mirror's start, shared by everyone who asks for it at the same time. */ mirrorStart?: Promise; } +/** + * A live shell's output file, read as it grows: upstream's progress watcher + * covers foreground runs alone, so the file the child process writes is the + * only place a running shell's output exists before the task's end event. + */ +interface OutputFileTail { + server: ZcodeAcpServer; + path: string; + /** Bytes of the file consumed so far — sent, or held in `pending`. */ + offset: number; + /** The start of a UTF-8 sequence the last read cut; sent once it completes. */ + pending: Buffer; + /** False until the first read chose where to start. */ + caughtUp: boolean; + /** Bytes sent from the file; past zero the end event's tail is never sent. */ + sent: number; + /** The read in flight; a second caller joins it instead of reading the same bytes twice. */ + busy?: Promise; + warned?: boolean; +} + /** taskId → task, per backend session. */ const tasks = new Map>(); /** Grace after a subagent finished before its transcript mirror is released (late rows). */ const MIRROR_RELEASE_MS = 3_000; +/** How often a live shell's output file is read for what it gained. */ +const OUTPUT_POLL_MS = 500; +/** What a first read goes back to at most: a shell first seen late shows its recent output, not its log. */ +const OUTPUT_CATCHUP_BYTES = 64 * 1024; +/** Upper bound of one `terminal_output_chunk`, so a burst never becomes one huge frame. */ +const OUTPUT_CHUNK_BYTES = 256 * 1024; +/** Reads at a task's end before its exit frame goes out; a flood at the very end is not waited on. */ +const OUTPUT_FINAL_READS = 8; +/** What a resume replays for a shell's output. */ +const OUTPUT_TAIL_CHARS = 8192; + export function backgroundTasksOf(zcodeSid: string): BackgroundTask[] { return [...(tasks.get(zcodeSid)?.values() ?? [])].filter((t) => !t.done); } @@ -283,11 +323,213 @@ export async function noteV2TaskRegistered( log(` [v2] background task listed: ${payload.taskId.slice(-12)} (${kind})`); } +// ---------- a running shell's output file ---------- + +/** + * How many leading bytes of `buffer` end complete UTF-8 sequences. A read can + * stop inside a multi-byte character; its unfinished tail waits for the next + * read instead of going out as a broken one. + */ +export function completeUtf8Prefix(buffer: Buffer): number { + const end = buffer.length; + for (let back = 1; back <= 3 && back <= end; back++) { + const byte = buffer[end - back]!; + if ((byte & 0xc0) === 0x80) continue; // a continuation byte: the lead is further back + const width = byte < 0x80 || byte >= 0xf8 ? 1 : byte < 0xe0 ? 2 : byte < 0xf0 ? 3 : 4; + return back < width ? end - back : end; + } + return end; +} + +/** The output a resume replays for a shell: the last stretch of what it wrote. */ +function keepOutputTail(previous: string | undefined, delta: string): string { + const kept = (previous ?? "") + delta; + if (kept.length <= OUTPUT_TAIL_CHARS) return kept; + const cut = kept.slice(-OUTPUT_TAIL_CHARS); + // A low surrogate first is one half of a pair the cut took the other half of. + const first = cut.charCodeAt(0); + return first >= 0xdc00 && first <= 0xdfff ? cut.slice(1) : cut; +} + +let outputPoll: ReturnType | undefined; + +function ensureOutputPoll(): void { + if (outputPoll) return; + outputPoll = setInterval(() => { + void pollOutputFiles().catch((e: unknown) => + warn(` [v2] shell output poll failed: ${e instanceof Error ? e.message : String(e)}`), + ); + }, OUTPUT_POLL_MS); + outputPoll.unref?.(); +} + +function stopOutputPoll(): void { + if (outputPoll) clearInterval(outputPoll); + outputPoll = undefined; +} + +/** + * The file a live shell writes its output to — every task event names it. + * From here on the file is read while the task runs, whether or not a V2 + * connection holds the session: the tail a resume replays stays current for + * a late joiner, and the chunks go out to whoever holds the session then. + */ +export function noteV2OutputFile( + server: ZcodeAcpServer, + zcodeSid: string, + taskId: string, + path: string | undefined, +): void { + const task = tasks.get(zcodeSid)?.get(taskId); + if (!task || task.done || !task.terminalId || !path || task.tail) return; + task.tail = { server, path, offset: 0, pending: Buffer.alloc(0), caughtUp: false, sent: 0 }; + ensureOutputPoll(); + log(` [v2] shell output watched: ${path}`); +} + +/** + * One pass over every live shell's output file: what each gained since its + * last read goes out as a chunk. Runs on a timer while any shell is live. + */ +export async function pollOutputFiles(): Promise { + let live = false; + for (const byTask of tasks.values()) { + for (const task of byTask.values()) { + if (!task.tail || task.done) continue; + live = true; + await pumpOutputFile(task); + } + } + if (!live) stopOutputPoll(); +} + +/** + * Read what a shell's output file gained, as one bounded chunk. Resolves true + * once nothing is left to read. + */ +function pumpOutputFile(task: BackgroundTask): Promise { + const tail = task.tail; + if (!tail) return Promise.resolve(true); + if (tail.busy) return tail.busy; + tail.busy = readOutputFile(task, tail).finally(() => { + tail.busy = undefined; + }); + return tail.busy; +} + +async function readOutputFile(task: BackgroundTask, tail: OutputFileTail): Promise { + let handle: FileHandle; + try { + handle = await open(tail.path, "r"); + } catch (e) { + return noteOutputFileError(tail, e); + } + try { + const { size } = await handle.stat(); + // Shorter than what was read already: rewritten in place, so its content is new output. + if (size < tail.offset) { + tail.offset = 0; + tail.pending = Buffer.alloc(0); + } + if (!tail.caughtUp) { + tail.caughtUp = true; + tail.offset = await catchUpOffset(handle, size); + } + if (size <= tail.offset) return true; + const length = Math.min(size - tail.offset, OUTPUT_CHUNK_BYTES); + const buffer = Buffer.allocUnsafe(length); + let read = 0; + while (read < length) { + const { bytesRead } = await handle.read(buffer, read, length - read, tail.offset + read); + if (bytesRead === 0) break; + read += bytesRead; + } + tail.offset += read; + // The task may have ended while the read was out: no output after its exit frame. + if (task.tail === tail) { + await sendOutputFile(task, tail, Buffer.concat([tail.pending, buffer.subarray(0, read)])); + } + return tail.offset >= size; + } catch (e) { + return noteOutputFileError(tail, e); + } finally { + await handle.close().catch(() => undefined); + } +} + +/** + * Where the first read of an already long output file starts: far enough back + * to show recent output, never mid-line. + */ +async function catchUpOffset(handle: FileHandle, size: number): Promise { + if (size <= OUTPUT_CATCHUP_BYTES) return 0; + const start = size - OUTPUT_CATCHUP_BYTES; + const probe = Buffer.allocUnsafe(4096); + await handle.read(probe, 0, probe.length, start); + const newline = probe.indexOf(0x0a); + let at = newline >= 0 ? newline + 1 : 0; + // No line start near enough: the next character boundary will do. + while (at < probe.length && (probe[at]! & 0xc0) === 0x80) at++; + return start + at; +} + +function noteOutputFileError(tail: OutputFileTail, e: unknown): boolean { + const code = (e as NodeJS.ErrnoException | undefined)?.code; + // Not there is the ordinary case: a shell that has not written yet, or whose file was cleaned up. + if (code !== "ENOENT" && !tail.warned) { + tail.warned = true; + warn(` [v2] shell output ${tail.path}: ${e instanceof Error ? e.message : String(e)}`); + } + return true; +} + +async function sendOutputFile( + task: BackgroundTask, + tail: OutputFileTail, + buffer: Buffer, +): Promise { + const end = completeUtf8Prefix(buffer); + tail.pending = Buffer.from(buffer.subarray(end)); + const delta = buffer.subarray(0, end); + if (delta.length === 0) return; + tail.sent += delta.length; + task.outputTail = keepOutputTail(task.outputTail, delta.toString("utf8")); + const acpSid = acpSidOf(tail.server, task.zcodeSid); + if (!acpSid || !tail.server.v2?.held(tail.server, acpSid)) return; + await emit(tail.server, acpSid, { + sessionUpdate: "terminal_output_chunk", + terminalId: task.terminalId!, + data: delta.toString("base64"), + }); +} + +/** + * The last of a shell's output: its file read to the end before the update + * that retires the terminal. + */ +export async function flushV2OutputFile(zcodeSid: string, taskId: string): Promise { + const task = tasks.get(zcodeSid)?.get(taskId); + if (!task?.tail) return; + for (let reads = 0; reads < OUTPUT_FINAL_READS; reads++) { + if (await pumpOutputFile(task)) break; + } +} + +/** + * Whether a shell's output came from its file. The end event's tail is the + * head of that same file: sent once the file was read, it would repeat output + * the client already has. + */ +export function streamedFromOutputFile(zcodeSid: string, taskId: string): boolean { + return (tasks.get(zcodeSid)?.get(taskId)?.tail?.sent ?? 0) > 0; +} + /** * A shell task's output as upstream last reported it: a CUMULATIVE snapshot * (`outputTail` / `stdoutTail` / `stderrTail` of a task event), not a delta. * Only the part newer than the last snapshot goes out as a chunk, and the - * tail a resume replays is kept whether or not a V2 connection is held. + * tail a resume replays is kept whether or not a V2 connection is held. The + * path for a shell whose output file could not be read (ADR-0039 B6). */ export async function noteV2TerminalOutput( server: ZcodeAcpServer, @@ -300,7 +542,7 @@ export async function noteV2TerminalOutput( const delta = snapshotDelta(task.outputSnapshot, snapshot); task.outputSnapshot = snapshot; if (!delta) return; - task.outputTail = ((task.outputTail ?? "") + delta).slice(-8192); + task.outputTail = keepOutputTail(task.outputTail, delta); const acpSid = acpSidOf(server, zcodeSid); if (!acpSid || !server.v2?.held(server, acpSid)) return; await emit(server, acpSid, { @@ -311,8 +553,9 @@ export async function noteV2TerminalOutput( } /** - * The task ended (completed / failed / cancelled): its final update, then it - * leaves the list. Idempotent — the listener may see a terminal status twice. + * The task ended (completed / failed / cancelled): a shell's remaining output + * first, then its final update, then it leaves the list. Idempotent — the + * listener may see a terminal status twice. */ export async function noteV2TaskTerminal( server: ZcodeAcpServer, @@ -323,7 +566,10 @@ export async function noteV2TaskTerminal( ): Promise { const task = tasks.get(zcodeSid)?.get(taskId); if (!task || task.done) return; + // Marked before the first await: a cancel and the end event may both land here. task.done = true; + await flushV2OutputFile(zcodeSid, taskId); + task.tail = undefined; const acpSid = acpSidOf(server, zcodeSid); if (!acpSid || !server.v2?.held(server, acpSid)) return; const stopReason = @@ -367,14 +613,23 @@ export async function noteV2TaskTerminal( /** Forget a session's tasks (the conversation closed). */ export function forgetBackground(zcodeSid: string): void { - for (const task of tasks.get(zcodeSid)?.values() ?? []) task.mirror?.stop(); + for (const task of tasks.get(zcodeSid)?.values() ?? []) { + task.mirror?.stop(); + task.tail = undefined; + } tasks.delete(zcodeSid); } /** Test seam. */ export function resetBackgroundForTests(): void { - for (const byTask of tasks.values()) for (const task of byTask.values()) task.mirror?.stop(); + for (const byTask of tasks.values()) { + for (const task of byTask.values()) { + task.mirror?.stop(); + task.tail = undefined; + } + } tasks.clear(); + stopOutputPoll(); } // ---------- cancel + resume ---------- diff --git a/tests/v2-background.test.ts b/tests/v2-background.test.ts index 5285769..de26814 100644 --- a/tests/v2-background.test.ts +++ b/tests/v2-background.test.ts @@ -7,12 +7,20 @@ * it does for V1; the V2 emissions hang off it. */ +import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { ZcodeBackend } from "../src/backend/client.js"; import type { ZcodeEvent } from "../src/backend/types.js"; import { ZcodeAcpServer } from "../src/server.js"; -import { resetBackgroundForTests, snapshotDelta } from "../src/v2/background.js"; +import { + completeUtf8Prefix, + pollOutputFiles, + resetBackgroundForTests, + snapshotDelta, +} from "../src/v2/background.js"; import { ingestV4Frame, resetV4TrackerForTests } from "../src/v2/queue.js"; import { connectV2, type TestClient } from "./v2-helpers.js"; @@ -728,6 +736,255 @@ describe("v2 workflow runs", () => { }); }); +describe("v2 background shell output file", () => { + // Upstream puts a background shell's output on the wire only with the task's + // end event; while the shell runs, its output is in the file every task + // event names, which the bridge reads as the file grows. + let dir: string; + let file: string; + const started = (path: string) => ({ + taskId: "exec_f", + toolCallId: "call_f", + taskKind: "bash", + status: "running", + description: "dev server", + outputPath: path, + }); + const chunksOf = (client: TestClient) => + client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "terminal_output_chunk") + .map((p) => Buffer.from(String(p.update.data), "base64").toString("utf8")); + const chunkSizes = (client: TestClient) => + client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "terminal_output_chunk") + .map((p) => Buffer.from(String(p.update.data), "base64").length); + /** The terminal's own frames alone, in order. */ + const terminalKinds = (client: TestClient) => + client + .updateKinds(SESSION) + .filter((k) => k === "terminal_update" || k === "terminal_output_chunk"); + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "v2-shell-output-")); + file = join(dir, "toolu-stdout.log"); + }); + afterEach(() => rmSync(dir, { recursive: true, force: true })); + + it("streams a running shell's output as its file grows, and the exit frame follows the last of it", async () => { + const { client, ev, push } = await setup(); + push([ev("session.updated", started(file))]); + await settle(); + expect(chunksOf(client)).toEqual([]); + + appendFileSync(file, "tick 1\n"); + await pollOutputFiles(); + await settle(); + expect(chunksOf(client)).toEqual(["tick 1\n"]); + + // Nothing new, nothing sent. + await pollOutputFiles(); + expect(chunksOf(client)).toEqual(["tick 1\n"]); + + appendFileSync(file, "tick 2\n"); + await pollOutputFiles(); + await settle(); + expect(chunksOf(client)).toEqual(["tick 1\n", "tick 2\n"]); + + // The end event's tail is the HEAD of the same file: sent again, the + // client would have the output twice. + push([ + ev("session.updated", { + taskId: "exec_f", + status: "completed", + outputTail: "tick 1\ntick 2\n", + }), + ]); + await settle(); + expect(chunksOf(client)).toEqual(["tick 1\n", "tick 2\n"]); + expect(terminalKinds(client)).toEqual([ + "terminal_update", + "terminal_output_chunk", + "terminal_output_chunk", + "terminal_update", + ]); + const end = client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "terminal_update") + .at(-1)?.update; + expect(end).toMatchObject({ exitStatus: { exitCode: 0 }, capabilities: null }); + expect(states(client).at(-1)).toMatchObject({ background: [] }); + + // Past the end, the file is no longer read. + appendFileSync(file, "late\n"); + await pollOutputFiles(); + expect(chunksOf(client)).toEqual(["tick 1\n", "tick 2\n"]); + }); + + it("delivers a short shell's whole output once when its start and end arrive back to back", async () => { + const { client, ev, push } = await setup(); + appendFileSync(file, "quick\n"); + push([ + ev("session.updated", started(file)), + ev("session.updated", { taskId: "exec_f", status: "completed", outputTail: "quick\n" }), + ]); + await settle(); + expect(chunksOf(client)).toEqual(["quick\n"]); + expect(terminalKinds(client)).toEqual([ + "terminal_update", + "terminal_output_chunk", + "terminal_update", + ]); + }); + + it("never cuts a multi-byte character between two reads", async () => { + const { client, ev, push } = await setup(); + push([ev("session.updated", started(file))]); + await settle(); + // "中" is E4 B8 AD: two of its bytes now, the third with the next output. + appendFileSync(file, Buffer.from([0x61, 0xe4, 0xb8])); + await pollOutputFiles(); + await settle(); + expect(chunksOf(client)).toEqual(["a"]); + appendFileSync(file, Buffer.from([0xad, 0x62, 0x0a])); + await pollOutputFiles(); + await settle(); + expect(chunksOf(client)).toEqual(["a", "中b\n"]); + }); + + it("shows only the recent output of a shell first seen with a long log, cut to a line", async () => { + const { client, ev, push } = await setup(); + const log = Array.from({ length: 12_000 }, (_, i) => `line ${i}\n`).join(""); + appendFileSync(file, log); + push([ev("session.updated", started(file))]); + await settle(); + await pollOutputFiles(); + await settle(); + const sent = chunksOf(client).join(""); + expect(Buffer.byteLength(log)).toBeGreaterThan(64 * 1024); + expect(sent.length).toBeLessThanOrEqual(64 * 1024); + expect(sent.length).toBeGreaterThan(64 * 1024 - 12); + expect(sent.startsWith("line ")).toBe(true); + expect(log.endsWith(sent)).toBe(true); + }); + + it("splits a burst so no single chunk is huge, and still delivers all of it", async () => { + const { client, ev, push } = await setup(); + appendFileSync(file, "start\n"); + push([ev("session.updated", started(file))]); + await settle(); + await pollOutputFiles(); + const burst = `${"x".repeat(600 * 1024)}\n`; + appendFileSync(file, burst); + await pollOutputFiles(); + await settle(); + expect(Math.max(...chunkSizes(client))).toBe(256 * 1024); + expect(chunksOf(client).join("")).not.toBe(`start\n${burst}`); + for (let tick = 0; tick < 4; tick++) await pollOutputFiles(); + await settle(); + expect(chunksOf(client).join("")).toBe(`start\n${burst}`); + }); + + it("falls back to the end event's tail when the output file cannot be read", async () => { + const { client, ev, push } = await setup(); + push([ev("session.updated", started(join(dir, "missing.log")))]); + await settle(); + push([ev("session.updated", { taskId: "exec_f", status: "completed", outputTail: "done\n" })]); + await settle(); + expect(chunksOf(client)).toEqual(["done\n"]); + expect(terminalKinds(client)).toEqual([ + "terminal_update", + "terminal_output_chunk", + "terminal_update", + ]); + }); + + it("reads a file rewritten in place — shorter than what was read — as new output", async () => { + const { client, ev, push } = await setup(); + appendFileSync(file, "first run\n"); + push([ev("session.updated", started(file))]); + await settle(); + await pollOutputFiles(); + writeFileSync(file, "again\n"); + await pollOutputFiles(); + await settle(); + expect(chunksOf(client)).toEqual(["first run\n", "again\n"]); + }); + + it("sends what a cancelled shell wrote before its exit frame", async () => { + const { server, client, ev, push } = await setup(); + server.terminalSentData.set("call_f", ""); + push([ev("session.updated", started(file))]); + await settle(); + appendFileSync(file, "before stop\n"); + const ok = await client.request("terminal/cancel", { + sessionId: SESSION, + terminalId: "call_f", + }); + expect(ok.error).toBeUndefined(); + await settle(); + expect(chunksOf(client)).toEqual(["before stop\n"]); + expect(terminalKinds(client)).toEqual([ + "terminal_update", + "terminal_output_chunk", + "terminal_update", + ]); + const end = client + .sessionUpdates(SESSION) + .filter((p) => p.update.sessionUpdate === "terminal_update") + .at(-1)?.update; + expect(end).toMatchObject({ + capabilities: null, + _meta: { zcode: { status: "cancelled" } }, + }); + }); + + it("keeps the replayed tail current while no V2 connection holds the session", async () => { + const { server, client, ev, push } = await setup(); + server.terminalSentData.set("call_f", ""); + server.clients.v2Handles()[0]!.attached.delete(SESSION); + push([ev("session.updated", started(file))]); + await settle(); + appendFileSync(file, "written while unattended\n"); + await pollOutputFiles(); + await settle(); + // Nobody holds the session: nothing went out, and nothing was lost either. + expect(chunksOf(client)).toEqual([]); + + const joiner = await connectV2(server); + const response = await joiner.request("session/resume", { + sessionId: SESSION, + cwd: process.env.HOME!, + }); + expect(response.error).toBeUndefined(); + const replayed = joiner + .sessionUpdates(SESSION) + .find((p) => p.update.sessionUpdate === "terminal_update")?.update; + expect(replayed).toMatchObject({ + terminalId: "call_f", + output: { data: "written while unattended\n" }, + capabilities: { cancel: {} }, + _meta: { zcode: { replayed: true } }, + }); + }); +}); + +describe("completeUtf8Prefix", () => { + it("keeps an unfinished sequence back and passes complete ones through", () => { + const bytes = (...list: number[]) => Buffer.from(list); + expect(completeUtf8Prefix(bytes(0x61, 0x62))).toBe(2); + expect(completeUtf8Prefix(bytes(0xe4, 0xb8, 0xad))).toBe(3); // 中 + expect(completeUtf8Prefix(bytes(0xf0, 0x9f, 0x98, 0x80))).toBe(4); // 😀 + expect(completeUtf8Prefix(bytes(0x61, 0xe4))).toBe(1); + expect(completeUtf8Prefix(bytes(0x61, 0xe4, 0xb8))).toBe(1); + expect(completeUtf8Prefix(bytes(0x61, 0xf0, 0x9f, 0x98))).toBe(1); + // Continuation bytes with no lead in sight are not a sequence to wait for. + expect(completeUtf8Prefix(bytes(0x80, 0x80))).toBe(2); + expect(completeUtf8Prefix(Buffer.alloc(0))).toBe(0); + }); +}); + describe("v2 per-item cancel", () => { it("terminal/cancel stops the task behind the terminal and answers unknown work with -32602", async () => { const { server, client, ev, push, calls } = await setup(); From 7052c84ddd623a49741bf44aeaadc5cc3613f369 Mon Sep 17 00:00:00 2001 From: William Wang Date: Tue, 1 Dec 2026 10:29:45 +0800 Subject: [PATCH 4/9] chore: document the V2 face's backend floor and its background, queue and authorization gotchas - AGENTS.md: the V2 face targets ZCode 4.0 and later only; why a running background shell's output is not on the wire, how a background agent is told from other tasks by its first event, which client reuses a launch card, the archive HTTP path, the child transcript replay rule, who is offered MCP authorization's URL form, and the v4 query watermark behind the rewind reads --- AGENTS.md | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 8305bc8..68120d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -204,6 +204,10 @@ ZCode protocol types into ACP notifications directly — always translate. state store, whose phase is DERIVED from engine facts at emit time, never counted at the emit points). Invariants that will bite anyone "simplifying" either side: + - **The V2 face targets ZCode 4.0 and later ONLY** (user, 2026-12-01): + no compat branch for a pre-4.0 backend is added on this face — the V1 + face keeps its own compatibility paths. The V2 facts below were read + from the 4.0.0 source, not probed from the bundle. - **`turn.face` gating**: `runEventTurn` settles V2 turns through `noteV2TurnEnd` on EVERY terminal — early cancel exits included (`cancelledResult`, session.ts ~4937). A `cancelledResult` call must @@ -263,6 +267,80 @@ ZCode protocol types into ACP notifications directly — always translate. `session/list` filter, the hub heartbeat and the `/sessions` rows; ANY bridge can flip it (remote/session-archive-endpoint.ts) because the bridge that lists a project is seldom the one holding the conversation. + Archiving also has an HTTP path — `POST /api/instances/{id}/sessions/ +{sid}/archive|unarchive`, relayed by the hub to the bridge's route — + because the session list and the history dialog hold no ACP connection. + - **A background shell's output is NOT on the wire while it runs** (source + 2026-12-01, 4.0.0): the Bash execution adapter watches output progress + for FOREGROUND runs alone (`file.watchProgress` only when the run is not + backgrounded, node-execution-adapter-run.ts), and a background record's + bytes and tails come from progress events alone + (`updateBackgroundTaskRecordFromEvent`) — so a backgrounded shell emits + no `BackgroundTaskUpdated` while it runs, and the END event's + `outputTail` is `result.stdout.text`, the HEAD of the output file + (`readBashOutput(path, maxBytes, tail=false)`, the inline limit — 10 MiB + by default), never its tail. No RPC reads a running task's output either + (`readBackgroundBashOutput` is an internal port method behind the + TaskOutput tool). `v2/background.ts` therefore reads the task's output + file itself — every task event names it (`outputPath`; a Bash task's + stdout and stderr are MERGED into one file under + `$TMPDIR/zcode-bash-*//-stdout.log`, else + `<~/.zcode | ZCODE_STORAGE_DIR>/cli/exec//…`): every 500 ms + while the task is live, the first read catches up the last 64 KiB cut to + a line start, a chunk is at most 256 KiB and never split inside a UTF-8 + sequence, the file is read to its end BEFORE the exit frame + (`flushV2OutputFile`), and once the file delivered anything the end + event's tail is NOT sent — it would repeat output the client already + has. The event-tail path (`noteV2TerminalOutput`, snapshot diffing) + remains only for a file that could not be read. Tailing runs whether or + not a V2 connection holds the session (the 8 KiB tail a resume replays + stays current for a late joiner); chunks go to whoever holds it. Live + 2026-12-01: a tick-per-second shell reached the client as one chunk per + second, exit frame last. + - **A background agent's first event is `SubagentSpawned`, which names no + `taskKind`** (source 2026-12-01): a generic `session.updated` carrying + `taskId`, `childSessionId` and `background: true`, written when the + child is ready — BEFORE the Agent call returns; `BackgroundTaskStarted` + with `taskKind: "subagent"` follows. A task is classified by its + `taskKind`, else by a `childSessionId` (`kindOf`): by first sighting + alone it was filed as "other" for good (a fake terminal plus a + cancellable tool call, no child transcript). Upstream's terminal + statuses are `completed`, `failed`, `timed_out`, `cancelled`, + `spawn_error`, `lost` (+ runtime `killed` / `stopped`): anything not + known to mean live ends the V2 item (`v2TaskOutcome`), so no wording can + strand it in the `background` list. + - **Only a client that declared `_meta.terminal_output` (Zed) reuses the + launch card** — `terminalSentData` is seeded by `dispatchTerminalUpdate` + alone — so the product clients' tasks mint `bg_` cards, and those + are the V2 `terminalId`s. Anything forwarded on the reused-launch-card + path alone never reaches React / GPUI; V2 output rides every task event + (and the file above) instead, and V2 notes settle per session in event + order (`settleV2`) so two task events cannot land out of order. + - **`session/prompt` on a busy or paused session answers + `attachmentsNotQueued`** (`-32603`, `reasonCode` in the error data) when + the prompt carries non-text blocks: that path is the v4 `sendText` (see + above), which would drop the images; the client keeps the input for the + legacy send. A `noop` queue-command ACK is a success (`sendV4Command` + with `noopOk`), and `_zcode/queue/lockEdit` / `releaseEdit` are the + upstream edit lock behind in-place queue editing. + - **A child transcript replay goes to the connection that resumed, never + around** (the history-replay rule): `replayBackground` re-announces each + live subagent with a `subagent_update` that CARRIES `capabilities` — the + clients' signal to clear the child transcript they hold — then the rows + the mirror has sent so far (≤ 2000), then the child's state. + - **MCP authorization's URL form is offered only to a connection that + declared BOTH `elicitation.url` and same-machine** (the OAuth callback + is the backend's loopback); nobody local, everybody declining, or 10 s + unanswered → the bridge opens the browser on its own machine and tells + the holders through `_zcode/mcp_authorization {openedLocal: true}`; a + finished flow clears that fallback (it used to pop a browser 10 s after + the client had completed the authorization). + - **`_zcode/rewind/*` reads are v4 QUERIES with the CAS watermark** + (`sendV4Query`: ensure the topic subscription, carry + `baseRevision` / `baseLogEpoch`, refresh and retry on a stale verdict) + — the v4 gateway schema is strict and rejected the earlier bare reads; + `_zcode/turn_summaries {sessionId}` lets a re-entering client read back + the file-change summaries of the turns already in its row window. - **ZCode backend version drift**: the backend may change event payloads between releases. When diff display or event handling breaks, check the raw backend event with `ZCODE_ACP_DEBUG=1` before changing translator code. From 045f44a90c3f979e8d488ad5938ba07c3703ad2f Mon Sep 17 00:00:00 2001 From: William Wang Date: Tue, 1 Dec 2026 10:29:45 +0800 Subject: [PATCH 5/9] feat: convert client MCP servers to the backend's wire shape on both faces - #457: the backend's session/create takes ONE strict shape (a stdio entry without type or _meta and with env as a required name/value array, an http entry with headers as pairs); forwarded verbatim, T3 Code's V2 entries failed every create, and the SDK 2.12.0 bump also dropped the SDK 1.x spelling from the V1 schema, so V1 session/new answered -32602 where 0.97.0 took it - client-mcp-servers.ts (new): toWireMcpServers accepts both spellings and rejects the rest with the entry's path; v1SessionParams lets the V1 session/new|resume|load routes parse mcpServers themselves - session.ts: convert at the top of newSession / resumeSession / loadSession, before any state is recorded, so a malformed entry leaves no placeholder - v2/initialize.ts: advertise session.mcp.stdio and session.mcp.http - tests: tests/client-mcp-servers.test.ts; AGENTS.md, docs/REMOTE-CLIENTS.md --- AGENTS.md | 26 ++ docs/REMOTE-CLIENTS.md | 6 +- src/config/client-mcp-servers.ts | 141 +++++++++++ src/handlers/session.ts | 25 +- src/index.ts | 33 ++- src/server.ts | 12 +- src/v2/initialize.ts | 5 +- tests/client-mcp-servers.test.ts | 395 +++++++++++++++++++++++++++++++ 8 files changed, 611 insertions(+), 32 deletions(-) create mode 100644 src/config/client-mcp-servers.ts create mode 100644 tests/client-mcp-servers.test.ts diff --git a/AGENTS.md b/AGENTS.md index 68120d2..18e4279 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -323,6 +323,32 @@ ZCode protocol types into ACP notifications directly — always translate. legacy send. A `noop` queue-command ACK is a success (`sendV4Command` with `noopOk`), and `_zcode/queue/lockEdit` / `releaseEdit` are the upstream edit lock behind in-place queue editing. + - **A client's `mcpServers` are converted to the backend's wire shape, on + both faces** (2026-12-01, #457): the backend's `session/create·resume` + take ONE shape (strict zod, `zcodeProtocolMcpServerSchema`) — a stdio + entry `{name, command, args, env}` with `env` a REQUIRED `[{name, +value}]` array and no `type`, an http/sse entry `{name, type, url, +headers}`, neither with `_meta` — and nothing else. Forwarded verbatim + (0.98.0), T3 Code's V2 `{type: "stdio", …}` failed every session's + create with `Unrecognized key: "type"`, and so did a V2 entry carrying + the `_meta` its own schema allows. The SDK 2.12.0 bump ALSO dropped the + SDK 1.x spelling (`env` / `headers` as string maps, fields optional) + from its V1 schema — the shape every V1 client written against SDK 1.x + sends — so 0.98.0's V1 `session/new` answered -32602 where 0.97.0's + took it. Two pieces (`src/config/client-mcp-servers.ts`): the V1 + routes `session/new|resume|load` parse `mcpServers` themselves + (`v1SessionParams`, index.ts — the rest of each request keeps the SDK's + required fields), and every face converts where it remembers the list + (`toWireMcpServers` at the top of `newSession` / `resumeSession` / + `loadSession`, before any state is recorded, so a malformed entry + leaves no placeholder). The stored list is wire-valid by construction + and every later create / resume / reload sends it as is. A `type` the + backend has no field for (V2's schema passes unknown transports + through) is a -32602 at `session/new`, never a create failure later; + the V2 face advertises `session.mcp.stdio` and `session.mcp.http`. Do + not forward a client entry again — the shape matrix was measured live + against 4.0.0 (`.zcode/scratch/v2-probes/live/mcp-shapes.live.ts`, no + model call). - **A child transcript replay goes to the connection that resumed, never around** (the history-replay rule): `replayBackground` re-announces each live subagent with a `subagent_update` that CARRIES `capabilities` — the diff --git a/docs/REMOTE-CLIENTS.md b/docs/REMOTE-CLIENTS.md index 7743c0f..9157b2d 100644 --- a/docs/REMOTE-CLIENTS.md +++ b/docs/REMOTE-CLIENTS.md @@ -402,8 +402,10 @@ ws(s):///acp?instance=&token= - `session/load { sessionId, cwd, mcpServers }` with an id from discovery — replays the conversation history (text + tool summaries) as `session/update`s, so a freshly attached client can render the full - story. `cwd` and `mcpServers` (even `[]`) are required — the SDK's params - schema rejects the request without them. + story. `cwd` is required — the params parser rejects the request + without it — and `mcpServers` (even `[]`) is sent as the ACP schemas + expect; both of its spellings are taken (`env` / `headers` as string + maps or as `[{name, value}]`). - `session/new { cwd? }` — a new session on that bridge. - `session/list` enumerates the bridge's known sessions. 3. Drive: `session/prompt`, `session/cancel`, `session/set_config_option` diff --git a/src/config/client-mcp-servers.ts b/src/config/client-mcp-servers.ts new file mode 100644 index 0000000..5d42d6c --- /dev/null +++ b/src/config/client-mcp-servers.ts @@ -0,0 +1,141 @@ +/** + * Client-declared MCP servers → the backend's wire shape. + * + * `mcpServers` rides session/new, resume, load and fork, and each protocol + * face validates it with its own schema before a handler runs. The backend + * accepts ONE shape (strict zod, `zcodeProtocolMcpServerSchema`, 4.0.0): a + * stdio entry is `{name, command, args, env}` with `env` a REQUIRED + * `[{name, value}]` array and no `type`; an http/sse entry is `{name, type, + * url, headers}` with `headers` the same pair array; neither takes `_meta`. + * Forwarded verbatim (the 0.98.0 behavior), every client entry but the bare + * V1 http one failed the session's first `session/create`: T3 Code's V2 + * `{type: "stdio", …}` with `Unrecognized key: "type"` (issue #457), a V2 + * entry carrying the `_meta` its schema allows with `Unrecognized key: + * "_meta"`. So the bridge converts the entries once, where it remembers them + * (`handlers/session.ts`): the stored list is wire-valid by construction and + * every later create, resume and reload sends it as is. + * + * Two spellings are accepted per transport: + * - the ACP spelling up to SDK 1.x: `env` / `headers` are string maps, `args` + * / `env` / `headers` may be absent, a stdio entry carries no `type`; + * - the SDK 2.12.0 spelling (what its schemas validate on both faces): + * `[{name, value}]` arrays, an http entry's `type` required, a V2 stdio + * entry's `"stdio"`. + * The V1 face must keep accepting the first: every V1 client written against + * SDK 1.x sends it, and the SDK 2.12.0 schema dropped it — its routes + * therefore parse `mcpServers` here and only the rest of the request with + * the SDK's shape (`v1SessionParams`, index.ts). The V2 face is the product's + * own and takes the SDK's V2 spelling alone. + */ + +import { RequestError } from "@agentclientprotocol/sdk/unstable"; +import { z } from "zod"; + +import type { ZcodeMcpServer } from "../backend/types.js"; + +const TRANSPORTS = new Set(["stdio", "http", "sse"]); +/** Every key either schema puts on an entry; anything else is a client bug. */ +const ENTRY_KEYS = new Set(["type", "name", "command", "args", "env", "url", "headers", "_meta"]); + +/** + * The `mcpServers` array of a session request in the backend's wire shape; + * undefined when the client sent none. A malformed entry is a -32602 naming + * its field, in the backend's own wording. + */ +export function toWireMcpServers(entries: unknown): ZcodeMcpServer[] | undefined { + if (entries === undefined || entries === null) return undefined; + if (!Array.isArray(entries)) { + throw new RequestError(-32602, "mcpServers: Invalid input"); + } + return entries.map(toWireServer); +} + +function toWireServer(entry: unknown, index: number): ZcodeMcpServer { + const at = `mcpServers.${index}`; + if (!entry || typeof entry !== "object" || Array.isArray(entry)) { + throw new RequestError(-32602, `${at}: Invalid input`); + } + const raw = entry as Record; + for (const key of Object.keys(raw)) { + if (!ENTRY_KEYS.has(key)) throw new RequestError(-32602, `${at}: Unrecognized key: "${key}"`); + } + const name = requiredString(raw.name, `${at}.name`); + // A transport the backend has no field for (V2 passes unknown `type`s + // through as "other") would fail the WHOLE create; name it here instead. + const type = raw.type; + if (type !== undefined && (typeof type !== "string" || !TRANSPORTS.has(type))) { + throw new RequestError(-32602, `${at}: Unsupported MCP transport: ${JSON.stringify(type)}`); + } + if (type === "http" || type === "sse") { + return { + name, + type, + url: requiredString(raw.url, `${at}.url`), + headers: pairs(raw.headers, `${at}.headers`), + }; + } + return { + name, + command: requiredString(raw.command, `${at}.command`), + args: stringArray(raw.args, `${at}.args`), + env: pairs(raw.env, `${at}.env`), + }; +} + +function requiredString(value: unknown, at: string): string { + if (typeof value !== "string") throw new RequestError(-32602, `${at}: Invalid input`); + return value; +} + +/** A string array, absent meaning empty. */ +function stringArray(value: unknown, at: string): string[] { + if (value === undefined || value === null) return []; + if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) { + throw new RequestError(-32602, `${at}: Invalid input`); + } + return value; +} + +/** + * `[{name, value}]` as the wire takes it, from that array (an item's `_meta` + * is dropped) or from the SDK 1.x string map; absent meaning empty. + */ +function pairs(value: unknown, at: string): { name: string; value: string }[] { + if (value === undefined || value === null) return []; + if (Array.isArray(value)) { + return value.map((item) => { + if (!item || typeof item !== "object" || Array.isArray(item)) { + throw new RequestError(-32602, `${at}: Invalid input`); + } + const { name, value: itemValue } = item as Record; + return { + name: requiredString(name, `${at}.name`), + value: requiredString(itemValue, `${at}.value`), + }; + }); + } + if (typeof value !== "object") throw new RequestError(-32602, `${at}: Invalid input`); + return Object.entries(value).map(([name, item]) => ({ + name, + value: requiredString(item, `${at}.${name}`), + })); +} + +/** + * Params parser for the V1 session routes that take `mcpServers` (new, load, + * resume). The SDK's 2.12.0 schema for these requests dropped the SDK 1.x + * `mcpServers` spelling every V1 client written against it sends — since + * 0.98.0 `session/new` answered such a client with -32602 — so the field is + * taken raw here, for the handler to convert (`toWireMcpServers`), and the + * rest of the request keeps the SDK's own required fields. Passthrough, so a + * field this parser does not name still reaches the handler. + */ +export function v1SessionParams(required: Record) { + return z + .object({ + ...required, + mcpServers: z.unknown().optional(), + _meta: z.record(z.unknown()).optional(), + }) + .passthrough(); +} diff --git a/src/handlers/session.ts b/src/handlers/session.ts index afd90ab..feb3005 100644 --- a/src/handlers/session.ts +++ b/src/handlers/session.ts @@ -29,6 +29,7 @@ import { resolveReal } from "../backend/sandbox.js"; import type { ZcodeCreateResult, ZcodeListResult, + ZcodeMcpServer, ZcodeMessage, ZcodeProjection, ZcodeSnapshot, @@ -73,6 +74,7 @@ import { buildResumeRuntimeModel, lastSwitchedModelValue, } from "../config/runtime-model.js"; +import { toWireMcpServers } from "../config/client-mcp-servers.js"; import { clientServersOf, mergeUserConfigMcpServers } from "../config/user-mcp-servers.js"; import { effectiveWorkflowGate, @@ -489,7 +491,7 @@ async function resumeParams( server: ZcodeAcpServer, zcodeSid: string, cwd: string, - mcpServers?: acp.McpServer[], + mcpServers?: ZcodeMcpServer[], ): Promise> { const params: Record = { sessionId: zcodeSid, @@ -558,7 +560,7 @@ function authoritativeSessionCwd(server: ZcodeAcpServer, acpSid: string): string function rememberSessionMcpServers( server: ZcodeAcpServer, acpSid: string, - mcpServers?: acp.McpServer[], + mcpServers?: ZcodeMcpServer[], ): void { if (mcpServers && mcpServers.length > 0) { server.sessionMcpServers.set(acpSid, mcpServers); @@ -780,6 +782,9 @@ export async function newSession( params: acp.NewSessionRequest, client?: acp.AgentContext, ): Promise { + // Converted before anything below records state: a malformed MCP entry is + // a -32602 and must leave no placeholder behind. + const mcpServers = toWireMcpServers(params.mcpServers); // Martty bookkeeping (ADR-0021): start the lazy refresher when THIS // connection is martty. Identity is per-connection — recorded at the // connection's own initialize (server.ts), never the sticky process flag, @@ -811,9 +816,9 @@ export async function newSession( const cwd = server.serveMode ? process.cwd() : (sanitizeClientCwd(params.cwd) ?? process.cwd()); - server.pendingSessions.set(bindSid, { cwd, mcpServers: params.mcpServers }); + server.pendingSessions.set(bindSid, { cwd, mcpServers }); server.sessionCwds.set(bindSid, cwd); - rememberSessionMcpServers(server, bindSid, params.mcpServers); + rememberSessionMcpServers(server, bindSid, mcpServers); // Remote-created: discovery must advertise it in the ACTIVE list for // as long as this bridge lives (a phone has no editor-side session // storage of its own; the window closing ends the listing). @@ -924,11 +929,11 @@ export async function newSession( // Placeholder id — the client addresses this session with it until the // backend session materializes; never shown in session/list. const acpSid = randomUUID(); - server.pendingSessions.set(acpSid, { cwd, mcpServers: params.mcpServers }); + server.pendingSessions.set(acpSid, { cwd, mcpServers }); // Persists past materialization (pendingSessions is cleared on first use) so // the remote discovery payload can still label the workspace. server.sessionCwds.set(acpSid, cwd); - rememberSessionMcpServers(server, acpSid, params.mcpServers); + rememberSessionMcpServers(server, acpSid, mcpServers); // Durable alias so the placeholder survives a bridge restart and session/ // resume can still resolve it (best-effort; failures are swallowed inside // the store). Serve-mode mints are remote-driven — advertise them. @@ -1314,7 +1319,7 @@ export async function ensureRealSession( log(`session/create carrying ${remembered.length} remembered client MCP server(s)`); } } - const clientMcp = createParams.mcpServers as acp.McpServer[] | undefined; + const clientMcp = createParams.mcpServers as ZcodeMcpServer[] | undefined; const mergedMcp = mergeUserConfigMcpServers(clientMcp, server.userMcpRejected); if (mergedMcp && mergedMcp !== clientMcp) { createParams.mcpServers = mergedMcp; @@ -1826,6 +1831,7 @@ export async function resumeSession( ): Promise { const acpSid = params.sessionId; if (!acpSid) throw new Error("sessionId required"); + const mcpServers = toWireMcpServers(params.mcpServers); // The Session Root never comes from the client (params.cwd is ignored): // start from what the bridge recorded, then let the backend's own resume // result correct it below — a remote client must not move a session's @@ -1861,7 +1867,7 @@ export async function resumeSession( // schema accepts the same array shape (verified: an unknown key would be // rejected before the session lookup). Remembered as session-lifetime // state so later reloads keep re-sending them (#193). - rememberSessionMcpServers(server, acpSid, params.mcpServers); + rememberSessionMcpServers(server, acpSid, mcpServers); const zcParams = await resumeParams( server, zcodeSid, @@ -2196,6 +2202,7 @@ export async function loadSession( ): Promise { const acpSid = params.sessionId; if (!acpSid) throw new Error("sessionId required"); + const mcpServers = toWireMcpServers(params.mcpServers); // The Session Root never comes from the client (params.cwd is ignored): // start from what the bridge recorded, then let the backend's own resume // result correct it below — a remote client must not move a session's @@ -2262,7 +2269,7 @@ export async function loadSession( if (!alreadyLive) { // Same mcpServers contract as resume: the client may re-declare them on // load; a stored set keeps riding along when it doesn't (#193). - rememberSessionMcpServers(server, acpSid, params.mcpServers); + rememberSessionMcpServers(server, acpSid, mcpServers); const zcParams = await resumeParams( server, zcodeSid, diff --git a/src/index.ts b/src/index.ts index 56fbe2e..1f11057 100644 --- a/src/index.ts +++ b/src/index.ts @@ -49,6 +49,7 @@ import { loadEarlier } from "./handlers/replay.js"; import { editUserMessage, retryTurn } from "./handlers/rewind.js"; import { steering } from "./handlers/steering.js"; import { resendPendingInteractions } from "./handlers/server-requests.js"; +import { v1SessionParams } from "./config/client-mcp-servers.js"; import { loadPluginCommands } from "./config/plugin-commands.js"; import { loadSkillCommands } from "./config/skill-discovery.js"; import { filterWorkflowCommands } from "./config/workflow-gate.js"; @@ -206,6 +207,12 @@ export function buildV1App( server.allCommands = allCommands; /** Passthrough params parser for the ZCode-specific extension methods. */ const extParams = z.object({ sessionId: z.string() }).passthrough(); + // session/new, resume and load take `mcpServers`, and both its spellings are + // the bridge's to parse (config/client-mcp-servers.ts): the SDK's 2.12.0 + // schema dropped the SDK 1.x one every V1 client written against it sends. + // The rest of each request keeps the SDK's own required fields. + const newSessionParams = v1SessionParams({ cwd: z.string() }); + const resumeSessionParams = v1SessionParams({ sessionId: z.string(), cwd: z.string() }); return ( acp @@ -215,8 +222,8 @@ export function buildV1App( // it answered -32601. Readiness check only — the bridge never takes // editor-side credentials (see handlers/authenticate.ts). .onRequest("authenticate", (ctx) => authenticate(ctx.params)) - .onRequest("session/new", async (ctx) => { - const result = await newSession(server, ctx.params, ctx.client); + .onRequest("session/new", newSessionParams, async (ctx) => { + const result = await newSession(server, ctx.params as acp.NewSessionRequest, ctx.client); // Holder bookkeeping (ADR-0039 B5): a V2 session/close stops the work // only when no connection of either face still holds the conversation. server.clients.attach(ctx.client, result.sessionId); @@ -230,16 +237,17 @@ export function buildV1App( return result; }) .onRequest("session/list", (ctx) => listSessions(server, ctx.params)) - .onRequest("session/resume", async (ctx) => { + .onRequest("session/resume", resumeSessionParams, async (ctx) => { + const params = ctx.params as acp.ResumeSessionRequest; // Replays target the REQUESTING connection only (ctx.client, not the // broadcast proxy): a replay is per-client rendering state, and // fanning it out appends the whole history to every OTHER attached // client's transcript at the bottom — the "replay disorder" report // (editor + TUI + app sharing one bridge through the hub). Live turn // updates keep fanning out via prompt()'s broadcast cx. - const result = await resumeSession(server, ctx.params, ctx.client); - server.clients.attach(ctx.client, ctx.params.sessionId); - for (const sid of server.sessionAliases(ctx.params.sessionId)) { + const result = await resumeSession(server, params, ctx.client); + server.clients.attach(ctx.client, params.sessionId); + for (const sid of server.sessionAliases(params.sessionId)) { sendAvailableCommandsDeferred( server.clients, sid, @@ -249,21 +257,22 @@ export function buildV1App( // A client that (re)connects catches up via resume/load; any interaction // request still waiting for an answer is re-sent to it so a question // fired while it was offline becomes answerable there. - resendPendingInteractions(server, ctx.client, ctx.params.sessionId); + resendPendingInteractions(server, ctx.client, params.sessionId); return result; }) - .onRequest("session/load", async (ctx) => { + .onRequest("session/load", resumeSessionParams, async (ctx) => { + const params = ctx.params as acp.LoadSessionRequest; // Targeted replay — see the session/resume comment above. - const result = await loadSession(server, ctx.params, ctx.client); - server.clients.attach(ctx.client, ctx.params.sessionId); - for (const sid of server.sessionAliases(ctx.params.sessionId)) { + const result = await loadSession(server, params, ctx.client); + server.clients.attach(ctx.client, params.sessionId); + for (const sid of server.sessionAliases(params.sessionId)) { sendAvailableCommandsDeferred( server.clients, sid, filterWorkflowCommands(server, allCommands), ); } - resendPendingInteractions(server, ctx.client, ctx.params.sessionId); + resendPendingInteractions(server, ctx.client, params.sessionId); return result; }) // Tail-replay pagination (non-standard; Proposal 0001) — params stay diff --git a/src/server.ts b/src/server.ts index f937b61..f6b3e2f 100644 --- a/src/server.ts +++ b/src/server.ts @@ -243,12 +243,10 @@ export class ZcodeAcpServer { { cwd: string; creating?: Promise; - /** Client-provided MCP servers from session/new, replayed verbatim into - * the backend's session/create when the lazy session materializes. The - * backend's mcpServers schema matches the ACP array shape (stdio entries - * carry command/args/env; remote entries carry type/url), so entries are - * passed through unchanged. */ - mcpServers?: acp.McpServer[]; + /** Client-declared MCP servers from session/new, in the backend's wire + * shape (config/client-mcp-servers.ts), replayed into the backend's + * session/create when the lazy session materializes. */ + mcpServers?: import("./backend/types.js").ZcodeMcpServer[]; /** * The model configOption `currentValue` last advertised to the client for * this placeholder (`session/new` response, or the catalog-probe update @@ -279,7 +277,7 @@ export class ZcodeAcpServer { * in at send time (never stored here, so a config edit reaches the next * create/resume). */ - readonly sessionMcpServers = new Map(); + readonly sessionMcpServers = new Map(); /** * In-flight `session/resume` single-flight, keyed by backend session id * (ADR-0017 first-entry race): the hub answers the App's incubation request diff --git a/src/v2/initialize.ts b/src/v2/initialize.ts index 087efa0..e2a63e4 100644 --- a/src/v2/initialize.ts +++ b/src/v2/initialize.ts @@ -24,8 +24,9 @@ export function v2AgentCapabilities(): v2.AgentCapabilities { return { session: { prompt: { image: {}, embeddedContext: {} }, - // http MCP configs are forwarded verbatim to the backend, as on V1. - mcp: { http: {} }, + // Both transports the backend serves; entries reach it in its wire + // shape (config/client-mcp-servers.ts). + mcp: { stdio: {}, http: {} }, // session/fork at a cursor the bridge announced, session/archive + unarchive. fork: {}, archive: {}, diff --git a/tests/client-mcp-servers.test.ts b/tests/client-mcp-servers.test.ts new file mode 100644 index 0000000..5fa05c6 --- /dev/null +++ b/tests/client-mcp-servers.test.ts @@ -0,0 +1,395 @@ +/** + * Client-declared `mcpServers` on both faces → the backend's wire shape + * (src/config/client-mcp-servers.ts). + * + * The backend's `session/create` takes one shape only (strict zod, 4.0.0): a + * stdio entry is `{name, command, args, env}` with `env` a REQUIRED + * `[{name, value}]` array and no `type`, an http one `{name, type, url, + * headers}`, neither with `_meta`. The V1 face must keep taking the SDK 1.x + * spelling (`env` / `headers` as string maps), which the SDK 2.12.0 schema + * dropped; the V2 face takes the SDK's typed spelling and must not forward it + * as is (T3 Code's `{type: "stdio", …}` failed every session's create — + * issue #457). + * + * Harness: the real protocol router over an in-memory transport + * (tests/v2-helpers.ts) on a recording fake backend whose `session/create` + * is strict like the real one — it answers -32602 in the backend's own + * wording for any entry that is not wire-shaped, so a create that succeeds + * here is one the real backend takes (the matrix was measured live, 4.0.0). + */ + +import { describe, expect, it, vi } from "vitest"; + +import type { ZcodeBackend } from "../src/backend/client.js"; +import type { ZcodeMessage } from "../src/backend/types.js"; +import { toWireMcpServers } from "../src/config/client-mcp-servers.js"; +import { ensureRealSession } from "../src/handlers/session.js"; +import { ZcodeAcpServer } from "../src/server.js"; +import { connect, connectV2, faces, type TestClient } from "./v2-helpers.js"; + +// session/new probes the initial model catalog by launching the real CLI, +// which syncs the official plugins under HOME — never inside a test +// (same mock as session-lazy.test.ts). +vi.mock("../src/config/initial-model-catalog.js", () => ({ + probeInitialModelCatalog: async () => null, +})); +vi.mock("../src/tasks-index.js", () => ({ + upsertSessionTask: async () => true, + updateSessionTitle: async () => true, +})); +vi.mock("../src/lazy-sessions.js", () => ({ + rememberLazySession: () => {}, + recordMaterializedSession: () => {}, + recordAdvertisedModel: () => {}, + recordModelChoice: () => {}, + lookupLazySession: () => undefined, + lookupModelChoiceByZcodeSid: () => undefined, +})); + +const HOME = process.env.HOME!; +const SESSION = "sess_v2"; +const ZSID = "zs_v2"; + +/** The SDK 1.x spelling: string maps, optional fields, no `type` on stdio. */ +const CLASSIC_STDIO = { name: "notes", command: "npx", args: ["-y", "notes"], env: { TOKEN: "t" } }; +const CLASSIC_HTTP = { + name: "remote", + type: "http", + url: "https://mcp.example.com/x", + headers: { Authorization: "Bearer a" }, +}; +/** The same two servers in the backend's wire shape. */ +const WIRE_STDIO = { + name: "notes", + command: "npx", + args: ["-y", "notes"], + env: [{ name: "TOKEN", value: "t" }], +}; +const WIRE_HTTP = { + name: "remote", + type: "http", + url: "https://mcp.example.com/x", + headers: [{ name: "Authorization", value: "Bearer a" }], +}; +/** What T3 Code sends on the V2 face (issue #457): the SDK 2.12.0 spelling. */ +const T3_STDIO = { + type: "stdio", + name: "t3-code", + command: "node", + args: ["apps/server/dist/index.js"], + env: [{ name: "T3", value: "1" }], + _meta: { t3: true }, +}; + +const isPairs = (value: unknown): boolean => + Array.isArray(value) && + value.every( + (pair) => + !!pair && + typeof pair === "object" && + typeof (pair as { name?: unknown }).name === "string" && + typeof (pair as { value?: unknown }).value === "string", + ); + +/** + * The backend's verdict on one entry of `mcpServers`, in its own wording; + * null when the entry is wire-shaped. + */ +function backendVerdict(entry: unknown, index: number): string | null { + const at = `Invalid params — mcpServers.${index}`; + if (!entry || typeof entry !== "object" || Array.isArray(entry)) return `${at}: Invalid input`; + const e = entry as Record; + const keys = Object.keys(e); + const stdio = ["name", "command", "args", "env"]; + const http = ["name", "type", "url", "headers"]; + const extra = keys.find((key) => !stdio.includes(key) && !http.includes(key)); + if (extra) return `${at}: Unrecognized key: "${extra}"`; + if (keys.length === stdio.length && stdio.every((key) => key in e)) { + return typeof e.command === "string" && Array.isArray(e.args) && isPairs(e.env) + ? null + : `${at}: Invalid input`; + } + if (keys.length === http.length && http.every((key) => key in e)) { + return (e.type === "http" || e.type === "sse") && + typeof e.url === "string" && + isPairs(e.headers) + ? null + : `${at}: Invalid input`; + } + return `${at}: Invalid input`; +} + +type Call = { method: string; params: Record }; + +/** Recording fake backend, strict about `mcpServers` like the real one. */ +function makeServer(): { server: ZcodeAcpServer; calls: Call[] } { + const calls: Call[] = []; + let created = 0; + const backend = { + isDead: false, + request: async (id: number, method: string, params: unknown) => { + const p = (params ?? {}) as Record; + calls.push({ method, params: p }); + if (method === "session/create" && Array.isArray(p.mcpServers)) { + const bad = p.mcpServers.map(backendVerdict).find((verdict) => verdict !== null); + if (bad) return { id, error: { code: -32602, message: bad } }; + } + switch (method) { + case "session/create": + created += 1; + return { id, result: { session: { sessionId: `sess_created_${created}`, title: "" } } }; + case "session/read": + return { id, result: { projection: { status: "idle" }, settings: {} } }; + case "session/messages": + return { id, result: { messages: [] satisfies ZcodeMessage[] } }; + default: + return { id, result: {} }; + } + }, + registerEventListener: () => {}, + unregisterEventListener: () => {}, + } as unknown as ZcodeBackend; + const server = new ZcodeAcpServer(); + server.backend = backend; + return { server, calls }; +} + +const creates = (calls: Call[]): Call[] => calls.filter((c) => c.method === "session/create"); + +/** A V1 connection over the router, handshaken. */ +async function connectV1(server: ZcodeAcpServer): Promise { + const client = connect(faces(server)); + const response = await client.request("initialize", { + protocolVersion: 1, + clientInfo: { name: "probe-v1", version: "0" }, + clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } }, + }); + expect(response.error).toBeUndefined(); + return client; +} + +const errorText = (response: { error?: { code?: number; message?: string } }): string => + response.error ? `${response.error.code} ${response.error.message}` : "(no error)"; + +describe("toWireMcpServers", () => { + it("reads no list as none, and an empty list as empty", () => { + expect(toWireMcpServers(undefined)).toBeUndefined(); + expect(toWireMcpServers(null)).toBeUndefined(); + expect(toWireMcpServers([])).toEqual([]); + }); + + it("takes the SDK 1.x spelling: string maps, optional fields, no type on stdio", () => { + expect(toWireMcpServers([CLASSIC_STDIO, CLASSIC_HTTP])).toEqual([WIRE_STDIO, WIRE_HTTP]); + expect(toWireMcpServers([{ name: "bare", command: "run" }])).toEqual([ + { name: "bare", command: "run", args: [], env: [] }, + ]); + expect(toWireMcpServers([{ name: "s", type: "sse", url: "https://s.example.com" }])).toEqual([ + { name: "s", type: "sse", url: "https://s.example.com", headers: [] }, + ]); + }); + + it("takes the SDK 2.12.0 spelling and drops what the backend has no field for", () => { + // T3 Code's V2 entry: the `type` and the `_meta` are the schema's, not the wire's. + expect(toWireMcpServers([T3_STDIO])).toEqual([ + { + name: "t3-code", + command: "node", + args: ["apps/server/dist/index.js"], + env: [{ name: "T3", value: "1" }], + }, + ]); + expect( + toWireMcpServers([ + { + type: "http", + name: "h", + url: "https://h.example.com", + headers: [{ name: "a", value: "b", _meta: { x: 1 } }], + _meta: { h: true }, + }, + ]), + ).toEqual([ + { + name: "h", + type: "http", + url: "https://h.example.com", + headers: [{ name: "a", value: "b" }], + }, + ]); + }); + + it("is idempotent on the wire shape", () => { + expect(toWireMcpServers([WIRE_STDIO, WIRE_HTTP])).toEqual([WIRE_STDIO, WIRE_HTTP]); + }); + + it("refuses a transport the backend has no field for, naming the index", () => { + expect(() => toWireMcpServers([WIRE_STDIO, { type: "_custom", name: "custom-mcp" }])).toThrow( + expect.objectContaining({ + code: -32602, + message: 'mcpServers.1: Unsupported MCP transport: "_custom"', + }), + ); + }); + + it("refuses a malformed entry in the backend's own wording", () => { + const cases: Array<[unknown, string]> = [ + ["x", "mcpServers: Invalid input"], + [[{ name: "s", command: "run", bogus: 1 }], 'mcpServers.0: Unrecognized key: "bogus"'], + [["run"], "mcpServers.0: Invalid input"], + [[{ name: "s" }], "mcpServers.0.command: Invalid input"], + [[{ name: "s", command: "run", args: ["ok", 5] }], "mcpServers.0.args: Invalid input"], + [[{ name: "s", command: "run", env: "PATH=/bin" }], "mcpServers.0.env: Invalid input"], + [ + [WIRE_HTTP, { name: "s", command: "run", env: [{ name: "A", value: 7 }] }], + "mcpServers.1.env.value: Invalid input", + ], + [[{ name: "h", type: "http", url: 1, headers: [] }], "mcpServers.0.url: Invalid input"], + [ + [{ name: "h", type: "http", url: "https://h", headers: { a: 1 } }], + "mcpServers.0.headers.a: Invalid input", + ], + ]; + for (const [entries, message] of cases) { + let caught: unknown; + try { + toWireMcpServers(entries); + } catch (error) { + caught = error; + } + expect(caught, JSON.stringify(entries)).toMatchObject({ code: -32602, message }); + } + }); +}); + +describe("V1 face", () => { + it("accepts the SDK 1.x spelling on session/new again and sends the backend the wire shape", async () => { + // 0.98.0 (SDK 2.12.0) answered this request with -32602 at the router. + const { server, calls } = makeServer(); + const client = await connectV1(server); + const created = await client.request("session/new", { + cwd: HOME, + mcpServers: [CLASSIC_STDIO, CLASSIC_HTTP], + }); + expect(errorText(created)).toBe("(no error)"); + const sid = (created.result as { sessionId: string }).sessionId; + expect(server.sessionMcpServers.get(sid)).toEqual([WIRE_STDIO, WIRE_HTTP]); + + await ensureRealSession(server, sid); + expect(creates(calls)).toHaveLength(1); + expect(creates(calls)[0]!.params.mcpServers).toEqual([WIRE_STDIO, WIRE_HTTP]); + }); + + it("takes the same spelling on session/resume", async () => { + const { server } = makeServer(); + server.registerSession(SESSION, ZSID); + const client = await connectV1(server); + const resumed = await client.request("session/resume", { + sessionId: SESSION, + cwd: HOME, + mcpServers: [CLASSIC_STDIO], + }); + expect(errorText(resumed)).toBe("(no error)"); + expect(server.sessionMcpServers.get(SESSION)).toEqual([WIRE_STDIO]); + }); + + it("keeps the SDK's required fields: session/new without cwd is still -32602", async () => { + const { server } = makeServer(); + const client = await connectV1(server); + const created = await client.request("session/new", { mcpServers: [] }); + expect(created.error).toMatchObject({ code: -32602 }); + }); + + it("rejects a malformed entry with its index and records no placeholder", async () => { + const { server } = makeServer(); + const client = await connectV1(server); + const created = await client.request("session/new", { + cwd: HOME, + mcpServers: [{ name: "s", command: "run", bogus: 1 }], + }); + expect(created.error).toMatchObject({ + code: -32602, + message: 'mcpServers.0: Unrecognized key: "bogus"', + }); + expect(server.pendingSessions.size).toBe(0); + }); +}); + +describe("V2 face", () => { + it("advertises both MCP transports the backend serves", async () => { + const { server } = makeServer(); + const client = await connectV2(server); + const initialized = client.received.find((m) => m.id === 1); + const capabilities = (initialized?.result as { capabilities?: { session?: { mcp?: unknown } } }) + .capabilities?.session?.mcp; + expect(capabilities).toEqual({ stdio: {}, http: {} }); + }); + + it("delivers T3 Code's typed stdio entry to the backend without its `type` (issue #457)", async () => { + const { server, calls } = makeServer(); + const client = await connectV2(server); + const created = await client.request("session/new", { cwd: HOME, mcpServers: [T3_STDIO] }); + expect(errorText(created)).toBe("(no error)"); + const sid = (created.result as { sessionId: string }).sessionId; + + await ensureRealSession(server, sid); + expect(creates(calls)).toHaveLength(1); + expect(creates(calls)[0]!.params.mcpServers).toEqual([ + { + name: "t3-code", + command: "node", + args: ["apps/server/dist/index.js"], + env: [{ name: "T3", value: "1" }], + }, + ]); + }); + + it("drops the `_meta` the V2 schema allows on an http entry", async () => { + const { server, calls } = makeServer(); + const client = await connectV2(server); + const created = await client.request("session/new", { + cwd: HOME, + mcpServers: [ + { type: "http", name: "h", url: "https://h.example.com", headers: [], _meta: { h: 1 } }, + ], + }); + expect(errorText(created)).toBe("(no error)"); + await ensureRealSession(server, (created.result as { sessionId: string }).sessionId); + expect(creates(calls)[0]!.params.mcpServers).toEqual([ + { name: "h", type: "http", url: "https://h.example.com", headers: [] }, + ]); + }); + + it("refuses a transport the backend has no field for before recording the session", async () => { + const { server } = makeServer(); + const client = await connectV2(server); + const created = await client.request("session/new", { + cwd: HOME, + mcpServers: [{ type: "_custom", name: "custom-mcp" }], + }); + expect(created.error).toMatchObject({ + code: -32602, + message: 'mcpServers.0: Unsupported MCP transport: "_custom"', + }); + expect(server.pendingSessions.size).toBe(0); + }); + + it("forwards the typed spelling on session/resume the same way", async () => { + const { server } = makeServer(); + server.registerSession(SESSION, ZSID); + const client = await connectV2(server); + const resumed = await client.request("session/resume", { + sessionId: SESSION, + cwd: HOME, + mcpServers: [T3_STDIO], + }); + expect(errorText(resumed)).toBe("(no error)"); + expect(server.sessionMcpServers.get(SESSION)).toEqual([ + { + name: "t3-code", + command: "node", + args: ["apps/server/dist/index.js"], + env: [{ name: "T3", value: "1" }], + }, + ]); + }); +}); From 9ec358f6564ab45e540d58e84fe5d9beac4f06d4 Mon Sep 17 00:00:00 2001 From: William Wang Date: Tue, 1 Dec 2026 10:29:46 +0800 Subject: [PATCH 6/9] fix: honor desktop 4.0's linked BigModel plan for a CN sign-in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - #456: a desktop 4.0 CN sign-in is the zai_cn provider and stores no oauth:bigmodel:access_token — the BigModel plan it is linked to rides oauth:linked_bigmodel ({userId, customerId, accessToken}), honored only while userId is the active profile's id and preferred over a direct sign-in's own token, as upstream's materialFromSnapshot does - project-token.ts: codingPlanLoginToken is the one reader of a family's plan login JWT; official-mcp-auth.ts and settings/coding-plan.ts read through it - tests: project-token.test.ts, account-provider.test.ts; AGENTS.md --- AGENTS.md | 12 +++- src/config/official-mcp-auth.ts | 23 +++--- src/config/project-token.ts | 68 +++++++++++++++++- src/settings/coding-plan.ts | 7 +- tests/account-provider.test.ts | 23 ++++++ tests/project-token.test.ts | 121 ++++++++++++++++++++++++++++++++ 6 files changed, 236 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 18e4279..dca4f88 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -434,7 +434,17 @@ headers}`, neither with `_meta` — and nothing else. Forwarded verbatim unions in UNCONDITIONALLY — both signals only exist on 3.15+ layouts, so nothing older can speak against it; `setting.json`'s `modelProviderFamilySelectedKeys` is a _selection_ record, not an - entitlement — only as a last resort when both are empty. + entitlement — only as a last resort when both are empty. Desktop 4.0's + regional login (#456): a CN sign-in is `zai_cn` and stores no + `oauth:bigmodel:access_token` — the BigModel plan it is linked to rides + `oauth:linked_bigmodel` (`{userId, customerId, accessToken}`), honored + only while `userId` is the active profile's ZCode user id and preferred + over a direct sign-in's own token, exactly as upstream's + `materialFromSnapshot`; `codingPlanLoginToken` (config/project-token.ts) + is the ONE reader of a family's plan login JWT (entitlement, the + project-token exchange, official MCP auth, the reset cards) — never read + `oauth::access_token` directly again. A `zai_cn` login alone + holds no plan (upstream derives no `zai` material from it either). `coding-plan-cache.json` (the 3.12–3.14 verdict) is deliberately NOT read — transitional releases, and a leftover cache surviving a 3.15+ upgrade would suppress the OAuth union (#359). A bridge account diff --git a/src/config/official-mcp-auth.ts b/src/config/official-mcp-auth.ts index 6cc5b34..83d9858 100644 --- a/src/config/official-mcp-auth.ts +++ b/src/config/official-mcp-auth.ts @@ -6,9 +6,8 @@ * - `targetOrigin` must match the authoritative ZCode API origin (credentials * must never leak to an untrusted domain); * - reads `zcodejwttoken` (-> `Authorization: Bearer ...`) and the active - * Coding Plan family's MaaS login JWT `oauth::access_token` - * (-> `X-Bigmodel-Authorization: Bearer ...` plus scope headers) from the - * local encrypted credential store; + * Coding Plan family's plan login JWT (-> `X-Bigmodel-Authorization: Bearer + * ...` plus scope headers) from the local encrypted credential store; * - team plans follow the upstream wire rules: a bigmodel team sends * `Bigmodel-Target-Type: TEAM` with organization/project as an atomic pair, * a zai team sends the plan token with NO scope headers; @@ -21,7 +20,11 @@ import process from "node:process"; import { readCredentialStoreSync } from "../backend/credential-store.js"; import { ZCODE_CREDS_PATH } from "../utils.js"; -import { isCodingPlanFamily, type CodingPlanFamily } from "./project-token.js"; +import { + codingPlanLoginToken, + isCodingPlanFamily, + type CodingPlanFamily, +} from "./project-token.js"; /** Default production ZCode service origin, used for plugin `${ZCODE_BASE_URL}` expansion and origin trust. */ export const DEFAULT_ZCODE_BASE_URL = "https://zcode.z.ai"; @@ -37,9 +40,7 @@ export const OFFICIAL_MCP_AUTH_HEADER_NAMES = { /** Official MCP auth failure reasons (aligned with the `interaction/requestOfficialMcpAuthHeaders` reply schema in `zcode.cjs`). */ export type OfficialMcpAuthFailureReason = - | "official_auth_unavailable" - | "official_auth_plan_required" - | "official_mcp_origin_untrusted"; + "official_auth_unavailable" | "official_auth_plan_required" | "official_mcp_origin_untrusted"; /** The reply shape for `interaction/requestOfficialMcpAuthHeaders`. */ export type OfficialMcpAuthHeadersOutcome = @@ -177,12 +178,16 @@ function readDesktopSetting(credsDir: string): DesktopSettingSnapshot | null { } } -/** Read a family's MaaS OAuth login token (bare value) from the credential store. */ +/** + * A family's plan login JWT (bare value) through the shared reader: the + * store's `oauth::access_token`, or desktop 4.0's linked + * `oauth:linked_bigmodel` for a CN sign-in bound to a BigModel account. + */ function readFamilyOAuthToken( store: Record, family: CodingPlanFamily, ): string | null { - return stripBearerPrefix(store[`oauth:${family}:access_token`]); + return codingPlanLoginToken(store, family); } /** diff --git a/src/config/project-token.ts b/src/config/project-token.ts index e7cb930..6e322a9 100644 --- a/src/config/project-token.ts +++ b/src/config/project-token.ts @@ -72,14 +72,76 @@ function oauthLoginCredentialKey(family: CodingPlanFamily): string { return `oauth:${family}:access_token`; } +/** + * Desktop 4.0's login is regional: a CN sign-in (`zai_cn`) stores no + * `oauth:bigmodel:access_token`. The BigModel plan of the account it is + * linked to rides `oauth:linked_bigmodel` instead — `{userId, customerId, + * accessToken}` as JSON — and the desktop honors it for the `bigmodel` + * family only while `userId` is the signed-in account's ZCode user id, which + * it reads from the active provider's `user_info` (a Z.ai provider persists + * the backend's raw profile, whose id is `user_id`; + * `oauthCredentialRepo.ts` `tokenSetFromSnapshot` / `materialFromSnapshot`, + * 4.0.0). It prefers that JWT over a direct `bigmodel` sign-in's own token. + * Nothing links a CN sign-in to the `zai` family: that login alone holds no + * plan (issue #456 — the ladder below found no key and every `account:*` + * model answered "Select a model before continuing"). + */ +const OAUTH_LINKED_BIGMODEL_KEY = "oauth:linked_bigmodel"; +const OAUTH_ACTIVE_PROVIDER_KEY = "oauth:active_provider"; + +function parseJsonObject(value: string | undefined): Record | null { + if (!value) return null; + try { + const parsed: unknown = JSON.parse(value); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) + ? (parsed as Record) + : null; + } catch { + return null; + } +} + +/** The signed-in account's ZCode user id, as the desktop binds a link to it. */ +function activeAccountId(store: Record): string | null { + const provider = store[OAUTH_ACTIVE_PROVIDER_KEY]?.trim(); + if (!provider) return null; + const profile = parseJsonObject(store[`oauth:${provider}:user_info`]); + if (!profile) return null; + if (typeof profile.id === "string") return profile.id; + const zai = provider === "zai" || provider === "zai_cn"; + return zai && typeof profile.user_id === "string" ? profile.user_id : null; +} + +/** The linked BigModel plan's JWT, only while it is bound to the signed-in account. */ +function linkedBigModelToken(store: Record): string | null { + const linked = parseJsonObject(store[OAUTH_LINKED_BIGMODEL_KEY]); + if (!linked || typeof linked.accessToken !== "string") return null; + const accountId = activeAccountId(store); + if (!accountId || linked.userId !== accountId) return null; + return linked.accessToken.trim() || null; +} + +/** + * The desktop's Coding Plan login token for `family` (a business JWT, bare), + * or null when the user holds no plan sign-in there. The one reader every + * consumer goes through: entitlement, the project-token exchange, official + * MCP auth and the reset cards. + */ +export function codingPlanLoginToken( + store: Record, + family: CodingPlanFamily, +): string | null { + const direct = store[oauthLoginCredentialKey(family)]?.trim() || null; + const linked = family === "bigmodel" ? linkedBigModelToken(store) : null; + return linked ?? (direct?.replace(/^Bearer\s+/iu, "") || null); +} + /** Credential store key of the ZCode JWT the host folds into the account scope. */ const ZCODE_JWT_CREDENTIAL_KEY = "zcodejwttoken"; /** The desktop's login token for `family`, or null when the user never signed in there. */ function readLoginToken(family: CodingPlanFamily): string | null { - const raw = readCredentialStoreSync()[oauthLoginCredentialKey(family)]?.trim(); - if (!raw) return null; - return raw.replace(/^Bearer\s+/iu, "") || null; + return codingPlanLoginToken(readCredentialStoreSync(), family); } /** Whether the desktop holds an OAuth sign-in for `family` (no network, no decryption beyond the store read). */ diff --git a/src/settings/coding-plan.ts b/src/settings/coding-plan.ts index e67e04e..c01a3aa 100644 --- a/src/settings/coding-plan.ts +++ b/src/settings/coding-plan.ts @@ -36,6 +36,7 @@ import { randomUUID } from "node:crypto"; import { readFile } from "node:fs/promises"; import { readCredentialStoreSync } from "../backend/credential-store.js"; +import { codingPlanLoginToken } from "../config/project-token.js"; import { zcodeCredentialsPath } from "../utils.js"; import { UpstreamError } from "./errors.js"; @@ -43,10 +44,6 @@ import { UpstreamError } from "./errors.js"; const CODING_PLAN_PROVIDER_PREFIX = "account:"; const ZCODE_JWT_KEY = "zcodejwttoken"; -const OAUTH_TOKEN_KEYS = { - bigmodel: "oauth:bigmodel:access_token", - zai: "oauth:zai:access_token", -} as const; /** The API origin; overridable for testing and for a self-hosted gateway. */ function apiOrigin(env: NodeJS.ProcessEnv = process.env): string { @@ -133,7 +130,7 @@ export async function resolveResetAuthorization( const zcodeJwt = credentials[ZCODE_JWT_KEY]?.trim(); if (!zcodeJwt) throw new Error("coding_plan_zcode_jwt_required"); const family = resetFamilyFor(providerId); - const codingPlanJwt = credentials[OAUTH_TOKEN_KEYS[family]]?.trim(); + const codingPlanJwt = codingPlanLoginToken(credentials, family); if (!codingPlanJwt) throw new Error("coding_plan_maas_jwt_required"); return { zcodeAuthorization: /^Bearer\s/iu.test(zcodeJwt) ? zcodeJwt : `Bearer ${zcodeJwt}`, diff --git a/tests/account-provider.test.ts b/tests/account-provider.test.ts index 51164f8..5a39f8a 100644 --- a/tests/account-provider.test.ts +++ b/tests/account-provider.test.ts @@ -634,6 +634,29 @@ describe("3.15+ desktop layout — OAuth sign-in + providerFamilyConnectionSelec ]); }); + it("entitles the BigModel plan of a desktop 4.0 CN sign-in from its linked record (#456)", () => { + // No config.json and no `oauth:bigmodel:access_token`: the login is `zai_cn` + // and the BigModel plan it is linked to rides `oauth:linked_bigmodel`. + writeCredentialStore({ + "oauth:active_provider": "zai_cn", + zcodejwttoken: "zcode-jwt", + "oauth:zai_cn:access_token": "cn-oauth-token", + "oauth:zai_cn:user_info": JSON.stringify({ user_id: "user-1", name: "Ada" }), + "oauth:linked_bigmodel": JSON.stringify({ + userId: "user-1", + customerId: "cust-1", + accessToken: "linked-bigmodel-jwt", + }), + }); + writeSetting({ bigmodel: { kind: "individual-coding-plan" } }); + const payload = buildAccountProviderConfig(); + const bigmodel = payload!.providers["account:bigmodel-individual-coding-plan"]!; + expect(bigmodel.access.entitled).toBe(true); + // A CN sign-in alone holds no Z.ai plan. + expect(payload!.providers["account:zai-individual-coding-plan"]!.access.entitled).toBe(false); + expect(oauthProjectTokenFamilyFor("account:bigmodel-individual-coding-plan")).toBe("bigmodel"); + }); + it("unions the OAuth selection even under a stale 3.12–3.14 coding-plan-cache (#359)", () => { writeCredentialStore({ "oauth:zai:access_token": "login-jwt" }); writeSetting({ zai: { kind: "individual-coding-plan" } }); diff --git a/tests/project-token.test.ts b/tests/project-token.test.ts index 8d1a6c6..506918a 100644 --- a/tests/project-token.test.ts +++ b/tests/project-token.test.ts @@ -218,3 +218,124 @@ describe("resolveOAuthProjectToken", () => { expect(calls).toHaveLength(0); }); }); + +/** + * Desktop 4.0's regional login (issue #456): a CN sign-in is `zai_cn`, stores + * no `oauth:bigmodel:access_token`, and carries the BigModel plan it is + * linked to under `oauth:linked_bigmodel`. + */ +const BIGMODEL = "https://bigmodel.cn"; +const BIGMODEL_KEYS_URL = `${BIGMODEL}/api/biz/v1/organization/org-personal/projects/proj-default/api_keys`; + +/** A `zai_cn` sign-in linked to a BigModel account, as desktop 4.0 stores it. */ +const CN_LINKED_STORE = { + "oauth:active_provider": "zai_cn", + zcodejwttoken: "zcode-jwt", + "oauth:zai_cn:access_token": "cn-oauth-token", + "oauth:zai_cn:user_info": JSON.stringify({ + user_id: "user-1", + name: "Ada", + email: "ada@example.com", + }), + "oauth:linked_bigmodel": JSON.stringify({ + userId: "user-1", + customerId: "cust-1", + accessToken: "linked-bigmodel-jwt", + }), +}; + +describe("a desktop 4.0 CN sign-in's linked BigModel plan", () => { + beforeEach(() => { + writeStore(CN_LINKED_STORE); + setProjectTokenNetworkForTest(async (input, init) => { + const url = String(input); + calls.push({ + url, + method: init?.method ?? "GET", + authorization: new Headers(init?.headers).get("Authorization"), + body: undefined, + }); + if (url === `${BIGMODEL}/api/biz/customer/getCustomerInfo`) return json(200, CUSTOMER); + if (url === BIGMODEL_KEYS_URL && (init?.method ?? "GET") === "GET") { + return json(200, { code: 200, data: keyList }); + } + if (url === `${BIGMODEL_KEYS_URL}/key-id-1/access_tokens`) return tokenOk("pat-linked")(); + throw new Error(`unexpected request ${init?.method ?? "GET"} ${url}`); + }); + }); + + it("counts as a BigModel plan sign-in, and never as a Z.ai one", () => { + expect(hasOAuthLogin("bigmodel")).toBe(true); + expect(hasOAuthLogin("zai")).toBe(false); + }); + + it("trades the LINKED JWT for the project token on bigmodel's origin", async () => { + const material = await resolveOAuthProjectToken("bigmodel"); + expect(material.token).toBe("pat-linked"); + expect(material.apiKeyId).toBe("key-id-1"); + // bigmodel's wire takes the customer and key-list calls bare, the exchange as Bearer. + expect(calls.map((c) => [c.method, c.authorization])).toEqual([ + ["GET", "linked-bigmodel-jwt"], + ["GET", "linked-bigmodel-jwt"], + ["POST", "Bearer linked-bigmodel-jwt"], + ]); + }); + + it("is honored only while it is bound to the signed-in account", () => { + const cases: Array<[string, Record]> = [ + [ + "a link to another account", + { + "oauth:linked_bigmodel": JSON.stringify({ + userId: "user-2", + customerId: "cust-1", + accessToken: "jwt", + }), + }, + ], + ["no active provider", { "oauth:active_provider": "" }], + ["no profile", { "oauth:zai_cn:user_info": "" }], + ["a malformed link", { "oauth:linked_bigmodel": "{nope" }], + [ + "a link without a token", + { "oauth:linked_bigmodel": JSON.stringify({ userId: "user-1", customerId: "cust-1" }) }, + ], + ]; + for (const [label, patch] of cases) { + writeStore({ ...CN_LINKED_STORE, ...patch }); + expect(hasOAuthLogin("bigmodel"), label).toBe(false); + } + expect(calls).toHaveLength(0); + }); + + it("reads a `bigmodel` sign-in's normalized profile too, and prefers the linked JWT", async () => { + writeStore({ + ...CN_LINKED_STORE, + "oauth:active_provider": "bigmodel", + "oauth:bigmodel:access_token": "direct-bigmodel-jwt", + "oauth:bigmodel:user_info": JSON.stringify({ + id: "user-1", + username: "ada", + displayName: "Ada", + }), + }); + expect(hasOAuthLogin("bigmodel")).toBe(true); + await resolveOAuthProjectToken("bigmodel"); + expect(calls[0]!.authorization).toBe("linked-bigmodel-jwt"); + }); + + it("leaves a direct bigmodel sign-in on its own token when nothing is linked", async () => { + writeStore({ + "oauth:active_provider": "bigmodel", + "oauth:bigmodel:access_token": "Bearer direct-bigmodel-jwt", + "oauth:bigmodel:user_info": JSON.stringify({ + id: "user-1", + username: "ada", + displayName: "Ada", + }), + }); + expect(hasOAuthLogin("bigmodel")).toBe(true); + await resolveOAuthProjectToken("bigmodel"); + expect(calls[0]!.authorization).toBe("direct-bigmodel-jwt"); + }); +}); From 3da8a64f80a92f5d035f6bed442d5118a96701e1 Mon Sep 17 00:00:00 2001 From: William Wang Date: Tue, 1 Dec 2026 10:38:17 +0800 Subject: [PATCH 7/9] fix: convert a fork's mcpServers to the backend's wire shape before forking MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - #455 follow-up: the shared fork() remembered a client's mcpServers verbatim, so a fork's next reload sent entries the backend's strict zcodeProtocolMcpServerSchema rejects — the #457 failure mode on the fork path; the V1 route's own copy of the SDK schema is gone with it - extensions.ts: fork() converts first (toWireMcpServers), so a malformed entry neither forks in the backend nor leaves anything recorded - index.ts: the V1 session/fork route parses mcpServers exactly as session/new does (v1SessionParams) - session.ts: adoptForkedSessionScope takes the converted list - tests: fork-response.test.ts, v2-ops.test.ts; AGENTS.md, docs/PROTOCOL.md --- AGENTS.md | 10 +++++---- docs/PROTOCOL.md | 5 ++++- src/handlers/extensions.ts | 7 +++++- src/handlers/session.ts | 17 +++++--------- tests/fork-response.test.ts | 28 +++++++++++++++++++---- tests/v2-ops.test.ts | 45 +++++++++++++++++++++++++++++++------ 6 files changed, 84 insertions(+), 28 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index dca4f88..392dae3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -336,15 +336,17 @@ headers}`, neither with `_meta` — and nothing else. Forwarded verbatim from its V1 schema — the shape every V1 client written against SDK 1.x sends — so 0.98.0's V1 `session/new` answered -32602 where 0.97.0's took it. Two pieces (`src/config/client-mcp-servers.ts`): the V1 - routes `session/new|resume|load` parse `mcpServers` themselves + routes `session/new|resume|load|fork` parse `mcpServers` themselves (`v1SessionParams`, index.ts — the rest of each request keeps the SDK's required fields), and every face converts where it remembers the list (`toWireMcpServers` at the top of `newSession` / `resumeSession` / - `loadSession`, before any state is recorded, so a malformed entry - leaves no placeholder). The stored list is wire-valid by construction + `loadSession` and of the shared `fork()`, before any state is recorded + and before the backend forks, so a malformed entry leaves no + placeholder behind). The stored list is wire-valid by construction and every later create / resume / reload sends it as is. A `type` the backend has no field for (V2's schema passes unknown transports - through) is a -32602 at `session/new`, never a create failure later; + through) is a -32602 at `session/new` / `session/fork`, never a create + failure later; the V2 face advertises `session.mcp.stdio` and `session.mcp.http`. Do not forward a client entry again — the shape matrix was measured live against 4.0.0 (`.zcode/scratch/v2-probes/live/mcp-shapes.live.ts`, no diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 3e4fbf6..b4fbd8b 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -759,7 +759,10 @@ A fork continues the source conversation, so it keeps the source session's working directory and MCP servers. This is the rule `session/resume` already applies: the session root never comes from the client. `cwd` is accepted but not applied. A non-empty `mcpServers` is remembered for the fork and re-sent -on its next load; an empty one keeps the source's servers. On V1, `cursorId`, +on its next load; an empty one keeps the source's servers. Both of its +spellings are taken and the list is kept in the backend's wire shape, as on +`session/new`; an entry the backend has no field for (an unknown `type`) is a +`-32602` before anything is forked. On V1, `cursorId`, `systemPrompt` and `configOptions` ride on capabilities the V1 face does not advertise and are ignored (the ACP V2 face handles `cursorId` separately). diff --git a/src/handlers/extensions.ts b/src/handlers/extensions.ts index 314163b..147f0f7 100644 --- a/src/handlers/extensions.ts +++ b/src/handlers/extensions.ts @@ -24,6 +24,7 @@ import * as acp from "@agentclientprotocol/sdk/unstable"; +import { toWireMcpServers } from "../config/client-mcp-servers.js"; import { emitInitialUsage, readContextUsed } from "../config/model-cache.js"; import { applyModelSwitch, lastSwitchedModelValue } from "../config/runtime-model.js"; import { @@ -79,6 +80,10 @@ type Result = Record; * (`forkedSessionId`, `snapshot`, etc.) without building ACP response options. */ export async function fork(server: ZcodeAcpServer, params: ExtensionParams): Promise { + // Converted first: a malformed entry must neither fork in the backend nor + // leave anything recorded, and every later reload of the fork sends what is + // remembered as is (#457 — the same rule as session/new). + const mcpServers = toWireMcpServers(params.mcpServers); const zcodeSid = await resolveSidOrThrow(server, params); const backend = await server.ensureBackend(); const resp = await backend.request( @@ -109,7 +114,7 @@ export async function fork(server: ZcodeAcpServer, params: ExtensionParams): Pro server, params.sessionId, result.forkedSessionId, - params.mcpServers, + mcpServers, result.snapshot, ); await server.ensureBackgroundListener(result.forkedSessionId); diff --git a/src/handlers/session.ts b/src/handlers/session.ts index a5b5b5f..3643dbe 100644 --- a/src/handlers/session.ts +++ b/src/handlers/session.ts @@ -587,28 +587,23 @@ function workspaceFromResumeResult(result: unknown): string | null { * therefore accepted but not applied. The root is the source session's * recorded one, or the fork's own snapshot when the source has none. * - * The draft's `mcpServers`, when non-empty, are remembered for the fork the - * way `session/new` remembers them, so a later reload re-sends them (#193). - * An empty or absent list keeps the source's set. Entry validation happens at - * each protocol face's trust boundary (the V1 route parser in `src/index.ts` - * and the V2 SDK schema). + * The draft's `mcpServers` — already in the backend's wire shape, converted + * by `fork()` before the backend forked — are remembered for the fork the way + * `session/new` remembers them, so a later reload re-sends them (#193). An + * empty or absent list keeps the source's set. */ export function adoptForkedSessionScope( server: ZcodeAcpServer, sourceSid: string, forkedSid: string, - mcpServers: unknown, + mcpServers: ZcodeMcpServer[] | undefined, snapshot: unknown, ): void { if (!server.sessionCwds.has(forkedSid)) { const root = server.sessionCwds.get(sourceSid) ?? workspaceFromResumeResult(snapshot); if (root) server.sessionCwds.set(forkedSid, root); } - rememberSessionMcpServers( - server, - forkedSid, - Array.isArray(mcpServers) ? (mcpServers as acp.McpServer[]) : undefined, - ); + rememberSessionMcpServers(server, forkedSid, mcpServers); if (!server.sessionMcpServers.has(forkedSid)) { const srcMcp = server.sessionMcpServers.get(sourceSid); if (srcMcp) server.sessionMcpServers.set(forkedSid, srcMcp); diff --git a/tests/fork-response.test.ts b/tests/fork-response.test.ts index b7daf7c..4e75fd5 100644 --- a/tests/fork-response.test.ts +++ b/tests/fork-response.test.ts @@ -218,12 +218,31 @@ describe("session/fork scope", () => { expect(server.sessionCwds.get(FORK)).toBe("/tmp/fork-ws"); }); - it("remembers the draft's mcpServers for the fork", async () => { + it("remembers the draft's mcpServers for the fork, in the backend's wire shape", async () => { const { server } = makeServer(); server.sessionMcpServers.set(SOURCE_ACP, SOURCE_MCP); - const forkMcp: acp.McpServer[] = [{ name: "fork-mcp", command: "fork-cmd" }]; - await forkV1(server, { sessionId: SOURCE_ACP, mcpServers: forkMcp }); - expect(server.sessionMcpServers.get(FORK)).toEqual(forkMcp); + // The SDK 1.x spelling (env as a string map, args absent) and the typed + // V2 one both land as what session/create would take. + await forkV1(server, { + sessionId: SOURCE_ACP, + mcpServers: [ + { name: "fork-mcp", command: "fork-cmd", env: { FORK: "1" } }, + { type: "stdio", name: "typed-mcp", command: "typed-cmd" }, + ], + }); + expect(server.sessionMcpServers.get(FORK)).toEqual([ + { name: "fork-mcp", command: "fork-cmd", args: [], env: [{ name: "FORK", value: "1" }] }, + { name: "typed-mcp", command: "typed-cmd", args: [], env: [] }, + ]); + }); + + it("rejects an entry the backend has no field for, before forking", async () => { + const { server, backend } = makeServer(); + await expect( + forkV1(server, { sessionId: SOURCE_ACP, mcpServers: [{ bogus: true }] }), + ).rejects.toMatchObject({ code: -32602 }); + expect(backend.calls).toEqual([]); + expect(server.sessionMcpServers.has(FORK)).toBe(false); }); it("keeps the source's MCP servers when the draft's list is empty or absent", async () => { @@ -281,6 +300,7 @@ describe("session/fork V1 router", () => { mcpServers: [{ bogus: true }], }); expect(resp.error).toMatchObject({ code: -32602 }); + expect(resp.error?.message).toContain("mcpServers.0"); expect(backend.calls).toEqual([]); } finally { c.close(); diff --git a/tests/v2-ops.test.ts b/tests/v2-ops.test.ts index aef9d59..0130fc6 100644 --- a/tests/v2-ops.test.ts +++ b/tests/v2-ops.test.ts @@ -176,23 +176,54 @@ describe("v2 session/fork", () => { } }); - it("remembers mcpServers including custom transport entries", async () => { + it("remembers mcpServers in the backend's wire shape", async () => { const { backend } = fakeBackend(); const server = setup(backend); server.sessionMcpServers.set(SESSION, [{ name: "source-mcp", command: "source-cmd" }]); - const forkMcp = [ - { type: "_custom", name: "custom-mcp", endpoint: "custom://local" }, - { type: "stdio", name: "v2-fork-mcp", command: "/usr/bin/fork-cmd" }, - ]; const c = await client(server); try { const response = await c.request("session/fork", { sessionId: SESSION, cwd: "/tmp/elsewhere", - mcpServers: forkMcp, + mcpServers: [ + { + type: "stdio", + name: "v2-fork-mcp", + command: "/usr/bin/fork-cmd", + env: [{ name: "K", value: "1" }], + }, + ], }); expect(response.result).toMatchObject({ sessionId: "sess_fork" }); - expect(server.sessionMcpServers.get("sess_fork")).toEqual(forkMcp); + expect(server.sessionMcpServers.get("sess_fork")).toEqual([ + { + name: "v2-fork-mcp", + command: "/usr/bin/fork-cmd", + args: [], + env: [{ name: "K", value: "1" }], + }, + ]); + } finally { + c.close(); + } + }); + + it("rejects a transport the backend has no field for, before forking", async () => { + const { backend, calls } = fakeBackend(); + const server = setup(backend); + const c = await client(server); + try { + const response = await c.request("session/fork", { + sessionId: SESSION, + cwd: "/tmp/elsewhere", + // The V2 schema passes an unknown transport through; the backend's + // strict one has no field for it (#457). + mcpServers: [{ type: "_custom", name: "custom-mcp", endpoint: "custom://local" }], + }); + expect(response.error).toMatchObject({ code: -32602 }); + expect(response.error?.message).toContain("mcpServers.0"); + expect(calls.filter((x) => x.method === "session/fork")).toEqual([]); + expect(server.sessionMcpServers.has("sess_fork")).toBe(false); } finally { c.close(); } From 7f58ca164db09e5b9f3032f6b5b78b4478871d23 Mon Sep 17 00:00:00 2001 From: William Wang Date: Tue, 1 Dec 2026 10:40:14 +0800 Subject: [PATCH 8/9] fix: cache a fork's model list from its snapshot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - fork() passed the whole fork result to cacheModelAvailability, but a fork result carries no top-level settings — they sit under `snapshot` (zcodeSessionForkResultSchema) — so the fork's model availability was never cached at fork time and an object-form session/setModel on a fresh fork resolved its level from the personal rule alone until the next resume flight - tests: fork-response.test.ts --- src/handlers/extensions.ts | 4 +++- tests/fork-response.test.ts | 25 ++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/handlers/extensions.ts b/src/handlers/extensions.ts index 147f0f7..3370b21 100644 --- a/src/handlers/extensions.ts +++ b/src/handlers/extensions.ts @@ -100,7 +100,9 @@ export async function fork(server: ZcodeAcpServer, params: ExtensionParams): Pro // The fork response carries a full session snapshot (the backend's fork // handler builds one without options) — mine it for the model-availability // list so switches on the fork resolve reasoning levels like create does. - cacheModelAvailability(server, result.forkedSessionId, result); + // The settings sit under `snapshot`, never at the top level + // (`zcodeSessionForkResultSchema`). + cacheModelAvailability(server, result.forkedSessionId, result.snapshot ?? {}); server.registerSession(result.forkedSessionId, result.forkedSessionId); // The fork is live in THIS backend already (session/fork created it) — // mark it loaded or a first-use ensureRealSession treats it as evicted diff --git a/tests/fork-response.test.ts b/tests/fork-response.test.ts index 4e75fd5..863039e 100644 --- a/tests/fork-response.test.ts +++ b/tests/fork-response.test.ts @@ -70,6 +70,7 @@ const SNAPSHOT = { class FakeBackend { isDead = false; calls: Array<{ method: string; params?: Record }> = []; + snapshot: unknown = SNAPSHOT; async request( id: number, @@ -84,7 +85,7 @@ class FakeBackend { forkedSessionId: FORK, parentSessionId: SOURCE_ZCODE, response: "", - snapshot: SNAPSHOT, + snapshot: this.snapshot, }, }; } @@ -171,6 +172,28 @@ describe("shared fork() core", () => { expect(result).not.toHaveProperty("sessionId"); expect(backend.calls.map((c) => c.method)).toEqual(["session/fork"]); }); + + it("caches the fork snapshot's model list for the fork", async () => { + const { server, backend } = makeServer(); + // The fork result carries no top-level settings: they live in its snapshot. + backend.snapshot = { + ...SNAPSHOT, + settings: { + model: { + available: [ + { + ref: { providerId: "builtin:bigmodel-coding-plan", modelId: "GLM-5.3" }, + reasoning: { defaultLevel: "high", levels: [{ value: "low" }, { value: "high" }] }, + }, + ], + }, + }, + }; + await fork(server, { sessionId: SOURCE_ACP }); + expect(server.modelAvailability.get(FORK)).toMatchObject([ + { providerId: "builtin:bigmodel-coding-plan", modelId: "GLM-5.3", defaultLevel: "high" }, + ]); + }); }); describe("session/fork request", () => { From 5a2f8d41c3a728104b289b6fd506c4e11f5f0532 Mon Sep 17 00:00:00 2001 From: William Wang Date: Tue, 1 Dec 2026 10:58:00 +0800 Subject: [PATCH 9/9] fix: address an edit or retry target by its row kind, not the first id match MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - a message's id is shared by the other rows of its turn: 4.0 opens a turn with a turnHeader row under the user message's id, and a reply's reasoning row carries the reply's id, so resolveEditRow and resolveRetryRow took the header (or the reasoning row) and every session/edit_user_message on 4.0 answered "only the latest user message can be edited" — the same for retry_turn by message id - rewind.ts: rowsOfMessage narrows a handle to its message's rows and the target is the userInput / assistantText row among them; an unknown id still answers not found, a wrong-kind or non-editable one the guard message - tests: a 4.0-shaped row window in tests/rewind.test.ts (read live from a one-turn session) --- src/handlers/rewind.ts | 28 +++++++++++++++++++------ tests/rewind.test.ts | 47 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 6 deletions(-) diff --git a/src/handlers/rewind.ts b/src/handlers/rewind.ts index a27946b..05aaf4d 100644 --- a/src/handlers/rewind.ts +++ b/src/handlers/rewind.ts @@ -19,6 +19,11 @@ * (product-projection.ts `entityId = messageId ?? pendingInputId`; * transcript-hydration.ts `entityId: String(message.info.id)`), i.e. the * same id the bridge replays as `_meta.zcode.mid` / top-level `messageId`. + * A message's id is also carried by the turn's OTHER rows (4.0 opens a turn + * with a `turnHeader` under the user message's id; a reply's `reasoning` + * row carries the reply's id) — a handle is resolved by kind too + * (`rowsOfMessage`), never by the first id match (which made every edit on + * 4.0 answer "only the latest user message can be edited"). * - `editUserQuery` is latest-real-user-query only, `retryTurn` latest * assistant row only (upstream guards `latestQueryEditOnly` / * `latestAssistantRetryOnly`); the rows' `actions.canEdit` / `canRetry` @@ -138,12 +143,22 @@ function rowNotFound(messageId: string): RequestError { ); } +/** Every row of the message a client handle names. A turn's rows share the + * entityId of the message they belong to — 4.0 leads a turn with a + * `turnHeader` row under the user message's id, and a reply's reasoning row + * carries the reply's id — so a handle is addressed by kind too, never by + * the first id match. */ +function rowsOfMessage(snapshot: RowsRangeSnapshot, messageId: string): RewindRow[] { + return snapshot.rows.filter((r) => r.entityId === messageId); +} + /** The edit target: the userInput row whose entityId is the client-supplied * message handle, and which the projection still marks editable. */ function resolveEditRow(snapshot: RowsRangeSnapshot, messageId: string): RewindRow { - const row = snapshot.rows.find((r) => r.entityId === messageId); - if (!row) throw rowNotFound(messageId); - if (row.kind !== "userInput" || !row.canEdit) { + const own = rowsOfMessage(snapshot, messageId); + if (own.length === 0) throw rowNotFound(messageId); + const row = own.find((r) => r.kind === "userInput"); + if (!row || !row.canEdit) { throw new RequestError( -32602, "only the latest user message can be edited (backend guard: guard.actionUnavailable)", @@ -156,9 +171,10 @@ function resolveEditRow(snapshot: RowsRangeSnapshot, messageId: string): RewindR * newest retryable assistant row = the latest turn. */ function resolveRetryRow(snapshot: RowsRangeSnapshot, messageId?: string): RewindRow { if (messageId) { - const row = snapshot.rows.find((r) => r.entityId === messageId); - if (!row) throw rowNotFound(messageId); - if (row.kind !== "assistantText" || !row.canRetry) { + const own = rowsOfMessage(snapshot, messageId); + if (own.length === 0) throw rowNotFound(messageId); + const row = own.find((r) => r.kind === "assistantText"); + if (!row || !row.canRetry) { throw new RequestError( -32602, "only the latest assistant reply can be regenerated (backend guard: guard.actionUnavailable)", diff --git a/tests/rewind.test.ts b/tests/rewind.test.ts index 35fd1bc..47fb4cf 100644 --- a/tests/rewind.test.ts +++ b/tests/rewind.test.ts @@ -47,6 +47,33 @@ const DEFAULT_SNAPSHOT: Record = { atSeq: 4, }; +/** A 4.0 row window, read live (rowsRange of a one-turn session): the turn + * opens with a `turnHeader` row carrying the USER message's id, and the + * reply's `reasoning` row carries the ASSISTANT message's id — the first id + * match is never the row an edit or a retry targets. */ +const ROWS_40: Record = { + rows: [ + { rowId: 1, kind: "turnHeader", entityId: "msg_u1" }, + { + rowId: 2, + kind: "userInput", + entityId: "msg_u1", + actions: { canEdit: true, editDisposition: "rewind" }, + }, + { rowId: 3, kind: "reasoning", entityId: "msg_a1" }, + { + rowId: 4, + kind: "assistantText", + entityId: "msg_a1", + actions: { canFork: true, canRetry: true }, + }, + ], + atRevision: 9, + atLogEpoch: "epoch-1", + hasMore: false, + atSeq: 4, +}; + function fakeBackend(): ZcodeBackend { return { isDead: false, @@ -148,6 +175,18 @@ describe("session/edit_user_message", () => { }); }); + it("addresses the user's own row in a 4.0 window, where a turn's rows share its id", async () => { + const server = setup(); + rowsResults = [ROWS_40, ROWS_40, ROWS_40]; + const result = await editUserMessage(server, { + sessionId: "sess_rw", + messageId: "msg_u1", + newText: "edited question", + }); + expect(result).toEqual({ ok: true, rewoundMessageId: "msg_u1" }); + expect(commands[0]!.payload).toMatchObject({ target: { rowId: 2, entityId: "msg_u1" } }); + }); + it("rejects a non-editable / unknown mid before any command", async () => { const server = setup(); await expect( @@ -191,6 +230,14 @@ describe("session/retry_turn", () => { expect(commands[0]!.payload).toEqual({ target: { rowId: 2, entityId: "msg_a1" } }); }); + it("addresses the reply's own row in a 4.0 window, where its reasoning row shares its id", async () => { + const server = setup(); + rowsResults = [ROWS_40, ROWS_40, ROWS_40]; + const result = await retryTurn(server, { sessionId: "sess_rw", messageId: "msg_a1" }); + expect(result).toEqual({ ok: true, rewoundMessageId: "msg_a1" }); + expect(commands[0]!.payload).toEqual({ target: { rowId: 4, entityId: "msg_a1" } }); + }); + it("rejects a non-retryable mid", async () => { const server = setup(); await expect(retryTurn(server, { sessionId: "sess_rw", messageId: "msg_a2" })).rejects.toThrow(