UNPKG

@bitkyc08/opencodex

Version:

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code

845 lines (816 loc) • 37.7 kB
import { spawn as nodeSpawn, type ChildProcess, type SpawnOptions } from "node:child_process"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, win32 } from "node:path"; import type { AdapterEvent, OcxParsedRequest, OcxProviderConfig } from "../../types"; import { isTranslatorBudgetExceededError } from "../../lib/translator-budget"; import { SendBudgetExhaustedError } from "../../lib/upstream-retry"; import type { SingleUseDispatchPermit } from "../../lib/request-execution-budget"; import { commandInvocation } from "../../lib/win-exec"; import { isStandaloneBinary } from "../../lib/standalone"; import { modelRecordValue } from "../../reasoning-effort"; import type { IncomingMeta } from "../base"; import { buildConversationInput, CodingAgentProtocolError, MAX_TOOL_BLOCK_STARTS, mapStreamMessageToEvents, projectedHistoryCharLimit, readJsonLines, releaseOpenToolBlocks, toolBridgeInitError, type StreamParseState, } from "./protocol"; import { isBatchDispatcher, resolveCodingAgentBinary, resolveProfileByBaseUrl, type CodingAgentProviderProfile, type WhichFn } from "./profile"; import { inspectBatchDispatcher, type ReadDispatcherFn } from "./batch-dispatcher"; import { killWindowsProcessTree } from "./process-tree"; /** Injectable spawn for tests; production uses node:child_process. */ export type SpawnFn = (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess; /** Injectable Windows process-tree terminator; production uses taskkill /T /F. */ export type KillWindowsProcessTreeFn = (pid: number) => void; /** Per-turn injectables: spawn/which seams for tests plus wall-clock ceilings for timeout, kill grace, and bounded reap. */ export interface CodingAgentDeps { spawn?: SpawnFn; which?: WhichFn; /** Overall wall-clock ceiling for one turn (ms). */ timeoutMs?: number; /** Grace period between SIGTERM and SIGKILL (ms). */ killGraceMs?: number; /** Maximum time to wait for a child that never reports close after termination (ms). */ reapTimeoutMs?: number; /** Test seam for Windows command-shim invocation. */ platform?: NodeJS.Platform; /** Test seam for reading a Windows batch dispatcher before it is trusted with empty arguments. */ readDispatcher?: ReadDispatcherFn; /** Test seam for terminating a Windows CLI and all descendants. */ killWindowsProcessTree?: KillWindowsProcessTreeFn; /** Test seam for a catalog/config write failure after private bridge-directory creation. */ writeToolBridgeFile?: typeof writeFile; /** Injectable timer primitives for deterministic tests without sleeping. */ setTimeout?: typeof setTimeout; clearTimeout?: typeof clearTimeout; } const DEFAULT_TIMEOUT_MS = 300_000; const DEFAULT_KILL_GRACE_MS = 2_000; /** Bound captured stderr so an error message can never carry an unbounded (or secret) payload. */ const MAX_STDERR_BYTES = 8 * 1024; /** Env keys a CLI needs to run; everything else is dropped so the child env is scoped and deterministic. */ const INHERITED_ENV_KEYS = [ "PATH", "HOME", "USERPROFILE", "LANG", "LC_ALL", "LC_CTYPE", "TMPDIR", "TEMP", "TMP", "SHELL", "SYSTEMROOT", "APPDATA", "LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "COMSPEC", "PATHEXT", "SYSTEMDRIVE", "USERNAME", "TZ", ] as const; /** * Base scoped child-process environment (§六/§十四). * * Never mutates `process.env` (no cross-provider pollution under concurrency) and never inherits a * parent vendor variable, so a stray region switch in the host shell cannot flip a provider's * region: the profile is the sole authority. Family builders layer the credential + region vars on * top of this. */ export function baseScopedEnv(): Record<string, string> { const env: Record<string, string> = {}; for (const key of INHERITED_ENV_KEYS) { const value = process.env[key]; if (typeof value === "string" && value.length > 0) env[key] = value; } return env; } /** * Redact the profile's credential and common secret shapes before surfacing diagnostics. * * `tokenEnv` is absent for a credentialless profile (the CLI owns its sign-in), which only drops * the `NAME=value` rule; the generic secret shapes are redacted either way. */ export function redactSecrets(text: string, tokenEnv: string | undefined, credential?: string): string { let redacted = text; if (credential) redacted = redacted.split(credential).join("[redacted]"); if (tokenEnv) { const escaped = tokenEnv.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); redacted = redacted.replace(new RegExp(`(${escaped}\\s*[:=]\\s*)\\S+`, "gi"), "$1[redacted]"); } return redacted .replace(/(authorization\s*[:=]\s*)\S+/gi, "$1[redacted]") .replace(/\b(sk-[A-Za-z0-9_-]{6,})\b/g, "[redacted]"); } export type CodingAgentFailure = { profile: CodingAgentProviderProfile; error: Extract<AdapterEvent, { type: "error" }>; } & ( | { source: "result"; frame: Record<string, unknown> } | { source: "process-exit"; exitCode: number; stderr: string } ); /** Inputs for one headless CLI turn: region profiles, request context, and family-specific arg/env builders. */ export interface CodingAgentTurnInput { /** Region profiles for this family; the turn fails closed if the base URL matches none. */ profiles: readonly CodingAgentProviderProfile[]; provider: OcxProviderConfig; parsed: OcxParsedRequest; incoming: IncomingMeta; emit: (event: AdapterEvent) => void; /** Observes accepted CLI result/stderr failures, before client-side error decoration. */ onCliOutputError?: (message: string) => void; /** Family-specific headless argument builder (tools disabled, model, reasoning, system prompt). */ buildArgs: (profile: CodingAgentProviderProfile, parsed: OcxParsedRequest, provider: OcxProviderConfig) => string[]; /** Family-specific scoped env builder (credential + region switch on top of baseScopedEnv). */ buildEnv: (profile: CodingAgentProviderProfile, apiKey: string) => Record<string, string>; /** * Opt-in isolated MCP catalog. The turn writes a catalog and MCP config to a private temp dir, * advertises only the selected names, and returns structured CLI tool intent to the client. * The MCP handler never executes the client tool. */ toolBridge?: CodingAgentToolBridgeInput; /** Vendor semantics and recovery permission stay with the adapter. */ classifyFailure?: (failure: CodingAgentFailure) => Extract<AdapterEvent, { type: "error" }>; /** Family-specific replay projection; other coding-agent providers keep their existing layout. */ conversationInput?: typeof buildConversationInput; deps: CodingAgentDeps; } /** Opt-in isolated tool catalog for one coding-agent CLI turn. */ export interface CodingAgentToolBridgeInput { /** MCP server name advertised to the CLI; tool_use blocks render it as `mcp__<name>__<tool>`. */ serverName: string; /** Absolute path of the MCP server module, run with the serving runtime. */ serverModulePath: string; /** Validated tool catalog advertised over ListTools; the server never executes a call. */ tools: ReadonlyArray<{ name: string; description: string; inputSchema: Record<string, unknown> }>; /** CLI-emitted tool name (`mcp__<server>__<tool>`) to the request's wire tool name. */ emittedNameMap: Map<string, string>; /** A CLI may emit an exact selected wire name instead of its MCP transport name. * These aliases are output-only: they never enter the CLI's --allowedTools list. */ acceptWireToolNames?: boolean; /** Tool_use blocks accepted in one assistant message. */ maxTurnToolCalls: number; /** Render prior tool calls with the CLI-emitted names. Off by default so CodeBuddy history is unchanged. */ projectHistoryToolNames?: boolean; /** Finish the turn when a complete assistant frame supplies structured tool_use blocks. */ completeAssistantToolUse?: boolean; /** Authoritative tool-turn stop signal; existing coding-agent bridges default to message_stop. */ toolTurnCompletionSignal?: "message_stop" | "assistant_tool_use_stop"; /** Family-specific CLI flag spelling and compiled MCP helper entrypoint. */ allowedToolsFlag?: string; standaloneEntrypoint?: string; /** * The request's `tool_choice` requires a tool call (`required`, or a named selection). * The nested CLI has no documented force-tool flag, so this is enforced locally: a * terminal text result on a required turn fails closed instead of silently succeeding. */ requireToolCall?: boolean; } export function codeBuddyMcpInvocation(serverModulePath: string, catalogPath: string, standalone = isStandaloneBinary()): string[] { return standalone ? ["__codebuddy-mcp", catalogPath] : [serverModulePath, catalogPath]; } /** * Run one headless coding-agent CLI turn as an OpenCodex `runTurn` (§七/§三十). * * Single transport for every official coding-agent CLI provider: fail closed on a non-canonical * destination, pre-flight the credential and binary, spawn with a scoped env and tools disabled, feed * the replayed conversation over stream-json, map the vendor's Anthropic-aligned frames to * AdapterEvents, and always reap the process. Codex retains tool ownership: the CLI runs with its own * tools disabled, so this turn yields text/reasoning (the control-protocol tool bridge is a * documented fast-follow). */ export async function runCodingAgentTurn(input: CodingAgentTurnInput): Promise<void> { const { profiles, provider, parsed, incoming, emit, buildArgs, buildEnv, deps } = input; const spawnFn = deps.spawn ?? nodeSpawn; const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS; const killGraceMs = deps.killGraceMs ?? DEFAULT_KILL_GRACE_MS; const reapTimeoutMs = deps.reapTimeoutMs ?? (killGraceMs * 2 + 250); const platform = deps.platform ?? process.platform; const setTimeoutFn = deps.setTimeout ?? setTimeout; const clearTimeoutFn = deps.clearTimeout ?? clearTimeout; if (incoming.abortSignal?.aborted) { emit({ type: "error", message: "Coding-agent turn was aborted before start." }); return; } // Fail closed on a non-canonical destination BEFORE any credential is placed in an env (§十六). const profile = resolveProfileByBaseUrl(profiles, provider.baseUrl); if (!profile) { emit({ type: "error", message: "Provider base URL is not a canonical region destination; the credential was not sent.", status: 400, errorType: "invalid_request_error", code: "non_canonical_destination", retryable: false, }); return; } const apiKey = provider.apiKey ?? ""; // A profile WITHOUT a tokenEnv owns no credential to pre-flight: the CLI reads the operator's // own sign-in (Claude Code), so an unauthenticated session is reported by the CLI itself as a // terminal result frame and surfaces through the family's error mapping (§二十六). if (profile.tokenEnv && !apiKey) { emit({ type: "error", message: `${profile.label} credential missing — add an API key for this provider (${profile.tokenEnv}).`, status: 401, errorType: "authentication_error", code: "missing_credential", retryable: false, }); return; } // Pre-flight binary discovery so a missing CLI is a clear error, not a mid-turn ENOENT (§二十六). const binary = resolveCodingAgentBinary(profile, deps.which); if (!binary) { emit({ type: "error", message: `${profile.label} CLI not found on PATH. Install it with: ${profile.installHint}`, status: 500, errorType: "upstream_error", code: "cli_not_found", retryable: false, }); return; } const toolBridge = input.toolBridge; const wireToolNames = toolBridge?.acceptWireToolNames ? new Set(toolBridge.emittedNameMap.values()) : undefined; const writeToolBridgeFile = deps.writeToolBridgeFile ?? writeFile; let toolBridgeDir: string | undefined; let toolBridgeMcpConfigPath: string | undefined; if (toolBridge) { if (toolBridge.tools.length === 0 || toolBridge.emittedNameMap.size === 0) { emit({ type: "error", message: "Coding-agent tool bridge was supplied without any isolated tools.", status: 500, errorType: "server_error", code: "tool_bridge_empty", retryable: false, }); return; } try { toolBridgeDir = await mkdtemp(join(tmpdir(), "ocx-coding-agent-tools-")); const catalogPath = join(toolBridgeDir, "catalog.json"); toolBridgeMcpConfigPath = join(toolBridgeDir, "mcp.json"); await writeToolBridgeFile(catalogPath, JSON.stringify(toolBridge.tools), { encoding: "utf8", mode: 0o600, flag: "wx" }); await writeToolBridgeFile( toolBridgeMcpConfigPath, JSON.stringify({ mcpServers: { [toolBridge.serverName]: { type: "stdio", command: process.execPath, args: toolBridge.standaloneEntrypoint ? (isStandaloneBinary() ? [toolBridge.standaloneEntrypoint, catalogPath] : [toolBridge.serverModulePath, catalogPath]) : codeBuddyMcpInvocation(toolBridge.serverModulePath, catalogPath), defer_loading: false, alwaysLoad: true, }, }, }), { encoding: "utf8", mode: 0o600, flag: "wx" }, ); } catch { emit({ type: "error", message: "Coding-agent tool bridge could not be staged securely.", status: 500, errorType: "server_error", code: "tool_bridge_setup_failed", retryable: false, }); if (toolBridgeDir) await rm(toolBridgeDir, { recursive: true, force: true }).catch(() => undefined); return; } } const args = buildArgs(profile, parsed, provider); // The family's isolation contract rides on empty-string values (`--tools ""`, and for Qoder and // Claude `--setting-sources ""`). A Windows batch dispatcher that cannot deliver them would let // the CLI read the next flag as the value, so refuse before spawn rather than run a turn whose // isolation the host can no longer state (#7518). if (platform === "win32" && isBatchDispatcher(binary) && args.includes("")) { const verdict = inspectBatchDispatcher(binary, deps.readDispatcher); if (!verdict.preservesEmptyArguments) { const natives = profile.binaryCandidates.map(candidate => `${candidate}.exe`).join(" or "); const cause = verdict.reason === "powershell_hop" ? "forwards arguments through PowerShell, which drops the empty values" : verdict.reason === "indirect_launch" ? "hands off to another launcher that could not be checked for the empty values" : "could not be read completely to confirm it keeps the empty values"; emit({ type: "error", message: `${profile.label} CLI resolved to the batch dispatcher ${win32.basename(binary)}, which ${cause} this provider passes for tool and settings isolation. Put the CLI's native executable (${natives}) on PATH.`, status: 500, errorType: "upstream_error", code: "cli_dispatcher_drops_empty_args", retryable: false, }); if (toolBridgeDir) await rm(toolBridgeDir, { recursive: true, force: true }).catch(() => undefined); return; } } if (toolBridge && toolBridgeMcpConfigPath) { // Exact names close the wildcard domain; --strict-mcp-config (family args) keeps user // servers out, so this isolated server is the only capability this turn can reach. args.push(toolBridge.allowedToolsFlag ?? "--allowedTools", [...toolBridge.emittedNameMap.keys()].join(","), "--mcp-config", toolBridgeMcpConfigPath); } const env = buildEnv(profile, apiKey); const invocation = commandInvocation(binary, args, platform, { env }); // An opaque CLI invocation is one send. Its internal retries are not observable here; // terminal usage still settles the complete amount, including usage above the estimate. let producer: { close(): void } | undefined; let permit: SingleUseDispatchPermit | undefined; try { if (incoming.abortSignal?.aborted) { emit({ type: "error", message: "Coding-agent turn was aborted before start.", retryable: false }); return; } producer = incoming.sendBudget?.beginSpendProducer?.(); const decision = incoming.sendBudget?.reserveDispatch({ sendClass: "initial", targetKey: `${provider.adapter}|${profile.canonicalBaseUrl}|${parsed.modelId}`, }); if (decision && !decision.allowed) throw new SendBudgetExhaustedError(); permit = decision?.allowed ? decision.permit : undefined; // Setup above awaits private catalog writes. Fence the actual CLI dispatch, outside // spawn-error mapping so the selection owner can rebuild a refused turn. incoming.beforePhysicalSend?.(); if (permit && !permit.use()) throw new SendBudgetExhaustedError(); incoming.onPhysicalSend?.({ ordinal: 1 }); let child: ChildProcess; try { child = spawnFn(invocation.file, invocation.args, { ...invocation.options, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, }); } catch (err) { emit({ type: "error", message: redactSecrets(err instanceof Error ? err.message : String(err), profile.tokenEnv, apiKey), status: 500, errorType: "upstream_error", code: "cli_spawn_failed", retryable: false, }); return; } // `spawn()` reports launch failures such as ENOENT asynchronously through `error`; they are not // reliably thrown by the call above. Subscribe immediately and create the lifecycle promise now, // before stdout can end, so neither a fast close nor a launch failure can be missed by the reap step. let childProcessError: Error | undefined; const processLifecycle = new Promise<void>(resolve => { let settled = false; const settle = (): void => { if (settled) return; settled = true; resolve(); }; child.once("error", err => { childProcessError = err; // A launch failure has no process to reap and is not guaranteed to emit `close` on every runtime. if (child.pid === undefined) settle(); }); child.once("close", settle); if (child.exitCode !== null) settle(); }); let terminalEmitted = false; const emitOnce = (event: AdapterEvent, cliOutputError?: string): void => { if (event.type === "done" || event.type === "error" || event.type === "incomplete") { if (terminalEmitted) return; terminalEmitted = true; } if (event.type === "error" && cliOutputError !== undefined) { try { input.onCliOutputError?.(cliOutputError); } catch { // An observer failure must never drop the client's terminal event or turn it into a rejection. } } emit(event); }; const stderrChunks: string[] = []; let killed = false; let killTimer: ReturnType<typeof setTimeout> | undefined; const kill = (): void => { if (killed || child.killed) return; killed = true; if (platform === "win32" && child.pid !== undefined) { try { (deps.killWindowsProcessTree ?? killWindowsProcessTree)(child.pid); return; } catch { /* fall back to terminating the direct child */ } } // The capture-only MCP server is the CLI's child. Its stdin closes when the CLI dies, and // mcp-server.ts exits on stdin EOF, so this ladder reaps the whole tree without knowing // the grandchild pid. try { child.kill("SIGTERM"); } catch { /* already gone */ } killTimer = setTimeoutFn(() => { try { child.kill("SIGKILL"); } catch { /* already gone */ } }, killGraceMs); }; const stopStream = (): void => { try { child.stdout?.destroy(); } catch { /* already closed */ } }; const onAbort = (): void => { kill(); stopStream(); }; incoming.abortSignal?.addEventListener("abort", onAbort, { once: true }); const timeoutTimer = setTimeoutFn(() => { kill(); stopStream(); emitOnce({ type: "error", message: `${profile.label} turn timed out.`, status: 504, errorType: "upstream_error", code: "timeout", retryable: true }); }, timeoutMs); child.stderr?.setEncoding("utf8"); child.stderr?.on("data", (chunk: string) => { if (stderrChunks.join("").length < MAX_STDERR_BYTES) stderrChunks.push(chunk); }); const cleanup = (): void => { clearTimeoutFn(timeoutTimer); incoming.abortSignal?.removeEventListener("abort", onAbort); try { child.stdin?.destroy(); } catch { /* ignore */ } // Termination is owned by the reap step below, not here: killing in cleanup would set // `child.killed` and let the wait resolve before the process is actually reaped (§三十). }; let streamProtocolError: string | undefined; let streamProtocolCode: string | undefined; let turnError: string | undefined; let failClosed = false; // A successful result frame that arrived after every captured tool call completed but // before an authoritative tool-turn stop. The bridge contract still ends the leg with // synthesized done(tool_use) at that stop, so result-derived done(stop) is deferred and its // usage (authoritative vendor accounting) is folded into the synthesis. Set inside the // stream loop; read by the synthesis and the stream-end error selection below. let deferredResultDone: Extract<AdapterEvent, { type: "done" }> | undefined; const state: StreamParseState = { sawPartialText: false, sawPartialThinking: false, sawTerminalResult: false, openToolBlocks: new Map(), translatorBudget: incoming.translatorBudget, maxToolBlockStarts: toolBridge?.maxTurnToolCalls, strictToolBlockCapture: Boolean(toolBridge), partialToolCallIds: toolBridge ? new Set<string>() : undefined, completeAssistantToolUse: toolBridge?.completeAssistantToolUse, toolBridgeNames: toolBridge?.completeAssistantToolUse ? profile.family === "qoder" && wireToolNames ? new Map([...toolBridge.emittedNameMap, ...Array.from(wireToolNames, name => [name, name] as const)]) : toolBridge.emittedNameMap : undefined, }; const toolTurnCompletionSignal = toolBridge?.toolTurnCompletionSignal ?? "message_stop"; const sawSelectedToolTurnStop = (): boolean => toolTurnCompletionSignal === "assistant_tool_use_stop" ? state.sawAssistantToolUseStop === true : state.sawMessageStop === true; try { // Write the replayed conversation, then close stdin so a single-shot turn can complete. const stdin = child.stdin; if (stdin) { stdin.on("error", () => { /* EPIPE if the CLI exits early; surfaced via close/stderr */ }); // The projected history scales with the model context window on the routed provider row // (catalog and config metadata merged): a 1M-token model keeps 3M characters of replay // where the flat cap cut it near 50k-130k tokens of content. Absent metadata keeps the // flat cap. const historyCharLimit = projectedHistoryCharLimit( modelRecordValue(provider.modelContextWindows, parsed.modelId) ?? provider.contextWindow, ); const vendorNameByWire = toolBridge?.projectHistoryToolNames ? new Map([...toolBridge.emittedNameMap].map(([emitted, wire]) => [wire, emitted])) : undefined; for (const line of (input.conversationInput ?? buildConversationInput)(parsed, { maxHistoryChars: historyCharLimit, vendorNameByWire })) stdin.write(`${line}\n`); stdin.end(); } const stdout = child.stdout; if (!stdout) throw new CodingAgentProtocolError(`${profile.label} CLI produced no stdout stream`); try { let initValidated = false; for await (const message of readJsonLines(stdout)) { if (incoming.abortSignal?.aborted) break; if (toolBridge) { const initError = toolBridgeInitError(message, toolBridge.serverName); if (initError) { emitOnce({ type: "error", message: initError, status: 502, errorType: "upstream_error", code: "tool_bridge_init_mismatch", retryable: false, }); kill(); break; } if (message.type === "system" && message.subtype === "init") initValidated = true; const rawEvent = message.type === "stream_event" && message.event !== null && typeof message.event === "object" ? message.event as Record<string, unknown> : undefined; const rawBlock = rawEvent?.content_block; const assistantMessage = toolBridge.completeAssistantToolUse && message.type === "assistant" && message.message !== null && typeof message.message === "object" ? message.message as Record<string, unknown> : undefined; const completeToolUse = Array.isArray(assistantMessage?.content) && assistantMessage.content.some(block => block !== null && typeof block === "object" && (block as Record<string, unknown>).type === "tool_use", ); if ( !initValidated && (completeToolUse || (rawEvent?.type === "content_block_start" && rawBlock !== null && typeof rawBlock === "object" && !Array.isArray(rawBlock) && (rawBlock as Record<string, unknown>).type === "tool_use")) ) { emitOnce({ type: "error", message: "Coding-agent CLI called a tool before the tool bridge init handshake completed.", status: 502, errorType: "upstream_error", code: "tool_bridge_init_missing", retryable: false, }); kill(); break; } } const mappedEvents = mapStreamMessageToEvents(message, state).map(event => { if (message.type !== "result" || event.type !== "error") return event; if (input.classifyFailure) return input.classifyFailure({ source: "result", frame: message, error: event, profile }); return event; }); if (state.toolCallLimitExceeded) { emitOnce({ type: "error", message: `Coding-agent CLI returned more than the ${Math.min(MAX_TOOL_BLOCK_STARTS, state.maxToolBlockStarts ?? MAX_TOOL_BLOCK_STARTS)}-tool-call turn limit.`, status: 502, errorType: "upstream_error", code: "tool_call_limit", retryable: false, }); kill(); break; } if (toolBridge && state.uncapturedToolUse) { emitOnce({ type: "error", message: "Coding-agent CLI returned a tool call without a partial tool capture.", status: 502, errorType: "upstream_error", code: "protocol_error", retryable: false, }); kill(); break; } for (const event of mappedEvents) { if (toolBridge && !initValidated && event.type === "done") { emitOnce({ type: "error", message: "Coding-agent CLI ended before the tool bridge init handshake completed.", status: 502, errorType: "upstream_error", code: "tool_bridge_init_missing", retryable: false, }); failClosed = true; kill(); break; } if (toolBridge && event.type === "tool_call_start") { const wireName = toolBridge.emittedNameMap.get(event.name) ?? (wireToolNames?.has(event.name) ? event.name : undefined); if (wireName === undefined) { emitOnce({ type: "error", message: "Coding-agent CLI called a tool outside the isolated catalog.", status: 502, errorType: "upstream_error", code: "undeclared_tool_call", retryable: false, }); failClosed = true; kill(); break; } emitOnce({ ...event, name: wireName }); continue; } if ( toolBridge?.requireToolCall === true && !terminalEmitted && event.type === "done" && event.stopReason !== "tool_use" && (state.completedToolCalls ?? 0) === 0 ) { // `tool_choice: required|named` on a bridge turn: a text-only terminal result must not // become a successful completion the client can accept. The capture-only bridge has no // way to force the nested CLI, so fail closed with the same stable error shape the // other bridge contract violations use. emitOnce({ type: "error", message: "Coding-agent CLI finished without calling the required tool.", status: 502, errorType: "upstream_error", code: "tool_call_required", retryable: false, }); failClosed = true; kill(); break; } if ( toolBridge && !terminalEmitted && event.type === "done" && (state.toolBlockStarts ?? 0) > 0 && (state.completedToolCalls ?? 0) !== (state.toolBlockStarts ?? 0) ) { // A terminal result that arrives while a captured tool call is still open must not // become a successful completion the client can accept. The message_stop check after // the event loop cannot cover this path: the CLI normally parks on the // never-answering capture server, but a stream that delivers the result frame // without (or before) message_stop emits done here, and started-but-unfinished // calls slipped through as successful turns. emitOnce({ type: "error", message: "Coding-agent CLI ended with an incomplete tool call.", status: 502, errorType: "upstream_error", code: "protocol_error", retryable: false, }); failClosed = true; kill(); break; } if ( toolBridge && !terminalEmitted && event.type === "done" && (state.toolBlockStarts ?? 0) > 0 && (state.completedToolCalls ?? 0) === (state.toolBlockStarts ?? 0) ) { // Every captured call completed and the CLI settled with a successful result before // message_stop (instead of parking on the never-answering capture server). Emitting // this done(stop) now would end the turn as a text completion and skip the // synthesized done(tool_use) the client contract expects. Defer it: an authoritative // tool-turn stop synthesizes the terminal event with this frame's usage, and a stream // that ends without a stop fails closed with protocol_error below. deferredResultDone = event; continue; } emitOnce(event.type === "error" ? { ...event, message: redactSecrets(event.message, profile.tokenEnv, apiKey) } : event, event.type === "error" && message.type === "result" ? redactSecrets(event.message, profile.tokenEnv, apiKey) : undefined); } if (failClosed) break; const sawToolTurnStop = sawSelectedToolTurnStop(); if ( toolBridge && !terminalEmitted && sawToolTurnStop && (state.toolBlockStarts ?? 0) > 0 && (state.completedToolCalls ?? 0) !== (state.toolBlockStarts ?? 0) ) { emitOnce({ type: "error", message: "Coding-agent CLI ended with an incomplete tool call.", status: 502, errorType: "upstream_error", code: "protocol_error", retryable: false, }); kill(); break; } if (toolBridge && !terminalEmitted && sawToolTurnStop && (state.toolBlockStarts ?? 0) > 0 && (state.completedToolCalls ?? 0) === (state.toolBlockStarts ?? 0)) { if (!initValidated) { emitOnce({ type: "error", message: "Coding-agent CLI ended before the tool bridge init handshake completed.", status: 502, errorType: "upstream_error", code: "tool_bridge_init_missing", retryable: false }); kill(); break; } // Both partial and complete tool calls require the validated handshake. // The capture-only MCP handler never answers, so the CLI parks after the tool-turn stop. // The completed tool_use blocks are this turn's structured output: end the leg here // and terminate the tree; the client executes, and the next request continues. // Pre-result usage snapshots keep this terminated leg accountable: no result frame // ever arrives for a turn parked on the never-answering capture server. const terminalUsage = deferredResultDone?.usage ?? state.partialUsage; emitOnce({ type: "done", stopReason: "tool_use", endTurn: false, ...(terminalUsage ? { usage: terminalUsage } : {}), }); kill(); break; } if (terminalEmitted) break; } } catch (err) { kill(); streamProtocolError = err instanceof Error ? err.message : String(err); if (isTranslatorBudgetExceededError(err)) streamProtocolCode = err.code; } } catch (err) { kill(); turnError = err instanceof Error ? err.message : String(err); } finally { releaseOpenToolBlocks(state); cleanup(); } // Reap the process so no zombie is left behind (§三十): wait for the real `close`, and // force-terminate only if it lingers past the grace window after the stream ended. const graceTimer = setTimeoutFn(() => { kill(); }, killGraceMs); let reapTimer: ReturnType<typeof setTimeout> | undefined; await Promise.race([ processLifecycle, new Promise<void>(resolve => { reapTimer = setTimeoutFn(resolve, reapTimeoutMs); }), ]); clearTimeoutFn(graceTimer); if (reapTimer) clearTimeoutFn(reapTimer); if (killTimer) clearTimeoutFn(killTimer); if (!terminalEmitted) { const stderr = redactSecrets(boundedStderr(stderrChunks), profile.tokenEnv, apiKey); if (incoming.abortSignal?.aborted) { emitOnce({ type: "error", message: `${profile.label} turn was aborted.`, retryable: false }); } else if (childProcessError) { emitOnce({ type: "error", message: `${profile.label} CLI failed to start: ${redactSecrets(childProcessError.message, profile.tokenEnv, apiKey)}`, status: 500, errorType: "upstream_error", code: "cli_spawn_failed", retryable: false, }); } else if (turnError) { emitOnce({ type: "error", message: redactSecrets(turnError, profile.tokenEnv, apiKey), status: 502, errorType: "upstream_error", }); } else if (streamProtocolError) { emitOnce({ type: "error", message: redactSecrets(streamProtocolError, profile.tokenEnv, apiKey), status: 502, errorType: "upstream_error", code: streamProtocolCode ?? "protocol_error", retryable: false, }); } else if (child.exitCode !== null && child.exitCode !== 0) { const exitMsg = stderr ? `${profile.label} CLI exited with code ${child.exitCode}: ${stderr}` : `${profile.label} CLI exited with non-zero exit code ${child.exitCode}`; const error: Extract<AdapterEvent, { type: "error" }> = { type: "error", message: exitMsg, status: 502, errorType: "upstream_error", code: "process_exit_error", retryable: false, }; emitOnce(input.classifyFailure ? input.classifyFailure({ source: "process-exit", exitCode: child.exitCode, stderr, error, profile }) : error, stderr || undefined); } else if (toolBridge && deferredResultDone !== undefined && !sawSelectedToolTurnStop()) { emitOnce({ type: "error", message: `${profile.label} CLI delivered a terminal result before the authoritative tool-turn stop on a tool-bridge turn.`, status: 502, errorType: "upstream_error", code: "protocol_error", retryable: false, }); } else if (!state.sawTerminalResult) { const msg = stderr ? `${profile.label} CLI ended without a terminal result frame: ${stderr}` : `${profile.label} CLI ended without a terminal result frame`; emitOnce({ type: "error", message: msg, status: 502, errorType: "upstream_error", code: "protocol_error", retryable: false, }, stderr || undefined); } } } finally { try { permit?.release(); } finally { try { producer?.close(); } finally { if (toolBridgeDir) await rm(toolBridgeDir, { recursive: true, force: true }).catch(() => undefined); } } } } function boundedStderr(chunks: string[]): string { let total = 0; const kept: string[] = []; for (const chunk of chunks) { if (total >= MAX_STDERR_BYTES) break; kept.push(chunk); total += chunk.length; } return kept.join("").slice(0, MAX_STDERR_BYTES).trim(); }