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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/claude-turn-runner-split.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion docs/decisions/claude-code-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/hardening.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions docs/decisions/policy-write-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/runtime-requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
142 changes: 142 additions & 0 deletions packages/ui-backend-claude/src/turn-inference-relay.ts
Original file line number Diff line number Diff line change
@@ -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<string, string | undefined>;

/**
* 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<StartTurnRequest["workerSandbox"]>["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<ReturnType<typeof retainNativeRouteInputs>> | undefined;
#relay: InferenceRelay | undefined;
#link: string | undefined;
#authorized = false;
readonly #configDirectory: string;
readonly #turnEnvironment: Environment | undefined;
readonly #authorizedOrigins: ReturnType<typeof resolveEnv>["claudeOAuthOrigins"];
readonly #recipient: NonNullable<StartTurnRequest["workerSandbox"]>["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<Record<string, string>> | 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 });
}
}
Loading
Loading