Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 213 additions & 2 deletions AGENTS.md

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion docs/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
6 changes: 4 additions & 2 deletions docs/REMOTE-CLIENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,8 +402,10 @@ ws(s)://<hub-host>/acp?instance=<id>&token=<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`
Expand Down
141 changes: 141 additions & 0 deletions src/config/client-mcp-servers.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;
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<string, unknown>;
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<string, z.ZodTypeAny>) {
return z
.object({
...required,
mcpServers: z.unknown().optional(),
_meta: z.record(z.unknown()).optional(),
})
.passthrough();
}
23 changes: 14 additions & 9 deletions src/config/official-mcp-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:<family>: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;
Expand All @@ -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";
Expand All @@ -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 =
Expand Down Expand Up @@ -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:<family>: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<string, string>,
family: CodingPlanFamily,
): string | null {
return stripBearerPrefix(store[`oauth:${family}:access_token`]);
return codingPlanLoginToken(store, family);
}

/**
Expand Down
68 changes: 65 additions & 3 deletions src/config/project-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> | null {
if (!value) return null;
try {
const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: 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, string>): 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, string>): 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<string, string>,
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). */
Expand Down
61 changes: 49 additions & 12 deletions src/handlers/background-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,13 @@ 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";

/** Shape of a `session.updated` payload that reports a background task state. */
Expand Down Expand Up @@ -630,19 +634,54 @@ 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<void> = 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<void> {
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 (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)}`),
if (!task) return;
await noteV2TaskRegistered(this.server, this.zcodeSid, p, task.acpCallId);
// 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,
this.zcodeSid,
p.taskId,
outcome,
outcome === "completed" ? 0 : 1,
);
}
}
Expand Down Expand Up @@ -850,8 +889,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)
Expand Down
Loading
Loading