diff --git a/.changeset/claude-turn-runner-split.md b/.changeset/claude-turn-runner-split.md new file mode 100644 index 0000000000..6fa3c6e4ca --- /dev/null +++ b/.changeset/claude-turn-runner-split.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-backend-claude": patch +--- + +The Claude backend's turn runner is now split into its terminal state, host inference relay, prompt gate, runtime reporting and stream loop. Turns behave as before: frames, outcomes, refusals and cleanup are unchanged. diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 5cf4074f1a..040338268f 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -1311,7 +1311,7 @@ profile's `baseUrl` from `BRAIN_UI_CLAUDE_PROFILES`, else the server's `ANTHROPIC_BASE_URL`, else first-party inference. The relay forwards to that route, keeping its base path. Before the prompt is sent, the runner refuses a route whose origin is neither first-party nor listed -(`const selectedUpstream`, `packages/ui-backend-claude/src/turn-runner.ts:430-445`). +(`qualify(settings`, `packages/ui-backend-claude/src/turn-inference-relay.ts:108-133`). Each dispatch checks the same list again before the credential is read. Native settings may repeat the server's route, compared as a canonical origin and base path, but never replace it. A discovered profile never carries a route or a diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index ea7c9e678b..2ea4396fdf 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1359,8 +1359,8 @@ also preserves the previous observation: it supplied no new bytes `packages/ui-backend-claude/src/permission-hooks.ts:107`). Claude keeps these observations in its backend-owned session map -(`const fileVersionsBySession`, -`packages/ui-backend-claude/src/turn-runner.ts:105`). Pi keeps them in its +(`fileVersionsBySession: new Map()`, +`packages/ui-backend-claude/src/turn-runner.ts:94`). Pi keeps them in its backend-owned session runtime across fresh per-turn workers (`const nativeFileVersions`, `packages/ui-backend-pi/src/session-runtime.ts:19`); internal RPC reports diff --git a/docs/decisions/hardening.md b/docs/decisions/hardening.md index 9078726593..d37237de94 100644 --- a/docs/decisions/hardening.md +++ b/docs/decisions/hardening.md @@ -144,7 +144,7 @@ instead, and treat 8 as the question it was answering. releases.** Dispatcher, store and page splits (U33) ship in the 0.34.x train, never in the container release. Because U28 changes frame production (`adapter.adapt(msg)`, - `packages/ui-backend-claude/src/turn-runner.ts:690`) and U33 changes frame + `packages/ui-backend-claude/src/turn-stream.ts:103`) and U33 changes frame consumption (`handleServerMessage`, `packages/ui-react/src/ws-client/inbound.ts:187`), the same symptom could come from either, so they are **0.34.0** (seam) and **0.34.1** (splits), each its own diff --git a/docs/decisions/policy-write-boundary.md b/docs/decisions/policy-write-boundary.md index 3fe86900e3..536843935a 100644 --- a/docs/decisions/policy-write-boundary.md +++ b/docs/decisions/policy-write-boundary.md @@ -639,8 +639,8 @@ as it exited. So the state is checked when the result arrives, the terminal result is held until the worker has exited and its state has been copied out, and the state is checked again then. A `statfs` of the tmpfs with no whole page free at either point, or a write error the worker reported, names the turn -`worker_state_exceeded` (`const unsaved`, -`packages/ui-backend-claude/src/turn-runner.ts:301-308`). A result, success or +`worker_state_exceeded` (`unsaved(result`, +`packages/ui-backend-claude/src/turn-terminal.ts:117-124`). A result, success or error, becomes an error result with that class and keeps its usage, so the client never presents unsaved output as saved; what was written before the limit is persisted with the usual checks, and if that copy-out is refused the @@ -651,9 +651,9 @@ the worker prints after it, and a refusal is recognized by its class from any copy of the module. A host cancellation outranks it. Cancellation is checked again after worker settlement, so a buffered SDK success or error cannot replace an accepted cancellation while exit or copy-out is pending -(`releaseTerminal`, `packages/ui-backend-claude/src/turn-runner.ts:312-330`). +(`async release`, `packages/ui-backend-claude/src/turn-terminal.ts:127-141`). Generated terminals also await worker settlement before emission -(`emitTerminal`, `packages/ui-backend-claude/src/turn-runner.ts:374-414`). +(`async emitGenerated`, `packages/ui-backend-claude/src/turn-terminal.ts:159-198`). **Residual:** a turn that fills the tmpfs and frees space again between those two checks is named only if the runtime printed the write error. diff --git a/docs/decisions/runtime-requirements.md b/docs/decisions/runtime-requirements.md index d4b76be441..8687e334d1 100644 --- a/docs/decisions/runtime-requirements.md +++ b/docs/decisions/runtime-requirements.md @@ -281,7 +281,7 @@ reciprocal host-version negotiation is involved. | `probeBackendRuntimes` (`export async function probeBackendRuntimes`, `packages/ui-server/src/agent/backend.ts:394-444`) | Forward validated host requirements; retain active-backend selection and separate unmeasured-pair logging. | | `BackendModuleContext` / `BackendRuntimeReport` (`export interface BackendModuleContext`, `packages/ui-sdk/src/server/backend-module.ts:96-111`; `export interface BackendRuntimeReport`, `packages/ui-sdk/src/server/backend-module.ts:118-131`) | Extend the existing construction context for optional minimums. Keep report identities and `measured` meanings; a compatibility result must never occupy `measured.matches`. | | `MEASURED_RUNTIME`, its guard and `scripts/measure-claude-runtime.ts` | Keep the constant, exact pair guard, keyless behavior probe and dated measurement receipts. A permitted pair can still be unmeasured. | -| Turn `reportRuntime` / `init` (`const reportRuntime`, `packages/ui-backend-claude/src/turn-runner.ts:216-223`; `if (msg.type === "system"`, `packages/ui-backend-claude/src/turn-runner.ts:674-689`) | Preserve actual per-turn SDK/runtime observations, billing/permission guards and normal failure terminal behavior. | +| Turn `reportRuntime` / `init` (`export function reportTurnRuntime`, `packages/ui-backend-claude/src/turn-reporting.ts:31-70`; `if (msg.type === "system"`, `packages/ui-backend-claude/src/turn-stream.ts:97-102`; `function initMatchesProbe`, `packages/ui-backend-claude/src/turn-stream.ts:184-196`) | Preserve actual per-turn SDK/runtime observations, billing/permission guards and normal failure terminal behavior. | | Index schema and graph floors | Remain reader-specific integer schema checks; do not compare them as SemVer or turn `brain.db` into authoritative state. | No new compatibility HTTP status field is required for enforcement. Keep diff --git a/packages/ui-backend-claude/src/turn-inference-relay.ts b/packages/ui-backend-claude/src/turn-inference-relay.ts new file mode 100644 index 0000000000..9ef4efa242 --- /dev/null +++ b/packages/ui-backend-claude/src/turn-inference-relay.ts @@ -0,0 +1,142 @@ +import { existsSync, linkSync, realpathSync, rmSync } from "node:fs"; +import { homedir } from "node:os"; +import { join, resolve } from "node:path"; +import type { StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { BackendRequestError } from "@schlessera/brain-ui-sdk/server"; +import { ANTHROPIC_INFERENCE_ROUTES, startInferenceRelay, type InferenceRelay } from "@schlessera/brain-ui-sdk/internal"; + +import { apiKeyRelayCredential, type ApiKeyRelayCredential } from "./api-key-relay.js"; +import { resolveEnv } from "./config/env.js"; +import { authorizeDestination, resolveClaudeHostOAuth } from "./host-oauth.js"; +import type { retainNativeRouteInputs } from "./native-route-inputs.js"; +import type { InferenceProfile } from "./profiles.js"; +import { selectedInferenceUpstream } from "./sdk-options.js"; +import { settingsRefusal, type CliSettingsReport } from "./subscription.js"; + +/** The host's stored Claude login: masked in a relayed worker, or refused when the brain itself holds it. */ +export function hostLoginFile(configDirectory: string, brainPath: string): { mask: string[]; inBrain: boolean } { + const file = join(configDirectory, ".credentials.json"); + if (!existsSync(file)) return { mask: [], inBrain: false }; + const real = realpathSync(file), brain = realpathSync(brainPath); + return real === brain || real.startsWith(`${brain}/`) ? { mask: [], inBrain: true } : { mask: [real], inBrain: false }; +} + +/** The same endpoint: canonical origin and base path, nothing else. */ +export function sameRoute(value: unknown, selected: string): boolean { + try { + const url = new URL(String(value)), expected = new URL(selected); + return typeof value === "string" && url.origin === expected.origin && !url.username && !url.password && !url.search && !url.hash + && url.pathname.replace(/\/+$/, "") === expected.pathname.replace(/\/+$/, ""); + } catch { return false; } +} + +type Environment = Record; + +/** + * The host inference relay of one interactive turn whose host prepared its + * egress: the relay holds the credential, the worker reaches it through a + * socket in its egress directory, and no credential leaves the relay until + * the prompt gate has qualified the CLI's native settings. + */ +export class TurnInferenceRelay { + /** The host-prepared egress; without it the turn runs no relay. */ + readonly egress: NonNullable["egress"] | undefined; + /** An API-billed profile's own key: declared by the host together with its route. */ + readonly apiCredential: ApiKeyRelayCredential | undefined; + readonly hostLogin: { mask: string[]; inBrain: boolean } | undefined; + readonly selectedUpstream: string; + /** The worker's base URL: the relay's socket, at the selected route's path. */ + baseUrl = "http://localhost"; + routeInputs: Awaited> | undefined; + #relay: InferenceRelay | undefined; + #link: string | undefined; + #authorized = false; + readonly #configDirectory: string; + readonly #turnEnvironment: Environment | undefined; + readonly #authorizedOrigins: ReturnType["claudeOAuthOrigins"]; + readonly #recipient: NonNullable["inferenceRecipient"] | undefined; + + /** Selects the route and credential; starts nothing (see `start`). */ + constructor(inputs: { req: StartTurnRequest; profile: InferenceProfile; turnEnvironment: Environment | undefined; brainPath: string }) { + const { req, profile, turnEnvironment } = inputs; + this.#turnEnvironment = turnEnvironment; + this.egress = !req.autonomous ? req.workerSandbox?.egress : undefined; + // Only what the profile itself declares: an ambient credential never rides along. + this.apiCredential = this.egress && profile.billing === "api" ? apiKeyRelayCredential(profile.id, profile.buildEnv()) : undefined; + this.#configDirectory = resolve(turnEnvironment?.CLAUDE_CONFIG_DIR || join(turnEnvironment?.HOME || homedir(), ".claude")); + this.hostLogin = this.egress ? hostLoginFile(this.#configDirectory, inputs.brainPath) : undefined; + // The server selects the route: the profile's baseUrl, else the host's + // ANTHROPIC_BASE_URL. Only the host's explicit list authorizes a custom + // origin to receive the login (docs/decisions/claude-code-runtime.md). + this.selectedUpstream = selectedInferenceUpstream(turnEnvironment); + // Provider folders admitted for a proven recipient (#2695): only its relay may carry this turn. + this.#recipient = !req.autonomous ? req.workerSandbox?.inferenceRecipient : undefined; + if (this.#recipient && !this.egress) throw new BackendRequestError("This turn's provider folders were admitted for a recipient, but it has no inference relay to hold it to."); + this.#authorizedOrigins = resolveEnv().claudeOAuthOrigins; + } + + /** + * Start the relay and link its socket into the egress directory. Each + * handle is owned as soon as it exists, so `stop` and `unlink` release a + * relay whose start failed part way. + */ + start(): void { + const egress = this.egress; + if (!egress) return; + this.#relay = startInferenceRelay({ upstream: this.selectedUpstream, routes: ANTHROPIC_INFERENCE_ROUTES, egress, + ...(this.#recipient ? { recipientOrigin: this.#recipient.origin } : {}), + credentials: async (signal, target) => { + if (!this.#authorized) throw new Error("Native inference has not passed its prompt gate"); + this.routeInputs?.assertUnchanged(); + if (this.apiCredential) return this.apiCredential.headers; + return { authorization: (await resolveClaudeHostOAuth(this.#configDirectory, this.#turnEnvironment ?? {}, + { origin: target.origin, authorizedOrigins: this.#authorizedOrigins }, signal)).authorization }; + }, + }); + this.baseUrl = `http://localhost${new URL(this.selectedUpstream).pathname.replace(/\/+$/, "")}`; + this.#link = join(egress.dir, "inference.sock"); + linkSync(this.#relay.socketPath, this.#link); + } + + /** + * Qualify the CLI's native settings for this prepared transport. The + * server's route must be authorized for the host login, and native + * settings may repeat that route but never replace it. Returns why the + * transport is refused, or undefined once the relay may hand out its + * credential. + */ + qualify(settings: CliSettingsReport | undefined, subscriptionOnly: boolean, + pinnedSettingsEnv: Readonly> | undefined): string | undefined { + try { this.routeInputs?.assertUnchanged(); } + catch { return "native inference settings changed during startup"; } + if (!Array.isArray(settings?.sources) || settings.sources.some(source => !["projectSettings", "flagSettings", "policySettings"].includes(source.source ?? ""))) { + return "the native inference settings sources are not qualified for this prepared transport"; + } + if (this.hostLogin?.inBrain) return "the host's Claude login is inside the brain, where the worker can read it; move the Claude config directory out of the brain"; + // A settings credential or helper would stand in for the relay's placeholder. + const credentialConflict = subscriptionOnly ? null : settingsRefusal(settings, pinnedSettingsEnv); + if (credentialConflict) return credentialConflict; + try { if (!this.apiCredential) authorizeDestination({ origin: new URL(this.selectedUpstream).origin, authorizedOrigins: this.#authorizedOrigins }); } + catch { return "the selected inference origin is not authorized to receive the host Claude login; list its exact origin in BRAIN_UI_CLAUDE_OAUTH_ORIGINS"; } + for (const source of settings?.sources ?? []) { + const value = source.settings?.env?.ANTHROPIC_BASE_URL; + // Native settings may repeat the server's route, never replace it. + if (value !== undefined && value !== "" && !(source.source === "flagSettings" && value === this.baseUrl) && !sameRoute(value, this.selectedUpstream)) { + return "the native inference source selects a destination not qualified for this prepared transport"; + } + } + if (settings?.effective?.env?.ANTHROPIC_BASE_URL !== this.baseUrl) { + return "native settings refused the prepared inference transport"; + } + this.#authorized = true; + return undefined; + } + + stop(): unknown { + return this.#relay?.stop(); + } + + unlink(): void { + if (this.#link) rmSync(this.#link, { force: true }); + } +} diff --git a/packages/ui-backend-claude/src/turn-prompt-gate.ts b/packages/ui-backend-claude/src/turn-prompt-gate.ts new file mode 100644 index 0000000000..f18489a88b --- /dev/null +++ b/packages/ui-backend-claude/src/turn-prompt-gate.ts @@ -0,0 +1,158 @@ +import { FIRST_PARTY_FAILURE_CLASSES } from "@schlessera/brain-ui-sdk/protocol"; +import type { AccountInfo, Query, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk"; +import { subscriptionAuthAction } from "@schlessera/brain-ui-sdk/server"; +import { VERSION_PROBE_TIMEOUT_MS } from "@schlessera/brain-ui-sdk/internal"; + +import type { BackendLogFn } from "./options.js"; +import type { ClaudeSdkTurn } from "./sdk-options.js"; +import { + settingsRefusal, + subscriptionRefusalMessage, + subscriptionVerdict, + type CliSettingsReport, +} from "./subscription.js"; +import type { ReportActivity } from "./turn-reporting.js"; +import type { TurnInferenceRelay } from "./turn-inference-relay.js"; +import type { TurnTerminal } from "./turn-terminal.js"; +import type { claudeRuntimeRequirements } from "./version-requirements.js"; + +export interface PromptGateInputs { + /** The SDK query, once `query()` has been called. */ + queryHandle: Promise; + /** The CLI's one initialization handshake, shared with the per-turn report. */ + initialize(cli: Query): ReturnType; + sdkTurn: Pick; + /** The turn's relay, when its host prepared egress for it. */ + relay: TurnInferenceRelay | undefined; + terminal: TurnTerminal; + runtimeRequirements: ReturnType; + phase: string; + abortController: AbortController; + profileId: string; + log: BackendLogFn; + reportActivity: ReportActivity; + reportRuntime(claudeCodeVersion: string | undefined, apiKeySource: string | undefined, selected: AccountInfo | undefined): void; +} + +/** + * The check the gated prompt runs exactly when the SDK asks for the first + * message: subscription policy, constrained runtime startup and the prepared + * inference transport. The earlier version probe identifies the selected + * executable; this gate waits for initialization before any user input can + * reach the model. A refusal records why on the terminal and withholds the + * prompt. + */ +export function promptGateCheck(inputs: PromptGateInputs): () => Promise { + const { sdkTurn, relay, terminal, runtimeRequirements, abortController } = inputs; + const refuseSubscription = (reason: string): false => { + const message = subscriptionRefusalMessage(reason); + terminal.refused = { + code: "CLAUDE_AUTH", + message, + failure: { + errorClass: FIRST_PARTY_FAILURE_CLASSES.subscription_required, + message, + authAction: subscriptionAuthAction("subscription_required"), + }, + }; + inputs.reportActivity({ kind: "auth_failure", errorClass: FIRST_PARTY_FAILURE_CLASSES.subscription_required, message: reason }); + inputs.log("warn", "subscription check refused the turn", { + "profile.id": inputs.profileId, + reason, + }); + return terminal.withhold(); + }; + const refuseTransport = (reason: string): false => { + const message = `Claude inference transport refused: ${reason}.`; + terminal.refused = { code: "CLAUDE_ERROR", message, failure: { errorClass: FIRST_PARTY_FAILURE_CLASSES.auth_failure, message } }; + inputs.reportActivity({ kind: "auth_failure", errorClass: FIRST_PARTY_FAILURE_CLASSES.auth_failure, message: reason }); + inputs.log("warn", "inference transport check refused the turn", { "profile.id": inputs.profileId, reason }); + return terminal.withhold(); + }; + return async () => { + const cli = await inputs.queryHandle; + let account: AccountInfo | undefined; + let settings: CliSettingsReport | undefined; + try { + const check = async () => { + account = (await inputs.initialize(cli)).account; + if (!sdkTurn.subscriptionOnly && !relay?.egress) return; + // Not on the public Query type; the SDK sends the CLI's own + // `get_settings` control request. Absent means unreadable, + // which refuses below. + const getSettings = (cli as { getSettings?: () => Promise }).getSettings; + settings = getSettings ? await getSettings.call(cli) : undefined; + }; + if (runtimeRequirements.length) await startupDeadline(check(), abortController.signal); + else await check(); + } catch (error) { + // A handshake the host cancelled is a cancelled turn, not a failed one. + if (abortController.signal.aborted) return terminal.withhold(); + terminal.refused = { + code: "CLAUDE_ERROR", + message: `@schlessera/brain-backend-claude runtime (claude-code) during ${inputs.phase}; requirements: ${runtimeRequirements.map(req => `${req.owner} minimum ${req.declaration}`).join("; ") || "subscription handshake"}; detected startup unknown. Claude Code did not complete its handshake: ${error instanceof Error ? error.message : String(error)}. Install/select a compatible executable that completes SDK initialization.`, + }; + return terminal.withhold(); + } + if (abortController.signal.aborted) return terminal.withhold(); + if (sdkTurn.subscriptionOnly) { + const verdict = subscriptionVerdict(account); + const conflict = verdict.ok ? settingsRefusal(settings, sdkTurn.pinnedSettingsEnv) : null; + if (!verdict.ok || conflict) { + // The CLI never reaches init, so this is the only report the + // refused turn gets: what the handshake said it would bill. + inputs.reportRuntime(undefined, account?.apiKeySource, account); + return refuseSubscription(verdict.ok ? conflict! : verdict.reason); + } + } + if (relay?.egress) { + // An API-billed turn is not a subscription refusal: name the transport instead. + const refuse = sdkTurn.subscriptionOnly ? refuseSubscription : refuseTransport; + const reason = relay.qualify(settings, sdkTurn.subscriptionOnly, sdkTurn.pinnedSettingsEnv); + if (reason !== undefined) return refuse(reason); + } + return true; + }; +} + +/** Startup settlement is bounded even if an injected/older SDK ignores abort. */ +export async function startupDeadline(operation: Promise, signal: AbortSignal): Promise { + let timer: ReturnType | undefined; + let onAbort: (() => void) | undefined; + try { + return await Promise.race([ + operation, + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(`SDK startup timed out after ${VERSION_PROBE_TIMEOUT_MS / 1000} s`)), VERSION_PROBE_TIMEOUT_MS); + onAbort = () => reject(signal.reason ?? new Error("SDK startup cancelled")); + signal.addEventListener("abort", onAbort, { once: true }); + if (signal.aborted) onAbort(); + }), + ]); + } finally { + clearTimeout(timer); + if (onAbort) signal.removeEventListener("abort", onAbort); + } +} + +/** + * The turn's prompt as a stream the SDK pulls from, released only if `check` + * passes. A string prompt becomes the single user message the SDK would have + * built from it. + */ +export async function* gatedPrompt( + prompt: string | AsyncIterable, + check: () => Promise +): AsyncIterable { + if (!(await check())) return; + if (typeof prompt !== "string") { + yield* prompt; + return; + } + yield { + type: "user", + parent_tool_use_id: null, + message: { role: "user", content: prompt }, + session_id: "", + }; +} diff --git a/packages/ui-backend-claude/src/turn-reporting.ts b/packages/ui-backend-claude/src/turn-reporting.ts new file mode 100644 index 0000000000..ceddf00801 --- /dev/null +++ b/packages/ui-backend-claude/src/turn-reporting.ts @@ -0,0 +1,107 @@ +import { FIRST_PARTY_FAILURE_CLASSES } from "@schlessera/brain-ui-sdk/protocol"; +import type { AccountInfo } from "@anthropic-ai/claude-agent-sdk"; +import type { BackendActivityEvent, StartTurnRequest, TurnFailure } from "@schlessera/brain-ui-sdk/server"; +import { createLimitTracker, limitFailureMessage, type WorkerLimitReport } from "@schlessera/brain-ui-sdk/internal"; + +import type { BackendLogFn } from "./options.js"; +import type { InferenceProfile } from "./profiles.js"; +import { installedAgentSdkVersion, isMeasuredRuntime } from "./runtime-probe.js"; +import { credentialFields, observedBilling } from "./subscription.js"; +import type { TurnRefusal } from "./turn-terminal.js"; + +export type ReportActivity = (event: BackendActivityEvent) => void; + +/** The turn's activity sink: observability must not break the observed turn. */ +export function turnActivityReporter(bridge: StartTurnRequest["bridge"]): ReportActivity { + return (event) => { + try { + bridge.activity?.(event); + } catch { + // Observability must not break the observed turn. + } + }; +} + +/** + * What ran, the credential it selected, and whether that honours the + * profile (#211). Checked against the profile's POLICY — a profile without + * its own credential requires the subscription — not against + * `classifyBilling`, since the two could regress together. + */ +export function reportTurnRuntime( + inputs: { profile: Pick; log: BackendLogFn; reportActivity: ReportActivity }, + claudeCodeVersion: string | undefined, + apiKeySource: string | undefined, + selected: AccountInfo | undefined +): void { + const { profile } = inputs; + const billing = observedBilling(selected, apiKeySource); + const policy = profile.billing === "api" ? "api" : "subscription"; + const agentSdk = installedAgentSdkVersion(); + // Any disagreement: a declared API profile that ran on something else + // lost its own credential, and the CLI picked another one. + const policyViolation = + billing === policy + ? undefined + : `${policy === "api" ? "a profile declared as API-billed" : "a profile without its own credential"} ran on ${ + billing === "api" + ? "an API credential" + : billing === "subscription" + ? "a subscription" + : "a credential that is not a recognised subscription" + }`; + if (policyViolation) { + inputs.log("warn", "billing policy violated", { + "profile.id": profile.id, + "billing.observed": billing, + reason: policyViolation, + }); + } + inputs.reportActivity({ + kind: "runtime_observed", + ...(claudeCodeVersion ? { runtime: { name: "claude-code", version: claudeCodeVersion } } : {}), + sdk: { name: "@anthropic-ai/claude-agent-sdk", version: agentSdk }, + credential: credentialFields(selected, apiKeySource), + billing, + policy, + ...(policyViolation ? { policyViolation } : {}), + measured: isMeasuredRuntime(claudeCodeVersion, agentSdk), + }); +} + +/** + * The host resource limits the turn's worker hit (#1660). Each new hit is + * reported next to the tool step that caused it; a limit that ended the + * worker becomes the turn's failure, with the limit named. + */ +export class WorkerLimitReporter { + /** Bound once the SDK turn is built. */ + limits: { current(): WorkerLimitReport; settled(): Promise } | undefined; + readonly #fresh = createLimitTracker(); + readonly #reportActivity: ReportActivity; + + constructor(reportActivity: ReportActivity) { + this.#reportActivity = reportActivity; + } + + report(report: WorkerLimitReport): void { + const fresh = this.#fresh(report); + if (fresh.length) this.#reportActivity({ kind: "resource_limit", limits: fresh, fatal: false }); + } + + /** Report the hits so far, when the worker reports any. */ + reportCurrent(): void { + if (this.limits) this.report(this.limits.current()); + } + + /** The turn's failure when a limit ended its worker, once the worker has exited. */ + async failure(): Promise<(TurnRefusal & { failure: TurnFailure }) | null> { + if (!this.limits) return null; + const report = await this.limits.settled(); + if (!report.fatal) { this.report(report); return null; } + this.#reportActivity({ kind: "resource_limit", limits: report.hits, fatal: true }); + const message = limitFailureMessage(report.hits); + return { code: "WORKER_RESOURCE_LIMIT", message, + failure: { errorClass: FIRST_PARTY_FAILURE_CLASSES.worker_resource_limit, message } }; + } +} diff --git a/packages/ui-backend-claude/src/turn-runner.ts b/packages/ui-backend-claude/src/turn-runner.ts index ae88720018..4ba56a0869 100644 --- a/packages/ui-backend-claude/src/turn-runner.ts +++ b/packages/ui-backend-claude/src/turn-runner.ts @@ -1,77 +1,35 @@ import { retainNativeRouteInputs } from "./native-route-inputs.js"; -import { FIRST_PARTY_FAILURE_CLASSES, type StateRoomObservation } from "@schlessera/brain-ui-sdk/protocol"; import { query } from "@anthropic-ai/claude-agent-sdk"; import type { AccountInfo, Query, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk"; -import type { - BackendActivityEvent, - FollowUpRequest, - ServerMessage, - StartTurnRequest, - TurnFailure, -} from "@schlessera/brain-ui-sdk/server"; -import { - assertTurnPosture, - BackendBusyError, - BackendRequestError, - subscriptionAuthAction, -} from "@schlessera/brain-ui-sdk/server"; -import { NativeFileVersions, createLimitTracker, limitFailureMessage, WorkerHostError, requireWorkerHostAsync, VERSION_PROBE_TIMEOUT_MS, - type WorkerLimitReport, startInferenceRelay, ANTHROPIC_INFERENCE_ROUTES, type InferenceRelay } from "@schlessera/brain-ui-sdk/internal"; +import type { FollowUpRequest, StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { assertTurnPosture, BackendBusyError, BackendRequestError } from "@schlessera/brain-ui-sdk/server"; +import { NativeFileVersions, requireWorkerHostAsync } from "@schlessera/brain-ui-sdk/internal"; import type { ClaudeBackendOptions, BackendLogFn } from "./options.js"; import { getProfile, type InferenceProfile } from "./profiles.js"; -import { existsSync, linkSync, realpathSync, rmSync } from "node:fs"; -import { homedir } from "node:os"; -import { authorizeDestination, resolveClaudeHostOAuth } from "./host-oauth.js"; -import { apiKeyRelayCredential } from "./api-key-relay.js"; - -/** The host's stored Claude login: masked in a relayed worker, or refused when the brain itself holds it. */ -function hostLoginFile(configDirectory: string, brainPath: string): { mask: string[]; inBrain: boolean } { - const file = join(configDirectory, ".credentials.json"); - if (!existsSync(file)) return { mask: [], inBrain: false }; - const real = realpathSync(file), brain = realpathSync(brainPath); - return real === brain || real.startsWith(`${brain}/`) ? { mask: [], inBrain: true } : { mask: [real], inBrain: false }; -} -/** The same endpoint: canonical origin and base path, nothing else. */ -function sameRoute(value: unknown, selected: string): boolean { - try { - const url = new URL(String(value)), expected = new URL(selected); - return typeof value === "string" && url.origin === expected.origin && !url.username && !url.password && !url.search && !url.hash - && url.pathname.replace(/\/+$/, "") === expected.pathname.replace(/\/+$/, ""); - } catch { return false; } -} -import { join, resolve } from "node:path"; -import { createClaudeSdkTurn, prepareClaudeTurnSandbox, selectedInferenceUpstream, turnEnv } from "./sdk-options.js"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { createClaudeSdkTurn, prepareClaudeTurnSandbox, turnEnv } from "./sdk-options.js"; import { StreamAdapter } from "./stream-adapter.js"; -import { probeClaudeRuntime, installedAgentSdkVersion, isMeasuredRuntime } from "./runtime-probe.js"; -import { - credentialFields, - observedBilling, - settingsRefusal, - subscriptionRefusalMessage, - subscriptionVerdict, - type CliSettingsReport, -} from "./subscription.js"; -import type { ActiveTurn } from "./turn-lock.js"; +import { probeClaudeRuntime } from "./runtime-probe.js"; +import type { ActiveTurn, TurnLockBinding } from "./turn-lock.js"; import { createTurnLockBinding } from "./turn-lock.js"; import { createTurnInput, type TurnInput } from "./turn-input.js"; import { DEFAULT_ALLOWED_TOOLS, VOICE_ALLOWED_TOOLS } from "./tool-policy.js"; -import { ambientExecConfig, resolveEnv } from "./config/env.js"; +import { ambientExecConfig } from "./config/env.js"; import { assertClaudeRuntime, claudeRuntimeRequirements } from "./version-requirements.js"; import type { KeyedLock } from "@schlessera/brain-ui-sdk/server"; -import { SessionTooLargeError } from "./worker-state.js"; -import { workerStateClass } from "./worker-spawn.js"; import { archiveIdleSessions, transcriptPaths } from "./transcript-archive.js"; +import { TurnInferenceRelay } from "./turn-inference-relay.js"; +import { gatedPrompt, promptGateCheck } from "./turn-prompt-gate.js"; +import { reportTurnRuntime, turnActivityReporter, WorkerLimitReporter } from "./turn-reporting.js"; +import { runTurnStream } from "./turn-stream.js"; +import { TurnFailureEscape, TurnFrames, TurnTerminal } from "./turn-terminal.js"; -const BACKEND_ID = "claude"; +export { FOLLOW_UP_ACK_GRACE_MS } from "./turn-stream.js"; -/** - * How long a held result waits for the CLI to report reading a follow-up - * before the input is closed anyway. The measured runtime reports it within - * milliseconds; the bound only matters for a runtime that never reports it. - */ -export const FOLLOW_UP_ACK_GRACE_MS = 3_000; +const BACKEND_ID = "claude"; /** A running turn, with the input stream a follow-up is delivered into. */ interface RunningTurn extends ActiveTurn { @@ -88,27 +46,59 @@ export interface ClaudeTurnRunner { followUp(req: FollowUpRequest): Promise; } -export function createClaudeTurnRunner(options: { +interface ClaudeTurnRunnerOptions { backend: ClaudeBackendOptions; resolveProfiles(): InferenceProfile[]; confirmPatterns: readonly RegExp[]; writeLock: KeyedLock; lockWaitMs: number; log: BackendLogFn; -}): ClaudeTurnRunner { +} + +/** The runner's state shared by its turns. */ +interface TurnRunnerState { + options: ClaudeTurnRunnerOptions; // Busy-ness is PER SESSION: one running turn per session key. Resuming a // session that already has a running turn rejects BackendBusyError; a NEW // turn (no sessionId yet) gets a unique placeholder key, so two concurrent // new-session turns always coexist. The slot is re-keyed to the real session // id once the SDK reports it. - const activeTurns = new Map(); - const fileVersionsBySession = new Map(); - const queryFn = options.backend.queryFn ?? query; + activeTurns: Map; + fileVersionsBySession: Map; + queryFn: typeof query; +} + +/** A turn that holds its session's slot and passed admission. */ +interface ClaimedTurn { + req: StartTurnRequest; + turn: RunningTurn; + /** The slot's key: a placeholder for a new session until the SDK reports its id. */ + key: string; + /** The turn's own prompt, set once the SDK turn is built; the input pulls it then. */ + prompt: { value?: string | AsyncIterable }; + input: TurnInput; + abortController: AbortController; + onHostAbort: () => void; + workerHost: Awaited>; + profile: InferenceProfile; + turnLock: TurnLockBinding; + turnEnvironment: ReturnType | undefined; + observationStorage: { directory: string; brainPath: string } | undefined; + fileVersions: NativeFileVersions | undefined; +} + +export function createClaudeTurnRunner(options: ClaudeTurnRunnerOptions): ClaudeTurnRunner { + const runner: TurnRunnerState = { + options, + activeTurns: new Map(), + fileVersionsBySession: new Map(), + queryFn: options.backend.queryFn ?? query, + }; async function followUp(req: FollowUpRequest): Promise { // Keyed by the real session id only once the SDK reported it, which is // also when the host first learns it: a placeholder key never matches. - const turn = activeTurns.get(req.sessionId); + const turn = runner.activeTurns.get(req.sessionId); if (!turn?.input?.push(req.prompt, req.attachments)) { throw new BackendRequestError( `No running turn for session ${req.sessionId} to deliver a follow-up to.` @@ -116,768 +106,265 @@ export function createClaudeTurnRunner(options: { } } - async function startTurn(req: StartTurnRequest): Promise { - // Before anything is claimed or emitted: a refused posture rejects, per - // the startTurn contract, and leaves no turn behind. - assertTurnPosture(req, true, true); - if (req.sessionId !== undefined && activeTurns.has(req.sessionId)) { - throw new BackendBusyError(BACKEND_ID, req.sessionId); - } + return { startTurn: (req) => startTurn(runner, req), followUp }; +} - // The session is claimed the moment startTurn is called (#1063): a live - // follow-up offered meanwhile joins this turn's input, which is held until - // the SDK first pulls the turn's own prompt. Only then is the per-turn - // host probe awaited, so the event loop keeps answering while a loaded - // host starts its worker (#2790). Its refusal, or the profile's, rejects - // and takes the claim back, leaving no turn behind. - const turn: RunningTurn = { pendingReleases: new Map(), ended: false }; - // Placeholder key for a new session; the real id (a resume's requested id, - // or the SDK-minted id for a new session) replaces it below. - let turnKey = req.sessionId ?? `new:${crypto.randomUUID()}`; - let sdkPrompt: string | AsyncIterable | undefined; - const input = createTurnInput(() => { - if (sdkPrompt === undefined) throw new Error("The turn's prompt was pulled before it was prepared."); - return sdkPrompt; - }); - if (!req.autonomous) turn.input = input; - activeTurns.set(turnKey, turn); +async function startTurn(runner: TurnRunnerState, req: StartTurnRequest): Promise { + const { options, activeTurns, fileVersionsBySession } = runner; + // Before anything is claimed or emitted: a refused posture rejects, per + // the startTurn contract, and leaves no turn behind. + assertTurnPosture(req, true, true); + if (req.sessionId !== undefined && activeTurns.has(req.sessionId)) { + throw new BackendBusyError(BACKEND_ID, req.sessionId); + } - // The host owns cancellation. Mirror its signal onto an internal - // AbortController that the SDK query listens to; from before the probe, - // so a cancel accepted while it runs still stops the turn. - const abortController = new AbortController(); - const onHostAbort = () => abortController.abort(); - if (req.signal.aborted) abortController.abort(); - else req.signal.addEventListener("abort", onHostAbort, { once: true }); + // The session is claimed the moment startTurn is called (#1063): a live + // follow-up offered meanwhile joins this turn's input, which is held until + // the SDK first pulls the turn's own prompt. Only then is the per-turn + // host probe awaited, so the event loop keeps answering while a loaded + // host starts its worker (#2790). Its refusal, or the profile's, rejects + // and takes the claim back, leaving no turn behind. + const turn: RunningTurn = { pendingReleases: new Map(), ended: false }; + // Placeholder key for a new session; the real id (a resume's requested id, + // or the SDK-minted id for a new session) replaces it once reported. + const turnKey = req.sessionId ?? `new:${crypto.randomUUID()}`; + const prompt: ClaimedTurn["prompt"] = {}; + const input = createTurnInput(() => { + if (prompt.value === undefined) throw new Error("The turn's prompt was pulled before it was prepared."); + return prompt.value; + }); + if (!req.autonomous) turn.input = input; + activeTurns.set(turnKey, turn); - // Everything up to here preceded the claim before it moved forward; a - // refusal anywhere in it takes the claim back. - let workerHost: Awaited>; - let profile: InferenceProfile; - let turnLock: ReturnType | undefined; - let turnEnvironment: ReturnType | undefined; - let observationStorage: { directory: string; brainPath: string } | undefined; - let fileVersions: NativeFileVersions | undefined; - let yielded = false; - try { - workerHost = await requireWorkerHostAsync(options.backend.brainPath); - profile = resolveProfile(options.resolveProfiles(), req.profileId); - turnLock = createTurnLockBinding({ - turn, - writeLock: req.workerLock ?? options.writeLock, - lockWaitMs: options.lockWaitMs, - log: options.log, - admission: { - signal: abortController.signal, - priority: req.autonomous ? "autonomous" : "interactive", - yieldAfterMs: req.autonomous?.yieldAfterMs, - onYield: req.autonomous?.onYield ? (key) => { - if (yielded || abortController.signal.aborted) return; - yielded = true; - try { req.autonomous!.onYield!(key); } - catch { req.bridge.emit({ type: "error", code: "AUTONOMOUS_YIELD_FAILED", message: "Autonomous yield checkpoint failed." }); } - finally { abortController.abort(); } - } : undefined, - }, - }); - turnEnvironment = req.autonomous ? undefined : turnEnv(profile); - observationStorage = !req.autonomous && existsSync(options.backend.brainPath) - ? { directory: join(transcriptPaths(options.backend.brainPath, turnEnvironment).archive, "native-observations"), brainPath: options.backend.brainPath } - : undefined; - fileVersions = req.autonomous ? undefined : fileVersionsBySession.get(turnKey) - ?? (req.sessionId && observationStorage ? await NativeFileVersions.restore({ ...observationStorage, sessionId: req.sessionId }) : new NativeFileVersions()); - if (fileVersions) fileVersionsBySession.set(turnKey, fileVersions); - } catch (error) { - req.signal.removeEventListener("abort", onHostAbort); - input.close(); - turnLock?.close(); - activeTurns.delete(turnKey); - throw error; - } + // The host owns cancellation. Mirror its signal onto an internal + // AbortController that the SDK query listens to; from before the probe, + // so a cancel accepted while it runs still stops the turn. + const abortController = new AbortController(); + const onHostAbort = () => abortController.abort(); + if (req.signal.aborted) abortController.abort(); + else req.signal.addEventListener("abort", onHostAbort, { once: true }); - const adapter = new StreamAdapter(req.bridge.activity, { - subscriptionAuth: profile.billing !== "api", - autonomousUsage: req.autonomous?.containment === "restricted", - freshRuntimeUsage: req.autonomous?.persistence === "none" && req.sessionId === undefined, + // Everything up to here preceded the claim before it moved forward; a + // refusal anywhere in it takes the claim back. + let workerHost: Awaited>; + let profile: InferenceProfile; + let turnLock: TurnLockBinding | undefined; + let turnEnvironment: ReturnType | undefined; + let observationStorage: { directory: string; brainPath: string } | undefined; + let fileVersions: NativeFileVersions | undefined; + let yielded = false; + try { + workerHost = await requireWorkerHostAsync(options.backend.brainPath); + profile = resolveProfile(options.resolveProfiles(), req.profileId); + turnLock = createTurnLockBinding({ + turn, + writeLock: req.workerLock ?? options.writeLock, + lockWaitMs: options.lockWaitMs, + log: options.log, + admission: { + signal: abortController.signal, + priority: req.autonomous ? "autonomous" : "interactive", + yieldAfterMs: req.autonomous?.yieldAfterMs, + onYield: req.autonomous?.onYield ? (key) => { + if (yielded || abortController.signal.aborted) return; + yielded = true; + try { req.autonomous!.onYield!(key); } + catch { req.bridge.emit({ type: "error", code: "AUTONOMOUS_YIELD_FAILED", message: "Autonomous yield checkpoint failed." }); } + finally { abortController.abort(); } + } : undefined, + }, }); - const reportActivity = (event: BackendActivityEvent): void => { - try { - req.bridge.activity?.(event); - } catch { - // Observability must not break the observed turn. - } - }; - /** - * What ran, the credential it selected, and whether that honours the - * profile (#211). Checked against the profile's POLICY — a profile without - * its own credential requires the subscription — not against - * `classifyBilling`, since the two could regress together. - */ - const reportRuntime = ( - claudeCodeVersion: string | undefined, - apiKeySource: string | undefined, - selected: AccountInfo | undefined - ): void => { - const billing = observedBilling(selected, apiKeySource); - const policy = profile.billing === "api" ? "api" : "subscription"; - const agentSdk = installedAgentSdkVersion(); - // Any disagreement: a declared API profile that ran on something else - // lost its own credential, and the CLI picked another one. - const policyViolation = - billing === policy - ? undefined - : `${policy === "api" ? "a profile declared as API-billed" : "a profile without its own credential"} ran on ${ - billing === "api" - ? "an API credential" - : billing === "subscription" - ? "a subscription" - : "a credential that is not a recognised subscription" - }`; - if (policyViolation) { - options.log("warn", "billing policy violated", { - "profile.id": profile.id, - "billing.observed": billing, - reason: policyViolation, - }); - } - reportActivity({ - kind: "runtime_observed", - ...(claudeCodeVersion ? { runtime: { name: "claude-code", version: claudeCodeVersion } } : {}), - sdk: { name: "@anthropic-ai/claude-agent-sdk", version: agentSdk }, - credential: credentialFields(selected, apiKeySource), - billing, - policy, - ...(policyViolation ? { policyViolation } : {}), - measured: isMeasuredRuntime(claudeCodeVersion, agentSdk), - }); - }; - // Scope every frame to its session once the identity is known. For a - // resume that is up front (the requested id); for a new session it is null - // until the SDK reports it, so the only pre-identity frames (status/ - // thinking) go out unscoped, then everything after is scoped. result and - // session_info already carry their own sessionId; the spread is a no-op on - // them. - let sessionId: string | null = req.sessionId ?? null; - let workerStateRoom: (() => StateRoomObservation | undefined) | undefined; - const emit = (msg: ServerMessage): void => { - const observation = msg.type === "result" - && !["worker_state_busy", "session_too_large", "worker_state_exceeded"].includes(msg.failure?.errorClass ?? "") - ? workerStateRoom?.() : undefined; - if (msg.type === "result" && observation) msg = { ...msg, stateRoom: observation }; - // The cast is safe: backends never emit the (unscoped) server_hello - // frame, and every other ServerMessage accepts a sessionId. - req.bridge.emit(sessionId !== null ? ({ ...msg, sessionId } as ServerMessage) : msg); - }; - const startedAt = Date.now(); - // Hoisted: the catch/finally paths must know whether the stream already - // produced its terminal result — a stream that yields a result and THEN - // throws must not get a second one. - let sawResult = false; - /** Bounds how long a held result waits for a follow-up's read report. */ - let ackGraceTimer: ReturnType | undefined; - let archiveEnv: Record | undefined; - let finishWorker: (() => Promise) | undefined; - let hostRelay: InferenceRelay | undefined; - let hostRelayLink: string | undefined; - let hostRelayAuthorized = false; - let relayBaseUrl = "http://localhost"; - let routeInputs: Awaited> | undefined; - let workerFailure: (() => TurnFailure | undefined) | undefined; - let workerStartFailure: (() => unknown) | undefined; - /** - * A worker whose runtime state refused or stopped the turn (#1625) ends it - * with that named class rather than the runtime's own error. - */ - /** - * The runtime reports its outcome even when its transcript writes failed - * on a full runtime-state tmpfs, and that output is then not saved - * (#1625). So the state is checked when the result arrives, the terminal - * result waits for the worker to exit and its state to be copied out, and - * a state found full at either point names the turn - * `worker_state_exceeded`. A refused copy-out names it - * `worker_state_save_refused`, keeping its usage. A host cancellation still - * outranks it. - */ - const unsaved = (result: Extract): Extract => { - if (result.outcome === "cancelled" || abortController.signal.aborted) return result; - const failure = workerFailure?.(); - if (failure?.errorClass !== FIRST_PARTY_FAILURE_CLASSES.worker_state_exceeded - && failure?.errorClass !== FIRST_PARTY_FAILURE_CLASSES.worker_state_save_refused) return result; - emit({ type: "error", code: "CLAUDE_ERROR", message: failure.message }); - return { ...result, outcome: "error", isError: true, failure }; - }; - /** The turn's terminal result, held until the worker has exited. */ - let terminal: Extract | undefined; - let terminalSent = false; - const releaseTerminal = async (): Promise => { - if (!terminal || terminalSent) return; - terminalSent = true; - // The worker's exit and copy-out must settle before the terminal frame. - await finishWorker?.().catch(() => {}); - // Cancellation can arrive after the SDK result, including while exit or - // copy-out is pending. Keep its accounting, but discard error-only fields. - // A startup refusal's own internal abort must remain a refusal. - if (wasCancelled()) { - const { failure: _failure, outcomeDetail: _detail, ...retained } = terminal; - emit({ type: "status", status: "cancelled" }); - emit({ ...retained, outcome: "cancelled", isError: false }); - } else emit(unsaved(terminal)); - }; - const workerRefusal = (): boolean => { - const failure = refused ? undefined : workerFailure?.(); - if (failure) refused = { code: "CLAUDE_ERROR", message: failure.message, failure }; - return Boolean(refused); - }; - /** - * The host resource limits the turn's worker hit (#1660). Each new hit is - * reported next to the tool step that caused it; a limit that ended the - * worker becomes the turn's failure, with the limit named. - */ - let workerLimits: { current(): WorkerLimitReport; settled(): Promise } | undefined; - /** The answer as it streams, for the turn-temp purge's linked-file guard (#1703). */ - let observeAnswerText: ((text: string) => void) | undefined; - const freshLimitHits = createLimitTracker(); - const reportLimitHits = (report: WorkerLimitReport): void => { - const fresh = freshLimitHits(report); - if (fresh.length) reportActivity({ kind: "resource_limit", limits: fresh, fatal: false }); - }; - const limitFailure = async (): Promise<{ code: string; message: string; failure: TurnFailure } | null> => { - if (!workerLimits) return null; - const report = await workerLimits.settled(); - if (!report.fatal) { reportLimitHits(report); return null; } - reportActivity({ kind: "resource_limit", limits: report.hits, fatal: true }); - const message = limitFailureMessage(report.hits); - return { code: "WORKER_RESOURCE_LIMIT", message, - failure: { errorClass: FIRST_PARTY_FAILURE_CLASSES.worker_resource_limit, message } }; - }; - /** - * Set when the subscription check refused the turn before its prompt was - * released. It outranks the abort it causes: the turn failed, it was not - * cancelled. - */ - let refused: { code: string; message: string; failure?: TurnFailure } | null = null; - /** - * The gate decided not to release the prompt, for whatever reason. Once - * set, nothing the stream says afterwards can turn the turn into a success. - */ - let withheld = false; - const wasCancelled = (): boolean => req.signal.aborted || (!refused && abortController.signal.aborted); - const phase = req.sessionId === undefined ? "start before prompt release" : "resume before prompt release"; - const runtimeRequirements = claudeRuntimeRequirements(options.backend.versionRequirements, phase, profile.model); - let probedVersion: string | undefined; - /** - * Unified terminal frame for cancelled/failed turns. With a session - * identity that is a `result`; WITHOUT one (an abort or failure before - * the SDK reported a session) the contract's terminal is a bare `error`, - * so a client keying on result/error is never left hanging. - */ - const emitTerminal = async (outcome: "error" | "cancelled", diagnostic?: { code: string; message: string }): Promise => { - if (sawResult) return; - sawResult = true; - // Generated terminals obey the same cleanup boundary as SDK results. - await finishWorker?.().catch(() => {}); - if (wasCancelled()) outcome = "cancelled"; - if (outcome === "cancelled") emit({ type: "status", status: "cancelled" }); - const reason = refused ?? diagnostic; - if (sessionId === null) { - emit( - reason && outcome === "error" - ? { type: "error", ...reason } - : { - type: "error", - code: outcome === "cancelled" ? "CANCELLED" : "CLAUDE_ERROR", - message: - outcome === "cancelled" - ? "Turn cancelled before the session was established" - : "Turn failed before the session was established", - } - ); - return; - } - // The failure rides the terminal frame only, so a client never reports - // it twice: here that is the result, not the diagnostic error. - const failure = refused?.failure ?? adapter.pendingFailure() ?? undefined; - if (reason && outcome === "error") emit({ type: "error", code: reason.code, message: reason.message }); - // costUsd deliberately absent (unknown); duration is real, numTurns 0 = - // "no completed turns" for a turn that never finished. - emit({ - type: "result", - sessionId, - outcome, - durationMs: Date.now() - startedAt, - numTurns: 0, - isError: outcome === "error", - ...(outcome === "error" && failure ? { failure } : {}), - }); - }; - - try { - // A voice turn selects the named voice posture in place of the profile's - // ordinary list (docs/decisions/voice-permission.md "The voice posture"). - const allowedTools = - req.autonomous?.allowedTools ?? - (req.posture === "voice" ? VOICE_ALLOWED_TOOLS : undefined) ?? - profile.allowedTools ?? options.backend.allowedTools ?? DEFAULT_ALLOWED_TOOLS; - const preparedEgress = !req.autonomous ? req.workerSandbox?.egress : undefined; - // An API-billed profile's own key: declared by the host together with its route. - // Only what the profile itself declares: an ambient credential never rides along. - const apiCredential = preparedEgress && profile.billing === "api" ? apiKeyRelayCredential(profile.id, profile.buildEnv()) : undefined; - const configDirectory = resolve(turnEnvironment?.CLAUDE_CONFIG_DIR || join(turnEnvironment?.HOME || homedir(), ".claude")); - const hostLogin = preparedEgress ? hostLoginFile(configDirectory, options.backend.brainPath) : undefined; - // The server selects the route: the profile's baseUrl, else the host's - // ANTHROPIC_BASE_URL. Only the host's explicit list authorizes a custom - // origin to receive the login (docs/decisions/claude-code-runtime.md). - const selectedUpstream = selectedInferenceUpstream(turnEnvironment); - // Provider folders admitted for a proven recipient (#2695): only its relay may carry this turn. - const recipient = !req.autonomous ? req.workerSandbox?.inferenceRecipient : undefined; - if (recipient && !preparedEgress) throw new BackendRequestError("This turn's provider folders were admitted for a recipient, but it has no inference relay to hold it to."); - const authorizedOrigins = resolveEnv().claudeOAuthOrigins; - if (preparedEgress) { - hostRelay = startInferenceRelay({ upstream: selectedUpstream, routes: ANTHROPIC_INFERENCE_ROUTES, egress: preparedEgress, - ...(recipient ? { recipientOrigin: recipient.origin } : {}), - credentials: async (signal, target) => { - if (!hostRelayAuthorized) throw new Error("Native inference has not passed its prompt gate"); - routeInputs?.assertUnchanged(); - if (apiCredential) return apiCredential.headers; - return { authorization: (await resolveClaudeHostOAuth(configDirectory, turnEnvironment ?? {}, { origin: target.origin, authorizedOrigins }, signal)).authorization }; - }, - }); - relayBaseUrl = `http://localhost${new URL(selectedUpstream).pathname.replace(/\/+$/, "")}`; - hostRelayLink = join(preparedEgress.dir, "inference.sock"); - linkSync(hostRelay.socketPath, hostRelayLink); - } - // A host without governed turns supplies no sandbox: Claude's own is - // awaited here, from the inputs its options would have used (#2796). - const own = await prepareClaudeTurnSandbox({ backend: options.backend, req, profile, turnEnvironment }); - const sdkTurn = createClaudeSdkTurn({ - ...(preparedEgress ? { hostInference: { proxyDir: preparedEgress.dir, baseUrl: relayBaseUrl, - ...(apiCredential ? { placeholders: apiCredential.placeholders } : {}) } } : {}), - backend: options.backend, - ...(workerHost?.identity === "separate_uid" && workerHost.workerUid !== undefined ? { identity: { kind: "separate_uid" as const, workerUid: workerHost.workerUid } } : {}), - turnEnvironment: own?.turnEnvironment ?? turnEnvironment, - fileVersions, - req: { ...req, signal: abortController.signal, ...(own ? { workerSandbox: own.workerSandbox } : {}), ...(preparedEgress && req.workerSandbox ? { workerSandbox: { ...req.workerSandbox, - // The relay holds the login: hide the host's file wherever the host masks do not. - maskPaths: [...req.workerSandbox.maskPaths ?? [], ...hostLogin?.mask ?? []] } } : {}) }, - profile, - abortController, - allowedTools, - confirmPatterns: options.confirmPatterns, - turnLock, - log: options.log, - }); - finishWorker = sdkTurn.finishWorker; - workerFailure = sdkTurn.workerFailure; - workerStartFailure = sdkTurn.workerStartFailure; - workerStateRoom = sdkTurn.workerStateRoom; - archiveEnv = sdkTurn.options.env; - workerLimits = sdkTurn.workerLimits; - observeAnswerText = sdkTurn.observeAnswerText; - // Always a stream that stays open, so follow-ups can join the turn. - sdkPrompt = sdkTurn.prompt; - if (runtimeRequirements.length) { - // Replaceable overrides are probed anew for BOTH new and resumed turns, - // before query() sees any user input. Capture uses the SDK's resolver. - const report = await probeClaudeRuntime({ - brainPath: options.backend.brainPath, - ...(options.backend.claudeCodePath !== undefined ? { claudeCodePath: options.backend.claudeCodePath } : {}), - env: sdkTurn.options.env ?? {}, exec: options.backend.exec ?? ambientExecConfig(), - versionRequirements: options.backend.versionRequirements, phase, - signal: abortController.signal, log: options.log, - }); - probedVersion = report.runtime.version; - assertClaudeRuntime(probedVersion, runtimeRequirements, phase); - abortController.signal.throwIfAborted(); - } - let initialization: ReturnType | undefined; - const initialize = (cli: Query) => initialization ??= Promise.resolve().then(() => cli.initializationResult()); - // Subscription policy and constrained runtime startup are checked INSIDE - // the prompt iterable, exactly when the SDK asks for the first message. - // The earlier version probe identifies the selected executable; this gate - // waits for initialization before any user input can reach the model. - let resolveQuery!: (value: Query) => void; - const queryHandle = new Promise((resolve) => { - resolveQuery = resolve; - }); - const prompt = sdkTurn.subscriptionOnly || preparedEgress || runtimeRequirements.length > 0 - ? gatedPrompt(input.messages, async () => { - const withhold = (): false => { - withheld = true; - abortController.abort(); - return false; - }; - const refuseSubscription = (reason: string): false => { - const message = subscriptionRefusalMessage(reason); - refused = { - code: "CLAUDE_AUTH", - message, - failure: { - errorClass: FIRST_PARTY_FAILURE_CLASSES.subscription_required, - message, - authAction: subscriptionAuthAction("subscription_required"), - }, - }; - reportActivity({ kind: "auth_failure", errorClass: FIRST_PARTY_FAILURE_CLASSES.subscription_required, message: reason }); - options.log("warn", "subscription check refused the turn", { - "profile.id": profile.id, - reason, - }); - return withhold(); - }; - const refuseTransport = (reason: string): false => { - const message = `Claude inference transport refused: ${reason}.`; - refused = { code: "CLAUDE_ERROR", message, failure: { errorClass: FIRST_PARTY_FAILURE_CLASSES.auth_failure, message } }; - reportActivity({ kind: "auth_failure", errorClass: FIRST_PARTY_FAILURE_CLASSES.auth_failure, message: reason }); - options.log("warn", "inference transport check refused the turn", { "profile.id": profile.id, reason }); - return withhold(); - }; - const cli = await queryHandle; - let account: AccountInfo | undefined; - let settings: CliSettingsReport | undefined; - try { - const check = async () => { - account = (await initialize(cli)).account; - if (!sdkTurn.subscriptionOnly && !preparedEgress) return; - // Not on the public Query type; the SDK sends the CLI's own - // `get_settings` control request. Absent means unreadable, - // which refuses below. - const getSettings = (cli as { getSettings?: () => Promise }).getSettings; - settings = getSettings ? await getSettings.call(cli) : undefined; - }; - if (runtimeRequirements.length) await startupDeadline(check(), abortController.signal); - else await check(); - } catch (error) { - // A handshake the host cancelled is a cancelled turn, not a failed one. - if (abortController.signal.aborted) return withhold(); - refused = { - code: "CLAUDE_ERROR", - message: `@schlessera/brain-backend-claude runtime (claude-code) during ${phase}; requirements: ${runtimeRequirements.map(req => `${req.owner} minimum ${req.declaration}`).join("; ") || "subscription handshake"}; detected startup unknown. Claude Code did not complete its handshake: ${error instanceof Error ? error.message : String(error)}. Install/select a compatible executable that completes SDK initialization.`, - }; - return withhold(); - } - if (abortController.signal.aborted) return withhold(); - if (sdkTurn.subscriptionOnly) { - const verdict = subscriptionVerdict(account); - const conflict = verdict.ok ? settingsRefusal(settings, sdkTurn.pinnedSettingsEnv) : null; - if (!verdict.ok || conflict) { - // The CLI never reaches init, so this is the only report the - // refused turn gets: what the handshake said it would bill. - reportRuntime(undefined, account?.apiKeySource, account); - return refuseSubscription(verdict.ok ? conflict! : verdict.reason); - } - } - if (preparedEgress) { - // An API-billed turn is not a subscription refusal: name the transport instead. - const refuse = sdkTurn.subscriptionOnly ? refuseSubscription : refuseTransport; - // The server's route must be authorized for the host login, and - // native settings may repeat that route but never replace it. - try { routeInputs?.assertUnchanged(); } - catch { return refuse("native inference settings changed during startup"); } - if (!Array.isArray(settings?.sources) || settings.sources.some(source => !["projectSettings", "flagSettings", "policySettings"].includes(source.source ?? ""))) { - return refuse("the native inference settings sources are not qualified for this prepared transport"); - } - if (hostLogin?.inBrain) return refuse("the host's Claude login is inside the brain, where the worker can read it; move the Claude config directory out of the brain"); - // A settings credential or helper would stand in for the relay's placeholder. - const credentialConflict = sdkTurn.subscriptionOnly ? null : settingsRefusal(settings, sdkTurn.pinnedSettingsEnv); - if (credentialConflict) return refuse(credentialConflict); - try { if (!apiCredential) authorizeDestination({ origin: new URL(selectedUpstream).origin, authorizedOrigins }); } - catch { return refuse("the selected inference origin is not authorized to receive the host Claude login; list its exact origin in BRAIN_UI_CLAUDE_OAUTH_ORIGINS"); } - for (const source of settings?.sources ?? []) { - const value = source.settings?.env?.ANTHROPIC_BASE_URL; - // Native settings may repeat the server's route, never replace it. - if (value !== undefined && value !== "" && !(source.source === "flagSettings" && value === relayBaseUrl) && !sameRoute(value, selectedUpstream)) { - return refuse("the native inference source selects a destination not qualified for this prepared transport"); - } - } - if (settings?.effective?.env?.ANTHROPIC_BASE_URL !== relayBaseUrl) { - return refuse("native settings refused the prepared inference transport"); - } - hostRelayAuthorized = true; - } - return true; - }) - : input.messages; - routeInputs = preparedEgress ? await retainNativeRouteInputs(req.workerSandbox?.profile === "governed" - ? options.backend.brainPath : req.workerStartupView ?? options.backend.brainPath) : undefined; - const result = queryFn({ prompt, options: { ...sdkTurn.options, ...(req.maxBudgetUsd !== undefined ? { maxBudgetUsd: req.maxBudgetUsd } : {}) } }); - resolveQuery(result); - // The account the CLI selected, for the per-turn report below. The SDK - // answers every call from the one handshake, so this and the gate agree. - const account = ( - typeof result.initializationResult === "function" - ? initialize(result).then((init) => init.account, () => undefined) - : Promise.resolve(undefined) - ) as Promise; - - let announced = false; - let reported = false; - /** - * A `result` that follow-ups outlived (#1003): the CLI runs them as - * continuation turns of the same process, so the one frame the client - * gets is built from the LAST result, with the per-run counts of the - * earlier ones added. The adapter tracks completed-response receipts across - * these continuations; session-cumulative SDK totals are evidence only. - */ - let carried: { - numTurns: number; - durationMs: number; - frames: ServerMessage[]; - /** The continuation began: the held result no longer describes the turn. */ - continued: boolean; - } | null = null; - const carry = (frames: ServerMessage[]): ServerMessage[] => { - if (!carried) return frames; - const earlier = carried; - return frames.map((frame) => - frame.type === "result" - ? { ...frame, numTurns: frame.numTurns + earlier.numTurns, durationMs: frame.durationMs + earlier.durationMs } - : frame - ); - }; - for await (const msg of result) { - input.observe(msg); - if (carried && (msg.type === "assistant" || msg.type === "user" || msg.type === "stream_event" - || (msg.type === "system" && msg.subtype === "init"))) { - carried.continued = true; - } - // A withheld turn has already decided its outcome; nothing the stream - // does after that may replace it. - if (withheld) break; - // Emit session_info as soon as the session identity is known, before - // any content frames (contract requirement). - if (!announced && msg.session_id) { - announced = true; - if (sessionId === null) { - // New session: adopt the SDK-minted id for scoping and re-key the - // busy slot from its placeholder, so a resume of this session while - // it still runs is detected as busy. - sessionId = msg.session_id; - // Saved off the event loop (#2416) and queued before any tool's - // observation save, which each native tool awaits. A failure - // refuses native writes until a later save succeeds. - if (fileVersions && observationStorage) fileVersions.retain({ ...observationStorage, sessionId }) - .catch(error => options.log("warn", "Claude native file observations could not be retained", { error: String(error) })); - if (fileVersions) { fileVersionsBySession.delete(turnKey); fileVersionsBySession.set(sessionId, fileVersions); } - activeTurns.delete(turnKey); - activeTurns.set(sessionId, turn); - turnKey = sessionId; - } - if (req.autonomous) { - reportActivity({ kind: "autonomous_identity", runtimeSessionId: sessionId, - backendId: BACKEND_ID, profileId: profile.id }); - } else { - emit({ type: "session_info", sessionId, isNew: !req.sessionId, - providerId: profile.id, backendId: BACKEND_ID }); - } - } - // After session_info, so the run is opened with its session. - if (msg.type === "system" && msg.subtype === "init") { - // Every continuation turn re-announces init; the run is reported once. - if (!reported) reportRuntime(msg.claude_code_version, msg.apiKeySource, await account); - reported = true; - if (runtimeRequirements.length) { - try { - assertClaudeRuntime(msg.claude_code_version ?? null, runtimeRequirements, "system/init observation", "running CLI did not report its version"); - if (msg.claude_code_version !== probedVersion) throw new Error(`@schlessera/brain-backend-claude runtime (claude-code) during system/init observation; required probed identity ${probedVersion}; detected ${msg.claude_code_version}. The executable changed after verification; select an immutable compatible executable and retry.`); - } catch (error) { - refused = { code: "CLAUDE_ERROR", message: error instanceof Error ? error.message : String(error) }; - withheld = true; - abortController.abort(); - break; - } - } - } - let frames = adapter.adapt(msg); - if (msg.type === "result") { - const { continues, unacknowledged } = input.settle(); - if (continues && !sawResult) { - // Not the turn's last: hold it, in case no continuation comes. - const held = carry(frames); - const final = held.find((frame) => frame.type === "result"); - if (final?.type === "result") { - carried = { numTurns: final.numTurns, durationMs: final.durationMs, frames: held, continued: false }; - } - // A follow-up the CLI has not reported reading may come from a - // runtime that does not report it at all, and would then wait for - // input forever. Closing is safe: what was pushed is still written, - // and the CLI drains it before it exits. It waits a moment first, - // because closing also refuses any later follow-up of this turn. - if (unacknowledged) { - clearTimeout(ackGraceTimer); - ackGraceTimer = setTimeout(() => { - if (input.unacknowledged()) input.close(); - }, FOLLOW_UP_ACK_GRACE_MS); - } - continue; - } - input.close(); - frames = carry(frames); - carried = null; - } - for (const serverMsg of frames) { - // Exactly one terminal frame per turn, whatever the stream does: - // a second SDK result is dropped rather than forwarded. - if (serverMsg.type === "result") { - if (sawResult) continue; - sawResult = true; - terminal = serverMsg; - // Checked now and again at exit: the runtime may free space as it exits. - workerFailure?.(); - continue; - } - // Release the write lock the moment a mutating tool's result frame - // lands (the turn-end backstop covers anything still held). - if (serverMsg.type === "tool_result") { - turnLock.releaseForTool(serverMsg.toolUseId); - if (workerLimits) reportLimitHits(workerLimits.current()); - } - if (serverMsg.type === "text_delta") observeAnswerText?.(serverMsg.text); - emit(serverMsg); - } - } - - // A held result is the turn's terminal frame only if no continuation - // began. One that began and ended without its own result is an abnormal - // end, reported below like any other. - if (carried && !carried.continued && !sawResult && !withheld && !abortController.signal.aborted) { - for (const serverMsg of carried.frames) { - if (serverMsg.type === "result") { sawResult = true; terminal = serverMsg; workerFailure?.(); continue; } - emit(serverMsg); - } - } - await releaseTerminal(); - // A worker that never started ends the turn with its own error (#2790). - if (!sawResult && workerStartFailure?.() !== undefined) throw workerStartFailure(); - // Stream ended without its terminal result: aborted → cancelled; not - // aborted → an abnormal end the client must still be released from. - if (!sawResult && !refused && !abortController.signal.aborted) refused = await limitFailure(); - else if (workerLimits) reportLimitHits(workerLimits.current()); - if (!sawResult) { - // A host cancellation keeps outranking a state failure found meanwhile. - if (refused) { - await emitTerminal("error"); - } else if (abortController.signal.aborted) { - await emitTerminal("cancelled"); - } else if (workerRefusal()) { - await emitTerminal("error"); - } else { - await emitTerminal("error", { - code: "CLAUDE_NO_RESULT", - message: "Backend stream ended without a result", - }); - } - } - } catch (caught) { - // The SDK reports a worker's deferred start failure as its own process - // error; the worker's error names the turn, as when its spawn threw it (#2790). - const err = workerStartFailure?.() ?? caught; - // error/cancelled frames are diagnostics; the terminal frame is the - // result with an outcome (for turns that have a session identity — a - // turn that died before any session id ends on the bare error). - // emitTerminal itself no-ops when the stream already delivered its - // result before throwing. Diagnostics only make sense BEFORE the - // terminal frame; when the stream already delivered its result, the turn - // is over and nothing may follow it. - // A worker ended by a host limit fails the turn with that limit named (#1660). - if (!sawResult && !refused && !abortController.signal.aborted) refused = await limitFailure().catch(() => null); - if (sawResult) { - // Terminal frame already decided — swallow the late failure. - await releaseTerminal(); - } else if (refused) { - await emitTerminal("error"); - } else if (abortController.signal.aborted) { - await emitTerminal("cancelled"); - } else if (workerRefusal()) { - await emitTerminal("error"); - } else { - let diagnostic: { code: string; message: string } | undefined; - const stateClass = workerStateClass(err); - if (err instanceof WorkerHostError || err instanceof SessionTooLargeError || stateClass) { - const { message } = err as Error; - refused = { code: "CLAUDE_ERROR", message, - failure: { errorClass: stateClass ?? (err as WorkerHostError | SessionTooLargeError).errorClass, message } }; - } else { - diagnostic = { code: "CLAUDE_ERROR", message: err instanceof Error ? err.message : String(err) }; - } - await emitTerminal("error", diagnostic); - } - } finally { - // A failed cleanup cannot strand the other owned resources or busy slot. - await cleanupTurn([ - () => finishWorker?.(), - () => routeInputs?.close(), - () => hostRelay?.stop(), - () => { if (hostRelayLink) rmSync(hostRelayLink, { force: true }); }, - () => clearTimeout(ackGraceTimer), - // Every turn's input, autonomous or not, so cleanup always ends it. - () => input.close(), - () => req.signal.removeEventListener("abort", onHostAbort), - // The new session's retain is not awaited where it is queued; the - // turn still settles only after every observation save has. - () => fileVersions?.settled(), - () => fileVersions?.cancelPending(), - () => { if (!sessionId) fileVersionsBySession.delete(turnKey); }, - () => turnLock.close(), - () => activeTurns.delete(turnKey), - () => req.autonomous ? undefined : archiveIdleSessions({ - brainPath: options.backend.brainPath, env: archiveEnv, - listSessionsFn: options.backend.listSessionsFn, - activeSessionIds: () => new Set(activeTurns.keys()), - log: (message, error) => options.log("warn", message, { error: String(error) }), - }), - ]); - } + turnEnvironment = req.autonomous ? undefined : turnEnv(profile); + observationStorage = !req.autonomous && existsSync(options.backend.brainPath) + ? { directory: join(transcriptPaths(options.backend.brainPath, turnEnvironment).archive, "native-observations"), brainPath: options.backend.brainPath } + : undefined; + fileVersions = req.autonomous ? undefined : fileVersionsBySession.get(turnKey) + ?? (req.sessionId && observationStorage ? await NativeFileVersions.restore({ ...observationStorage, sessionId: req.sessionId }) : new NativeFileVersions()); + if (fileVersions) fileVersionsBySession.set(turnKey, fileVersions); + } catch (error) { + req.signal.removeEventListener("abort", onHostAbort); + input.close(); + turnLock?.close(); + activeTurns.delete(turnKey); + throw error; } - return { startTurn, followUp }; + // Called, not scheduled: the admitted turn continues in this same task. + await runAdmittedTurn(runner, { req, turn, key: turnKey, prompt, input, abortController, onHostAbort, + workerHost, profile, turnLock, turnEnvironment, observationStorage, fileVersions }); } -async function cleanupTurn(actions: Array<() => unknown>): Promise { - const failures: unknown[] = []; - for (const action of actions) { try { await action(); } catch (error) { failures.push(error); } } - if (failures.length) throw new AggregateError(failures, "Claude turn cleanup did not complete"); -} +/** Run an admitted turn to its one terminal frame, then release everything it owns. */ +async function runAdmittedTurn(runner: TurnRunnerState, claim: ClaimedTurn): Promise { + const { options } = runner; + const { req, profile, abortController, input } = claim; + const adapter = new StreamAdapter(req.bridge.activity, { + subscriptionAuth: profile.billing !== "api", + autonomousUsage: req.autonomous?.containment === "restricted", + freshRuntimeUsage: req.autonomous?.persistence === "none" && req.sessionId === undefined, + }); + const reportActivity = turnActivityReporter(req.bridge); + const reportRuntime = (claudeCodeVersion: string | undefined, apiKeySource: string | undefined, selected: AccountInfo | undefined): void => + reportTurnRuntime({ profile, log: options.log, reportActivity }, claudeCodeVersion, apiKeySource, selected); + const frames = new TurnFrames(req.bridge, req.sessionId ?? null); + const terminal = new TurnTerminal({ frames, hostSignal: req.signal, abortController, startedAt: Date.now(), + pendingFailure: () => adapter.pendingFailure() }); + const limits = new WorkerLimitReporter(reportActivity); + const ackGrace: { timer?: ReturnType } = {}; + let archiveEnv: Record | undefined; + let relay: TurnInferenceRelay | undefined; + const phase = req.sessionId === undefined ? "start before prompt release" : "resume before prompt release"; + const runtimeRequirements = claudeRuntimeRequirements(options.backend.versionRequirements, phase, profile.model); -/** Startup settlement is bounded even if an injected/older SDK ignores abort. */ -async function startupDeadline(operation: Promise, signal: AbortSignal): Promise { - let timer: ReturnType | undefined; - let onAbort: (() => void) | undefined; try { - return await Promise.race([ - operation, - new Promise((_resolve, reject) => { - timer = setTimeout(() => reject(new Error(`SDK startup timed out after ${VERSION_PROBE_TIMEOUT_MS / 1000} s`)), VERSION_PROBE_TIMEOUT_MS); - onAbort = () => reject(signal.reason ?? new Error("SDK startup cancelled")); - signal.addEventListener("abort", onAbort, { once: true }); - if (signal.aborted) onAbort(); - }), - ]); + relay = new TurnInferenceRelay({ req, profile, turnEnvironment: claim.turnEnvironment, brainPath: options.backend.brainPath }); + relay.start(); + // A host without governed turns supplies no sandbox: Claude's own is + // awaited here, from the inputs its options would have used (#2796). + const own = await prepareClaudeTurnSandbox({ backend: options.backend, req, profile, turnEnvironment: claim.turnEnvironment }); + const sdkTurn = buildSdkTurn(runner, claim, relay, own); + terminal.worker = { finishWorker: sdkTurn.finishWorker, workerFailure: sdkTurn.workerFailure, + workerStartFailure: sdkTurn.workerStartFailure }; + frames.stateRoom = sdkTurn.workerStateRoom; + archiveEnv = sdkTurn.options.env; + limits.limits = sdkTurn.workerLimits; + // Always a stream that stays open, so follow-ups can join the turn. + claim.prompt.value = sdkTurn.prompt; + let probedVersion: string | undefined; + if (runtimeRequirements.length) { + // Replaceable overrides are probed anew for BOTH new and resumed turns, + // before query() sees any user input. Capture uses the SDK's resolver. + const report = await probeClaudeRuntime({ + brainPath: options.backend.brainPath, + ...(options.backend.claudeCodePath !== undefined ? { claudeCodePath: options.backend.claudeCodePath } : {}), + env: sdkTurn.options.env ?? {}, exec: options.backend.exec ?? ambientExecConfig(), + versionRequirements: options.backend.versionRequirements, phase, + signal: abortController.signal, log: options.log, + }); + probedVersion = report.runtime.version; + assertClaudeRuntime(probedVersion, runtimeRequirements, phase); + abortController.signal.throwIfAborted(); + } + let initialization: ReturnType | undefined; + const initialize = (cli: Query) => initialization ??= Promise.resolve().then(() => cli.initializationResult()); + // Subscription policy and constrained runtime startup are checked INSIDE + // the prompt iterable, exactly when the SDK asks for the first message. + let resolveQuery!: (value: Query) => void; + const queryHandle = new Promise((resolve) => { + resolveQuery = resolve; + }); + const prompt = sdkTurn.subscriptionOnly || relay.egress || runtimeRequirements.length > 0 + ? gatedPrompt(input.messages, promptGateCheck({ queryHandle, initialize, sdkTurn, relay, terminal, runtimeRequirements, + phase, abortController, profileId: profile.id, log: options.log, reportActivity, reportRuntime })) + : input.messages; + relay.routeInputs = relay.egress ? await retainNativeRouteInputs(req.workerSandbox?.profile === "governed" + ? options.backend.brainPath : req.workerStartupView ?? options.backend.brainPath) : undefined; + const result = runner.queryFn({ prompt, options: { ...sdkTurn.options, ...(req.maxBudgetUsd !== undefined ? { maxBudgetUsd: req.maxBudgetUsd } : {}) } }); + resolveQuery(result); + // The account the CLI selected, for the per-turn report. The SDK answers + // every call from the one handshake, so this and the gate agree. + const account = ( + typeof result.initializationResult === "function" + ? initialize(result).then((init) => init.account, () => undefined) + : Promise.resolve(undefined) + ) as Promise; + await runTurnStream({ stream: result, input, adapter, frames, terminal, req, backendId: BACKEND_ID, profileId: profile.id, + account, reportActivity, reportRuntime, runtimeRequirements, probedVersion, turnLock: claim.turnLock, limits, + observeAnswerText: sdkTurn.observeAnswerText, abortController, ackGrace, + adoptSessionId: (sessionId) => adoptSessionId(runner, claim, sessionId) }); + } catch (caught) { + if (caught instanceof TurnFailureEscape) throw caught.cause; + await terminal.fail(caught, limits); } finally { - clearTimeout(timer); - if (onAbort) signal.removeEventListener("abort", onAbort); + // A failed cleanup cannot strand the other owned resources or busy slot. + await cleanupTurn(turnCleanup(runner, claim, { terminal, frames, relay, ackGrace, archiveEnv })); } } +/** The SDK turn, from the claimed turn and its relay. */ +function buildSdkTurn(runner: TurnRunnerState, claim: ClaimedTurn, relay: TurnInferenceRelay, + own: Awaited>): ReturnType { + const { options } = runner; + const { req, profile, workerHost } = claim; + const egress = relay.egress; + // A voice turn selects the named voice posture in place of the profile's + // ordinary list (docs/decisions/voice-permission.md "The voice posture"). + const allowedTools = + req.autonomous?.allowedTools ?? + (req.posture === "voice" ? VOICE_ALLOWED_TOOLS : undefined) ?? + profile.allowedTools ?? options.backend.allowedTools ?? DEFAULT_ALLOWED_TOOLS; + return createClaudeSdkTurn({ + ...(egress ? { hostInference: { proxyDir: egress.dir, baseUrl: relay.baseUrl, + ...(relay.apiCredential ? { placeholders: relay.apiCredential.placeholders } : {}) } } : {}), + backend: options.backend, + ...(workerHost?.identity === "separate_uid" && workerHost.workerUid !== undefined ? { identity: { kind: "separate_uid" as const, workerUid: workerHost.workerUid } } : {}), + turnEnvironment: own?.turnEnvironment ?? claim.turnEnvironment, + fileVersions: claim.fileVersions, + req: { ...req, signal: claim.abortController.signal, ...(own ? { workerSandbox: own.workerSandbox } : {}), ...(egress && req.workerSandbox ? { workerSandbox: { ...req.workerSandbox, + // The relay holds the login: hide the host's file wherever the host masks do not. + maskPaths: [...req.workerSandbox.maskPaths ?? [], ...relay.hostLogin?.mask ?? []] } } : {}) }, + profile, + abortController: claim.abortController, + allowedTools, + confirmPatterns: options.confirmPatterns, + turnLock: claim.turnLock, + log: options.log, + }); +} + /** - * The turn's prompt as a stream the SDK pulls from, released only if `check` - * passes. A string prompt becomes the single user message the SDK would have - * built from it. + * A new session's SDK-minted id: re-key the busy slot from its placeholder, + * so a resume of this session while it still runs is detected as busy. */ -async function* gatedPrompt( - prompt: string | AsyncIterable, - check: () => Promise -): AsyncIterable { - if (!(await check())) return; - if (typeof prompt !== "string") { - yield* prompt; - return; - } - yield { - type: "user", - parent_tool_use_id: null, - message: { role: "user", content: prompt }, - session_id: "", - }; +function adoptSessionId(runner: TurnRunnerState, claim: ClaimedTurn, sessionId: string): void { + const { fileVersions, observationStorage } = claim; + // Saved off the event loop (#2416) and queued before any tool's + // observation save, which each native tool awaits. A failure + // refuses native writes until a later save succeeds. + if (fileVersions && observationStorage) fileVersions.retain({ ...observationStorage, sessionId }) + .catch(error => runner.options.log("warn", "Claude native file observations could not be retained", { error: String(error) })); + if (fileVersions) { runner.fileVersionsBySession.delete(claim.key); runner.fileVersionsBySession.set(sessionId, fileVersions); } + runner.activeTurns.delete(claim.key); + runner.activeTurns.set(sessionId, claim.turn); + claim.key = sessionId; +} + +/** Everything a turn owns, released in order whatever its outcome. */ +function turnCleanup(runner: TurnRunnerState, claim: ClaimedTurn, owned: { + terminal: TurnTerminal; frames: TurnFrames; relay: TurnInferenceRelay | undefined; + ackGrace: { timer?: ReturnType }; archiveEnv: Record | undefined; +}): Array<() => unknown> { + const { options, activeTurns, fileVersionsBySession } = runner; + const { req, input, fileVersions } = claim; + return [ + () => owned.terminal.worker.finishWorker?.(), + () => owned.relay?.routeInputs?.close(), + () => owned.relay?.stop(), + () => owned.relay?.unlink(), + () => clearTimeout(owned.ackGrace.timer), + // Every turn's input, autonomous or not, so cleanup always ends it. + () => input.close(), + () => req.signal.removeEventListener("abort", claim.onHostAbort), + // The new session's retain is not awaited where it is queued; the + // turn still settles only after every observation save has. + () => fileVersions?.settled(), + () => fileVersions?.cancelPending(), + () => { if (!owned.frames.sessionId) fileVersionsBySession.delete(claim.key); }, + () => claim.turnLock.close(), + () => activeTurns.delete(claim.key), + () => req.autonomous ? undefined : archiveIdleSessions({ + brainPath: options.backend.brainPath, env: owned.archiveEnv, + listSessionsFn: options.backend.listSessionsFn, + activeSessionIds: () => new Set(activeTurns.keys()), + log: (message, error) => options.log("warn", message, { error: String(error) }), + }), + ]; +} + +async function cleanupTurn(actions: Array<() => unknown>): Promise { + const failures: unknown[] = []; + for (const action of actions) { try { await action(); } catch (error) { failures.push(error); } } + if (failures.length) throw new AggregateError(failures, "Claude turn cleanup did not complete"); } function resolveProfile( diff --git a/packages/ui-backend-claude/src/turn-stream.ts b/packages/ui-backend-claude/src/turn-stream.ts new file mode 100644 index 0000000000..a04eb63818 --- /dev/null +++ b/packages/ui-backend-claude/src/turn-stream.ts @@ -0,0 +1,230 @@ +import type { AccountInfo, SDKMessage } from "@anthropic-ai/claude-agent-sdk"; +import type { ServerMessage, StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; + +import type { StreamAdapter } from "./stream-adapter.js"; +import type { TurnInput } from "./turn-input.js"; +import type { TurnLockBinding } from "./turn-lock.js"; +import type { ReportActivity, WorkerLimitReporter } from "./turn-reporting.js"; +import { TurnFailureEscape, type TurnFrames, type TurnTerminal } from "./turn-terminal.js"; +import { assertClaudeRuntime, type claudeRuntimeRequirements } from "./version-requirements.js"; + +/** + * How long a held result waits for the CLI to report reading a follow-up + * before the input is closed anyway. The measured runtime reports it within + * milliseconds; the bound only matters for a runtime that never reports it. + */ +export const FOLLOW_UP_ACK_GRACE_MS = 3_000; + +export interface TurnStreamInputs { + stream: AsyncIterable; + input: TurnInput; + adapter: StreamAdapter; + frames: TurnFrames; + terminal: TurnTerminal; + req: Pick; + backendId: string; + profileId: string; + /** The account the CLI selected, for the per-turn runtime report. */ + account: Promise; + reportActivity: ReportActivity; + reportRuntime(claudeCodeVersion: string | undefined, apiKeySource: string | undefined, selected: AccountInfo | undefined): void; + runtimeRequirements: ReturnType; + probedVersion: string | undefined; + turnLock: TurnLockBinding; + limits: WorkerLimitReporter; + observeAnswerText: ((text: string) => void) | undefined; + abortController: AbortController; + /** Bounds how long a held result waits for a follow-up's read report; cleared at turn end. */ + ackGrace: { timer?: ReturnType }; + /** A new session's SDK-minted id: re-key the turn's slot and retain its observations. */ + adoptSessionId(sessionId: string): void; +} + +/** + * A `result` that follow-ups outlived (#1003): the CLI runs them as + * continuation turns of the same process, so the one frame the client gets is + * built from the LAST result, with the per-run counts of the earlier ones + * added. The adapter tracks completed-response receipts across these + * continuations; session-cumulative SDK totals are evidence only. + */ +export class CarriedResult { + numTurns = 0; + durationMs = 0; + frames: ServerMessage[] = []; + /** The continuation began: the held result no longer describes the turn. */ + continued = false; + + /** The frames of a result, with every earlier carried run's counts added. */ + static carry(carried: CarriedResult | null, frames: ServerMessage[]): ServerMessage[] { + if (!carried) return frames; + return frames.map((frame) => + frame.type === "result" + ? { ...frame, numTurns: frame.numTurns + carried.numTurns, durationMs: frame.durationMs + carried.durationMs } + : frame + ); + } + + /** Whether `msg` begins the continuation turn. */ + static continues(msg: SDKMessage): boolean { + return msg.type === "assistant" || msg.type === "user" || msg.type === "stream_event" + || (msg.type === "system" && msg.subtype === "init"); + } +} + +/** + * Consume the SDK stream into the turn's frames, then settle its terminal. + * Exactly one terminal frame per turn, whatever the stream does. + */ +export async function runTurnStream(inputs: TurnStreamInputs): Promise { + const { input, adapter, terminal } = inputs; + let announced = false; + let reported = false; + let carried: CarriedResult | null = null; + try { + for await (const msg of inputs.stream) { + input.observe(msg); + if (carried && CarriedResult.continues(msg)) carried.continued = true; + // A withheld turn has already decided its outcome; nothing the stream + // does after that may replace it. + if (terminal.withheld) break; + // Emit session_info as soon as the session identity is known, before + // any content frames (contract requirement). + if (!announced && msg.session_id) { + announced = true; + announceSession(inputs, msg.session_id); + } + // After session_info, so the run is opened with its session. + if (msg.type === "system" && msg.subtype === "init") { + // Every continuation turn re-announces init; the run is reported once. + if (!reported) inputs.reportRuntime(msg.claude_code_version, msg.apiKeySource, await inputs.account); + reported = true; + if (!initMatchesProbe(inputs, msg.claude_code_version)) break; + } + let frames = adapter.adapt(msg); + if (msg.type === "result") { + const { continues, unacknowledged } = input.settle(); + if (continues && !terminal.sawResult) { + // Not the turn's last: hold it, in case no continuation comes. + carried = holdContinued(carried, frames); + // A follow-up the CLI has not reported reading may come from a + // runtime that does not report it at all, and would then wait for + // input forever. Closing is safe: what was pushed is still written, + // and the CLI drains it before it exits. It waits a moment first, + // because closing also refuses any later follow-up of this turn. + if (unacknowledged) { + clearTimeout(inputs.ackGrace.timer); + inputs.ackGrace.timer = setTimeout(() => { + if (input.unacknowledged()) input.close(); + }, FOLLOW_UP_ACK_GRACE_MS); + } + continue; + } + input.close(); + frames = CarriedResult.carry(carried, frames); + carried = null; + } + forwardFrames(inputs, frames); + } + + // A held result is the turn's terminal frame only if no continuation + // began. One that began and ended without its own result is an abnormal + // end, reported below like any other. + if (carried && !carried.continued && !terminal.sawResult && !terminal.withheld && !inputs.abortController.signal.aborted) { + for (const serverMsg of carried.frames) { + if (serverMsg.type === "result") { terminal.hold(serverMsg); continue; } + inputs.frames.emit(serverMsg); + } + } + // The stream ended: release its held result, or end the turn without + // one. Aborted → cancelled; not aborted → an abnormal end the client must + // still be released from. + await terminal.release(); + // A worker that never started ends the turn with its own error (#2790). + const workerStartFailure = terminal.worker.workerStartFailure; + if (!terminal.sawResult && workerStartFailure?.() !== undefined) throw workerStartFailure(); + if (!terminal.sawResult && !terminal.refused && !inputs.abortController.signal.aborted) terminal.refused = await inputs.limits.failure(); + else inputs.limits.reportCurrent(); + if (!terminal.sawResult) { + await terminal.endUnfinished(() => ({ + diagnostic: { code: "CLAUDE_NO_RESULT", message: "Backend stream ended without a result" }, + })); + } + } catch (caught) { + // The turn's failure is decided here, in the same microtask as the + // stream's throw. A failure of that handling still rejects startTurn. + try { await terminal.fail(caught, inputs.limits); } + catch (error) { throw new TurnFailureEscape(error); } + } +} + +/** The session identity is known: scope the turn to it and announce it. */ +function announceSession(inputs: TurnStreamInputs, streamSessionId: string): void { + const { frames, req } = inputs; + if (frames.sessionId === null) { + // New session: adopt the SDK-minted id for scoping and re-key the busy + // slot from its placeholder, so a resume of this session while it still + // runs is detected as busy. + frames.sessionId = streamSessionId; + inputs.adoptSessionId(streamSessionId); + } + const sessionId = frames.sessionId; + if (req.autonomous) { + inputs.reportActivity({ kind: "autonomous_identity", runtimeSessionId: sessionId, + backendId: inputs.backendId, profileId: inputs.profileId }); + } else { + inputs.frames.emit({ type: "session_info", sessionId, isNew: !req.sessionId, + providerId: inputs.profileId, backendId: inputs.backendId }); + } +} + +/** + * The running CLI must be the executable the probe verified. A mismatch + * refuses the turn and withholds whatever the stream says next. + */ +function initMatchesProbe(inputs: TurnStreamInputs, version: string | undefined): boolean { + const { runtimeRequirements, terminal } = inputs; + if (!runtimeRequirements.length) return true; + try { + assertClaudeRuntime(version ?? null, runtimeRequirements, "system/init observation", "running CLI did not report its version"); + if (version !== inputs.probedVersion) throw new Error(`@schlessera/brain-backend-claude runtime (claude-code) during system/init observation; required probed identity ${inputs.probedVersion}; detected ${version}. The executable changed after verification; select an immutable compatible executable and retry.`); + return true; + } catch (error) { + terminal.refused = { code: "CLAUDE_ERROR", message: error instanceof Error ? error.message : String(error) }; + terminal.withhold(); + return false; + } +} + +/** Hold a result that follow-ups may outlive, carrying every earlier run's counts. */ +function holdContinued(carried: CarriedResult | null, frames: ServerMessage[]): CarriedResult | null { + const held = CarriedResult.carry(carried, frames); + const final = held.find((frame) => frame.type === "result"); + if (final?.type !== "result") return carried; + const next = new CarriedResult(); + next.numTurns = final.numTurns; + next.durationMs = final.durationMs; + next.frames = held; + return next; +} + +/** Forward a message's frames; its result is held as the turn's terminal. */ +function forwardFrames(inputs: TurnStreamInputs, frames: ServerMessage[]): void { + const { terminal } = inputs; + for (const serverMsg of frames) { + // Exactly one terminal frame per turn, whatever the stream does: + // a second SDK result is dropped rather than forwarded. + if (serverMsg.type === "result") { + if (terminal.sawResult) continue; + terminal.hold(serverMsg); + continue; + } + // Release the write lock the moment a mutating tool's result frame + // lands (the turn-end backstop covers anything still held). + if (serverMsg.type === "tool_result") { + inputs.turnLock.releaseForTool(serverMsg.toolUseId); + inputs.limits.reportCurrent(); + } + if (serverMsg.type === "text_delta") inputs.observeAnswerText?.(serverMsg.text); + inputs.frames.emit(serverMsg); + } +} diff --git a/packages/ui-backend-claude/src/turn-terminal.ts b/packages/ui-backend-claude/src/turn-terminal.ts new file mode 100644 index 0000000000..966cbb6b93 --- /dev/null +++ b/packages/ui-backend-claude/src/turn-terminal.ts @@ -0,0 +1,272 @@ +import { FIRST_PARTY_FAILURE_CLASSES, type StateRoomObservation } from "@schlessera/brain-ui-sdk/protocol"; +import type { ServerMessage, StartTurnRequest, TurnFailure } from "@schlessera/brain-ui-sdk/server"; +import { WorkerHostError } from "@schlessera/brain-ui-sdk/internal"; + +import { SessionTooLargeError } from "./worker-state.js"; +import { workerStateClass } from "./worker-spawn.js"; +import type { WorkerLimitReporter } from "./turn-reporting.js"; + +export type ResultFrame = Extract; + +/** Why the turn failed when the host did not cancel it: a refusal or a named failure. */ +export interface TurnRefusal { + code: string; + message: string; + failure?: TurnFailure; +} + +/** The worker hooks the terminal waits for and consults, bound once the SDK turn is built. */ +export interface TurnTerminalWorker { + finishWorker?: () => Promise; + workerFailure?: () => TurnFailure | undefined; + workerStartFailure?: () => unknown; +} + +/** + * The turn's frame sink. Every frame is scoped to its session once the + * identity is known. For a resume that is up front (the requested id); for a + * new session it is null until the SDK reports it, so the only pre-identity + * frames (status/thinking) go out unscoped, then everything after is scoped. + * result and session_info already carry their own sessionId; the spread is a + * no-op on them. + */ +export class TurnFrames { + sessionId: string | null; + /** The worker's runtime-state observation, attached to a result frame. */ + stateRoom: (() => StateRoomObservation | undefined) | undefined; + readonly #bridge: StartTurnRequest["bridge"]; + + constructor(bridge: StartTurnRequest["bridge"], sessionId: string | null) { + this.#bridge = bridge; + this.sessionId = sessionId; + } + + emit(msg: ServerMessage): void { + const observation = msg.type === "result" + && !["worker_state_busy", "session_too_large", "worker_state_exceeded"].includes(msg.failure?.errorClass ?? "") + ? this.stateRoom?.() : undefined; + if (msg.type === "result" && observation) msg = { ...msg, stateRoom: observation }; + // The cast is safe: backends never emit the (unscoped) server_hello + // frame, and every other ServerMessage accepts a sessionId. + this.#bridge.emit(this.sessionId !== null ? ({ ...msg, sessionId: this.sessionId } as ServerMessage) : msg); + } +} + +/** + * The turn's terminal state: whether its terminal result was seen, whether it + * was refused or its prompt withheld, and the rules for the one terminal + * frame it emits. + */ +export class TurnTerminal { + /** + * The stream produced its terminal result, or a generated terminal was + * emitted. A stream that yields a result and THEN throws must not get a + * second one. + */ + sawResult = false; + /** + * Set when a startup check refused the turn before its prompt was + * released, or when the turn failed for a named reason. It outranks the + * abort it causes: the turn failed, it was not cancelled. + */ + refused: TurnRefusal | null = null; + /** + * The gate decided not to release the prompt, for whatever reason. Once + * set, nothing the stream says afterwards can turn the turn into a success. + */ + withheld = false; + worker: TurnTerminalWorker = {}; + /** The turn's terminal result, held until the worker has exited. */ + #held: ResultFrame | undefined; + #sent = false; + readonly #inputs: TurnTerminalInputs; + + constructor(inputs: TurnTerminalInputs) { + this.#inputs = inputs; + } + + wasCancelled(): boolean { + return this.#inputs.hostSignal.aborted || (!this.refused && this.#inputs.abortController.signal.aborted); + } + + /** Withhold the prompt: the turn's outcome is decided, and the SDK query stops. */ + withhold(): false { + this.withheld = true; + this.#inputs.abortController.abort(); + return false; + } + + /** Hold the stream's terminal result until the worker has exited. */ + hold(frame: ResultFrame): void { + this.sawResult = true; + this.#held = frame; + // Checked now and again at exit: the runtime may free space as it exits. + this.worker.workerFailure?.(); + } + + /** + * The runtime reports its outcome even when its transcript writes failed + * on a full runtime-state tmpfs, and that output is then not saved + * (#1625). So the state is checked when the result arrives, the terminal + * result waits for the worker to exit and its state to be copied out, and + * a state found full at either point names the turn + * `worker_state_exceeded`. A refused copy-out names it + * `worker_state_save_refused`, keeping its usage. A host cancellation still + * outranks it. + */ + unsaved(result: ResultFrame): ResultFrame { + if (result.outcome === "cancelled" || this.#inputs.abortController.signal.aborted) return result; + const failure = this.worker.workerFailure?.(); + if (failure?.errorClass !== FIRST_PARTY_FAILURE_CLASSES.worker_state_exceeded + && failure?.errorClass !== FIRST_PARTY_FAILURE_CLASSES.worker_state_save_refused) return result; + this.#inputs.frames.emit({ type: "error", code: "CLAUDE_ERROR", message: failure.message }); + return { ...result, outcome: "error", isError: true, failure }; + } + + /** Emit the held terminal result, once, after the worker has exited. */ + async release(): Promise { + if (!this.#held || this.#sent) return; + this.#sent = true; + // The worker's exit and copy-out must settle before the terminal frame. + await this.worker.finishWorker?.().catch(() => {}); + const terminal = this.#held; + // Cancellation can arrive after the SDK result, including while exit or + // copy-out is pending. Keep its accounting, but discard error-only fields. + // A startup refusal's own internal abort must remain a refusal. + if (this.wasCancelled()) { + const { failure: _failure, outcomeDetail: _detail, ...retained } = terminal; + this.#inputs.frames.emit({ type: "status", status: "cancelled" }); + this.#inputs.frames.emit({ ...retained, outcome: "cancelled", isError: false }); + } else this.#inputs.frames.emit(this.unsaved(terminal)); + } + + /** + * A worker whose runtime state refused or stopped the turn (#1625) ends it + * with that named class rather than the runtime's own error. + */ + workerRefusal(): boolean { + const failure = this.refused ? undefined : this.worker.workerFailure?.(); + if (failure) this.refused = { code: "CLAUDE_ERROR", message: failure.message, failure }; + return Boolean(this.refused); + } + + /** + * Unified terminal frame for cancelled/failed turns. With a session + * identity that is a `result`; WITHOUT one (an abort or failure before + * the SDK reported a session) the contract's terminal is a bare `error`, + * so a client keying on result/error is never left hanging. + */ + async emitGenerated(outcome: "error" | "cancelled", diagnostic?: { code: string; message: string }): Promise { + if (this.sawResult) return; + this.sawResult = true; + const { frames } = this.#inputs; + // Generated terminals obey the same cleanup boundary as SDK results. + await this.worker.finishWorker?.().catch(() => {}); + if (this.wasCancelled()) outcome = "cancelled"; + if (outcome === "cancelled") frames.emit({ type: "status", status: "cancelled" }); + const reason = this.refused ?? diagnostic; + if (frames.sessionId === null) { + frames.emit( + reason && outcome === "error" + ? { type: "error", ...reason } + : { + type: "error", + code: outcome === "cancelled" ? "CANCELLED" : "CLAUDE_ERROR", + message: + outcome === "cancelled" + ? "Turn cancelled before the session was established" + : "Turn failed before the session was established", + } + ); + return; + } + // The failure rides the terminal frame only, so a client never reports + // it twice: here that is the result, not the diagnostic error. + const failure = this.refused?.failure ?? this.#inputs.pendingFailure() ?? undefined; + if (reason && outcome === "error") frames.emit({ type: "error", code: reason.code, message: reason.message }); + // costUsd deliberately absent (unknown); duration is real, numTurns 0 = + // "no completed turns" for a turn that never finished. + frames.emit({ + type: "result", + sessionId: frames.sessionId, + outcome, + durationMs: Date.now() - this.#inputs.startedAt, + numTurns: 0, + isError: outcome === "error", + ...(outcome === "error" && failure ? { failure } : {}), + }); + } + + /** + * The terminal for a turn whose stream ended or threw without its result: + * a refusal fails it, a host cancellation outranks a state failure found + * meanwhile, and anything else fails it with `fallback`'s reason. + */ + async endUnfinished(fallback: () => { refusal?: TurnRefusal; diagnostic?: { code: string; message: string } }): Promise { + if (this.refused) { + await this.emitGenerated("error"); + } else if (this.#inputs.abortController.signal.aborted) { + await this.emitGenerated("cancelled"); + } else if (this.workerRefusal()) { + await this.emitGenerated("error"); + } else { + const { refusal, diagnostic } = fallback(); + if (refusal) this.refused = refusal; + await this.emitGenerated("error", diagnostic); + } + } + + /** + * The terminal for a turn that threw. error/cancelled frames are + * diagnostics; the terminal frame is the result with an outcome (for turns + * that have a session identity — a turn that died before any session id + * ends on the bare error). Diagnostics only make sense BEFORE the terminal + * frame; when the stream already delivered its result, the turn is over, + * the late failure is swallowed and nothing may follow it. + */ + async fail(caught: unknown, limits: Pick): Promise { + // The SDK reports a worker's deferred start failure as its own process + // error; the worker's error names the turn, as when its spawn threw it (#2790). + const err = this.worker.workerStartFailure?.() ?? caught; + // A worker ended by a host limit fails the turn with that limit named (#1660). + if (!this.sawResult && !this.refused && !this.#inputs.abortController.signal.aborted) this.refused = await limits.failure().catch(() => null); + if (this.sawResult) await this.release(); + else await this.endUnfinished(() => thrownTurnFailure(err)); + } +} + +/** + * A failure of the turn's own failure handling inside the stream. It still + * rejects startTurn, after cleanup, without being handled a second time. + */ +export class TurnFailureEscape { + readonly cause: unknown; + constructor(cause: unknown) { + this.cause = cause; + } +} + +export interface TurnTerminalInputs { + frames: TurnFrames; + /** The host's own cancellation signal. */ + hostSignal: AbortSignal; + /** The turn's internal abort, which the SDK query listens to. */ + abortController: AbortController; + startedAt: number; + /** A failure the stream reported without its result. */ + pendingFailure(): TurnFailure | null | undefined; +} + +/** + * Why a turn that threw before its terminal result failed: the worker host's + * or runtime state's named class, else the error itself as a diagnostic. + */ +export function thrownTurnFailure(err: unknown): { refusal?: TurnRefusal; diagnostic?: { code: string; message: string } } { + const stateClass = workerStateClass(err); + if (err instanceof WorkerHostError || err instanceof SessionTooLargeError || stateClass) { + const { message } = err as Error; + return { refusal: { code: "CLAUDE_ERROR", message, + failure: { errorClass: stateClass ?? (err as WorkerHostError | SessionTooLargeError).errorClass, message } } }; + } + return { diagnostic: { code: "CLAUDE_ERROR", message: err instanceof Error ? err.message : String(err) } }; +} diff --git a/packages/ui-backend-claude/tests/helpers/ack-grace-clock.ts b/packages/ui-backend-claude/tests/helpers/ack-grace-clock.ts index 5d7fd7486b..2e0f86835a 100644 --- a/packages/ui-backend-claude/tests/helpers/ack-grace-clock.ts +++ b/packages/ui-backend-claude/tests/helpers/ack-grace-clock.ts @@ -18,7 +18,7 @@ export function ackGraceClock() { const schedule = ((callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => { // Select the importing owner, not the expected duration: a wrong interval // must still be controlled and fail the boundary/registration assertions. - if (!new Error().stack?.split("\n")[2]?.includes("/src/turn-runner.ts:")) return nativeSet(callback, delay, ...args); + if (!new Error().stack?.split("\n")[2]?.includes("/src/turn-stream.ts:")) return nativeSet(callback, delay, ...args); const registration = { delay: delay ?? 0, due: now + (delay ?? 0), fired: false, cleared: false, callback: () => callback(...args) }; const handle = {} as Handle; registrations.push(registration); diff --git a/packages/ui-backend-claude/tests/turn-units.test.ts b/packages/ui-backend-claude/tests/turn-units.test.ts new file mode 100644 index 0000000000..01ef5c18f3 --- /dev/null +++ b/packages/ui-backend-claude/tests/turn-units.test.ts @@ -0,0 +1,359 @@ +/** + * Direct tests for the units split out of the Claude backend's startTurn + * (#1360): the turn's terminal state, its runtime and limit reporting, the + * host inference relay's transport qualification, the prompt gate's check + * and the stream loop. The whole-turn behaviour stays covered by the + * backend contract and characterization suites. + */ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { Query, SDKMessage } from "@anthropic-ai/claude-agent-sdk"; +import type { BackendActivityEvent, ServerMessage, StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { WorkerHostError, type WorkerLimitReport } from "@schlessera/brain-ui-sdk/internal"; + +import { DEFAULT_PROFILES, type InferenceProfile } from "../src/profiles"; +import { StreamAdapter } from "../src/stream-adapter"; +import { createTurnInput } from "../src/turn-input"; +import { TurnInferenceRelay, hostLoginFile, sameRoute } from "../src/turn-inference-relay"; +import { promptGateCheck } from "../src/turn-prompt-gate"; +import { WorkerLimitReporter, reportTurnRuntime } from "../src/turn-reporting"; +import { runTurnStream, type TurnStreamInputs } from "../src/turn-stream"; +import { TurnFailureEscape, TurnFrames, TurnTerminal, thrownTurnFailure, type ResultFrame } from "../src/turn-terminal"; + +const temps: string[] = []; +afterEach(() => { + while (temps.length) rmSync(temps.pop()!, { recursive: true, force: true }); +}); +function tempDir(): string { + const dir = mkdtempSync(join(tmpdir(), "turn-units-")); + temps.push(dir); + return dir; +} + +function bridge() { + const frames: ServerMessage[] = []; + const activity: BackendActivityEvent[] = []; + return { frames, activity, bridge: { emit: (msg: ServerMessage) => frames.push(msg), activity: (event: BackendActivityEvent) => activity.push(event) } as unknown as StartTurnRequest["bridge"] }; +} + +function terminalFixture(sessionId: string | null = "s1") { + const sink = bridge(); + const host = new AbortController(); + const abortController = new AbortController(); + const frames = new TurnFrames(sink.bridge, sessionId); + const terminal = new TurnTerminal({ frames, hostSignal: host.signal, abortController, startedAt: Date.now(), pendingFailure: () => null }); + return { ...sink, host, abortController, frames: sink.frames, scoped: frames, terminal }; +} + +const result = (extra: Partial = {}): ResultFrame => + ({ type: "result", sessionId: "s1", outcome: "success", durationMs: 5, numTurns: 1, isError: false, ...extra }) as ResultFrame; + +describe("TurnFrames", () => { + test("scopes frames once the session is known and attaches the state room to a result", () => { + const sink = bridge(); + const frames = new TurnFrames(sink.bridge, null); + frames.stateRoom = () => ({ observed: true }) as never; + frames.emit({ type: "status", status: "thinking" } as ServerMessage); + frames.sessionId = "s1"; + frames.emit(result()); + frames.emit(result({ failure: { errorClass: "session_too_large", message: "x" } } as Partial)); + expect(sink.frames[0]).toEqual({ type: "status", status: "thinking" } as ServerMessage); + expect(sink.frames[1]).toMatchObject({ sessionId: "s1", stateRoom: { observed: true } }); + expect(sink.frames[2]).not.toHaveProperty("stateRoom"); + }); +}); + +describe("TurnTerminal", () => { + test("a held result is released once, only after the worker has finished", async () => { + const { terminal, frames } = terminalFixture(); + const order: string[] = []; + terminal.worker = { finishWorker: async () => { order.push("finished"); } }; + terminal.hold(result()); + expect(terminal.sawResult).toBe(true); + const releasing = terminal.release(); + expect(frames).toHaveLength(0); + await releasing; + order.push(`emitted:${frames.length}`); + await terminal.release(); + expect(order).toEqual(["finished", "emitted:1"]); + expect(frames).toEqual([result()]); + }); + + test("a cancellation during the worker's exit keeps the accounting but drops error fields", async () => { + const { terminal, frames, host } = terminalFixture(); + terminal.worker = { finishWorker: async () => { host.abort(); } }; + terminal.hold(result({ outcome: "error", isError: true, failure: { errorClass: "api_error", message: "x" } } as Partial)); + await terminal.release(); + expect(frames).toEqual([ + { type: "status", status: "cancelled", sessionId: "s1" }, + { type: "result", sessionId: "s1", outcome: "cancelled", durationMs: 5, numTurns: 1, isError: false }, + ] as ServerMessage[]); + }); + + test("a refusal's own internal abort is not a cancellation", () => { + const { terminal, abortController } = terminalFixture(); + terminal.refused = { code: "CLAUDE_AUTH", message: "no" }; + expect(terminal.withhold()).toBe(false); + expect(terminal.withheld).toBe(true); + expect(abortController.signal.aborted).toBe(true); + expect(terminal.wasCancelled()).toBe(false); + }); + + test("without a session the generated terminal is a bare error", async () => { + const { terminal, frames } = terminalFixture(null); + await terminal.emitGenerated("error"); + await terminal.emitGenerated("error"); + expect(frames).toEqual([{ type: "error", code: "CLAUDE_ERROR", message: "Turn failed before the session was established" }] as ServerMessage[]); + }); + + test("with a session a refusal is a diagnostic error followed by a result carrying its failure", async () => { + const { terminal, frames } = terminalFixture(); + const failure = { errorClass: "subscription_required", message: "sub" } as const; + terminal.refused = { code: "CLAUDE_AUTH", message: "sub", failure }; + await terminal.endUnfinished(() => { throw new Error("fallback must not run for a refusal"); }); + expect(frames[0]).toEqual({ type: "error", code: "CLAUDE_AUTH", message: "sub", sessionId: "s1" } as ServerMessage); + expect(frames[1]).toMatchObject({ type: "result", outcome: "error", isError: true, numTurns: 0, failure }); + }); + + test("an unfinished turn the host aborted ends cancelled, before any worker state failure", async () => { + const { terminal, frames, abortController } = terminalFixture(); + terminal.worker = { workerFailure: () => ({ errorClass: "worker_state_exceeded", message: "full" }) }; + abortController.abort(); + await terminal.endUnfinished(() => ({})); + expect(frames.map((frame) => frame.type === "result" ? frame.outcome : frame.type)).toEqual(["status", "cancelled"]); + }); + + test("a worker state failure names an unfinished turn", async () => { + const { terminal, frames } = terminalFixture(); + terminal.worker = { workerFailure: () => ({ errorClass: "worker_state_exceeded", message: "full" }) }; + await terminal.endUnfinished(() => { throw new Error("fallback must not run for a worker refusal"); }); + expect(frames.at(-1)).toMatchObject({ outcome: "error", failure: { errorClass: "worker_state_exceeded" } }); + }); + + test("a full worker state turns a successful result into its named failure", () => { + const { terminal, frames } = terminalFixture(); + terminal.worker = { workerFailure: () => ({ errorClass: "worker_state_exceeded", message: "full" }) }; + expect(terminal.unsaved(result())).toMatchObject({ outcome: "error", isError: true, failure: { errorClass: "worker_state_exceeded" } }); + expect(frames).toEqual([{ type: "error", code: "CLAUDE_ERROR", message: "full", sessionId: "s1" } as ServerMessage]); + }); + + test("a failure after the result was seen is swallowed and the result released", async () => { + const { terminal, frames } = terminalFixture(); + terminal.hold(result()); + await terminal.fail(new Error("late"), { failure: async () => { throw new Error("not consulted"); } }); + expect(frames).toEqual([result()]); + }); + + test("a turn whose worker a host limit ended fails with that limit named, not the thrown error", async () => { + const { terminal, frames } = terminalFixture(); + const failure = { errorClass: "worker_resource_limit", message: "memory limit" } as const; + await terminal.fail(new Error("process exited"), { failure: async () => ({ code: "WORKER_RESOURCE_LIMIT", message: "memory limit", failure }) }); + expect(frames).toEqual([ + { type: "error", code: "WORKER_RESOURCE_LIMIT", message: "memory limit", sessionId: "s1" }, + expect.objectContaining({ type: "result", outcome: "error", failure }), + ] as ServerMessage[]); + }); + + test("a thrown worker host error names the turn; anything else is a diagnostic", async () => { + expect(thrownTurnFailure(new Error("boom"))).toEqual({ diagnostic: { code: "CLAUDE_ERROR", message: "boom" } }); + const hostError = new WorkerHostError("no host"); + const named = thrownTurnFailure(hostError); + expect(named.refusal).toEqual({ code: "CLAUDE_ERROR", message: hostError.message, + failure: { errorClass: hostError.errorClass, message: hostError.message } }); + const { terminal, frames } = terminalFixture(); + await terminal.fail(new Error("boom"), { failure: async () => null }); + expect(frames).toEqual([ + { type: "error", code: "CLAUDE_ERROR", message: "boom", sessionId: "s1" }, + expect.objectContaining({ type: "result", outcome: "error" }), + ] as ServerMessage[]); + }); +}); + +describe("turn reporting", () => { + test("each limit hit is reported once; a fatal one becomes the turn's failure", async () => { + const activity: BackendActivityEvent[] = []; + const limits = new WorkerLimitReporter((event) => activity.push(event)); + expect(await limits.failure()).toBeNull(); + const hit = { resource: "memory", limit: 1, observed: 2 }; + const report = { hits: [hit], fatal: false } as unknown as WorkerLimitReport; + limits.limits = { current: () => report, settled: async () => ({ ...report, fatal: true }) as WorkerLimitReport }; + limits.reportCurrent(); + limits.reportCurrent(); + expect(activity).toHaveLength(1); + expect(activity[0]).toMatchObject({ kind: "resource_limit", limits: [hit], fatal: false }); + expect(await limits.failure()).toMatchObject({ code: "WORKER_RESOURCE_LIMIT", failure: { errorClass: "worker_resource_limit" } }); + expect(activity.at(-1)).toMatchObject({ kind: "resource_limit", fatal: true }); + }); + + test("a profile without its own credential that ran on an API key is a policy violation", () => { + const activity: BackendActivityEvent[] = []; + const logs: string[] = []; + reportTurnRuntime({ profile: { id: "p", billing: "subscription" } as InferenceProfile, log: (_level, message) => logs.push(message), + reportActivity: (event) => activity.push(event) }, "2.0.0", "ANTHROPIC_API_KEY", undefined); + expect(logs).toEqual(["billing policy violated"]); + expect(activity[0]).toMatchObject({ kind: "runtime_observed", billing: "api", policy: "subscription", + policyViolation: "a profile without its own credential ran on an API credential" }); + }); +}); + +describe("TurnInferenceRelay", () => { + function relayFor(env: Record = {}) { + const config = tempDir(); + const req = { workerSandbox: { egress: { dir: tempDir() } } } as unknown as StartTurnRequest; + const profile = { ...DEFAULT_PROFILES[0]!, billing: "subscription" } as InferenceProfile; + return new TurnInferenceRelay({ req, profile, turnEnvironment: { CLAUDE_CONFIG_DIR: config, ...env }, brainPath: tempDir() }); + } + const qualified = (baseUrl: string) => ({ + sources: [{ source: "flagSettings", settings: { env: { ANTHROPIC_BASE_URL: baseUrl } } }], + effective: { env: { ANTHROPIC_BASE_URL: baseUrl } }, + }); + + test("a turn without prepared egress runs no relay", () => { + const relay = new TurnInferenceRelay({ req: {} as StartTurnRequest, profile: DEFAULT_PROFILES[0]!, turnEnvironment: undefined, brainPath: tempDir() }); + expect(relay.egress).toBeUndefined(); + expect(relay.hostLogin).toBeUndefined(); + relay.start(); + expect(relay.stop()).toBeUndefined(); + }); + + test("qualifies only the relay's own route, and authorizes nothing before that", () => { + const relay = relayFor(); + expect(relay.selectedUpstream).toBe("https://api.anthropic.com"); + expect(relay.qualify(undefined, true, undefined)).toBe("the native inference settings sources are not qualified for this prepared transport"); + expect(relay.qualify({ sources: [{ source: "userSettings" }] }, true, undefined)).toBe("the native inference settings sources are not qualified for this prepared transport"); + expect(relay.qualify(qualified("https://elsewhere.example"), true, undefined)).toBe("the native inference source selects a destination not qualified for this prepared transport"); + expect(relay.qualify({ sources: [], effective: { env: {} } }, true, undefined)).toBe("native settings refused the prepared inference transport"); + expect(relay.qualify(qualified(relay.baseUrl), true, undefined)).toBeUndefined(); + }); + + test("an unlisted custom origin is refused before the host login", () => { + const relay = relayFor({ ANTHROPIC_BASE_URL: "https://gateway.example/v1" }); + expect(relay.qualify(qualified(relay.baseUrl), true, undefined)).toBe("the selected inference origin is not authorized to receive the host Claude login; list its exact origin in BRAIN_UI_CLAUDE_OAUTH_ORIGINS"); + }); + + test("changed native route inputs refuse the transport first", () => { + const relay = relayFor(); + relay.routeInputs = { assertUnchanged: () => { throw new Error("changed"); }, close: async () => {} } as never; + expect(relay.qualify(qualified(relay.baseUrl), true, undefined)).toBe("native inference settings changed during startup"); + }); + + test("a route comparison ignores trailing slashes but nothing else", () => { + expect(sameRoute("https://gateway.example/v1/", "https://gateway.example/v1")).toBe(true); + expect(sameRoute("https://user@gateway.example/v1", "https://gateway.example/v1")).toBe(false); + expect(sameRoute("https://gateway.example/v2", "https://gateway.example/v1")).toBe(false); + expect(hostLoginFile(tempDir(), tempDir())).toEqual({ mask: [], inBrain: false }); + }); +}); + +describe("promptGateCheck", () => { + function gate(overrides: { account?: unknown; initialize?: () => Promise } = {}) { + const { terminal, abortController } = terminalFixture(); + const activity: BackendActivityEvent[] = []; + const reported: unknown[] = []; + const check = promptGateCheck({ + queryHandle: Promise.resolve({} as Query), + initialize: (overrides.initialize ?? (async () => ({ account: overrides.account }))) as never, + sdkTurn: { subscriptionOnly: true }, + relay: undefined, + terminal, + runtimeRequirements: [], + phase: "start before prompt release", + abortController, + profileId: "default", + log: () => {}, + reportActivity: (event) => activity.push(event), + reportRuntime: (...args) => reported.push(args), + }); + return { check, terminal, abortController, activity, reported }; + } + + test("a subscription turn the CLI would bill elsewhere is refused and withheld", async () => { + const { check, terminal, abortController, activity, reported } = gate({ account: undefined }); + expect(await check()).toBe(false); + expect(terminal.refused).toMatchObject({ code: "CLAUDE_AUTH", failure: { errorClass: "subscription_required" } }); + expect(terminal.withheld).toBe(true); + expect(abortController.signal.aborted).toBe(true); + expect(activity).toMatchObject([{ kind: "auth_failure", errorClass: "subscription_required" }]); + expect(reported).toHaveLength(1); + }); + + test("a handshake failure refuses the turn, unless the host cancelled it", async () => { + const failed = gate({ initialize: async () => { throw new Error("no handshake"); } }); + expect(await failed.check()).toBe(false); + expect(failed.terminal.refused?.message).toContain("Claude Code did not complete its handshake: no handshake"); + + const cancelled = gate({ initialize: async () => { cancelled.abortController.abort(); throw new Error("aborted"); } }); + expect(await cancelled.check()).toBe(false); + expect(cancelled.terminal.refused).toBeNull(); + expect(cancelled.terminal.withheld).toBe(true); + }); +}); + +describe("runTurnStream", () => { + function streamOf(messages: unknown[], thrown?: Error): AsyncIterable { + return (async function* () { + for (const message of messages) yield message as SDKMessage; + if (thrown) throw thrown; + })(); + } + function run(messages: unknown[], options: { thrown?: Error; sessionId?: string; frames?: ServerMessage[] } = {}) { + const sink = bridge(); + const abortController = new AbortController(); + const frames = new TurnFrames(sink.bridge, options.sessionId ?? null); + const terminal = new TurnTerminal({ frames, hostSignal: new AbortController().signal, abortController, startedAt: Date.now(), pendingFailure: () => null }); + const adopted: string[] = []; + const inputs: TurnStreamInputs = { + stream: streamOf(messages, options.thrown), + input: createTurnInput("hello"), + adapter: new StreamAdapter(undefined, { subscriptionAuth: true }), + frames, terminal, req: { sessionId: options.sessionId }, backendId: "claude", profileId: "default", + account: Promise.resolve(undefined), reportActivity: () => {}, reportRuntime: () => {}, + runtimeRequirements: [], probedVersion: undefined, + turnLock: { acquireForTool: async () => ({ ok: true }), releaseForTool: () => {}, close: () => {} }, + limits: new WorkerLimitReporter(() => {}), observeAnswerText: undefined, abortController, ackGrace: {}, + adoptSessionId: (id) => adopted.push(id), + }; + return { done: runTurnStream(inputs), frames: sink.frames, adopted, terminal }; + } + const sdkResult = { type: "result", subtype: "success", session_id: "s1", total_cost_usd: 0.01, duration_ms: 5, num_turns: 1, + is_error: false, result: "ok", usage: { input_tokens: 1, output_tokens: 1 }, modelUsage: {} }; + + test("announces a new session, adopts its id and ends on exactly one result", async () => { + const turn = run([{ type: "system", subtype: "init", session_id: "s1" }, sdkResult, { ...sdkResult, duration_ms: 9 }]); + await turn.done; + expect(turn.adopted).toEqual(["s1"]); + expect(turn.frames[0]).toMatchObject({ type: "session_info", sessionId: "s1", isNew: true }); + expect(turn.frames.filter((frame) => frame.type === "result")).toHaveLength(1); + expect(turn.frames.at(-1)).toMatchObject({ type: "result", durationMs: 5 }); + }); + + test("a stream that ends without a result fails the turn", async () => { + const turn = run([{ type: "system", subtype: "init", session_id: "s1" }]); + await turn.done; + expect(turn.frames.slice(-2)).toMatchObject([ + { type: "error", code: "CLAUDE_NO_RESULT" }, + { type: "result", outcome: "error" }, + ]); + }); + + test("a stream that throws is failed in place; one that throws after its result keeps it", async () => { + const thrown = run([{ type: "system", subtype: "init", session_id: "s1" }], { thrown: new Error("broken pipe") }); + await thrown.done; + expect(thrown.frames.slice(-2)).toMatchObject([{ type: "error", message: "broken pipe" }, { type: "result", outcome: "error" }]); + + const late = run([{ type: "system", subtype: "init", session_id: "s1" }, sdkResult], { thrown: new Error("late") }); + await late.done; + expect(late.frames.at(-1)).toMatchObject({ type: "result", outcome: "success" }); + expect(late.frames.some((frame) => frame.type === "error")).toBe(false); + }); + + test("a failure of the failure handling escapes once, marked", async () => { + const turn = run([], { thrown: new Error("broken") }); + turn.terminal.fail = async () => { throw new Error("handler failed"); }; + const escaped = await turn.done.then(() => undefined, (error: unknown) => error); + expect(escaped).toBeInstanceOf(TurnFailureEscape); + expect((escaped as TurnFailureEscape).cause).toEqual(new Error("handler failed")); + }); +}); diff --git a/packages/ui-react/tests/turn-journal-runtime.test.ts b/packages/ui-react/tests/turn-journal-runtime.test.ts index d243c5981f..464e59bd37 100644 --- a/packages/ui-react/tests/turn-journal-runtime.test.ts +++ b/packages/ui-react/tests/turn-journal-runtime.test.ts @@ -72,7 +72,7 @@ beforeAll(() => hook.phase("setup", async () => { const temporary = resolve(root, "memory-worker"); await mkdir(temporary); memoryState.populate(temporary); await app.wsHost.journal!.begin(memoryId, metadata, error => { throw error; }); await writeFile(resolve(temporary, project, "memory/voyage.md"), "Athena remembers the crossing.\r\n"); - // The Claude backend awaits copy-out before its turn ends (`releaseTerminal`); so does this fixture. + // The Claude backend awaits copy-out before its turn ends (`TurnTerminal.release`); so does this fixture. await memoryState.persist(temporary, undefined, (change, save) => app.wsHost.journal!.persistClaudeMemory(memoryId, change, save)); memoryState.release(); await app.wsHost.journal!.finish(memoryId); const memorySeed = JSON.stringify({ turnId: memoryId, summary: app.wsHost.journal!.summary(memoryId) });