From 37ca1ab6a0ab454f1e8455dc4377648352cb61be Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 01:24:03 +0000 Subject: [PATCH 1/5] refactor(ui-server): run a session's turns through named lifecycle stages runRetainedSession was a 791-line closure: setup, admission, the backend call, outcome classification and teardown all shared about 20 mutable `let` flags, which one nested ternary resolved into the turn outcome. It is now a 54-line loop over stages in packages/ui-server/src/ws/session-run/: - slot.ts: routing and the starting gate (openSessionSlot), the first request, binding a request to the slot, dequeue/hand-over, and slot close. - admission.ts: the worker-host check (a discriminated admitted/denied result), the turn timeout, the recorder, the start announcement, and governed admission: hold, budget, journal, worktree generation, reference tools and scope caps. Governed admission returns admitted (with the profile preference) or revoked. - budget.ts: one budgetEvent() builder for all four budget_warning and budget_block sites. Each site keeps its current actor (the turn's origin) and its profile and source. Mid-turn accounting lives in createTurnBudget. - backend-entry.ts: prompt and bridge, relayed egress, the startTurn request. - outcome.ts: pure classifyCompletedTurn/classifyFailedTurn. The failure delivery is cancelled_before_start | scope_stopped | reported, in place of the cancelledAdmission/revokedAdmission flags. Asynchronous budget, journal and scope stops are one TurnStops record. - teardown.ts: release order and the slot's final status frame. - turn.ts: one request from host admission to teardown. resolveRunBilling and HandoffHooks are re-exported from run-session.ts for existing importers. No protocol, ordering or concurrency change. Refs #1359 Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/ws/run-session.ts | 961 +----------------- .../ui-server/src/ws/session-run/admission.ts | 246 +++++ .../src/ws/session-run/backend-entry.ts | 229 +++++ .../ui-server/src/ws/session-run/billing.ts | 38 + .../ui-server/src/ws/session-run/budget.ts | 132 +++ .../src/ws/session-run/cancellations.ts | 51 + .../ui-server/src/ws/session-run/outcome.ts | 129 +++ packages/ui-server/src/ws/session-run/slot.ts | 224 ++++ .../ui-server/src/ws/session-run/teardown.ts | 88 ++ packages/ui-server/src/ws/session-run/turn.ts | 151 +++ .../ui-server/src/ws/session-run/types.ts | 139 +++ 11 files changed, 1464 insertions(+), 924 deletions(-) create mode 100644 packages/ui-server/src/ws/session-run/admission.ts create mode 100644 packages/ui-server/src/ws/session-run/backend-entry.ts create mode 100644 packages/ui-server/src/ws/session-run/billing.ts create mode 100644 packages/ui-server/src/ws/session-run/budget.ts create mode 100644 packages/ui-server/src/ws/session-run/cancellations.ts create mode 100644 packages/ui-server/src/ws/session-run/outcome.ts create mode 100644 packages/ui-server/src/ws/session-run/slot.ts create mode 100644 packages/ui-server/src/ws/session-run/teardown.ts create mode 100644 packages/ui-server/src/ws/session-run/turn.ts create mode 100644 packages/ui-server/src/ws/session-run/types.ts diff --git a/packages/ui-server/src/ws/run-session.ts b/packages/ui-server/src/ws/run-session.ts index cbe727c94a..5250ea2f40 100644 --- a/packages/ui-server/src/ws/run-session.ts +++ b/packages/ui-server/src/ws/run-session.ts @@ -1,139 +1,30 @@ -import { prepareTurnEgress } from "../brain/turn-egress.js"; -import { sessionTaint } from "../governance/session-taint.js"; import { createTurnLifecycle } from "../activity/turn-lifecycle.js"; -import { BudgetExceeded, BudgetUnavailable, inferenceBudgetLimits, inferenceBudgetContext } from "../brain/turn-budgets.js"; import { withTrackFiles } from "../tracks/read.js"; import type { - BillingMode, ChatImageAttachment, ClientEnvironment, DraftRef, LocalExchange, MessageSource, - PricingRoute, ThinkingLevel, } from "@schlessera/brain-ui-sdk/protocol"; import { BackendRequestError } from "@schlessera/brain-ui-sdk/server"; -import { linkSync, lstatSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { createHash } from "node:crypto"; -import { isEnvName, PROTECTED_TIER_A, PROVIDER_RELAY_KEYS_NAME, PROVIDER_RELAY_SOCKET_NAME, heldCustomProviderKeys, startProviderRelay, type ProviderRelay } from "@schlessera/brain-ui-sdk/internal"; -import type { BudgetObservation } from "@schlessera/brain-ui-sdk/protocol"; -import { requireWorkerHostRecorded } from "../agent/worker-host.js"; -import type { BackendRegistry } from "../agent/backend.js"; import type { WSContext } from "./clients.js"; import { withSessionId, withTurnScope } from "./frames.js"; -import { makeBridge, emitTurnError, settleTurnIndex } from "./bridge.js"; -import { protectedPaths } from "@schlessera/brain-common/internal/protected-paths"; -import { createTurnRecorder, type TurnRecorder } from "../activity/recorder.js"; -import { resolveTurnTarget } from "./routing.js"; import { withLocalContext } from "./local-exchanges.js"; import { acceptDraft } from "./drafts.js"; import { acceptRequest } from "./recovery.js"; -import type { AuthorizationContext, HostWork, HostWorkOutcome, QueuedFollowUp, RunningTurn, StartingSession } from "./turns.js"; -import { queuedBytes, queuedFollowUpBytes, REVOKED_REASON } from "./turns.js"; - -/** Why a follow-up leaves when its session's slot ends without running it (#1002). */ -const SLOT_ENDED_REASON = "The session stopped before it ran."; +import type { AuthorizationContext, HostWork, QueuedFollowUp, RunningTurn } from "./turns.js"; +import { queuedBytes, queuedFollowUpBytes } from "./turns.js"; import type { WsHost } from "./host.js"; -import { MAX_SESSION_QUEUE, QUEUE_MAX_BYTES, QUEUE_WARN_BYTES, turnLogAttributes } from "./limits.js"; - -/** - * Run one session slot: the initial turn, then any queued follow-up turns in - * order. The host owns per-turn cancellation (AbortController + timeout). Never - * throws — runtime failures are emitted as error frames. - */ -/** - * Write out cancellations that were accepted before a recorder existed. - * - * A cancel can land while routing or billing is still in flight, when there is - * nothing to record it on yet, so the actor is buffered on the turn. Both exits - * from that window have to drain it — the ordinary one, which then has a - * recorder, and the revoked one, which must build a throwaway recorder rather - * than drop a decision someone actually made. - */ -function recordPendingCancellations( - host: WsHost, - turn: RunningTurn, - billing: Awaited> | undefined, - lifecycle?: ReturnType -): void { - if (turn.pendingCancellationPrincipalIds.length === 0) return; - if (lifecycle && !turn.recorder) { - for (const principalId of turn.pendingCancellationPrincipalIds) lifecycle.recordCancellation(principalId); - turn.pendingCancellationPrincipalIds.length = 0; - return; - } - const recorder = - turn.recorder ?? - (host.activity - ? createTurnRecorder( - { - store: host.activity.store, - ...(host.activity.runtime ? { runtime: host.activity.runtime } : {}), - ...(host.activity.governance ? { governance: host.activity.governance } : {}), - onWrite: () => host.activity!.stream.pump(), - log: host.log, - }, - { - turnId: turn.turnId, - sessionId: turn.sessionId, - principalId: turn.principalId, - ...billing, - } - ) - : undefined); - for (const principalId of turn.pendingCancellationPrincipalIds) { - recorder?.recordCancellation(principalId); - } - turn.pendingCancellationPrincipalIds.length = 0; -} +import { MAX_SESSION_QUEUE, QUEUE_MAX_BYTES, QUEUE_WARN_BYTES } from "./limits.js"; +import { bindRequest, closeSessionSlot, dequeueRequest, dropHandedOver, firstRequest, openSessionSlot, requestLifecycle } from "./session-run/slot.js"; +import { runSlotTurn } from "./session-run/turn.js"; +import type { HandoffHooks, RunSessionInput, TurnLifecycle } from "./session-run/types.js"; +import { REVOKED_REASON } from "./turns.js"; -type RunSessionInput = { - shareId?: string; - authorization: AuthorizationContext; - replayPrompt?: string; - isRetry?: boolean; - text: string; - sessionId?: string; - historyOwnerId?: string; - attachments: ChatImageAttachment[]; - files?: import("@schlessera/brain-ui-sdk/protocol").SharedFileMeta[]; - providerId?: string; - client?: ClientEnvironment; - source?: MessageSource; - thinkingLevel?: ThinkingLevel; - requestId?: string; - /** Client correlation id for a new conversation; echoed on session_info. */ - draftId?: string; - /** The saved draft revision this message was sent from (#979). */ - draftRef?: DraftRef; - profileDraftId?: string; - /** Accepted-work revision of this request (#964), for a known session. */ - revision?: number; - /** - * Local exchanges the draft conversation holds (#582). Recorded against - * the session once `session_info` names it, and carried on its first - * prompt. - */ - localExchanges?: LocalExchange[]; - /** A handoff destination's hooks (#61); only on a new conversation. */ - handoffHooks?: HandoffHooks; - /** Host-orchestrated work this message carries (#957). */ - work?: HostWork; -}; - -/** - * What a handoff creation (#61) needs from the run that creates its - * destination: the moment `session_info` names it, and the moment the - * attempt is over, whichever way it ended. - */ -export interface HandoffHooks { - /** The conversation handed off: its provider history continues in the destination (#2695). */ - readonly sourceSessionId?: string; - onNamed(sessionId: string): void; - onSettled(): void; -} +export { resolveRunBilling } from "./session-run/billing.js"; +export type { HandoffHooks } from "./session-run/types.js"; /** * A queue lease that also settles the work it carries. Every queue exit @@ -150,23 +41,10 @@ function leaseFor(authorization: AuthorizationContext, work: HostWork | undefine } /** - * Record a new conversation's local exchanges against the session its first - * turn created, and tell every client whether each one is kept: the client - * that ran them holds them in a draft that has just become this session. + * Run one session slot: the initial turn, then any queued follow-up turns in + * order. The host owns per-turn cancellation (AbortController + timeout). Never + * throws — runtime failures are emitted as error frames. */ -function recordDraftExchanges(host: WsHost, sessionId: string, exchanges: readonly LocalExchange[]): void { - for (const exchange of exchanges) { - // Each is answered once it is stored (#2850). - void (host.catalog.recordLocalExchange?.(sessionId, exchange, true) ?? Promise.resolve(false)).then(saved => host.sendToClients({ - type: "local_exchange_result", - sessionId, - exchangeId: exchange.id, - saved, - ...(saved ? {} : { reason: "The server could not store it." }), - })); - } -} - export async function runSession(host: WsHost, initial: RunSessionInput): Promise { if (host.closing) throw new Error("The host is shutting down; no new turn was started."); const turnId = crypto.randomUUID(); @@ -193,829 +71,64 @@ export async function runSession(host: WsHost, initial: RunSessionInput): Promis } } +/** + * The slot's lifecycle: setup, then each request in queue order, then + * teardown. Each request is bound to the slot, run as one turn + * (`session-run/turn.ts`), and the slot advances to the session and profile + * that turn left behind. + */ async function runRetainedSession( host: WsHost, initial: RunSessionInput, initialTurnId: string, - initialLifecycle: ReturnType | undefined + initialLifecycle: TurnLifecycle | undefined ): Promise { - const { coordinator } = host; - const starting: StartingSession = { - queue: [], - cancelled: false, - ...(initial.revision !== undefined ? { revision: initial.revision } : {}), - }; - coordinator.beginStarting(initial.sessionId, starting); - let target: Awaited>; - try { - target = await resolveTurnTarget(host.registry, host.catalog, initial.sessionId, initial.providerId); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - initialLifecycle?.finish("error", message); - // No turn exists yet — routing failed before one was minted — so the - // report carries only the session identity the client asked for. - host.reportTurnFailed("BACKEND_ERROR", { sessionId: initial.sessionId }, message); - initial.work?.settle("error", { reason: message }); - // Messages queued behind this start have no runner now: settle their - // work and release their leases instead of stranding them. - for (const entry of starting.queue) entry.work?.settle("error", { reason: message }); - if (initial.sessionId) coordinator.dropStartingQueue(initial.sessionId, starting, message); - else for (const entry of starting.queue.splice(0)) entry.releaseAuthorization(); - host.sendToClients({ - type: "error", - code: "BACKEND_ERROR", - message, - ...(initial.sessionId ? { sessionId: initial.sessionId } : {}), - ...(initial.requestId ? { requestId: initial.requestId } : {}), - }); - return; - } finally { - coordinator.endStarting(initial.sessionId, starting); - } - - if (starting.cancelled || host.closing) { - for (const entry of starting.queue.splice(0)) entry.releaseAuthorization(); - return; - } - if (!initial.authorization.valid) { - if (initial.sessionId) coordinator.dropStartingQueue(initial.sessionId, starting, REVOKED_REASON); - else for (const entry of starting.queue.splice(0)) entry.releaseAuthorization(); - return; - } - - const { backend, profileId: initialProfileId } = target; - if (target.droppedPin) { - host.log.emit({ - severityText: "WARN", - body: "pinned profile unavailable; running on the default profile", - attributes: { "session.id": initial.sessionId, profile: target.droppedPin }, - }); - host.sendToClients({ - type: "status", - status: "thinking", - detail: `Pinned model "${target.droppedPin}" is unavailable — running on the default.`, - ...(initial.sessionId ? { sessionId: initial.sessionId } : {}), - }); - } - const turn: RunningTurn = { - principalId: initial.authorization.principalId, - authorization: initial.authorization, - sessionId: initial.sessionId ?? null, - turnId: initialTurnId, - // Only meaningful when the client had no session id to send. - draftId: initial.sessionId ? null : (initial.draftId ?? null), - providerId: initialProfileId ?? null, - backend, - abortController: new AbortController(), - timeoutHandle: setTimeout(() => {}, 0), - queue: starting.queue, - pendingCancellationPrincipalIds: [], - cancelled: false, - lastResult: null, - }; - turn.shareId = initial.shareId; - const firstTurnId = turn.turnId; - clearTimeout(turn.timeoutHandle); - coordinator.registerTurn(turn); - - let profileId = initialProfileId; - let resumeId = initial.sessionId; - // Only the first turn of a new conversation carries the draft's exchanges. - let draftExchanges = initial.sessionId ? [] : (initial.localExchanges ?? []); - let next: QueuedFollowUp | null = { - principalId: initial.authorization.principalId, - authorization: initial.authorization, - text: initial.text, - attachments: initial.attachments, - ...(initial.files?.length ? { files: initial.files } : {}), - ...(initial.client ? { client: initial.client } : {}), - ...(initial.source ? { source: initial.source } : {}), - ...(initial.thinkingLevel !== undefined ? { thinkingLevel: initial.thinkingLevel } : {}), - ...(initial.requestId ? { requestId: initial.requestId } : {}), - ...(initial.draftRef ? { draftRef: initial.draftRef } : {}), - ...(initial.revision !== undefined ? { revision: initial.revision } : {}), - ...(initial.work ? { work: initial.work } : {}), - releaseAuthorization: () => { - initial.work?.settle("cancelled", { reason: "The session ended before this request ran" }); - }, - }; - let releaseActiveAuthorization: (() => void) | undefined; - // Take the next queued follow-up. It stays pending, as `handingOver`, until - // its turn reaches the backend (#1002). - const dequeue = (): QueuedFollowUp | null => { - const entry = turn.queue.shift() ?? null; - turn.handingOver = entry ?? undefined; - if (entry) { - // A queued follow-up is its own turn — give it a fresh identity, and - // its own terminal disposition. - turn.turnId = entry.lifecycleTurnId ?? crypto.randomUUID(); - turn.lastResult = null; - } - return entry; - }; - // A handed-over entry that will not run leaves the pending list with why. - const dropHandedOver = (entry: QueuedFollowUp, reason: string): void => { - if (turn.handingOver !== entry) return; - turn.handingOver = undefined; - coordinator.queueChanged(turn.sessionId, { dropped: { entries: [entry], reason } }); - }; - + const slot = await openSessionSlot(host, initial, initialTurnId, initialLifecycle); + if (!slot) return; + const { turn } = slot; + let next: QueuedFollowUp | null = firstRequest(initial); let activeLifecycle = initialLifecycle; try { while (next && !turn.cancelled) { const current: QueuedFollowUp = next; - const lifecycle = turn.turnId === initialTurnId ? initialLifecycle : current.lifecycle ?? (host.activity - ? createTurnLifecycle(host.activity.store, turn.turnId, turn.sessionId, current.queuedAt ?? Date.now(), () => host.activity!.stream.pump()) : undefined); + const lifecycle = requestLifecycle(slot, current, initialLifecycle); activeLifecycle = lifecycle; if (current.queuedAt !== undefined) lifecycle?.mark("dequeuedAt"); - releaseActiveAuthorization = current.releaseAuthorization; - // The slot now holds this request; recovery reads it as queued until - // its turn is handed to the backend (#964). - turn.revision = current.revision; - turn.startedAt = undefined; - turn.principalId = current.principalId; - turn.authorization = current.authorization; - if (!turn.authorization.valid) { - lifecycle?.finish("cancelled", REVOKED_REASON); - releaseActiveAuthorization(); - releaseActiveAuthorization = undefined; - host.budgets?.end(turn.turnId); - turn.revision = undefined; - dropHandedOver(current, REVOKED_REASON); - next = dequeue(); + slot.releaseActive = current.releaseAuthorization; + if (bindRequest(slot, current, lifecycle) === "revoked") { + dropHandedOver(slot, current, REVOKED_REASON); + next = dequeueRequest(turn); continue; } - const { text, attachments, files, client, source, thinkingLevel, requestId, draftRef, work } = current; - turn.requestId = requestId; - turn.draftRef = draftRef; - turn.work = work; next = null; - - let workerIdentity: import("@schlessera/brain-ui-sdk/internal").WorkerNoteFacts["identity"]; - // The turn's own controller exists before the host check is awaited, so - // a cancel accepted while the probe runs (#2416) aborts this turn's - // admission, as one accepted during billing does. - const abortController = new AbortController(); - turn.abortController = abortController; - // Before transcript/source/failure recording or any runtime initialization. - // Every queued interactive or voice turn repeats the actual host check. - try { - const workerHost = await requireWorkerHostRecorded(host.brainPath ?? process.cwd(), "ordinary", host.activity?.runtime, { identitySentinelDirectory: host.identitySentinelDirectory }); - if (workerHost?.identity === "separate_uid" && workerHost.workerUid !== undefined) workerIdentity = { kind: "separate_uid", workerUid: workerHost.workerUid }; - // Pi turn-runner declares no voice tool posture. Keep this early - // admission refusal aligned with that direct-consumer guard if Pi - // gains a voice posture, before any native maintenance workers start. - if (backend.id === "pi" && work?.posture === "voice") - throw new BackendRequestError("The pi backend declares no voice tool posture; a voice turn cannot run on it."); - } - catch (error) { - lifecycle?.finish("denied", error instanceof Error ? error.message : String(error)); - emitTurnError(host, turn, error); - work?.settle("error", { reason: error instanceof Error ? error.message : String(error) }); - break; - } - - const timeoutHandle = setTimeout(() => { - host.log.emit({ - severityText: "WARN", - body: "turn timed out", - // Read from the live turn: session_info may have named the session - // after this timer was armed. - attributes: { ...turnLogAttributes(turn), "timeout.ms": host.turnTimeoutMs }, - }); - abortController.abort(); - // Reject any pending interactive request for this turn too. A bridge - // that awaits askUser/approval without racing the abort signal would - // otherwise leave startTurn parked forever after abort(), leaking a - // concurrency slot until restart. Draining unblocks the unwind. - coordinator.drainPendingForTurn(turn, "Turn timed out"); - }, host.turnTimeoutMs); - turn.timeoutHandle = timeoutHandle; - - // One recorder per turn identity: a queued follow-up re-mints turnId - // and gets its own run in the activity record. The recorder is handed - // the RESOLVED profile — `profileId` here is post pin-drop fallback and - // carries any session_info re-pin forward between queued turns — plus - // its billing mode, so the run's root span classifies what actually ran, - // never what was requested. - const billing = await resolveRunBilling(host.registry, backend.id, profileId); - const failureRecording = await host.failureReplay.begin(backend, resumeId, turn.turnId, abortController.signal); - // Revocation can land while routing or billing is in flight. This is the - // final await boundary before startTurn, so an invalid principal never - // reaches the backend while an already-running turn remains untouched. - // Expiry is authoritative, not advisory: the sweep that turns an expired - // principal into a revocation runs on a timer, and a follow-up dequeued - // inside that window would otherwise start — reviewer measured one - // starting 12ms past expiry — and then survive, because a started turn is - // deliberately never aborted. Enforce it at the same boundary that - // enforces revocation, so the timer only has to close the socket. - host.expireAuthorizationContexts(); - if (!turn.authorization.valid) { - host.budgets?.end(turn.turnId); - turn.revision = undefined; - await failureRecording.finish(); - clearTimeout(timeoutHandle); - // A cancellation accepted while billing was in flight is already a - // decision someone made; losing it because the turn's own principal - // was revoked a moment later would erase the actor, not the turn. Drain - // the buffer before leaving. - recordPendingCancellations(host, turn, billing, lifecycle); - lifecycle?.finish("cancelled", REVOKED_REASON); - releaseActiveAuthorization(); - releaseActiveAuthorization = undefined; - dropHandedOver(current, REVOKED_REASON); - next = dequeue(); + const result = await runSlotTurn(slot, current, lifecycle); + if (result === "stop") break; + if (result === "revoked") { + dropHandedOver(slot, current, REVOKED_REASON); + next = dequeueRequest(turn); continue; } - const recorder: TurnRecorder | undefined = host.activity - ? createTurnRecorder( - { - store: host.activity.store, - ...(host.activity.runtime ? { runtime: host.activity.runtime } : {}), - ...(host.activity.governance ? { governance: host.activity.governance } : {}), - onWrite: () => host.activity!.stream.pump(), - log: host.log, - ...(host.activity.governanceDb ? { governanceDb: host.activity.governanceDb } : {}), - ...(host.activity.governanceWrites ? { governanceWrites: host.activity.governanceWrites } : {}), - ...(host.brainPath ? { brainPath: host.brainPath } : {}), - abort: error => abortController.abort(error), - }, - { - turnId: turn.turnId, - sessionId: turn.sessionId, - principalId: turn.principalId, - lifecycle, - ...billing, - ...(work?.posture === "voice" ? { posture: "voice" as const } : {}), - } - ) - : undefined; - let mainModel: string | null = billing?.model ?? null; - if (mainModel) recorder?.setMainModel(mainModel); - turn.recorder = recorder; - for (const principalId of turn.pendingCancellationPrincipalIds) { - recorder?.recordCancellation(principalId); - } - turn.pendingCancellationPrincipalIds.length = 0; - // The message's source is recorded in the order the backend receives - // its text, which is the order replay counts identical texts in. A - // resumed session is known now; a new one is named by session_info. - const recordSource = (sid: string): void => - host.catalog.recordMessageSource?.(sid, text, source ?? "typed", { thinkingLevel, turnId: turn.turnId, files }); - // A follow-up the backend refused had its source recorded when it was - // first handed over (#1063). - turn.retryRequest = { - type: "chat_message", text, attachments, - ...(files?.length ? { files: files.map(file => ({ kind: "file" as const, path: file.path })) } : {}), - ...(profileId ? { providerId: profileId } : {}), - ...(client ? { client } : {}), ...(source ? { source } : {}), - ...(thinkingLevel !== undefined ? { thinkingLevel } : {}), - ...(requestId ? { requestId } : {}), - }; - turn.isManualRetry = initial.isRetry === true && turn.turnId === firstTurnId; - const startedAt = Date.now(); - // Host admission has started: recovery reads this request as running. - turn.startedAt = startedAt; - if (turn.revision !== undefined && resumeId) { - host.catalog.dispatchWork?.(resumeId, turn.revision, turn.turnId, backend.id, startedAt); - } - // The follow-up is the agent's now: it leaves the pending list ahead of - // every frame of its own turn, so a client can place it in the - // transcript where it entered the conversation (#1002). A cancel that - // landed while billing resolved has already reported it dropped. - if (turn.handingOver === current) { - turn.handingOver = undefined; - coordinator.queueChanged(turn.sessionId, { started: { entry: current, turnId: turn.turnId } }); - } - host.reportTurnStarted(turn); - work?.started(turn.turnId); - let lifecycleOutcome: import("@schlessera/brain-ui-sdk/protocol").ActivitySpanOutcome = "error"; - let workOutcome: HostWorkOutcome = "error"; - let workReason: string | undefined; - let governedHold: import("../brain/governed-turn.js").GovernedTurnHold | undefined; - let turnEgress: Awaited> | undefined; - let providerRelay: ProviderRelay | undefined; - let worktreeGeneration: import("../brain/reference-worktrees.js").ReferenceWorktreeGeneration | undefined; - let referenceViews: { public: string; private: string } | null = null, referenceTurn = false; - let journalFailure: Error | undefined; - let budgetFailure: Error | undefined; - const budgetWrites = new Set>(); - let scopeStopReason: string | undefined; - turn.backendStarted = false; - let enteredBackend = false; - // Index updates this turn's applications queued (#2835): flushed once its - // workers stop, before its Activity terminal, on every outcome. - let settleIndex: (() => Promise) | undefined; - let cancelledAdmission = false; - let revokedAdmission = false; - try { - if (initial.profileDraftId && (!initial.draftId || !initial.requestId || initial.sessionId - || (initial.draftRef && initial.draftRef.draftId !== initial.profileDraftId))) - throw new Error("A draft profile requires the matching first-send identity and correlation."); - const origin = work?.posture === "voice" ? "voice" : "interactive"; - const preference = origin === "interactive" - ? host.sessionProfiles?.preference(turn.principalId, resumeId, resumeId ? undefined : initial.profileDraftId) : undefined; - if (host.governedTurns) lifecycle?.mark("governedStartedAt"); - else lifecycle?.skip("governed"); - // Only a backend whose turn runs on the host inference relay can name - // the origin that relay forwards to; admission proves the recipient - // from it, and the relay below refuses any other (#2695). - const relayed = backend.id === "claude" || backend.id === "pi"; - const inferenceOrigin = host.governedTurns && relayed && backend.inferenceOrigin - ? await backend.inferenceOrigin({ ...(profileId ? { profileId } : {}), ...(resumeId ? { sessionId: resumeId } : {}) }).catch(() => undefined) : undefined; - abortController.signal.throwIfAborted(); - const handoffSource = !resumeId && turn.turnId === firstTurnId ? initial.handoffHooks?.sourceSessionId : undefined; - governedHold = await host.governedTurns?.begin(turn.turnId, abortController.signal, origin, preference, { - ...(inferenceOrigin ? { inferenceOrigin } : {}), ...(resumeId ? { sessionId: resumeId } : {}), ...(handoffSource ? { inherit: [handoffSource] } : {}) }); - if (governedHold) lifecycle?.mark("governedAcquiredAt"); - if (!governedHold || !host.budgets) lifecycle?.skip("budget"); - if (!governedHold || !host.journal) lifecycle?.skip("journal"); - if (governedHold && host.budgets) { - lifecycle?.mark("budgetStartedAt"); - try { await host.budgets.begin(turn.turnId,resumeId,governedHold.policy.policy,billing?.pricingRoute); } - catch (error) { if(error instanceof BudgetExceeded) throw error; throw new BudgetUnavailable(); } - } - if (governedHold && host.budgets) lifecycle?.mark("budgetAdmittedAt"); - try { if(governedHold && host.budgets) for(const item of await host.budgets.warnings(turn.turnId)) host.activity?.governance?.({ - kind:"budget_warning",turnId:turn.turnId,sessionId:turn.sessionId,actor:origin,model:mainModel,profile:governedHold.sandbox.profile ?? "strict", - payload:{scope:item.scope,unit:item.costUsd !== null && item.costUsd >= item.warnUsd ? "usd":"tokens", - limit:item.costUsd !== null && item.costUsd >= item.warnUsd ? item.warnUsd:item.warnTokens!, - observed:item.costUsd !== null && item.costUsd >= item.warnUsd ? item.costUsd:item.tokens!,source:governedHold.policy.hash ? "policy":"default"}}); } catch {throw new BudgetUnavailable();} - if (governedHold) recorder?.setWorkerProfile(governedHold.sandbox.profile ?? "strict"); - if (governedHold && host.journal) { - lifecycle?.mark("journalStartedAt"); - await host.journal.begin(turn.turnId, { sessionId: turn.sessionId ?? null, - actor: work?.posture === "voice" ? "voice" : "interactive", model: mainModel, - profile: governedHold.sandbox.profile === "governed" ? "governed" : "strict", policyHash: governedHold.policy.hash }, - error => { - // A real timeout/cancel already won; never relabel that terminal. - if (abortController.signal.aborted || turn.cancelled) return; - journalFailure = error; - abortController.abort(error); - coordinator.drainPendingForTurn(turn, error.message); - }, abortController.signal); - lifecycle?.mark("journalBeganAt"); - } - abortController.signal.throwIfAborted(); - // Managed worktrees (#2430): a journaled turn's workers bind one empty generation. - // A worktree reaches it only through an access that first covers it in this journal. - if (governedHold && host.journal && host.referenceWorktreeAccess && host.referenceWorktrees && host.journal.summary(turn.turnId).state === "recording") { - try { - worktreeGeneration = await host.referenceWorktrees.openGeneration({ principalId: turn.principalId, turnId: turn.turnId, - profile: governedHold.sandbox.profile === "governed" ? "governed" : "strict", signal: abortController.signal }); - host.referenceWorktreeGenerations.set(turn.turnId, worktreeGeneration); - } catch (error) { - // The turn runs without worktree access; nothing was granted. - if (abortController.signal.aborted) throw error; - host.log.emit({ severityText: "WARN", body: `managed worktree generation unavailable for this turn: ${String(error)}` }); - } - } - // Reference tools (#2432): the turn's workers bind the principal's source - // views and the generation above; the tools report only what they bind. - if (governedHold && host.referenceTools) { - referenceTurn = true; - referenceViews = await host.referenceTools.begin(turn.turnId, { principalId: turn.principalId, posture: work?.posture === "voice" ? "voice" : "interactive", - generation: worktreeGeneration ?? null, signal: abortController.signal }); - } - const scopeTurnId = turn.turnId; - if (governedHold && host.scope) await host.scope.begin(scopeTurnId, { sessionId: turn.sessionId ?? null, principalId: turn.principalId, - origin, model: () => mainModel, profile: governedHold.sandbox.profile === "governed" ? "governed" : "strict", policy: governedHold.policy.policy, - source: governedHold.policy.source === "default" ? "default" : "policy", hardTimeoutMs: host.turnTimeoutMs, - current: () => turn.turnId === scopeTurnId && !abortController.signal.aborted && current.authorization.valid && current.authorization.expiresAt > Date.now() && host.isPrincipalAuthorized(current.principalId), - stop: reason => { - if (turn.turnId !== scopeTurnId || abortController.signal.aborted) return; - scopeStopReason = reason; turn.cancelled = true; - const frame = withTurnScope({ type: "text_delta", text: reason }, turn, turn.turnId); - host.sendToClients(frame); work?.observe(frame); - abortController.abort(new Error(reason)); coordinator.drainPendingForTurn(turn, reason); - } }); - abortController.signal.throwIfAborted(); - // Native admission awaits can outlive principal revocation or expiry. - // Refuse this request without cancelling another principal's queue. - host.expireAuthorizationContexts(); - if (!turn.authorization.valid) { revokedAdmission = true; throw new Error(REVOKED_REASON); } - if (resumeId && !current.refusedFollowUp) recordSource(resumeId); - // Locally answered commands the agent has not seen yet ride on this - // prompt (#582), taken here, past the last await, so an exchange is - // only marked carried by a prompt that is actually handed over. The - // source above is recorded for the user's text alone, which is what - // replay matches once the context is stripped again. - const drafted = draftExchanges; - draftExchanges = []; - const prompt = (initial.replayPrompt !== undefined && turn.turnId === firstTurnId) ? initial.replayPrompt : withLocalContext(withTrackFiles(text, files), [ - ...drafted, - ...(current.refusedFollowUp?.exchanges ?? []), - ...(resumeId ? (host.catalog.takePendingLocalExchanges?.(resumeId) ?? []) : []), - ]); - turn.retryPrompt = prompt; - // One budget observation's warnings and block: the agent's own - // inference or a relayed CLI provider request (#1673). - const budgetAttribution = () => ({turnId:turn.turnId,sessionId:turn.sessionId,actor:origin,model:mainModel, - profile:governedHold!.sandbox.profile ?? "strict"} as const); - const budgetWarnings = (warnings: readonly BudgetObservation[]) => { - for (const item of warnings) host.activity?.governance?.({kind:"budget_warning",...budgetAttribution(), - payload:{scope:item.scope,unit:item.costUsd !== null && item.costUsd >= item.warnUsd ? "usd":"tokens", - limit:item.costUsd !== null && item.costUsd >= item.warnUsd ? item.warnUsd:item.warnTokens!, - observed:item.costUsd !== null && item.costUsd >= item.warnUsd ? item.costUsd:item.tokens!, - source:governedHold!.policy.hash ? "policy":"default"}}); - }; - const budgetBlocked = (item: BudgetObservation, backstop: boolean) => { - host.activity?.governance?.({kind:"budget_block",...budgetAttribution(),payload:{scope:item.scope, - unit:backstop || item.costUsd !== null && item.costUsd >= item.blockUsd ? "usd":"tokens", - limit:backstop || item.costUsd !== null && item.costUsd >= item.blockUsd ? item.blockUsd:item.blockTokens, - observed:backstop ? item.costUsd ?? 0 : item.costUsd !== null && item.costUsd >= item.blockUsd ? item.costUsd:item.tokens!, - source:governedHold!.policy.hash ? "policy":"default",stage:backstop ? "sdk_backstop":"mid_turn"}}); - budgetFailure=new BudgetExceeded(item,backstop ? "sdk_backstop":"mid_turn"); - recorder?.recordBudgetStop(budgetFailure.message); - abortController.abort(budgetFailure);coordinator.drainPendingForTurn(turn,budgetFailure.message); - }; - const budgetUnavailable = () => { - budgetFailure = new BudgetUnavailable(); - recorder?.recordBudgetStop(budgetFailure.message,"budget_unavailable"); - abortController.abort(budgetFailure);coordinator.drainPendingForTurn(turn,"Inference budget accounting became unavailable."); - }; - // A budget write's commit, and what the turn does with its outcome; - // the turn's outcome waits for every one (#2850). - const budgetWrite = (work: Promise) => { - const pending = work.catch(() => { if (!budgetFailure) budgetUnavailable(); }).finally(() => budgetWrites.delete(pending)); - budgetWrites.add(pending); - }; - const bridge = await makeBridge( - host, - turn, - text, - backend.id, - recorder, - resumeId - ? undefined - : (sid) => { - // A new conversation is accepted the moment it has a name, - // and its turn is already running (#964). - const revision = acceptRequest(host, sid, turn.requestId, backend.id); - turn.revision = revision; - if (revision !== undefined && turn.startedAt !== undefined) { - host.catalog.dispatchWork?.(sid, revision, turn.turnId, backend.id, turn.startedAt); - } - void host.governedTurns?.bindSession(turn.turnId, sid).catch(() => { /* Its exposures stay unbound: a later turn treats the session as unrecorded. */ }); - recordSource(sid); - recordDraftExchanges(host, sid, drafted); - initial.handoffHooks?.onNamed(sid); - }, - failureRecording.observe, - // A follow-up's pill label is its turn's request label (#1004). - () => current.label, - backend.brainApplicationPolicy?.({ profileId, - ...(work?.posture === "voice" ? { posture: "voice", noGrantSurface: true, enforceAllowedTools: true } : {}) }), - governedHold ? protectedPaths(governedHold.policy.policy) : undefined, - governedHold ? { origin, actualProfile: governedHold.sandbox.profile === "governed" ? "governed" : "strict", - ...(initial.profileDraftId && !resumeId && preference ? { draftId: initial.profileDraftId, preference } : {}) } : undefined, - host.budgets && governedHold ? (usage,backstop=false) => { - if (budgetFailure || abortController.signal.aborted || turn.cancelled) return; - // The report is priced now; its receipt, warnings and any block - // follow its commit (#2850), judged against the turn as it is then. - const live = () => !budgetFailure && !abortController.signal.aborted && !turn.cancelled; - try { - if (backstop) { - budgetWrite(host.budgets!.backstop(turn.turnId).then(saved => { if (live()) budgetBlocked({...saved.scopes[0]!,blocked:true}, true); })); - return; - } - const observed = host.budgets!.observe(turn.turnId,usage); - if (!observed) return; - const listPrice = host.budgets!.listPrice(turn.turnId,usage); - budgetWrite(observed.then(result => { - if (!live()) return; - budgetWarnings(result.warnings); - const {costUsd:reportedCost,...counts}=usage; - void reportedCost; - host.sendToClients(withTurnScope({type:"usage",turnId:turn.turnId,usage:{...counts, - ...(result.receipt.listPriceCostUsd !== null ? {costUsd:result.receipt.listPriceCostUsd} : {})}, - observedAt:result.receipt.observedAt,budget:result.receipt},turn)); - if (result.blocked) budgetBlocked(result.blocked, false); - })); - return {...usage,...(listPrice !== null ? {costUsd:listPrice} : {})}; - } catch { budgetUnavailable(); } - } : undefined, - billing, - { current: () => mainModel, bind: model => { - if (host.journal && governedHold && !host.journal.bindModel(scopeTurnId, turn.sessionId, model)) return; - mainModel = model; recorder?.setMainModel(model); - } }, - governedHold?.sandbox.providerMasks ? { folders: governedHold.sandbox.providerMasks.folders, policy: governedHold.policy, - ...(governedHold.typeFolders ? { typeFolders: governedHold.typeFolders } : {}), - ...(governedHold.sandbox.inferenceRecipient ? { recipient: governedHold.sandbox.inferenceRecipient.name } : {}) } : undefined, - governedHold?.dataTree ? { tree: governedHold.dataTree, ...(governedHold.startupView ? { view: governedHold.startupView.root } : {}) } : undefined - ); - // A failed update is already on each application's Activity record, - // and its paths stay queued for the next reader; the turn still ends. - settleIndex = () => settleTurnIndex(bridge).catch(() => {}); - const fallback = governedHold?.sandbox.fallbackReason; - if (fallback) { - const match = /Error: (.+?) is (?:a )?(symlink|hardlinked)/.exec(fallback); - if (match || fallback.includes("another mount")) host.activity?.governance?.({ - kind: "strict_fallback", payload: { path: match?.[1] ?? ".", reason: match?.[2] === "symlink" ? "symlink" : match ? "hardlink" : "mount_point" }, - turnId: turn.turnId, sessionId: turn.sessionId, actor: work?.posture === "voice" ? "voice" : "interactive", model: mainModel, profile: "strict", - }); - } - // A governed or strict Claude or pi turn on managed native storage gets - // its own proxy and the host inference relay (#1665). Without that - // storage the turn keeps its current network; worker-host status says which. - if (governedHold?.sandbox.inferenceRecipient && !(governedHold.managedStorage && relayed)) - throw new Error("This turn's provider folders were admitted for a recipient its inference relay cannot enforce; retry the turn."); - if (governedHold?.managedStorage && relayed) { - const governance = host.activity?.governance, governanceWrites = host.activity?.governanceWrites; - turnEgress = await prepareTurnEgress({ policy: governedHold.policy.policy, bridge, controller: abortController, - turnId: turn.turnId, sessionId: () => turn.sessionId ?? null, model: () => mainModel, - profile: governedHold.sandbox.profile === "governed" ? "governed" : "strict", origin, - // A record's commit failure stops the turn, as a synchronous one did (#2850). - ...(governanceWrites ? { record: (event: Parameters[0]) => governanceWrites.record(event), governanceWrites } - : governance ? { record: (event: Parameters[0]) => governance(event) } : {}), - ...(host.activity?.governanceDb ? { governanceDb: host.activity.governanceDb } : {}), - }); - // The CLI's paid providers reach the network only through this relay, - // which holds their keys, shares the turn's egress admission and - // meters each request on the turn (#1673). - // The turn this relay meters, fixed now: a late report never lands on a later turn. - const egress = turnEgress, hold = governedHold, relayTurnId = turn.turnId; - providerRelay = startProviderRelay({ egress, ...(host.cliProviderOrigins ? { origins: host.cliProviderOrigins } : {}), - admit: async () => { - if (budgetFailure) return { allowed: false, message: budgetFailure.message }; - if (!host.budgets) return { allowed: true }; - try { - const blocked = await host.budgets.providerAdmission(relayTurnId, hold.policy.policy); - // The turn may have stopped while admission waited for earlier budget writes. - const stopped = budgetFailure as Error | undefined; - if (stopped) return { allowed: false, message: stopped.message }; - return blocked ? { allowed: false, message: new BudgetExceeded(blocked, "mid_turn").message } : { allowed: true }; - } catch { return { allowed: false, message: new BudgetUnavailable().message }; } - }, - observe: attempt => { - if (!host.budgets) return; - try { - budgetWrite(host.budgets.observeProvider(relayTurnId, attempt).then(result => { - if (!result || budgetFailure || abortController.signal.aborted || turn.cancelled) return; - // A crossed block refuses each further relayed request (ruling D3 on - // #1673); the agent's next completed response, which sees the same - // scopes, stops the turn as any usage over a block does. - budgetWarnings(result.warnings); - })); - } catch { if (!budgetFailure) budgetUnavailable(); } - }, - }); - linkSync(providerRelay.socketPath, join(egress.dir, PROVIDER_RELAY_SOCKET_NAME)); - const customKeys = heldCustomProviderKeys(host.cliProviderOrigins); - if (customKeys.length) writeFileSync(join(egress.dir, PROVIDER_RELAY_KEYS_NAME), `${customKeys.join("\n")}\n`, { mode: 0o640 }); - } - // The session's recorded untrusted input, read live by outward admission and the note (G6). - const governanceDb = host.activity?.governanceDb; - const commandPolicy = governedHold?.sandbox.commandPolicy && governanceDb ? { ...governedHold.sandbox.commandPolicy, - // A taint submitted to the write worker counts before it commits (#2850). - taint: () => host.activity?.governanceWrites ? host.activity.governanceWrites.taint(turn.turnId, turn.sessionId ?? null) - : sessionTaint(governanceDb, turn.turnId, turn.sessionId ?? null) } : governedHold?.sandbox.commandPolicy; - enteredBackend = true; - turn.backendStarted = true; - lifecycle?.mark("backendInvokedAt"); - await backend.startTurn({ - applicationAuthority: "server", - ...(host.journal && governedHold ? { persistClaudeMemory: (change, save) => host.journal!.persistClaudeMemory(turn.turnId, change, save) } : {}), - ...(governedHold?.startupView ? { workerStartupView: governedHold.startupView } : {}), - ...(host.scope && governedHold ? { workerStarted: worker => host.scope!.workerStarted(scopeTurnId, worker) } : {}), - ...(host.journal && governedHold ? { toolExecution: (toolUseId, path) => host.journal!.toolExecuted(scopeTurnId, toolUseId, path) } : {}), - ...(governedHold ? { workerSandbox: { ...governedHold.sandbox, ...(commandPolicy ? { commandPolicy } : {}), ...(turnEgress ? { egress: turnEgress } : {}), - ...(worktreeGeneration ? { worktrees: { source: worktreeGeneration.path } } : {}), ...(referenceViews ? { references: referenceViews } : {}), noteFacts: { - ...governedHold.sandbox.noteFacts, - ...(workerIdentity ? { identity: workerIdentity } : {}), - history: { journal: Boolean(host.journal && host.journal.summary(turn.turnId).state === "recording"), - userRevert: Boolean(host.turnReverts && host.journal && host.journal.summary(turn.turnId).state === "recording" && work?.posture !== "voice") }, - } }, workerLock: host.workerLock } : {}), - prompt, - ...(host.budgets && governedHold ? {maxBudgetUsd:host.budgets.remaining(turn.turnId), - sessionBudgetLimits: inferenceBudgetLimits(host.budgets.receipt(turn.turnId)), - budgetContext: inferenceBudgetContext(host.budgets.receipt(turn.turnId)), - } : {}), - attachments, - sessionId: resumeId, - profileId, - signal: abortController.signal, - // The budget this very timer enforces, so the backend can put the - // real number in front of the model instead of it finding the cap - // mid-flight. - turnBudgetMs: host.turnTimeoutMs, - bridge: turnEgress?.bridge ?? bridge, - turnId: turn.turnId, - ...(client ? { client } : {}), - ...(thinkingLevel !== undefined ? { thinkingLevel } : {}), - // A new turn started by voice runs the voice posture: the backend's - // named voice allowlist, enforced, with no surface that could grant - // a card (docs/decisions/voice-permission.md). A backend without a - // voice posture refuses the turn. A follow-up joining an ordinary - // turn never gets here, so that turn keeps its posture. - ...(work?.posture === "voice" ? { posture: "voice" as const, enforceAllowedTools: true, noGrantSurface: true } : {}), - }); - turn.backendStarted = false; - await settleIndex?.(); - // Every relayed attempt reports before the turn's accounting closes. - await providerRelay?.stop(); - turnEgress?.stop(); - // Every egress record commits, or fails the turn, before its outcome (#2850). - await turnEgress?.settled(); - const egressFailure = turnEgress?.recordingFailure(); - if (egressFailure) throw egressFailure; - // Final observation is part of this host outcome, after worker writes - // stop and before its Activity terminal, quarantine or gate release. - // A worktree generation retires first: no grant can follow that observation. - if (worktreeGeneration) await host.referenceWorktrees!.retireGeneration(worktreeGeneration.id); - await host.journal?.finish(turn.turnId); - while (budgetWrites.size) await Promise.all([...budgetWrites]); - if (budgetFailure) throw budgetFailure; - if (journalFailure) throw journalFailure; - // A host timeout ends the turn like a cancel: its late result is - // never narrated, and the receipt keeps the reason. - workOutcome = turn.cancelled || abortController.signal.aborted || turn.lastResult === "cancelled" - ? "cancelled" - : turn.lastResult === "error" - ? "error" - : "completed"; - if (scopeStopReason) workReason = scopeStopReason; - else if (abortController.signal.aborted && !turn.cancelled) workReason = "Turn timed out"; - // A resolved startTurn is not a successful turn: backends resolve for - // runtime failures and report them on the terminal result frame, which - // the bridge recorded on the turn. - if (turn.lastResult === "error") { - host.reportTurnFailed("BACKEND_RESULT_ERROR", turn); - } else { - host.reportTurnCompleted(turn, Date.now() - startedAt); - } - // Terminal precedence: cancellation and timeout are host-owned facts; - // otherwise the recorder refines from the buffered result frame. - lifecycleOutcome = turn.cancelled ? "cancelled" : abortController.signal.aborted ? "timeout" : turn.lastResult === "error" ? "error" : "success"; - recorder?.finish( - turn.cancelled - ? "cancelled" - : abortController.signal.aborted - ? "timeout" - : turn.lastResult === "error" - ? "error" - : "success" - ); - } catch (err) { - lifecycle?.mark("failureObservedAt"); - await settleIndex?.(); - await turnEgress?.settled(); - while (budgetWrites.size) await Promise.all([...budgetWrites]); - const egressFailure = turnEgress?.recordingFailure(); - const terminal = budgetFailure ?? journalFailure ?? egressFailure ?? err; - if (terminal instanceof BudgetExceeded && terminal.stage === "admission") { - recorder?.recordBudgetStop(terminal.message); - const item=terminal.observation; - host.activity?.governance?.({kind:"budget_block",turnId:turn.turnId,sessionId:turn.sessionId, - actor:work?.posture === "voice" ? "voice":"interactive",model:mainModel,profile:governedHold?.sandbox.profile ?? "strict", - payload:{scope:item.scope,unit:item.costUsd !== null && item.costUsd >= item.blockUsd ? "usd":"tokens", - limit:item.costUsd !== null && item.costUsd >= item.blockUsd ? item.blockUsd:item.blockTokens, - observed:item.costUsd !== null && item.costUsd >= item.blockUsd ? item.costUsd:item.tokens!, - source:governedHold?.policy.hash ? "policy":"default",stage:"admission"}}); - } - if (terminal instanceof BudgetUnavailable) recorder?.recordBudgetStop(terminal.message,"budget_unavailable"); - cancelledAdmission = !enteredBackend && (turn.cancelled || revokedAdmission) && !budgetFailure && !journalFailure && !egressFailure && !scopeStopReason; - turn.backendStarted = false; - if (!cancelledAdmission && (!scopeStopReason || budgetFailure || journalFailure || egressFailure)) emitTurnError(host, turn, terminal); - lifecycleOutcome = terminal instanceof BudgetExceeded && terminal.stage === "admission" ? "denied" : budgetFailure ? "error" : turn.cancelled || revokedAdmission ? "cancelled" : journalFailure || egressFailure ? "error" : abortController.signal.aborted ? "timeout" : "error"; - recorder?.finish( - budgetFailure ? "error" : turn.cancelled || revokedAdmission ? "cancelled" : journalFailure || egressFailure ? "error" : abortController.signal.aborted ? "timeout" : "error" - ); - // A host timeout is host-terminal like a cancel: its late result is - // never narrated (the work keeps the reason). - workOutcome = budgetFailure ? "error" : turn.cancelled || revokedAdmission || !journalFailure && !egressFailure && abortController.signal.aborted ? "cancelled" : "error"; - workReason = !turn.cancelled && !budgetFailure && !journalFailure && !egressFailure && abortController.signal.aborted - ? "Turn timed out" - : terminal instanceof Error ? terminal.message : String(terminal); - } finally { - await providerRelay?.stop(); - turnEgress?.stop(); - // The session's next turn reads these hosts back as contacted (G6). - await turnEgress?.settled(); - host.dialogue.retireTurn(turn.turnId); - if (referenceTurn) host.referenceTools?.end(turn.turnId); - // No grant after this point: the final observation covers everything granted. - if (worktreeGeneration) await host.referenceWorktrees!.retireGeneration(worktreeGeneration.id).catch(() => {}); - try { - // Observe after backend writers stop, before quarantine and gate release. - await host.journal?.finish(turn.turnId); - } catch (error) { host.log.emit({ severityText: "ERROR", body: `journal final observation failed: ${String(error)}` }); } - if (worktreeGeneration) { - // Its workers exited and the final observation is recorded: park what it held. - host.referenceWorktreeGenerations.delete(turn.turnId); - try { await host.referenceWorktrees!.closeGeneration(worktreeGeneration.id); await host.referenceWorktrees!.reconcile(); } - catch (error) { host.log.emit({ severityText: "ERROR", body: `managed worktree generation close failed; startup recovery retries it: ${String(error)}` }); } - } - host.scope?.finish(turn.turnId); - try { - const reconciled = await governedHold?.end(); - for (const item of reconciled?.quarantined ?? []) { - const info = lstatSync(item.to); - host.activity?.governance?.({ kind: "quarantine", payload: { path: item.path, - tier: isEnvName(item.path) || PROTECTED_TIER_A.includes(item.path as never) ? "A" : "B", - entry: info.isFile() ? "file" : info.isDirectory() ? "directory" : info.isSymbolicLink() ? "symlink" : "other", - bytes: info.isFile() ? info.size : null, trigger: "turn_end", objectId: createHash("sha256").update(item.to).digest("hex") }, - turnId: turn.turnId, sessionId: turn.sessionId, actor: work?.posture === "voice" ? "voice" : "interactive", model: mainModel, - profile: governedHold?.sandbox.profile ?? "strict" }); - } - } - catch (error) { host.log.emit({ severityText: "ERROR", body: `governed reconciliation failed: ${String(error)}` }); } - if (governedHold?.sandbox.profile === "governed") host.governedTurns?.refresh(host.workerLock); - // The recorder has written the terminal: from here on the Activity - // record, not this slot, answers for the request (#964). - await host.inboxTools?.shares?.end(turn.turnId); - turn.shareId = undefined; - host.budgets?.end(turn.turnId); - turn.revision = undefined; - turn.startedAt = undefined; - turn.backendStarted = false; - await failureRecording.finish(turn.sessionId); - lifecycle?.finish(lifecycleOutcome, workReason ?? null); - clearTimeout(timeoutHandle); - turn.recorder = undefined; - work?.settle(workOutcome, { sessionId: turn.sessionId, ...(workReason ? { reason: workReason } : {}) }); - turn.work = undefined; - releaseActiveAuthorization(); - releaseActiveAuthorization = undefined; - // The recorder's writes, terminal included, commit off the event loop - // (#2814); recovery must see them before the final idle notification. - await recorder?.settled(); - // No backend existed to publish its usual cancelled status. Send it - // only after native preparation and host cleanup have settled. - if (cancelledAdmission) host.sendToClients(withTurnScope({ type: "status", status: "cancelled", - detail: "Cancelled before starting", ...(turn.requestId ? { requestId: turn.requestId } : {}) }, turn)); - // A backend result can precede asynchronous journal finalization. - // Recovery now reads the committed terminal, before a successor starts. - else if (turn.sessionId) host.sendToClients(withTurnScope({ type: "status", status: "idle" }, turn)); - } // Subsequent (queued) turns resume the now-known session and keep its // pin. turn.providerId is the resolved profile (set from initial routing // and re-pinned by session_info); carrying it forward stops a queued // follow-up from silently dropping onto the default profile/model/billing. - resumeId = turn.sessionId ?? resumeId; - profileId = turn.providerId ?? profileId; + slot.resumeId = turn.sessionId ?? slot.resumeId; + slot.profileId = turn.providerId ?? slot.profileId; // A live follow-up still being delivered may yet be refused and rejoin // the queue ahead of the messages sent after it: let it settle before // the next of those starts (#1063). With nothing queued the slot ends // as before; a delivery may outlive its turn. if (!turn.cancelled && turn.queue.length > 0) await settleDeliveries(turn); - if (!turn.cancelled) next = dequeue(); + if (!turn.cancelled) next = dequeueRequest(turn); } } catch (error) { activeLifecycle?.finish(turn.cancelled ? "cancelled" : turn.abortController?.signal.aborted ? "timeout" : "error", error instanceof Error ? error.message : String(error)); throw error; } finally { - releaseActiveAuthorization?.(); - next?.releaseAuthorization(); - // Whatever is still pending will never run in this slot. A handed-over - // entry's lease is `next`'s or the active one, both released above. - const unstarted = turn.handingOver; - turn.handingOver = undefined; - const queued = turn.queue.splice(0); - for (const entry of queued) entry.releaseAuthorization(); - coordinator.queueChanged(turn.sessionId, { - dropped: { entries: unstarted ? [unstarted, ...queued] : queued, reason: SLOT_ENDED_REASON }, - }); - coordinator.unregisterTurn(turn); - coordinator.drainPendingForTurn(turn, "Session ended"); - } -} - -/** - * Profile identity + billing mode for a turn's root span. When the slot has no - * resolved profile id (a resumed session whose pin was dropped), the backend - * runs its default profile — the backend's first roster entry — so THAT - * profile's identity and billing are recorded, not the dead pin's. Hidden - * profiles are included: a session pinned to a profile the user later hid - * still runs on it and must classify as it. Never throws: an unreadable - * roster records no billing attrs, and the rollup leaves billing unknown - * rather than inferring it from server credentials. - */ -export async function resolveRunBilling( - registry: BackendRegistry, - backendId: string, - profileId: string | undefined -): Promise< - { profileId: string; model?: string; billingMode?: BillingMode; pricingRoute?: PricingRoute } | undefined -> { - try { - const providers = await registry.listAllProviders({ includeHidden: true }); - const resolved = profileId - ? providers.find((provider) => provider.id === profileId) - : providers.find((provider) => provider.backendId === backendId); - if (!resolved) return undefined; - return { - profileId: resolved.id, - ...(resolved.model ? { model: resolved.model } : {}), - ...(resolved.billingMode ? { billingMode: resolved.billingMode } : {}), - ...(resolved.pricingRoute ? { pricingRoute: resolved.pricingRoute } : {}), - }; - } catch { - return undefined; + closeSessionSlot(slot, next); } } diff --git a/packages/ui-server/src/ws/session-run/admission.ts b/packages/ui-server/src/ws/session-run/admission.ts new file mode 100644 index 0000000000..e0d3d65724 --- /dev/null +++ b/packages/ui-server/src/ws/session-run/admission.ts @@ -0,0 +1,246 @@ +import type { AgentBackend } from "@schlessera/brain-ui-sdk/server"; +import { BackendRequestError } from "@schlessera/brain-ui-sdk/server"; +import type { WorkerNoteFacts } from "@schlessera/brain-ui-sdk/internal"; +import { requireWorkerHostRecorded } from "../../agent/worker-host.js"; +import { createTurnRecorder, type TurnRecorder } from "../../activity/recorder.js"; +import { BudgetExceeded, BudgetUnavailable } from "../../brain/turn-budgets.js"; +import { withTurnScope } from "../frames.js"; +import type { WsHost } from "../host.js"; +import { turnLogAttributes } from "../limits.js"; +import type { HostWork, QueuedFollowUp, RunningTurn } from "../turns.js"; +import type { RunBilling } from "./billing.js"; +import { budgetAttribution, budgetEvent } from "./budget.js"; +import type { SessionSlot, TurnLifecycle, TurnRun } from "./types.js"; + +export type WorkerHostAdmission = + | { readonly kind: "admitted"; readonly identity: WorkerNoteFacts["identity"] | undefined } + | { readonly kind: "denied"; readonly error: unknown }; + +/** + * The host check every interactive or voice turn repeats, before transcript, + * source or failure recording and before any runtime initialization. + */ +export async function admitWorkerHost(host: WsHost, backend: AgentBackend, work: HostWork | undefined): Promise { + try { + const workerHost = await requireWorkerHostRecorded(host.brainPath ?? process.cwd(), "ordinary", host.activity?.runtime, { identitySentinelDirectory: host.identitySentinelDirectory }); + const identity: WorkerNoteFacts["identity"] | undefined = workerHost?.identity === "separate_uid" && workerHost.workerUid !== undefined + ? { kind: "separate_uid", workerUid: workerHost.workerUid } : undefined; + // Pi turn-runner declares no voice tool posture. Keep this early + // admission refusal aligned with that direct-consumer guard if Pi + // gains a voice posture, before any native maintenance workers start. + if (backend.id === "pi" && work?.posture === "voice") + throw new BackendRequestError("The pi backend declares no voice tool posture; a voice turn cannot run on it."); + return { kind: "admitted", identity }; + } catch (error) { + return { kind: "denied", error }; + } +} + +/** + * Arm the host's turn timeout. On expiry the turn aborts, and any pending + * interactive request for it is rejected too: a bridge that awaits + * askUser/approval without racing the abort signal would otherwise leave + * startTurn parked forever after abort(), leaking a concurrency slot until + * restart. Draining unblocks the unwind. + */ +export function armTurnTimeout(host: WsHost, turn: RunningTurn, abortController: AbortController): ReturnType { + const timeoutHandle = setTimeout(() => { + host.log.emit({ + severityText: "WARN", + body: "turn timed out", + // Read from the live turn: session_info may have named the session + // after this timer was armed. + attributes: { ...turnLogAttributes(turn), "timeout.ms": host.turnTimeoutMs }, + }); + abortController.abort(); + host.coordinator.drainPendingForTurn(turn, "Turn timed out"); + }, host.turnTimeoutMs); + turn.timeoutHandle = timeoutHandle; + return timeoutHandle; +} + +/** + * One recorder per turn identity: a queued follow-up re-mints turnId and gets + * its own run in the activity record. The recorder is handed the RESOLVED + * profile — post pin-drop fallback, carrying any session_info re-pin forward + * between queued turns — plus its billing mode, so the run's root span + * classifies what actually ran, never what was requested. + */ +export function createRunRecorder( + host: WsHost, + turn: RunningTurn, + lifecycle: TurnLifecycle | undefined, + billing: RunBilling, + abortController: AbortController, + work: HostWork | undefined +): TurnRecorder | undefined { + return host.activity + ? createTurnRecorder( + { + store: host.activity.store, + ...(host.activity.runtime ? { runtime: host.activity.runtime } : {}), + ...(host.activity.governance ? { governance: host.activity.governance } : {}), + onWrite: () => host.activity!.stream.pump(), + log: host.log, + ...(host.activity.governanceDb ? { governanceDb: host.activity.governanceDb } : {}), + ...(host.activity.governanceWrites ? { governanceWrites: host.activity.governanceWrites } : {}), + ...(host.brainPath ? { brainPath: host.brainPath } : {}), + abort: error => abortController.abort(error), + }, + { + turnId: turn.turnId, + sessionId: turn.sessionId, + principalId: turn.principalId, + lifecycle, + ...billing, + ...(work?.posture === "voice" ? { posture: "voice" as const } : {}), + } + ) + : undefined; +} + +/** + * Mark the request as the agent's: recovery reads it as running from here, + * and it leaves the pending list ahead of every frame of its own turn, so a + * client can place it in the transcript where it entered the conversation + * (#1002). A cancel that landed while billing resolved has already reported + * it dropped. + */ +export function announceTurnStart(slot: SessionSlot, current: QueuedFollowUp, startedAt: number): void { + const { host, turn, backend, resumeId } = slot; + // Host admission has started: recovery reads this request as running. + turn.startedAt = startedAt; + if (turn.revision !== undefined && resumeId) { + host.catalog.dispatchWork?.(resumeId, turn.revision, turn.turnId, backend.id, startedAt); + } + if (turn.handingOver === current) { + turn.handingOver = undefined; + host.coordinator.queueChanged(turn.sessionId, { started: { entry: current, turnId: turn.turnId } }); + } + host.reportTurnStarted(turn); + current.work?.started(turn.turnId); +} + +/** The worker profile a governed turn records: anything not `governed` runs strict. */ +export function heldProfile(run: Pick): "governed" | "strict" { + return run.held.governedHold!.sandbox.profile === "governed" ? "governed" : "strict"; +} + +export type GovernedAdmission = + | { + readonly kind: "admitted"; + /** The principal's profile preference for an interactive turn, which a draft's first send records. */ + readonly preference: "governed" | "strict" | undefined; + } + | { readonly kind: "revoked" }; + +/** + * Governed admission, in order: the governed hold, the budget and its + * warnings, the journal, a managed worktree generation (#2430), reference + * tools (#2432) and per-turn scope caps. What it acquires is recorded on + * {@link TurnRun.held} as it goes, so teardown releases it whichever way the + * turn ends. Throws a refusal or an abort; resolves `revoked` when the + * principal lost authority during the native awaits. + */ +export async function admitGovernedTurn(run: TurnRun): Promise { + const { host, slot, turn, backend, lifecycle, abortController, billing, recorder, held, stops, origin, profileId, resumeId } = run; + const { initial } = slot; + if (initial.profileDraftId && (!initial.draftId || !initial.requestId || initial.sessionId + || (initial.draftRef && initial.draftRef.draftId !== initial.profileDraftId))) + throw new Error("A draft profile requires the matching first-send identity and correlation."); + const preference = origin === "interactive" + ? host.sessionProfiles?.preference(turn.principalId, resumeId, resumeId ? undefined : initial.profileDraftId) : undefined; + if (host.governedTurns) lifecycle?.mark("governedStartedAt"); + else lifecycle?.skip("governed"); + // Only a backend whose turn runs on the host inference relay can name + // the origin that relay forwards to; admission proves the recipient + // from it, and the relay refuses any other (#2695). + const inferenceOrigin = host.governedTurns && isRelayed(backend) && backend.inferenceOrigin + ? await backend.inferenceOrigin({ ...(profileId ? { profileId } : {}), ...(resumeId ? { sessionId: resumeId } : {}) }).catch(() => undefined) : undefined; + abortController.signal.throwIfAborted(); + const handoffSource = !resumeId && turn.turnId === slot.firstTurnId ? initial.handoffHooks?.sourceSessionId : undefined; + held.governedHold = await host.governedTurns?.begin(turn.turnId, abortController.signal, origin, preference, { + ...(inferenceOrigin ? { inferenceOrigin } : {}), ...(resumeId ? { sessionId: resumeId } : {}), ...(handoffSource ? { inherit: [handoffSource] } : {}) }); + const governedHold = held.governedHold; + if (governedHold) lifecycle?.mark("governedAcquiredAt"); + if (!governedHold || !host.budgets) lifecycle?.skip("budget"); + if (!governedHold || !host.journal) lifecycle?.skip("journal"); + if (governedHold && host.budgets) { + lifecycle?.mark("budgetStartedAt"); + try { await host.budgets.begin(turn.turnId, resumeId, governedHold.policy.policy, billing?.pricingRoute); } + catch (error) { if (error instanceof BudgetExceeded) throw error; throw new BudgetUnavailable(); } + } + if (governedHold && host.budgets) lifecycle?.mark("budgetAdmittedAt"); + try { + if (governedHold && host.budgets) for (const item of await host.budgets.warnings(turn.turnId)) + host.activity?.governance?.(budgetEvent("budget_warning", item, budgetAttribution(run))); + } catch { throw new BudgetUnavailable(); } + if (governedHold) recorder?.setWorkerProfile(governedHold.sandbox.profile ?? "strict"); + if (governedHold && host.journal) { + lifecycle?.mark("journalStartedAt"); + await host.journal.begin(turn.turnId, { sessionId: turn.sessionId ?? null, + actor: origin, model: run.mainModel, + profile: heldProfile(run), policyHash: governedHold.policy.hash }, + error => { + // A real timeout/cancel already won; never relabel that terminal. + if (abortController.signal.aborted || turn.cancelled) return; + stops.journal = error; + abortController.abort(error); + host.coordinator.drainPendingForTurn(turn, error.message); + }, abortController.signal); + lifecycle?.mark("journalBeganAt"); + } + abortController.signal.throwIfAborted(); + // Managed worktrees (#2430): a journaled turn's workers bind one empty generation. + // A worktree reaches it only through an access that first covers it in this journal. + if (governedHold && host.journal && host.referenceWorktreeAccess && host.referenceWorktrees && host.journal.summary(turn.turnId).state === "recording") { + try { + held.worktreeGeneration = await host.referenceWorktrees.openGeneration({ principalId: turn.principalId, turnId: turn.turnId, + profile: heldProfile(run), signal: abortController.signal }); + host.referenceWorktreeGenerations.set(turn.turnId, held.worktreeGeneration); + } catch (error) { + // The turn runs without worktree access; nothing was granted. + if (abortController.signal.aborted) throw error; + host.log.emit({ severityText: "WARN", body: `managed worktree generation unavailable for this turn: ${String(error)}` }); + } + } + // Reference tools (#2432): the turn's workers bind the principal's source + // views and the generation above; the tools report only what they bind. + if (governedHold && host.referenceTools) { + held.referenceTurn = true; + held.referenceViews = await host.referenceTools.begin(turn.turnId, { principalId: turn.principalId, posture: origin, + generation: held.worktreeGeneration ?? null, signal: abortController.signal }); + } + if (governedHold && host.scope) await beginTurnScope(run); + abortController.signal.throwIfAborted(); + // Native admission awaits can outlive principal revocation or expiry. + host.expireAuthorizationContexts(); + if (!turn.authorization.valid) return { kind: "revoked" }; + return { kind: "admitted", preference }; +} + +/** Whether the backend's turn runs on the host inference relay. */ +export function isRelayed(backend: AgentBackend): boolean { + return backend.id === "claude" || backend.id === "pi"; +} + +/** + * Per-turn scope caps (#1670). A cap stops the turn by narrating its reason + * as the turn's text, then aborting it like a cancel. + */ +async function beginTurnScope(run: TurnRun): Promise { + const { host, turn, current, abortController, stops, origin, turnId: scopeTurnId } = run; + const governedHold = run.held.governedHold!; + const work = current.work; + await host.scope!.begin(scopeTurnId, { sessionId: turn.sessionId ?? null, principalId: turn.principalId, + origin, model: () => run.mainModel, profile: heldProfile(run), policy: governedHold.policy.policy, + source: governedHold.policy.source === "default" ? "default" : "policy", hardTimeoutMs: host.turnTimeoutMs, + current: () => turn.turnId === scopeTurnId && !abortController.signal.aborted && current.authorization.valid && current.authorization.expiresAt > Date.now() && host.isPrincipalAuthorized(current.principalId), + stop: reason => { + if (turn.turnId !== scopeTurnId || abortController.signal.aborted) return; + stops.scope = reason; turn.cancelled = true; + const frame = withTurnScope({ type: "text_delta", text: reason }, turn, turn.turnId); + host.sendToClients(frame); work?.observe(frame); + abortController.abort(new Error(reason)); host.coordinator.drainPendingForTurn(turn, reason); + } }); +} diff --git a/packages/ui-server/src/ws/session-run/backend-entry.ts b/packages/ui-server/src/ws/session-run/backend-entry.ts new file mode 100644 index 0000000000..c8041e2223 --- /dev/null +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -0,0 +1,229 @@ +import { linkSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { PROVIDER_RELAY_KEYS_NAME, PROVIDER_RELAY_SOCKET_NAME, heldCustomProviderKeys, startProviderRelay } from "@schlessera/brain-ui-sdk/internal"; +import { protectedPaths } from "@schlessera/brain-common/internal/protected-paths"; +import type { BackendBridge, StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { prepareTurnEgress } from "../../brain/turn-egress.js"; +import { BudgetExceeded, BudgetUnavailable, inferenceBudgetContext, inferenceBudgetLimits } from "../../brain/turn-budgets.js"; +import { sessionTaint } from "../../governance/session-taint.js"; +import { withTrackFiles } from "../../tracks/read.js"; +import { makeBridge, settleTurnIndex } from "../bridge.js"; +import { withLocalContext } from "../local-exchanges.js"; +import { acceptRequest } from "../recovery.js"; +import type { WsHost } from "../host.js"; +import type { LocalExchange } from "@schlessera/brain-ui-sdk/protocol"; +import { heldProfile, isRelayed, type GovernedAdmission } from "./admission.js"; +import type { TurnBudget } from "./budget.js"; +import type { TurnRun } from "./types.js"; + +/** + * Record a new conversation's local exchanges against the session its first + * turn created, and tell every client whether each one is kept: the client + * that ran them holds them in a draft that has just become this session. + */ +export function recordDraftExchanges(host: WsHost, sessionId: string, exchanges: readonly LocalExchange[]): void { + for (const exchange of exchanges) { + // Each is answered once it is stored (#2850). + void (host.catalog.recordLocalExchange?.(sessionId, exchange, true) ?? Promise.resolve(false)).then(saved => host.sendToClients({ + type: "local_exchange_result", + sessionId, + exchangeId: exchange.id, + saved, + ...(saved ? {} : { reason: "The server could not store it." }), + })); + } +} + +/** The message's source, recorded in the order the backend receives its text, which is the order replay counts identical texts in. */ +function recordSource(run: TurnRun, sessionId: string): void { + const { text, source, thinkingLevel, files } = run.current; + run.host.catalog.recordMessageSource?.(sessionId, text, source ?? "typed", { thinkingLevel, turnId: run.turn.turnId, files }); +} + +/** + * Build the turn's prompt and its event bridge. A resumed session records the + * message source now; a new one does once session_info names it. Locally + * answered commands the agent has not seen yet ride on this prompt (#582), + * taken past the last admission await, so an exchange is only marked carried + * by a prompt that is actually handed over. The source is recorded for the + * user's text alone, which is what replay matches once the context is + * stripped again. + */ +export async function openTurnBridge( + run: TurnRun, + admission: Extract, + budget: TurnBudget | undefined +): Promise<{ prompt: string; bridge: BackendBridge }> { + const { host, slot, turn, backend, current, recorder, failureRecording, billing, held, origin, profileId, resumeId } = run; + const { initial } = slot; + const { text, files, work } = current; + const governedHold = held.governedHold; + if (resumeId && !current.refusedFollowUp) recordSource(run, resumeId); + const drafted = slot.draftExchanges; + slot.draftExchanges = []; + const prompt = (initial.replayPrompt !== undefined && turn.turnId === slot.firstTurnId) ? initial.replayPrompt : withLocalContext(withTrackFiles(text, files), [ + ...drafted, + ...(current.refusedFollowUp?.exchanges ?? []), + ...(resumeId ? (host.catalog.takePendingLocalExchanges?.(resumeId) ?? []) : []), + ]); + turn.retryPrompt = prompt; + const { preference } = admission; + const bridge = await makeBridge( + host, + turn, + text, + backend.id, + recorder, + resumeId + ? undefined + : (sid) => { + // A new conversation is accepted the moment it has a name, + // and its turn is already running (#964). + const revision = acceptRequest(host, sid, turn.requestId, backend.id); + turn.revision = revision; + if (revision !== undefined && turn.startedAt !== undefined) { + host.catalog.dispatchWork?.(sid, revision, turn.turnId, backend.id, turn.startedAt); + } + void host.governedTurns?.bindSession(turn.turnId, sid).catch(() => { /* Its exposures stay unbound: a later turn treats the session as unrecorded. */ }); + recordSource(run, sid); + recordDraftExchanges(host, sid, drafted); + initial.handoffHooks?.onNamed(sid); + }, + failureRecording.observe, + // A follow-up's pill label is its turn's request label (#1004). + () => current.label, + backend.brainApplicationPolicy?.({ profileId, + ...(work?.posture === "voice" ? { posture: "voice", noGrantSurface: true, enforceAllowedTools: true } : {}) }), + governedHold ? protectedPaths(governedHold.policy.policy) : undefined, + governedHold ? { origin, actualProfile: heldProfile(run), + ...(initial.profileDraftId && !resumeId && preference ? { draftId: initial.profileDraftId, preference } : {}) } : undefined, + budget?.observeUsage, + billing, + { current: () => run.mainModel, bind: model => { + if (host.journal && governedHold && !host.journal.bindModel(run.turnId, turn.sessionId, model)) return; + run.mainModel = model; recorder?.setMainModel(model); + } }, + governedHold?.sandbox.providerMasks ? { folders: governedHold.sandbox.providerMasks.folders, policy: governedHold.policy, + ...(governedHold.typeFolders ? { typeFolders: governedHold.typeFolders } : {}), + ...(governedHold.sandbox.inferenceRecipient ? { recipient: governedHold.sandbox.inferenceRecipient.name } : {}) } : undefined, + governedHold?.dataTree ? { tree: governedHold.dataTree, ...(governedHold.startupView ? { view: governedHold.startupView.root } : {}) } : undefined + ); + // A failed update is already on each application's Activity record, + // and its paths stay queued for the next reader; the turn still ends. + held.settleIndex = () => settleTurnIndex(bridge).catch(() => {}); + const fallback = governedHold?.sandbox.fallbackReason; + if (fallback) { + const match = /Error: (.+?) is (?:a )?(symlink|hardlinked)/.exec(fallback); + if (match || fallback.includes("another mount")) host.activity?.governance?.({ + kind: "strict_fallback", payload: { path: match?.[1] ?? ".", reason: match?.[2] === "symlink" ? "symlink" : match ? "hardlink" : "mount_point" }, + turnId: turn.turnId, sessionId: turn.sessionId, actor: origin, model: run.mainModel, profile: "strict", + }); + } + return { prompt, bridge }; +} + +/** + * A governed or strict Claude or pi turn on managed native storage gets its + * own proxy and the host inference relay (#1665). Without that storage the + * turn keeps its current network; worker-host status says which. The CLI's + * paid providers reach the network only through this relay, which holds + * their keys, shares the turn's egress admission and meters each request on + * the turn (#1673). + */ +export async function prepareRelayedEgress(run: TurnRun, bridge: BackendBridge, budget: TurnBudget | undefined): Promise { + const { host, turn, backend, abortController, held, stops, origin } = run; + const governedHold = held.governedHold; + const relayed = isRelayed(backend); + if (governedHold?.sandbox.inferenceRecipient && !(governedHold.managedStorage && relayed)) + throw new Error("This turn's provider folders were admitted for a recipient its inference relay cannot enforce; retry the turn."); + if (!governedHold?.managedStorage || !relayed) return; + const governance = host.activity?.governance, governanceWrites = host.activity?.governanceWrites; + held.turnEgress = await prepareTurnEgress({ policy: governedHold.policy.policy, bridge, controller: abortController, + turnId: turn.turnId, sessionId: () => turn.sessionId ?? null, model: () => run.mainModel, + profile: heldProfile(run), origin, + // A record's commit failure stops the turn, as a synchronous one did (#2850). + ...(governanceWrites ? { record: (event: Parameters[0]) => governanceWrites.record(event), governanceWrites } + : governance ? { record: (event: Parameters[0]) => governance(event) } : {}), + ...(host.activity?.governanceDb ? { governanceDb: host.activity.governanceDb } : {}), + }); + // The turn this relay meters, fixed now: a late report never lands on a later turn. + const egress = held.turnEgress, hold = governedHold, relayTurnId = turn.turnId; + held.providerRelay = startProviderRelay({ egress, ...(host.cliProviderOrigins ? { origins: host.cliProviderOrigins } : {}), + admit: async () => { + if (stops.budget) return { allowed: false, message: stops.budget.message }; + if (!host.budgets) return { allowed: true }; + try { + const blocked = await host.budgets.providerAdmission(relayTurnId, hold.policy.policy); + // The turn may have stopped while admission waited for earlier budget writes. + const stopped = stops.budget as Error | undefined; + if (stopped) return { allowed: false, message: stopped.message }; + return blocked ? { allowed: false, message: new BudgetExceeded(blocked, "mid_turn").message } : { allowed: true }; + } catch { return { allowed: false, message: new BudgetUnavailable().message }; } + }, + observe: attempt => { + if (!host.budgets) return; + try { + budget!.write(host.budgets.observeProvider(relayTurnId, attempt).then(result => { + if (!result || stops.budget || abortController.signal.aborted || turn.cancelled) return; + // A crossed block refuses each further relayed request (ruling D3 on + // #1673); the agent's next completed response, which sees the same + // scopes, stops the turn as any usage over a block does. + budget!.warn(result.warnings); + })); + } catch { if (!stops.budget) budget!.unavailable(); } + }, + }); + linkSync(held.providerRelay.socketPath, join(egress.dir, PROVIDER_RELAY_SOCKET_NAME)); + const customKeys = heldCustomProviderKeys(host.cliProviderOrigins); + if (customKeys.length) writeFileSync(join(egress.dir, PROVIDER_RELAY_KEYS_NAME), `${customKeys.join("\n")}\n`, { mode: 0o640 }); +} + +/** The request the backend's startTurn receives for this admitted turn. */ +export function turnRequest(run: TurnRun, prompt: string, bridge: BackendBridge): StartTurnRequest { + const { host, turn, current, abortController, held, workerIdentity, turnId: scopeTurnId, profileId, resumeId } = run; + const { attachments, client, thinkingLevel, work } = current; + const { governedHold, turnEgress, worktreeGeneration, referenceViews } = held; + // The session's recorded untrusted input, read live by outward admission and the note (G6). + const governanceDb = host.activity?.governanceDb; + const commandPolicy = governedHold?.sandbox.commandPolicy && governanceDb ? { ...governedHold.sandbox.commandPolicy, + // A taint submitted to the write worker counts before it commits (#2850). + taint: () => host.activity?.governanceWrites ? host.activity.governanceWrites.taint(turn.turnId, turn.sessionId ?? null) + : sessionTaint(governanceDb, turn.turnId, turn.sessionId ?? null) } : governedHold?.sandbox.commandPolicy; + return { + applicationAuthority: "server", + ...(host.journal && governedHold ? { persistClaudeMemory: (change, save) => host.journal!.persistClaudeMemory(turn.turnId, change, save) } : {}), + ...(governedHold?.startupView ? { workerStartupView: governedHold.startupView } : {}), + ...(host.scope && governedHold ? { workerStarted: worker => host.scope!.workerStarted(scopeTurnId, worker) } : {}), + ...(host.journal && governedHold ? { toolExecution: (toolUseId, path) => host.journal!.toolExecuted(scopeTurnId, toolUseId, path) } : {}), + ...(governedHold ? { workerSandbox: { ...governedHold.sandbox, ...(commandPolicy ? { commandPolicy } : {}), ...(turnEgress ? { egress: turnEgress } : {}), + ...(worktreeGeneration ? { worktrees: { source: worktreeGeneration.path } } : {}), ...(referenceViews ? { references: referenceViews } : {}), noteFacts: { + ...governedHold.sandbox.noteFacts, + ...(workerIdentity ? { identity: workerIdentity } : {}), + history: { journal: Boolean(host.journal && host.journal.summary(turn.turnId).state === "recording"), + userRevert: Boolean(host.turnReverts && host.journal && host.journal.summary(turn.turnId).state === "recording" && work?.posture !== "voice") }, + } }, workerLock: host.workerLock } : {}), + prompt, + ...(host.budgets && governedHold ? {maxBudgetUsd:host.budgets.remaining(turn.turnId), + sessionBudgetLimits: inferenceBudgetLimits(host.budgets.receipt(turn.turnId)), + budgetContext: inferenceBudgetContext(host.budgets.receipt(turn.turnId)), + } : {}), + attachments, + sessionId: resumeId, + profileId, + signal: abortController.signal, + // The budget this very timer enforces, so the backend can put the + // real number in front of the model instead of it finding the cap + // mid-flight. + turnBudgetMs: host.turnTimeoutMs, + bridge: turnEgress?.bridge ?? bridge, + turnId: turn.turnId, + ...(client ? { client } : {}), + ...(thinkingLevel !== undefined ? { thinkingLevel } : {}), + // A new turn started by voice runs the voice posture: the backend's + // named voice allowlist, enforced, with no surface that could grant + // a card (docs/decisions/voice-permission.md). A backend without a + // voice posture refuses the turn. A follow-up joining an ordinary + // turn never gets here, so that turn keeps its posture. + ...(work?.posture === "voice" ? { posture: "voice" as const, enforceAllowedTools: true, noGrantSurface: true } : {}), + }; +} diff --git a/packages/ui-server/src/ws/session-run/billing.ts b/packages/ui-server/src/ws/session-run/billing.ts new file mode 100644 index 0000000000..56cbea8e48 --- /dev/null +++ b/packages/ui-server/src/ws/session-run/billing.ts @@ -0,0 +1,38 @@ +import type { BillingMode, PricingRoute } from "@schlessera/brain-ui-sdk/protocol"; +import type { BackendRegistry } from "../../agent/backend.js"; + +export type RunBilling = Awaited>; + +/** + * Profile identity + billing mode for a turn's root span. When the slot has no + * resolved profile id (a resumed session whose pin was dropped), the backend + * runs its default profile — the backend's first roster entry — so THAT + * profile's identity and billing are recorded, not the dead pin's. Hidden + * profiles are included: a session pinned to a profile the user later hid + * still runs on it and must classify as it. Never throws: an unreadable + * roster records no billing attrs, and the rollup leaves billing unknown + * rather than inferring it from server credentials. + */ +export async function resolveRunBilling( + registry: BackendRegistry, + backendId: string, + profileId: string | undefined +): Promise< + { profileId: string; model?: string; billingMode?: BillingMode; pricingRoute?: PricingRoute } | undefined +> { + try { + const providers = await registry.listAllProviders({ includeHidden: true }); + const resolved = profileId + ? providers.find((provider) => provider.id === profileId) + : providers.find((provider) => provider.backendId === backendId); + if (!resolved) return undefined; + return { + profileId: resolved.id, + ...(resolved.model ? { model: resolved.model } : {}), + ...(resolved.billingMode ? { billingMode: resolved.billingMode } : {}), + ...(resolved.pricingRoute ? { pricingRoute: resolved.pricingRoute } : {}), + }; + } catch { + return undefined; + } +} diff --git a/packages/ui-server/src/ws/session-run/budget.ts b/packages/ui-server/src/ws/session-run/budget.ts new file mode 100644 index 0000000000..cdbbc3c467 --- /dev/null +++ b/packages/ui-server/src/ws/session-run/budget.ts @@ -0,0 +1,132 @@ +import type { BudgetObservation, TurnUsage } from "@schlessera/brain-ui-sdk/protocol"; +import { BudgetExceeded, BudgetUnavailable } from "../../brain/turn-budgets.js"; +import type { GovernanceEventInput } from "../../governance/events.js"; +import { withTurnScope } from "../frames.js"; +import type { TurnRun } from "./types.js"; + +/** Who a budget event is recorded for: the turn as it is when the event is written. */ +export interface BudgetAttribution { + readonly turnId: string; + readonly sessionId: string | null; + readonly actor: "voice" | "interactive"; + readonly model: string | null; + readonly profile: NonNullable; + /** Whether the limits came from the brain's policy or the defaults. */ + readonly source: "policy" | "default"; +} + +export type BudgetBlockStage = "admission" | "mid_turn" | "sdk_backstop"; + +/** Read a budget event's attribution from the live turn. */ +export function budgetAttribution(run: Pick): BudgetAttribution { + const hold = run.held.governedHold; + return { + turnId: run.turn.turnId, + sessionId: run.turn.sessionId, + actor: run.origin, + model: run.mainModel, + profile: hold?.sandbox.profile ?? "strict", + source: hold?.policy.hash ? "policy" : "default", + }; +} + +/** + * The `budget_warning` or `budget_block` governance event for one budget + * observation. A scope is reported in dollars once its cost crosses the + * limit in question, otherwise in tokens; the SDK backstop is always dollars. + */ +export function budgetEvent(kind: "budget_warning", item: BudgetObservation, attribution: BudgetAttribution): GovernanceEventInput<"budget_warning">; +export function budgetEvent(kind: "budget_block", item: BudgetObservation, attribution: BudgetAttribution, stage: BudgetBlockStage): GovernanceEventInput<"budget_block">; +export function budgetEvent( + kind: "budget_warning" | "budget_block", + item: BudgetObservation, + attribution: BudgetAttribution, + stage?: BudgetBlockStage +): GovernanceEventInput<"budget_warning"> | GovernanceEventInput<"budget_block"> { + const { turnId, sessionId, actor, model, profile, source } = attribution; + if (kind === "budget_warning") { + const usd = item.costUsd !== null && item.costUsd >= item.warnUsd; + return { kind, turnId, sessionId, actor, model, profile, + payload: { scope: item.scope, unit: usd ? "usd" : "tokens", limit: usd ? item.warnUsd : item.warnTokens!, + observed: usd ? item.costUsd! : item.tokens!, source } }; + } + const backstop = stage === "sdk_backstop"; + const usd = backstop || item.costUsd !== null && item.costUsd >= item.blockUsd; + return { kind, turnId, sessionId, actor, model, profile, + payload: { scope: item.scope, unit: usd ? "usd" : "tokens", limit: usd ? item.blockUsd : item.blockTokens, + observed: backstop ? item.costUsd ?? 0 : usd ? item.costUsd! : item.tokens!, source, stage: stage! } }; +} + +/** One governed turn's mid-turn budget accounting: warnings, blocks and write commits. */ +export interface TurnBudget { + /** Record each warning of one observation. */ + warn(warnings: readonly BudgetObservation[]): void; + /** Stop the turn on a crossed block, the agent's own or the SDK backstop's. */ + block(item: BudgetObservation, backstop: boolean): void; + /** Stop the turn because its accounting cannot be trusted any more. */ + unavailable(): void; + /** Track a budget write's commit and what the turn does with its outcome. */ + write(work: Promise): void; + /** The bridge's usage report: price it now, commit and judge it later (#2850). */ + observeUsage(usage: TurnUsage, backstop?: boolean): TurnUsage | undefined; +} + +/** + * Mid-turn accounting for one budgeted, governed turn: the agent's own + * inference or a relayed CLI provider request (#1673). A block or an + * accounting failure stops the turn through {@link TurnRun.stops}. + */ +export function createTurnBudget(run: TurnRun): TurnBudget { + const { host, turn, abortController, recorder, stops, budgetWrites } = run; + const budgets = host.budgets!; + const unavailable = () => { + stops.budget = new BudgetUnavailable(); + recorder?.recordBudgetStop(stops.budget.message, "budget_unavailable"); + abortController.abort(stops.budget); host.coordinator.drainPendingForTurn(turn, "Inference budget accounting became unavailable."); + }; + const block = (item: BudgetObservation, backstop: boolean) => { + host.activity?.governance?.(budgetEvent("budget_block", item, budgetAttribution(run), backstop ? "sdk_backstop" : "mid_turn")); + stops.budget = new BudgetExceeded(item, backstop ? "sdk_backstop" : "mid_turn"); + recorder?.recordBudgetStop(stops.budget.message); + abortController.abort(stops.budget); host.coordinator.drainPendingForTurn(turn, stops.budget.message); + }; + const warn = (warnings: readonly BudgetObservation[]) => { + for (const item of warnings) host.activity?.governance?.(budgetEvent("budget_warning", item, budgetAttribution(run))); + }; + const write = (work: Promise) => { + const pending = work.catch(() => { if (!stops.budget) unavailable(); }).finally(() => budgetWrites.delete(pending)); + budgetWrites.add(pending); + }; + const observeUsage = (usage: TurnUsage, backstop = false): TurnUsage | undefined => { + if (stops.budget || abortController.signal.aborted || turn.cancelled) return; + // The report is priced now; its receipt, warnings and any block + // follow its commit (#2850), judged against the turn as it is then. + const live = () => !stops.budget && !abortController.signal.aborted && !turn.cancelled; + try { + if (backstop) { + write(budgets.backstop(turn.turnId).then(saved => { if (live()) block({ ...saved.scopes[0]!, blocked: true }, true); })); + return; + } + const observed = budgets.observe(turn.turnId, usage); + if (!observed) return; + const listPrice = budgets.listPrice(turn.turnId, usage); + write(observed.then(result => { + if (!live()) return; + warn(result.warnings); + const { costUsd: reportedCost, ...counts } = usage; + void reportedCost; + host.sendToClients(withTurnScope({ type: "usage", turnId: turn.turnId, usage: { ...counts, + ...(result.receipt.listPriceCostUsd !== null ? { costUsd: result.receipt.listPriceCostUsd } : {}) }, + observedAt: result.receipt.observedAt, budget: result.receipt }, turn)); + if (result.blocked) block(result.blocked, false); + })); + return { ...usage, ...(listPrice !== null ? { costUsd: listPrice } : {}) }; + } catch { unavailable(); } + }; + return { warn, block, unavailable, write, observeUsage }; +} + +/** Wait for every budget write the turn started, including any a commit started. */ +export async function settleBudgetWrites(run: Pick): Promise { + while (run.budgetWrites.size) await Promise.all([...run.budgetWrites]); +} diff --git a/packages/ui-server/src/ws/session-run/cancellations.ts b/packages/ui-server/src/ws/session-run/cancellations.ts new file mode 100644 index 0000000000..d7931f4dba --- /dev/null +++ b/packages/ui-server/src/ws/session-run/cancellations.ts @@ -0,0 +1,51 @@ +import { createTurnRecorder } from "../../activity/recorder.js"; +import type { WsHost } from "../host.js"; +import type { RunningTurn } from "../turns.js"; +import type { RunBilling } from "./billing.js"; +import type { TurnLifecycle } from "./types.js"; + +/** + * Write out cancellations that were accepted before a recorder existed. + * + * A cancel can land while routing or billing is still in flight, when there is + * nothing to record it on yet, so the actor is buffered on the turn. Both exits + * from that window have to drain it — the ordinary one, which then has a + * recorder, and the revoked one, which must build a throwaway recorder rather + * than drop a decision someone actually made. + */ +export function recordPendingCancellations( + host: WsHost, + turn: RunningTurn, + billing: RunBilling | undefined, + lifecycle?: TurnLifecycle +): void { + if (turn.pendingCancellationPrincipalIds.length === 0) return; + if (lifecycle && !turn.recorder) { + for (const principalId of turn.pendingCancellationPrincipalIds) lifecycle.recordCancellation(principalId); + turn.pendingCancellationPrincipalIds.length = 0; + return; + } + const recorder = + turn.recorder ?? + (host.activity + ? createTurnRecorder( + { + store: host.activity.store, + ...(host.activity.runtime ? { runtime: host.activity.runtime } : {}), + ...(host.activity.governance ? { governance: host.activity.governance } : {}), + onWrite: () => host.activity!.stream.pump(), + log: host.log, + }, + { + turnId: turn.turnId, + sessionId: turn.sessionId, + principalId: turn.principalId, + ...billing, + } + ) + : undefined); + for (const principalId of turn.pendingCancellationPrincipalIds) { + recorder?.recordCancellation(principalId); + } + turn.pendingCancellationPrincipalIds.length = 0; +} diff --git a/packages/ui-server/src/ws/session-run/outcome.ts b/packages/ui-server/src/ws/session-run/outcome.ts new file mode 100644 index 0000000000..38cdf01a23 --- /dev/null +++ b/packages/ui-server/src/ws/session-run/outcome.ts @@ -0,0 +1,129 @@ +import type { ActivitySpanOutcome } from "@schlessera/brain-ui-sdk/protocol"; +import { BudgetExceeded, BudgetUnavailable } from "../../brain/turn-budgets.js"; +import { REVOKED_REASON, type HostWorkOutcome, type RunningTurn } from "../turns.js"; +import type { TurnStops } from "./types.js"; + +/** The terminal a turn's recorder writes; cancellation and timeout are host-owned facts. */ +export type RecorderDisposition = "success" | "error" | "cancelled" | "timeout"; + +/** How a turn ended, for its lifecycle span and its host work item. */ +export interface TurnOutcome { + readonly lifecycle: ActivitySpanOutcome; + readonly work: HostWorkOutcome; + readonly reason?: string; + /** No backend ran, so the slot publishes the cancelled status itself. */ + readonly cancelledBeforeStart: boolean; +} + +/** What teardown records when classification itself never ran. */ +export const UNCLASSIFIED_OUTCOME: TurnOutcome = { lifecycle: "error", work: "error", cancelledBeforeStart: false }; + +/** + * Native admission awaits can outlive principal revocation or expiry. The + * request is refused without cancelling another principal's queue; this is + * the error that carries that refusal to failure classification. + */ +export class AdmissionRevoked extends Error { + constructor() { + super(REVOKED_REASON); + } +} + +/** The host facts a turn's outcome is read from, sampled once it has stopped. */ +export interface TurnFacts { + readonly cancelled: boolean; + readonly aborted: boolean; + readonly lastResult: RunningTurn["lastResult"]; + readonly stops: TurnStops; +} + +export type CompletedTurn = TurnOutcome & { + readonly recorder: RecorderDisposition; + /** The backend resolved but reported a runtime failure on its result frame. */ + readonly resultFailed: boolean; +}; + +/** + * Classify a turn whose backend call resolved. A resolved startTurn is not a + * successful turn: backends resolve for runtime failures and report them on + * the terminal result frame, which the bridge recorded on the turn. A host + * timeout ends the turn like a cancel: its late result is never narrated, and + * the receipt keeps the reason. + */ +export function classifyCompletedTurn(facts: TurnFacts): CompletedTurn { + const { cancelled, aborted, lastResult, stops } = facts; + const work: HostWorkOutcome = cancelled || aborted || lastResult === "cancelled" + ? "cancelled" + : lastResult === "error" + ? "error" + : "completed"; + const reason = stops.scope ? stops.scope : aborted && !cancelled ? "Turn timed out" : undefined; + // Terminal precedence: cancellation and timeout are host-owned facts; + // otherwise the recorder refines from the buffered result frame. + const recorder: RecorderDisposition = cancelled ? "cancelled" : aborted ? "timeout" : lastResult === "error" ? "error" : "success"; + return { + lifecycle: recorder, + work, + ...(reason !== undefined ? { reason } : {}), + cancelledBeforeStart: false, + recorder, + resultFailed: lastResult === "error", + }; +} + +export interface FailedTurnFacts extends TurnFacts { + readonly error: unknown; + readonly egressFailure: Error | undefined; + readonly enteredBackend: boolean; +} + +/** + * How a failed turn is reported to clients: + * + * - `cancelled_before_start`: cancelled or revoked during admission with no + * other failure; no error frame, and the slot publishes `cancelled`. + * - `scope_stopped`: a scope cap already narrated why it stopped the turn. + * - `reported`: the terminal is emitted as an error frame. + */ +export type FailedTurnDelivery = "cancelled_before_start" | "scope_stopped" | "reported"; + +export type FailedTurn = TurnOutcome & { + readonly delivery: FailedTurnDelivery; + readonly recorder: RecorderDisposition; + /** What the turn ended on: an asynchronous stop wins over the error that unwound it. */ + readonly terminal: unknown; + /** Admission refused the turn on a budget block, which Activity records as denied. */ + readonly admissionBlock: BudgetExceeded | undefined; + readonly budgetUnavailable: boolean; +}; + +/** Classify a turn whose admission or backend call threw. */ +export function classifyFailedTurn(facts: FailedTurnFacts): FailedTurn { + const { cancelled, aborted, stops, egressFailure, enteredBackend, error } = facts; + const budget = stops.budget, journal = stops.journal, scope = stops.scope; + const revoked = error instanceof AdmissionRevoked; + const terminal = budget ?? journal ?? egressFailure ?? error; + const admissionBlock = terminal instanceof BudgetExceeded && terminal.stage === "admission" ? terminal : undefined; + const cancelledBeforeStart = !enteredBackend && (cancelled || revoked) && !budget && !journal && !egressFailure && !scope; + const delivery: FailedTurnDelivery = cancelledBeforeStart + ? "cancelled_before_start" + : !scope || budget || journal || egressFailure ? "reported" : "scope_stopped"; + const recorder: RecorderDisposition = budget ? "error" : cancelled || revoked ? "cancelled" : journal || egressFailure ? "error" : aborted ? "timeout" : "error"; + // A host timeout is host-terminal like a cancel: its late result is + // never narrated (the work keeps the reason). + const work: HostWorkOutcome = budget ? "error" : cancelled || revoked || !journal && !egressFailure && aborted ? "cancelled" : "error"; + const reason = !cancelled && !budget && !journal && !egressFailure && aborted + ? "Turn timed out" + : terminal instanceof Error ? terminal.message : String(terminal); + return { + lifecycle: admissionBlock ? "denied" : recorder, + work, + reason, + cancelledBeforeStart, + delivery, + recorder, + terminal, + admissionBlock, + budgetUnavailable: terminal instanceof BudgetUnavailable, + }; +} diff --git a/packages/ui-server/src/ws/session-run/slot.ts b/packages/ui-server/src/ws/session-run/slot.ts new file mode 100644 index 0000000000..4dc3065f8b --- /dev/null +++ b/packages/ui-server/src/ws/session-run/slot.ts @@ -0,0 +1,224 @@ +import { createTurnLifecycle } from "../../activity/turn-lifecycle.js"; +import type { WsHost } from "../host.js"; +import { resolveTurnTarget } from "../routing.js"; +import type { QueuedFollowUp, RunningTurn, StartingSession } from "../turns.js"; +import { REVOKED_REASON } from "../turns.js"; +import type { RunSessionInput, SessionSlot, TurnLifecycle } from "./types.js"; + +/** Why a follow-up leaves when its session's slot ends without running it (#1002). */ +export const SLOT_ENDED_REASON = "The session stopped before it ran."; + +/** + * Route a new slot and register its turn. Messages that arrive while routing + * queue on the starting session and become the turn's queue. Resolves + * undefined when the slot ends before any turn: routing failed (reported + * here), the start was cancelled, the host is closing, or the principal was + * revoked. + */ +export async function openSessionSlot( + host: WsHost, + initial: RunSessionInput, + initialTurnId: string, + initialLifecycle: TurnLifecycle | undefined +): Promise { + const { coordinator } = host; + const starting: StartingSession = { + queue: [], + cancelled: false, + ...(initial.revision !== undefined ? { revision: initial.revision } : {}), + }; + coordinator.beginStarting(initial.sessionId, starting); + let target: Awaited>; + try { + target = await resolveTurnTarget(host.registry, host.catalog, initial.sessionId, initial.providerId); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + initialLifecycle?.finish("error", message); + // No turn exists yet — routing failed before one was minted — so the + // report carries only the session identity the client asked for. + host.reportTurnFailed("BACKEND_ERROR", { sessionId: initial.sessionId }, message); + initial.work?.settle("error", { reason: message }); + // Messages queued behind this start have no runner now: settle their + // work and release their leases instead of stranding them. + for (const entry of starting.queue) entry.work?.settle("error", { reason: message }); + if (initial.sessionId) coordinator.dropStartingQueue(initial.sessionId, starting, message); + else for (const entry of starting.queue.splice(0)) entry.releaseAuthorization(); + host.sendToClients({ + type: "error", + code: "BACKEND_ERROR", + message, + ...(initial.sessionId ? { sessionId: initial.sessionId } : {}), + ...(initial.requestId ? { requestId: initial.requestId } : {}), + }); + return undefined; + } finally { + coordinator.endStarting(initial.sessionId, starting); + } + + if (starting.cancelled || host.closing) { + for (const entry of starting.queue.splice(0)) entry.releaseAuthorization(); + return undefined; + } + if (!initial.authorization.valid) { + if (initial.sessionId) coordinator.dropStartingQueue(initial.sessionId, starting, REVOKED_REASON); + else for (const entry of starting.queue.splice(0)) entry.releaseAuthorization(); + return undefined; + } + + const { backend, profileId } = target; + if (target.droppedPin) { + host.log.emit({ + severityText: "WARN", + body: "pinned profile unavailable; running on the default profile", + attributes: { "session.id": initial.sessionId, profile: target.droppedPin }, + }); + host.sendToClients({ + type: "status", + status: "thinking", + detail: `Pinned model "${target.droppedPin}" is unavailable — running on the default.`, + ...(initial.sessionId ? { sessionId: initial.sessionId } : {}), + }); + } + const turn: RunningTurn = { + principalId: initial.authorization.principalId, + authorization: initial.authorization, + sessionId: initial.sessionId ?? null, + turnId: initialTurnId, + // Only meaningful when the client had no session id to send. + draftId: initial.sessionId ? null : (initial.draftId ?? null), + providerId: profileId ?? null, + backend, + abortController: new AbortController(), + timeoutHandle: setTimeout(() => {}, 0), + queue: starting.queue, + pendingCancellationPrincipalIds: [], + cancelled: false, + lastResult: null, + }; + turn.shareId = initial.shareId; + clearTimeout(turn.timeoutHandle); + coordinator.registerTurn(turn); + return { + host, + initial, + turn, + backend, + firstTurnId: turn.turnId, + profileId, + resumeId: initial.sessionId, + draftExchanges: initial.sessionId ? [] : (initial.localExchanges ?? []), + releaseActive: undefined, + }; +} + +/** The slot's first request, as a queue entry whose lease settles its work. */ +export function firstRequest(initial: RunSessionInput): QueuedFollowUp { + return { + principalId: initial.authorization.principalId, + authorization: initial.authorization, + text: initial.text, + attachments: initial.attachments, + ...(initial.files?.length ? { files: initial.files } : {}), + ...(initial.client ? { client: initial.client } : {}), + ...(initial.source ? { source: initial.source } : {}), + ...(initial.thinkingLevel !== undefined ? { thinkingLevel: initial.thinkingLevel } : {}), + ...(initial.requestId ? { requestId: initial.requestId } : {}), + ...(initial.draftRef ? { draftRef: initial.draftRef } : {}), + ...(initial.revision !== undefined ? { revision: initial.revision } : {}), + ...(initial.work ? { work: initial.work } : {}), + releaseAuthorization: () => { + initial.work?.settle("cancelled", { reason: "The session ended before this request ran" }); + }, + }; +} + +/** + * The lifecycle a request's turn reports on: the slot's own for its first + * turn, the one the queue created for a follow-up, or a new one. + */ +export function requestLifecycle( + slot: SessionSlot, + current: QueuedFollowUp, + initialLifecycle: TurnLifecycle | undefined +): TurnLifecycle | undefined { + const { host, turn } = slot; + if (turn.turnId === slot.firstTurnId) return initialLifecycle; + return current.lifecycle ?? (host.activity + ? createTurnLifecycle(host.activity.store, turn.turnId, turn.sessionId, current.queuedAt ?? Date.now(), () => host.activity!.stream.pump()) + : undefined); +} + +/** + * Bind the slot to the request it now holds; recovery reads it as queued + * until its turn is handed to the backend (#964). A request whose principal + * is no longer valid is released instead, and the slot moves on. + */ +export function bindRequest(slot: SessionSlot, current: QueuedFollowUp, lifecycle: TurnLifecycle | undefined): "bound" | "revoked" { + const { host, turn } = slot; + turn.revision = current.revision; + turn.startedAt = undefined; + turn.principalId = current.principalId; + turn.authorization = current.authorization; + if (!turn.authorization.valid) { + lifecycle?.finish("cancelled", REVOKED_REASON); + releaseActive(slot); + host.budgets?.end(turn.turnId); + turn.revision = undefined; + return "revoked"; + } + turn.requestId = current.requestId; + turn.draftRef = current.draftRef; + turn.work = current.work; + return "bound"; +} + +/** Release the running request's queue lease, once. */ +export function releaseActive(slot: SessionSlot): void { + slot.releaseActive!(); + slot.releaseActive = undefined; +} + +/** + * Take the next queued follow-up. It stays pending, as `handingOver`, until + * its turn reaches the backend (#1002). + */ +export function dequeueRequest(turn: RunningTurn): QueuedFollowUp | null { + const entry = turn.queue.shift() ?? null; + turn.handingOver = entry ?? undefined; + if (entry) { + // A queued follow-up is its own turn — give it a fresh identity, and + // its own terminal disposition. + turn.turnId = entry.lifecycleTurnId ?? crypto.randomUUID(); + turn.lastResult = null; + } + return entry; +} + +/** A handed-over entry that will not run leaves the pending list with why. */ +export function dropHandedOver(slot: SessionSlot, entry: QueuedFollowUp, reason: string): void { + const { turn } = slot; + if (turn.handingOver !== entry) return; + turn.handingOver = undefined; + slot.host.coordinator.queueChanged(turn.sessionId, { dropped: { entries: [entry], reason } }); +} + +/** + * End the slot. Whatever is still pending will never run in it: every lease + * is released, the pending list learns why, and the turn leaves the + * coordinator with its pending requests drained. + */ +export function closeSessionSlot(slot: SessionSlot, next: QueuedFollowUp | null): void { + const { host: { coordinator }, turn } = slot; + slot.releaseActive?.(); + next?.releaseAuthorization(); + // A handed-over entry's lease is `next`'s or the active one, both released above. + const unstarted = turn.handingOver; + turn.handingOver = undefined; + const queued = turn.queue.splice(0); + for (const entry of queued) entry.releaseAuthorization(); + coordinator.queueChanged(turn.sessionId, { + dropped: { entries: unstarted ? [unstarted, ...queued] : queued, reason: SLOT_ENDED_REASON }, + }); + coordinator.unregisterTurn(turn); + coordinator.drainPendingForTurn(turn, "Session ended"); +} diff --git a/packages/ui-server/src/ws/session-run/teardown.ts b/packages/ui-server/src/ws/session-run/teardown.ts new file mode 100644 index 0000000000..4ded1ba676 --- /dev/null +++ b/packages/ui-server/src/ws/session-run/teardown.ts @@ -0,0 +1,88 @@ +import { lstatSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { isEnvName, PROTECTED_TIER_A } from "@schlessera/brain-ui-sdk/internal"; +import { withTurnScope } from "../frames.js"; +import type { TurnOutcome } from "./outcome.js"; +import { releaseActive } from "./slot.js"; +import type { TurnRun } from "./types.js"; + +/** + * Release everything a turn held, in the order its invariants need: relay + * and egress stop and settle (the session's next turn reads those hosts back + * as contacted, G6); the worktree generation retires before the journal's + * final observation, so no grant follows it; the observation precedes + * quarantine and gate release; and the recorder's terminal commits before + * the slot reports its status. Never throws for a release that can fail on + * its own; those are logged and recovered at startup. + */ +export async function teardownTurn(run: TurnRun, outcome: TurnOutcome): Promise { + const { host, slot, turn, current, lifecycle, timeoutHandle, recorder, failureRecording, held } = run; + const { governedHold, worktreeGeneration } = held; + const work = current.work; + await held.providerRelay?.stop(); + held.turnEgress?.stop(); + // The session's next turn reads these hosts back as contacted (G6). + await held.turnEgress?.settled(); + host.dialogue.retireTurn(turn.turnId); + if (held.referenceTurn) host.referenceTools?.end(turn.turnId); + // No grant after this point: the final observation covers everything granted. + if (worktreeGeneration) await host.referenceWorktrees!.retireGeneration(worktreeGeneration.id).catch(() => {}); + try { + // Observe after backend writers stop, before quarantine and gate release. + await host.journal?.finish(turn.turnId); + } catch (error) { host.log.emit({ severityText: "ERROR", body: `journal final observation failed: ${String(error)}` }); } + if (worktreeGeneration) { + // Its workers exited and the final observation is recorded: park what it held. + host.referenceWorktreeGenerations.delete(turn.turnId); + try { await host.referenceWorktrees!.closeGeneration(worktreeGeneration.id); await host.referenceWorktrees!.reconcile(); } + catch (error) { host.log.emit({ severityText: "ERROR", body: `managed worktree generation close failed; startup recovery retries it: ${String(error)}` }); } + } + host.scope?.finish(turn.turnId); + try { + const reconciled = await governedHold?.end(); + for (const item of reconciled?.quarantined ?? []) { + const info = lstatSync(item.to); + host.activity?.governance?.({ kind: "quarantine", payload: { path: item.path, + tier: isEnvName(item.path) || PROTECTED_TIER_A.includes(item.path as never) ? "A" : "B", + entry: info.isFile() ? "file" : info.isDirectory() ? "directory" : info.isSymbolicLink() ? "symlink" : "other", + bytes: info.isFile() ? info.size : null, trigger: "turn_end", objectId: createHash("sha256").update(item.to).digest("hex") }, + turnId: turn.turnId, sessionId: turn.sessionId, actor: run.origin, model: run.mainModel, + profile: governedHold?.sandbox.profile ?? "strict" }); + } + } + catch (error) { host.log.emit({ severityText: "ERROR", body: `governed reconciliation failed: ${String(error)}` }); } + if (governedHold?.sandbox.profile === "governed") host.governedTurns?.refresh(host.workerLock); + // The recorder has written the terminal: from here on the Activity + // record, not this slot, answers for the request (#964). + await host.inboxTools?.shares?.end(turn.turnId); + turn.shareId = undefined; + host.budgets?.end(turn.turnId); + turn.revision = undefined; + turn.startedAt = undefined; + turn.backendStarted = false; + await failureRecording.finish(turn.sessionId); + lifecycle?.finish(outcome.lifecycle, outcome.reason ?? null); + clearTimeout(timeoutHandle); + turn.recorder = undefined; + work?.settle(outcome.work, { sessionId: turn.sessionId, ...(outcome.reason ? { reason: outcome.reason } : {}) }); + turn.work = undefined; + releaseActive(slot); + // The recorder's writes, terminal included, commit off the event loop + // (#2814); recovery must see them before the final idle notification. + await recorder?.settled(); + publishTurnStatus(run, outcome); +} + +/** + * The slot's status once a turn has settled. No backend existed to publish + * its usual cancelled status, so a turn cancelled before it started is + * reported here, after native preparation and host cleanup. Otherwise a + * backend result can precede asynchronous journal finalization, so recovery + * reads the committed terminal from `idle`, before a successor starts. + */ +export function publishTurnStatus(run: Pick, outcome: Pick): void { + const { host, turn } = run; + if (outcome.cancelledBeforeStart) host.sendToClients(withTurnScope({ type: "status", status: "cancelled", + detail: "Cancelled before starting", ...(turn.requestId ? { requestId: turn.requestId } : {}) }, turn)); + else if (turn.sessionId) host.sendToClients(withTurnScope({ type: "status", status: "idle" }, turn)); +} diff --git a/packages/ui-server/src/ws/session-run/turn.ts b/packages/ui-server/src/ws/session-run/turn.ts new file mode 100644 index 0000000000..35c3b74983 --- /dev/null +++ b/packages/ui-server/src/ws/session-run/turn.ts @@ -0,0 +1,151 @@ +import { emitTurnError } from "../bridge.js"; +import type { QueuedFollowUp } from "../turns.js"; +import { REVOKED_REASON } from "../turns.js"; +import { recordPendingCancellations } from "./cancellations.js"; +import { admitGovernedTurn, admitWorkerHost, announceTurnStart, armTurnTimeout, createRunRecorder } from "./admission.js"; +import { openTurnBridge, prepareRelayedEgress, turnRequest } from "./backend-entry.js"; +import { resolveRunBilling } from "./billing.js"; +import { budgetAttribution, budgetEvent, createTurnBudget, settleBudgetWrites } from "./budget.js"; +import { AdmissionRevoked, classifyCompletedTurn, classifyFailedTurn, UNCLASSIFIED_OUTCOME, type TurnOutcome } from "./outcome.js"; +import { releaseActive } from "./slot.js"; +import { teardownTurn } from "./teardown.js"; +import type { SessionSlot, TurnLifecycle, TurnRun } from "./types.js"; + +/** + * How one request of a slot ended: it `ran` (whatever its outcome), its + * principal was `revoked` before it reached admission, or the host refused + * it and the slot `stop`s. + */ +export type SlotTurnResult = "ran" | "revoked" | "stop"; + +/** Run the request the slot is bound to as one turn, from host admission to teardown. */ +export async function runSlotTurn(slot: SessionSlot, current: QueuedFollowUp, lifecycle: TurnLifecycle | undefined): Promise { + const { host, turn, backend } = slot; + const work = current.work; + // The turn's own controller exists before the host check is awaited, so + // a cancel accepted while the probe runs (#2416) aborts this turn's + // admission, as one accepted during billing does. + const abortController = new AbortController(); + turn.abortController = abortController; + const workerHost = await admitWorkerHost(host, backend, work); + if (workerHost.kind === "denied") { + const { error } = workerHost; + lifecycle?.finish("denied", error instanceof Error ? error.message : String(error)); + emitTurnError(host, turn, error); + work?.settle("error", { reason: error instanceof Error ? error.message : String(error) }); + return "stop"; + } + const timeoutHandle = armTurnTimeout(host, turn, abortController); + const billing = await resolveRunBilling(host.registry, backend.id, slot.profileId); + const failureRecording = await host.failureReplay.begin(backend, slot.resumeId, turn.turnId, abortController.signal); + // Revocation can land while routing or billing is in flight. This is the + // final await boundary before startTurn, so an invalid principal never + // reaches the backend while an already-running turn remains untouched. + // Expiry is authoritative, not advisory: the sweep that turns an expired + // principal into a revocation runs on a timer, and a follow-up dequeued + // inside that window would otherwise start — reviewer measured one + // starting 12ms past expiry — and then survive, because a started turn is + // deliberately never aborted. Enforce it at the same boundary that + // enforces revocation, so the timer only has to close the socket. + host.expireAuthorizationContexts(); + if (!turn.authorization.valid) { + host.budgets?.end(turn.turnId); + turn.revision = undefined; + await failureRecording.finish(); + clearTimeout(timeoutHandle); + // A cancellation accepted while billing was in flight is already a + // decision someone made; losing it because the turn's own principal + // was revoked a moment later would erase the actor, not the turn. Drain + // the buffer before leaving. + recordPendingCancellations(host, turn, billing, lifecycle); + lifecycle?.finish("cancelled", REVOKED_REASON); + releaseActive(slot); + return "revoked"; + } + const recorder = createRunRecorder(host, turn, lifecycle, billing, abortController, work); + const mainModel = billing?.model ?? null; + if (mainModel) recorder?.setMainModel(mainModel); + turn.recorder = recorder; + for (const principalId of turn.pendingCancellationPrincipalIds) recorder?.recordCancellation(principalId); + turn.pendingCancellationPrincipalIds.length = 0; + // A follow-up the backend refused had its source recorded when it was + // first handed over (#1063). + turn.retryRequest = { + type: "chat_message", text: current.text, attachments: current.attachments, + ...(current.files?.length ? { files: current.files.map(file => ({ kind: "file" as const, path: file.path })) } : {}), + ...(slot.profileId ? { providerId: slot.profileId } : {}), + ...(current.client ? { client: current.client } : {}), ...(current.source ? { source: current.source } : {}), + ...(current.thinkingLevel !== undefined ? { thinkingLevel: current.thinkingLevel } : {}), + ...(current.requestId ? { requestId: current.requestId } : {}), + }; + turn.isManualRetry = slot.initial.isRetry === true && turn.turnId === slot.firstTurnId; + const run: TurnRun = { + slot, host, turn, backend, current, turnId: turn.turnId, lifecycle, abortController, timeoutHandle, billing, + failureRecording, recorder, workerIdentity: workerHost.identity, origin: work?.posture === "voice" ? "voice" : "interactive", + profileId: slot.profileId, resumeId: slot.resumeId, startedAt: Date.now(), mainModel, + stops: {}, budgetWrites: new Set(), held: { referenceViews: null, referenceTurn: false, enteredBackend: false }, + }; + announceTurnStart(slot, current, run.startedAt); + await executeTurn(run); + return "ran"; +} + +/** Admit, enter the backend, classify the outcome and tear the turn down. */ +async function executeTurn(run: TurnRun): Promise { + const { host, turn, backend, lifecycle, abortController, recorder, held, stops } = run; + let outcome: TurnOutcome = UNCLASSIFIED_OUTCOME; + turn.backendStarted = false; + try { + const admission = await admitGovernedTurn(run); + if (admission.kind === "revoked") throw new AdmissionRevoked(); + const budget = host.budgets && held.governedHold ? createTurnBudget(run) : undefined; + const { prompt, bridge } = await openTurnBridge(run, admission, budget); + await prepareRelayedEgress(run, bridge, budget); + held.enteredBackend = true; + turn.backendStarted = true; + lifecycle?.mark("backendInvokedAt"); + await backend.startTurn(turnRequest(run, prompt, bridge)); + turn.backendStarted = false; + await held.settleIndex?.(); + // Every relayed attempt reports before the turn's accounting closes. + await held.providerRelay?.stop(); + held.turnEgress?.stop(); + // Every egress record commits, or fails the turn, before its outcome (#2850). + await held.turnEgress?.settled(); + const egressFailure = held.turnEgress?.recordingFailure(); + if (egressFailure) throw egressFailure; + // Final observation is part of this host outcome, after worker writes + // stop and before its Activity terminal, quarantine or gate release. + // A worktree generation retires first: no grant can follow that observation. + if (held.worktreeGeneration) await host.referenceWorktrees!.retireGeneration(held.worktreeGeneration.id); + await host.journal?.finish(turn.turnId); + await settleBudgetWrites(run); + if (stops.budget) throw stops.budget; + if (stops.journal) throw stops.journal; + const completed = classifyCompletedTurn({ cancelled: turn.cancelled, aborted: abortController.signal.aborted, lastResult: turn.lastResult, stops }); + if (completed.resultFailed) host.reportTurnFailed("BACKEND_RESULT_ERROR", turn); + else host.reportTurnCompleted(turn, Date.now() - run.startedAt); + outcome = completed; + recorder?.finish(completed.recorder); + } catch (err) { + lifecycle?.mark("failureObservedAt"); + await held.settleIndex?.(); + await held.turnEgress?.settled(); + await settleBudgetWrites(run); + const failed = classifyFailedTurn({ + cancelled: turn.cancelled, aborted: abortController.signal.aborted, lastResult: turn.lastResult, stops, + error: err, egressFailure: held.turnEgress?.recordingFailure(), enteredBackend: held.enteredBackend, + }); + if (failed.admissionBlock) { + recorder?.recordBudgetStop(failed.admissionBlock.message); + host.activity?.governance?.(budgetEvent("budget_block", failed.admissionBlock.observation, budgetAttribution(run), "admission")); + } + if (failed.budgetUnavailable) recorder?.recordBudgetStop((failed.terminal as Error).message, "budget_unavailable"); + turn.backendStarted = false; + if (failed.delivery === "reported") emitTurnError(host, turn, failed.terminal); + outcome = failed; + recorder?.finish(failed.recorder); + } finally { + await teardownTurn(run, outcome); + } +} diff --git a/packages/ui-server/src/ws/session-run/types.ts b/packages/ui-server/src/ws/session-run/types.ts new file mode 100644 index 0000000000..7d9db61792 --- /dev/null +++ b/packages/ui-server/src/ws/session-run/types.ts @@ -0,0 +1,139 @@ +import type { + ChatImageAttachment, + ClientEnvironment, + DraftRef, + LocalExchange, + MessageSource, + ThinkingLevel, +} from "@schlessera/brain-ui-sdk/protocol"; +import type { AgentBackend } from "@schlessera/brain-ui-sdk/server"; +import type { ProviderRelay, WorkerNoteFacts } from "@schlessera/brain-ui-sdk/internal"; +import type { createTurnLifecycle } from "../../activity/turn-lifecycle.js"; +import type { TurnRecorder } from "../../activity/recorder.js"; +import type { prepareTurnEgress } from "../../brain/turn-egress.js"; +import type { GovernedTurnHold } from "../../brain/governed-turn.js"; +import type { ReferenceWorktreeGeneration } from "../../brain/reference-worktrees.js"; +import type { WsHost } from "../host.js"; +import type { AuthorizationContext, HostWork, QueuedFollowUp, RunningTurn } from "../turns.js"; +import type { RunBilling } from "./billing.js"; + +export type TurnLifecycle = ReturnType; +export type FailureRecording = Awaited>; +export type TurnEgress = Awaited>; + +export type RunSessionInput = { + shareId?: string; + authorization: AuthorizationContext; + replayPrompt?: string; + isRetry?: boolean; + text: string; + sessionId?: string; + historyOwnerId?: string; + attachments: ChatImageAttachment[]; + files?: import("@schlessera/brain-ui-sdk/protocol").SharedFileMeta[]; + providerId?: string; + client?: ClientEnvironment; + source?: MessageSource; + thinkingLevel?: ThinkingLevel; + requestId?: string; + /** Client correlation id for a new conversation; echoed on session_info. */ + draftId?: string; + /** The saved draft revision this message was sent from (#979). */ + draftRef?: DraftRef; + profileDraftId?: string; + /** Accepted-work revision of this request (#964), for a known session. */ + revision?: number; + /** + * Local exchanges the draft conversation holds (#582). Recorded against + * the session once `session_info` names it, and carried on its first + * prompt. + */ + localExchanges?: LocalExchange[]; + /** A handoff destination's hooks (#61); only on a new conversation. */ + handoffHooks?: HandoffHooks; + /** Host-orchestrated work this message carries (#957). */ + work?: HostWork; +}; + +/** + * What a handoff creation (#61) needs from the run that creates its + * destination: the moment `session_info` names it, and the moment the + * attempt is over, whichever way it ended. + */ +export interface HandoffHooks { + /** The conversation handed off: its provider history continues in the destination (#2695). */ + readonly sourceSessionId?: string; + onNamed(sessionId: string): void; + onSettled(): void; +} + +/** What one session slot carries from each of its turns to the next. */ +export interface SessionSlot { + readonly host: WsHost; + readonly initial: RunSessionInput; + readonly turn: RunningTurn; + readonly backend: AgentBackend; + /** The slot's first turn: a manual retry and a replay prompt apply only to it. */ + readonly firstTurnId: string; + /** The resolved profile, re-pinned by session_info between queued turns. */ + profileId: string | undefined; + /** The session the next turn resumes, once one is known. */ + resumeId: string | undefined; + /** Only the first turn of a new conversation carries the draft's exchanges. */ + draftExchanges: LocalExchange[]; + /** The running request's queue lease, until it is released. */ + releaseActive: (() => void) | undefined; +} + +/** + * Why a running turn was stopped from outside its own control flow: a + * budget write or block, a journal failure, or a scope cap. Each is set at + * most once, by a callback, and read when the turn's outcome is classified. + */ +export interface TurnStops { + budget?: Error; + journal?: Error; + scope?: string; +} + +/** What admission and backend entry acquired, which teardown releases. */ +export interface TurnHeld { + governedHold?: GovernedTurnHold; + worktreeGeneration?: ReferenceWorktreeGeneration; + referenceViews: { public: string; private: string } | null; + referenceTurn: boolean; + turnEgress?: TurnEgress; + providerRelay?: ProviderRelay; + /** Index updates this turn's applications queued (#2835), flushed once its workers stop. */ + settleIndex?: () => Promise; + enteredBackend: boolean; +} + +/** One request of a slot, from host admission to teardown. */ +export interface TurnRun { + readonly slot: SessionSlot; + readonly host: WsHost; + readonly turn: RunningTurn; + readonly backend: AgentBackend; + readonly current: QueuedFollowUp; + /** The turn's identity as it started; the slot re-mints it for the next request. */ + readonly turnId: string; + readonly lifecycle: TurnLifecycle | undefined; + readonly abortController: AbortController; + readonly timeoutHandle: ReturnType; + readonly billing: RunBilling; + readonly failureRecording: FailureRecording; + readonly recorder: TurnRecorder | undefined; + readonly workerIdentity: WorkerNoteFacts["identity"] | undefined; + readonly origin: "voice" | "interactive"; + /** The slot's profile and session as this turn started; the slot advances them after it. */ + readonly profileId: string | undefined; + readonly resumeId: string | undefined; + readonly startedAt: number; + /** The model the turn runs, rebound when the backend reports its actual model. */ + mainModel: string | null; + readonly stops: TurnStops; + /** A budget write's commit and its outcome; the turn's outcome waits for every one (#2850). */ + readonly budgetWrites: Set>; + readonly held: TurnHeld; +} From 9644197bbef67bd0925d7a6ca6f5c21f16afa0de Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 01:24:03 +0000 Subject: [PATCH 2/5] test(ui-server): test each retained-session stage directly and re-anchor moved citations Each stage is called directly over a real WsHost and TurnCoordinator: outcome classification tables, budget event payloads and mid-turn accounting, slot setup, binding, dequeue, hand-over and close, host admission and the timeout, one slot turn (denied, revoked during billing, ran), the backend request, and the slot status. Citations of run-session.ts follow the code into session-run/admission.ts, slot.ts, turn.ts and teardown.ts, or to its new lines. Refs #1359 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/design-kit/show-block-brief.md | 2 +- docs/decisions/governed-writable-workers.md | 2 +- docs/decisions/managed-worktrees.md | 4 +- docs/decisions/session-principals.md | 6 +- docs/decisions/voice-permission.md | 4 +- .../plans/async-collaboration-requirements.md | 4 +- docs/plans/async-collaboration.md | 10 +- docs/plans/navigation-recovery.md | 2 +- .../tests/session-run-stages.test.ts | 479 ++++++++++++++++++ scripts/measure-show-block.ts | 2 +- 10 files changed, 497 insertions(+), 18 deletions(-) create mode 100644 packages/ui-server/tests/session-run-stages.test.ts diff --git a/docs/decisions/design-kit/show-block-brief.md b/docs/decisions/design-kit/show-block-brief.md index ab2d083f99..e29f9190e7 100644 --- a/docs/decisions/design-kit/show-block-brief.md +++ b/docs/decisions/design-kit/show-block-brief.md @@ -38,7 +38,7 @@ Four rules decide what counts, and each of them changed a number: frames a subagent produced, and the chat adapter keeps those off the surface. - **The turn budget is enforced, not just advertised.** Production aborts a turn at `turnTimeoutMs` (`timeoutHandle = setTimeout`, - `packages/ui-server/src/ws/run-session.ts:378`), so + `packages/ui-server/src/ws/session-run/admission.ts:47`), so the harness aborts at the same 180 s. Without it an answer no reader could have received still scored: an earlier run had five turns of 190–306 s. - **A turn that did not complete is excluded from every rate**, in both diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 3956b066b7..ea7c9e678b 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1520,7 +1520,7 @@ unmet rather than relaxed. **Why.** Every governed turn queues an automatic index refresh after it (`host.governedTurns?.refresh(host.workerLock)`, -`packages/ui-server/src/ws/run-session.ts:924`). The refresh usually finishes +`packages/ui-server/src/ws/session-run/teardown.ts:54`). The refresh usually finishes while the next turn runs, so that turn's finish observation found a rewritten `brain.db` and copied a whole new version of it into retained objects, inside the observation's worker hold. #2831 measured 36 versions of a ~120 MB index in diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 75cd8b3a21..7262386706 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -97,7 +97,7 @@ unknown; what happens next is in [hygiene and cleanup](#hygiene-and-cleanup). Each governed or strict turn whose journal is recording opens one worker generation, and every worker of that turn binds the generation's root-owned directory whole at `/tmp/brain-worktrees`, inside the turn's own `/tmp` -(`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/run-session.ts:560-572`; +(`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/session-run/admission.ts:194-206`; `// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:852-863`). A granted worktree appears there as `/tmp/brain-worktrees//` on the worker's next path lookup; the worker cannot create entries beside it, and a @@ -199,7 +199,7 @@ The host side is `createReferenceTools` start, the host records its principal and what those workers bind: the public view, the principal's private view and the turn's worker generation, if one opened -(`// Reference tools (#2432): the turn's workers bind the principal's source`, `packages/ui-server/src/ws/run-session.ts:573-579`). +(`// Reference tools (#2432): the turn's workers bind the principal's source`, `packages/ui-server/src/ws/session-run/admission.ts:207-213`). A call carries only a repository, a revision or a worktree identity. The bridge adds the turn's own principal, and a call for a turn the host did not prepare, or under another principal, refuses diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 21ceee3645..9fc5facbe6 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -102,7 +102,7 @@ Both reviewers verified every row below against the source. | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | -| Follow-up queue | `QueuedFollowUp`, `ws/turns.ts:61-103`; `slot.queue.push(entry)`, `run-session.ts:1112` | queued entries re-mint `turnId` in the same slot and may come from another socket | +| Follow-up queue | `QueuedFollowUp`, `ws/turns.ts:61-103`; `slot.queue.push(entry)`, `run-session.ts:225` | queued entries re-mint `turnId` in the same slot and may come from another socket | | Password login | `acquirePasswordVerification(key)`, `auth.ts:739` | argon2id verify, failure counting, in-flight reservation, then `issueSessionCookie` | | Passkey login | `issueLoginSession`, `packages/ui-server/src/middleware/passkeys.ts:441` | assertion verified, then `issueSessionCookie`; `row.id` is in scope | | Passkey **registration** | `INSERT INTO passkey_credentials`, `packages/ui-server/src/db/account-writes.ts:31-36` | inserts a credential; calls **neither** helper | @@ -178,8 +178,8 @@ ceremony in flight can mint a session for a credential deleted meanwhile. **5. Revocation is a boundary that outlives admission.** Closing a socket is not revocation: `onMessage` dispatches without re-checking (`ws/connection.ts:173`), turn startup awaits routing and billing before `startTurn` -(`resolveTurnTarget`, `ws/run-session.ts:209`; `const billing = await resolveRunBilling`, -`ws/run-session.ts:401`), and queued follow-ups execute later. Each connection holds a +(`resolveTurnTarget`, `ws/session-run/slot.ts:33`; `const billing = await resolveRunBilling`, +`ws/session-run/turn.ts:39`), and queued follow-ups execute later. Each connection holds a server-resolved authorization context; revocation marks it invalid synchronously, refuses later frames, drops that principal's queued unstarted follow-ups, and leaves running work running (cancelling a slot would take other diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index 4d488cc84c..292e326421 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -398,7 +398,7 @@ budget. That is already fail-closed: nothing runs. The user hears nothing further, because a model that nags about a request the user ignored is worse than one that lets the turn lapse. When the budget expires the host drains every pending approval for that turn as a denial and deletes it -(`coordinator.drainPendingForTurn`, `packages/ui-server/src/ws/run-session.ts:391` → +(`host.coordinator.drainPendingForTurn`, `packages/ui-server/src/ws/session-run/admission.ts:56` → `drainPendingForTurn`, `packages/ui-server/src/ws/turns.ts:993-1012`), so **on the server nothing is left waiting**: the request is resolved, not parked. The model therefore says @@ -411,7 +411,7 @@ those two citations and is left to #54. The chat store clears a pending approval on `tool_result` (`packages/ui-react/src/hooks/websocket-handlers/chat.ts`), and on the timeout path `abortController.abort()` fires before the drain -(`abortController.abort()`, `run-session.ts:386`; `drainPendingForTurn`, `run-session.ts:391`), +(`abortController.abort()`, `session-run/admission.ts:55`; `drainPendingForTurn`, `session-run/admission.ts:56`), so whether a `tool_result` still streams for that tool use is a question a live turn has to answer. It matters only for the wording: if a dead card can survive on screen, the spoken line above is right diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 30d61b337e..3e0ea9c399 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -256,7 +256,7 @@ Stated before the requirements because five of them derive from it. (`export function createTurnRecorder(`, `packages/ui-server/src/activity/recorder.ts:125-203`). - R25. **Autonomous work gets its own pool** (`MAX_AUTONOMOUS_RUNS`, default 2) — but a second counter alone does not deliver "interactive always wins". The host cap applies only when - starting WS sessions (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1323-1335`), and an autonomous + starting WS sessions (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:436-448`), and an autonomous turn can hold a path write lock while an interactive turn waits or is denied at 30 seconds (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`). Required: an admission controller with reserved interactive capacity and hybrid yield at an explicit denial-risk @@ -266,7 +266,7 @@ Stated before the requirements because five of them derive from it. promise (`return new Promise((resolve) => {`, `packages/ui-server/src/ws/bridge.ts:406-464`) — while blocked on it the model cannot write anything, so "writes its findings, then aborts" has nowhere to run. The autonomous bridge must, in one server-side step: capture the checkpoint, create the Action and block the item, unwind without a live approval promise, preserving the tested timeout - path's abort-then-drain order (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:386-392`). Aborting does **not** undo completed tool side + path's abort-then-drain order (`abortController.abort();`, `packages/ui-server/src/ws/session-run/admission.ts:55-57`). Aborting does **not** undo completed tool side effects, so every attempt gets an isolated staging directory with idempotent cleanup. This does not reopen the abort-and-redo decision; it corrects revision 1's claim that the decision needed no new machinery. diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index cfbc875a4f..0c2b3cb955 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -135,7 +135,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:362-456`). Timeout unwind is - (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:386-392`). Durable escalation must checkpoint + (`abortController.abort();`, `packages/ui-server/src/ws/session-run/admission.ts:55-57`). Durable escalation must checkpoint before unwinding; the existing ordinary bridge does not do that. - **Tool enforcement:** (`const enforcementHook: HookCallback`, `packages/ui-backend-claude/src/permission-hooks.ts:200-229`) closes measured bypasses. (`export const DEFAULT_ALLOWED_TOOLS = [`, `packages/ui-backend-claude/src/tool-policy.ts:27-80`) is still a broad interactive @@ -156,7 +156,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. - **Share provenance/limits:** (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:101`) assigns the source in server code. (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2401`) bounds text, not binary uploads; extracted T1 context needs its own byte/token bound. -- **Interactive locks:** (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1323-1335`) gates WS starts; +- **Interactive locks:** (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:436-448`) gates WS starts; (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`) owns tool locks. Shared-target priority and cooperative yield belong to the keyed lock and backend lifecycle. @@ -884,7 +884,7 @@ AE3, AE4, AE8 **Approach:** - **Escalation** is one server-side step: capture the checkpoint → create the Action with validated effects → transition the Queue item to `blocked` → unwind without parking. The timeout path aborts then drains permissions at - `abortController.abort()`, (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:386-392`) + `abortController.abort()`, (`abortController.abort();`, `packages/ui-server/src/ws/session-run/admission.ts:55-57`) - **Resolution** is one transaction: record resolution (unique) → validate the effect against its schema again → apply it → transition the blocked item to `superseded` → for `enqueue` only, mint one follow-up with `dedup_key` from `(action_id, option_id)` @@ -1274,7 +1274,7 @@ full-v1 enablement; predicates and schema tests cannot substitute for it. **Approach:** **hybrid — reserve capacity normally, yield only at denial risk.** `MAX_AUTONOMOUS_RUNS` (default 2) is necessary but not sufficient: the host cap applies only at -WS session start (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1323-1335`) and an autonomous turn can hold a path write lock +WS session start (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:436-448`) and an autonomous turn can hold a path write lock while an interactive turn waits or is denied at 30s (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`). @@ -1285,7 +1285,7 @@ The hybrid has three pieces: waiter's continued wait signals the holder. The number is a constant, not a judgement call, so both edges are testable - **A yield channel into a running autonomous turn** — the signal aborts the holder through - the same unwind order as the timeout path (`abortController.abort();`, `packages/ui-server/src/ws/run-session.ts:386-392`), returning its item + the same unwind order as the timeout path (`abortController.abort();`, `packages/ui-server/src/ws/session-run/admission.ts:55-57`), returning its item to `ready` and releasing its reservation Below the threshold nothing yields, so the common case costs nothing. Above it, one autonomous diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index 74eeff8d74..fe21b681e9 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -399,7 +399,7 @@ implementation. Any PR moving these lines owns their citation repairs. - API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:912`). -- Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:1089-1134`). +- Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:202-247`). - Approval target: (`function mutateLastAssistant(`, `packages/ui-react/src/stores/chat-slices/buffers.ts:142-172`). diff --git a/packages/ui-server/tests/session-run-stages.test.ts b/packages/ui-server/tests/session-run-stages.test.ts new file mode 100644 index 0000000000..3ff36daf42 --- /dev/null +++ b/packages/ui-server/tests/session-run-stages.test.ts @@ -0,0 +1,479 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import type { BudgetObservation, ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { BackendRequestError, type AgentBackend } from "@schlessera/brain-ui-sdk/server"; + +import { createStaticBackendRegistry, type BackendRegistry } from "../src/agent/backend"; +import { BudgetExceeded, BudgetUnavailable } from "../src/brain/turn-budgets"; +import { createRecordingObservability } from "../src/observability/index"; +import type { WSContext } from "../src/ws/clients"; +import { WsHost } from "../src/ws/host"; +import type { SessionCatalog } from "../src/ws/session-catalog"; +import { REVOKED_REASON, type AuthorizationContext, type HostWork, type QueuedFollowUp } from "../src/ws/turns"; +import { admitWorkerHost, announceTurnStart, armTurnTimeout } from "../src/ws/session-run/admission"; +import { recordDraftExchanges, turnRequest } from "../src/ws/session-run/backend-entry"; +import { budgetAttribution, budgetEvent, createTurnBudget, settleBudgetWrites, type BudgetAttribution } from "../src/ws/session-run/budget"; +import { + AdmissionRevoked, + classifyCompletedTurn, + classifyFailedTurn, + type FailedTurnFacts, + type TurnFacts, +} from "../src/ws/session-run/outcome"; +import { + bindRequest, + closeSessionSlot, + dequeueRequest, + dropHandedOver, + firstRequest, + openSessionSlot, + releaseActive, + SLOT_ENDED_REASON, +} from "../src/ws/session-run/slot"; +import { publishTurnStatus } from "../src/ws/session-run/teardown"; +import { runSlotTurn } from "../src/ws/session-run/turn"; +import type { SessionSlot, TurnRun } from "../src/ws/session-run/types"; +import { makeFakeBackend } from "./helpers/fake-backend"; +import { testAuthorization } from "./helpers/principal"; + +const AUTHORIZATION = testAuthorization(); + +function catalog(): SessionCatalog { + return { + getStoredProviderId: () => null, + getStoredBackendId: () => null, + persistSessionStub() {}, + persistSession() {}, + }; +} + +function setupHost(backend: AgentBackend = makeFakeBackend({ id: "fake" }), options: { registry?: BackendRegistry; catalog?: SessionCatalog; turnTimeoutMs?: number } = {}) { + const sent: ServerMessage[] = []; + const ws: WSContext = { send(data) { sent.push(JSON.parse(data) as ServerMessage); } }; + const host = new WsHost({ + registry: options.registry ?? createStaticBackendRegistry([backend], backend.id), + catalog: options.catalog ?? catalog(), + observability: createRecordingObservability(), + turnTimeoutMs: options.turnTimeoutMs ?? 5_000, + }); + host.clients.add(ws, AUTHORIZATION.principalId); + return { host, sent }; +} + +/** A queue lease that counts its releases. */ +function countedAuthorization(valid = true): AuthorizationContext & { releases: number } { + const authorization = { ...testAuthorization(), valid, releases: 0 } as AuthorizationContext & { releases: number }; + authorization.retain = () => () => { authorization.releases += 1; }; + return authorization; +} + +function queued(text: string, authorization: AuthorizationContext = AUTHORIZATION, extra: Partial = {}): QueuedFollowUp & { released: number } { + const entry = { + principalId: authorization.principalId, + authorization, + text, + attachments: [], + released: 0, + releaseAuthorization: () => { entry.released += 1; }, + ...extra, + } as QueuedFollowUp & { released: number }; + return entry; +} + +function recordingWork(posture?: "voice"): HostWork & { settled: Array<[string, unknown]>; startedWith: string[] } { + const work = { + settled: [] as Array<[string, unknown]>, + startedWith: [] as string[], + ...(posture ? { posture } : {}), + started(turnId: string) { work.startedWith.push(turnId); }, + settle(outcome: string, detail: unknown) { work.settled.push([outcome, detail]); }, + observe() {}, + }; + return work as unknown as HostWork & { settled: Array<[string, unknown]>; startedWith: string[] }; +} + +/** Replace one method on an instance and restore its exact descriptor afterwards. */ +const restores: Array<() => void> = []; +function spyOn(target: T, key: K, replacement: T[K]): void { + const own = Object.getOwnPropertyDescriptor(target, key); + Object.defineProperty(target, key, { configurable: true, writable: true, value: replacement }); + restores.push(() => { + if (own) Object.defineProperty(target, key, own); + else delete (target as Record)[key as PropertyKey]; + }); +} +afterEach(() => { while (restores.length) restores.pop()!(); }); + +async function openSlot(host: WsHost, input: Partial[1]> = {}): Promise { + const slot = await openSessionSlot(host, { authorization: AUTHORIZATION, text: "hello", attachments: [], ...input }, "turn-1", undefined); + if (!slot) throw new Error("the slot did not open"); + return slot; +} + +const OBSERVATION: BudgetObservation = { + scope: "turn", costUsd: 2, tokens: 900, unknownRuns: 0, + warnUsd: 1, blockUsd: 5, blockTokens: 10_000, warnTokens: 800, warning: true, blocked: false, +}; +const ATTRIBUTION: BudgetAttribution = { turnId: "turn-1", sessionId: "session-1", actor: "interactive", model: "model-a", profile: "governed", source: "policy" }; + +describe("outcome classification", () => { + const facts = (overrides: Partial = {}): TurnFacts => ({ cancelled: false, aborted: false, lastResult: "success", stops: {}, ...overrides }); + const failed = (overrides: Partial = {}): FailedTurnFacts => ({ + ...facts(), error: new Error("boom"), egressFailure: undefined, enteredBackend: true, ...overrides, + }); + + test("a completed turn reads success, a reported result error, cancellation and timeout", () => { + expect(classifyCompletedTurn(facts())).toEqual({ lifecycle: "success", work: "completed", cancelledBeforeStart: false, recorder: "success", resultFailed: false }); + expect(classifyCompletedTurn(facts({ lastResult: "error" }))).toMatchObject({ lifecycle: "error", work: "error", resultFailed: true }); + expect(classifyCompletedTurn(facts({ lastResult: "cancelled" }))).toMatchObject({ lifecycle: "success", work: "cancelled" }); + expect(classifyCompletedTurn(facts({ cancelled: true, aborted: true }))).toMatchObject({ lifecycle: "cancelled", work: "cancelled" }); + expect(classifyCompletedTurn(facts({ cancelled: true, aborted: true })).reason).toBeUndefined(); + expect(classifyCompletedTurn(facts({ aborted: true }))).toMatchObject({ lifecycle: "timeout", recorder: "timeout", work: "cancelled", reason: "Turn timed out" }); + }); + + test("a completed turn stopped by a scope cap keeps the cap's reason", () => { + expect(classifyCompletedTurn(facts({ cancelled: true, aborted: true, stops: { scope: "Tool call cap reached" } }))) + .toMatchObject({ lifecycle: "cancelled", work: "cancelled", reason: "Tool call cap reached" }); + }); + + test("a cancel or revocation during admission is cancelled before start, with no error frame", () => { + const cancelled = classifyFailedTurn(failed({ cancelled: true, enteredBackend: false })); + expect(cancelled).toMatchObject({ delivery: "cancelled_before_start", cancelledBeforeStart: true, lifecycle: "cancelled", work: "cancelled", reason: "boom" }); + const revoked = classifyFailedTurn(failed({ error: new AdmissionRevoked(), enteredBackend: false })); + expect(revoked).toMatchObject({ delivery: "cancelled_before_start", lifecycle: "cancelled", recorder: "cancelled", work: "cancelled", reason: REVOKED_REASON }); + // Once the backend was entered, the same cancel is reported. + expect(classifyFailedTurn(failed({ cancelled: true })).delivery).toBe("reported"); + }); + + test("an asynchronous stop wins over the error that unwound the turn, budget first", () => { + const budget = new BudgetUnavailable(); + const journal = new Error("journal storage failed"); + const egress = new Error("egress record failed"); + const both = classifyFailedTurn(failed({ aborted: true, stops: { budget, journal }, egressFailure: egress })); + expect(both).toMatchObject({ terminal: budget, delivery: "reported", lifecycle: "error", work: "error", reason: budget.message, budgetUnavailable: true }); + const journalOnly = classifyFailedTurn(failed({ aborted: true, stops: { journal }, egressFailure: egress })); + expect(journalOnly).toMatchObject({ terminal: journal, lifecycle: "error", work: "error", reason: journal.message, budgetUnavailable: false }); + expect(classifyFailedTurn(failed({ aborted: true, egressFailure: egress }))).toMatchObject({ terminal: egress, lifecycle: "error", work: "error" }); + }); + + test("a timeout is cancelled host work that keeps its reason", () => { + expect(classifyFailedTurn(failed({ aborted: true }))).toMatchObject({ delivery: "reported", lifecycle: "timeout", recorder: "timeout", work: "cancelled", reason: "Turn timed out" }); + }); + + test("a scope stop already narrated is not reported again unless something else failed", () => { + expect(classifyFailedTurn(failed({ cancelled: true, aborted: true, stops: { scope: "cap" } }))) + .toMatchObject({ delivery: "scope_stopped", lifecycle: "cancelled", work: "cancelled", cancelledBeforeStart: false }); + expect(classifyFailedTurn(failed({ cancelled: true, aborted: true, stops: { scope: "cap" }, egressFailure: new Error("egress") })).delivery).toBe("reported"); + }); + + test("an admission budget block is denied in Activity and an error for the work", () => { + const block = new BudgetExceeded(OBSERVATION, "admission"); + const outcome = classifyFailedTurn(failed({ error: block, enteredBackend: false })); + expect(outcome).toMatchObject({ admissionBlock: block, lifecycle: "denied", recorder: "error", work: "error", delivery: "reported" }); + const midTurn = new BudgetExceeded(OBSERVATION, "mid_turn"); + expect(classifyFailedTurn(failed({ stops: { budget: midTurn } }))).toMatchObject({ admissionBlock: undefined, lifecycle: "error" }); + }); + + test("a non-Error terminal reports its string form", () => { + expect(classifyFailedTurn(failed({ error: "plain" })).reason).toBe("plain"); + }); +}); + +describe("budget events", () => { + test("a warning reports dollars once its cost crosses the warning, otherwise tokens", () => { + expect(budgetEvent("budget_warning", OBSERVATION, ATTRIBUTION)).toEqual({ + kind: "budget_warning", turnId: "turn-1", sessionId: "session-1", actor: "interactive", model: "model-a", profile: "governed", + payload: { scope: "turn", unit: "usd", limit: 1, observed: 2, source: "policy" }, + }); + expect(budgetEvent("budget_warning", { ...OBSERVATION, costUsd: null }, ATTRIBUTION).payload) + .toEqual({ scope: "turn", unit: "tokens", limit: 800, observed: 900, source: "policy" }); + }); + + test("a block names its stage; the SDK backstop is always dollars", () => { + expect(budgetEvent("budget_block", OBSERVATION, ATTRIBUTION, "mid_turn").payload) + .toEqual({ scope: "turn", unit: "tokens", limit: 10_000, observed: 900, source: "policy", stage: "mid_turn" }); + expect(budgetEvent("budget_block", { ...OBSERVATION, costUsd: 6 }, ATTRIBUTION, "admission").payload) + .toEqual({ scope: "turn", unit: "usd", limit: 5, observed: 6, source: "policy", stage: "admission" }); + expect(budgetEvent("budget_block", { ...OBSERVATION, costUsd: null }, ATTRIBUTION, "sdk_backstop").payload) + .toEqual({ scope: "turn", unit: "usd", limit: 5, observed: 0, source: "policy", stage: "sdk_backstop" }); + }); + + test("attribution is read from the live turn, and an unheld turn records strict defaults", () => { + const run = { turn: { turnId: "turn-2", sessionId: null }, origin: "voice", mainModel: null, held: {} } as unknown as TurnRun; + expect(budgetAttribution(run)).toEqual({ turnId: "turn-2", sessionId: null, actor: "voice", model: null, profile: "strict", source: "default" }); + }); +}); + +describe("turn budget accounting", () => { + function budgetRun(budgets: Record) { + const { host, sent } = setupHost(); + const governance: unknown[] = []; + const stops: Record = {}; + const abortController = new AbortController(); + const recorded: unknown[][] = []; + Object.defineProperty(host, "budgets", { configurable: true, value: budgets }); + Object.defineProperty(host, "activity", { configurable: true, value: { governance: (event: unknown) => governance.push(event) } }); + const run = { + host, turn: { turnId: "turn-1", sessionId: "session-1", cancelled: false }, origin: "interactive", mainModel: "model-a", + held: { governedHold: { sandbox: { profile: "governed" }, policy: { hash: "abc" } } }, + abortController, stops, budgetWrites: new Set>(), + recorder: { recordBudgetStop: (...args: unknown[]) => recorded.push(args) }, + } as unknown as TurnRun; + return { run, sent, governance, stops, abortController, recorded }; + } + + test("an observed block stops the turn after its write commits", async () => { + const { run, sent, governance, stops, abortController, recorded } = budgetRun({ + observe: async () => ({ warnings: [OBSERVATION], blocked: { ...OBSERVATION, tokens: 20_000 }, receipt: { listPriceCostUsd: 1.5, observedAt: 7 } }), + listPrice: () => 1.25, + }); + const budget = createTurnBudget(run); + expect(budget.observeUsage({ inputTokens: 10, outputTokens: 5, costUsd: 9 } as never)).toEqual({ inputTokens: 10, outputTokens: 5, costUsd: 1.25 } as never); + expect(abortController.signal.aborted).toBe(false); + await settleBudgetWrites(run); + expect(governance.map(event => (event as { kind: string }).kind)).toEqual(["budget_warning", "budget_block"]); + expect(sent.find(frame => frame.type === "usage")).toMatchObject({ turnId: "turn-1", usage: { inputTokens: 10, outputTokens: 5, costUsd: 1.5 } }); + expect(stops.budget).toBeInstanceOf(BudgetExceeded); + expect(recorded).toEqual([[(stops.budget as Error).message]]); + expect(abortController.signal.aborted).toBe(true); + // A stopped turn ignores later usage. + expect(budget.observeUsage({ inputTokens: 1 } as never)).toBeUndefined(); + }); + + test("a failed write makes accounting unavailable", async () => { + const { run, stops, abortController, recorded } = budgetRun({ observe: () => Promise.reject(new Error("disk")), listPrice: () => null }); + createTurnBudget(run).observeUsage({ inputTokens: 1 } as never); + await settleBudgetWrites(run); + expect(stops.budget).toBeInstanceOf(BudgetUnavailable); + expect(recorded).toEqual([[(stops.budget as Error).message, "budget_unavailable"]]); + expect(abortController.signal.aborted).toBe(true); + }); +}); + +describe("slot setup", () => { + test("a routing failure reports the error, settles the work and opens no slot", async () => { + const registry = { ...createStaticBackendRegistry([makeFakeBackend({ id: "fake" })], "fake"), getBackendForSession: async () => { throw new Error("no backend"); } } as unknown as BackendRegistry; + const { host, sent } = setupHost(undefined, { registry }); + const work = recordingWork(); + const slot = await openSessionSlot(host, { authorization: AUTHORIZATION, text: "hi", attachments: [], requestId: "req-1", work, sessionId: "session-1" }, "turn-1", undefined); + expect(slot).toBeUndefined(); + expect(sent.filter(frame => frame.type === "error")).toEqual([expect.objectContaining({ code: "BACKEND_ERROR", message: "no backend", sessionId: "session-1", requestId: "req-1" })] as never); + expect(work.settled[0]?.[0]).toBe("error"); + expect(host.coordinator.startingSessions).toBe(0); + }); + + test("a revoked principal opens no slot", async () => { + const { host } = setupHost(); + const revoked = countedAuthorization(false); + expect(await openSessionSlot(host, { authorization: revoked, text: "hi", attachments: [] }, "turn-1", undefined)).toBeUndefined(); + expect(host.coordinator.running.size).toBe(0); + }); + + test("an opened slot registers its turn and carries a new conversation's draft exchanges", async () => { + const { host } = setupHost(); + const exchange = { id: "x-1" } as never; + const slot = await openSlot(host, { draftId: "draft-1", localExchanges: [exchange] }); + expect(slot.turn).toMatchObject({ turnId: "turn-1", sessionId: null, draftId: "draft-1", providerId: "fake" }); + expect(slot.firstTurnId).toBe("turn-1"); + expect(slot.draftExchanges).toEqual([exchange]); + expect(host.coordinator.running.has(slot.turn)).toBe(true); + const resumed = await openSlot(host, { sessionId: "session-9", draftId: "ignored", localExchanges: [exchange] }); + expect(resumed.turn.draftId).toBeNull(); + expect(resumed.draftExchanges).toEqual([]); + }); + + test("the first request's lease settles its work as cancelled", () => { + const work = recordingWork(); + const request = firstRequest({ authorization: AUTHORIZATION, text: "hi", attachments: [], requestId: "req-1", revision: 3, work }); + expect(request).toMatchObject({ text: "hi", requestId: "req-1", revision: 3, work }); + request.releaseAuthorization(); + expect(work.settled).toEqual([["cancelled", { reason: "The session ended before this request ran" }]]); + }); +}); + +describe("slot queue", () => { + test("binding a revoked request releases its lease and keeps the slot's request fields", async () => { + const { host } = setupHost(); + const slot = await openSlot(host); + const entry = queued("later", countedAuthorization(false), { requestId: "req-2", revision: 4 }); + slot.releaseActive = entry.releaseAuthorization; + expect(bindRequest(slot, entry, undefined)).toBe("revoked"); + expect(entry.released).toBe(1); + expect(slot.releaseActive).toBeUndefined(); + expect(slot.turn.revision).toBeUndefined(); + expect(slot.turn.requestId).toBeUndefined(); + const valid = queued("now", AUTHORIZATION, { requestId: "req-3", revision: 5 }); + expect(bindRequest(slot, valid, undefined)).toBe("bound"); + expect(slot.turn).toMatchObject({ requestId: "req-3", revision: 5 }); + }); + + test("dequeueing re-mints the turn and a dropped hand-over leaves the pending list", async () => { + const { host } = setupHost(); + const slot = await openSlot(host, { sessionId: "session-1" }); + const changes: unknown[] = []; + spyOn(host.coordinator, "queueChanged", ((sessionId: string | null, change: unknown) => { changes.push([sessionId, change]); }) as never); + const entry = queued("next", AUTHORIZATION, { lifecycleTurnId: "turn-queued" }); + slot.turn.queue.push(entry); + slot.turn.lastResult = "success"; + expect(dequeueRequest(slot.turn)).toBe(entry); + expect(slot.turn).toMatchObject({ turnId: "turn-queued", lastResult: null, handingOver: entry }); + dropHandedOver(slot, queued("other"), REVOKED_REASON); + expect(changes).toEqual([]); + dropHandedOver(slot, entry, REVOKED_REASON); + expect(changes).toEqual([["session-1", { dropped: { entries: [entry], reason: REVOKED_REASON } }]]); + expect(dequeueRequest(slot.turn)).toBeNull(); + expect(slot.turn.handingOver).toBeUndefined(); + }); + + test("closing the slot releases every lease once and unregisters its turn", async () => { + const { host } = setupHost(); + const slot = await openSlot(host, { sessionId: "session-1" }); + const changes: unknown[] = []; + spyOn(host.coordinator, "queueChanged", ((sessionId: string | null, change: unknown) => { changes.push([sessionId, change]); }) as never); + const active = queued("active"), next = queued("next"), handed = queued("handed"), waiting = queued("waiting"); + slot.releaseActive = active.releaseAuthorization; + slot.turn.handingOver = handed; + slot.turn.queue.push(waiting); + closeSessionSlot(slot, next); + expect([active.released, next.released, handed.released, waiting.released]).toEqual([1, 1, 0, 1]); + expect(changes).toEqual([["session-1", { dropped: { entries: [handed, waiting], reason: SLOT_ENDED_REASON } }]]); + expect(host.coordinator.running.has(slot.turn)).toBe(false); + expect(slot.turn.queue).toEqual([]); + }); + + test("releasing the active lease clears it", async () => { + const { host } = setupHost(); + const slot = await openSlot(host); + const active = queued("active"); + slot.releaseActive = active.releaseAuthorization; + releaseActive(slot); + expect(active.released).toBe(1); + expect(slot.releaseActive).toBeUndefined(); + }); +}); + +describe("host admission", () => { + test("a voice turn on pi is denied before any runtime starts", async () => { + const { host } = setupHost(); + const admission = await admitWorkerHost(host, makeFakeBackend({ id: "pi" }), recordingWork("voice")); + expect(admission.kind).toBe("denied"); + expect((admission as { error: unknown }).error).toBeInstanceOf(BackendRequestError); + expect((await admitWorkerHost(host, makeFakeBackend({ id: "pi" }), recordingWork())).kind).toBe("admitted"); + }); + + test("the turn timeout aborts the turn and drains its pending requests", async () => { + const { host } = setupHost(undefined, { turnTimeoutMs: 5 }); + const slot = await openSlot(host); + const drained: string[] = []; + spyOn(host.coordinator, "drainPendingForTurn", ((_turn: unknown, reason: string) => { drained.push(reason); }) as never); + const controller = new AbortController(); + const handle = armTurnTimeout(host, slot.turn, controller); + expect(slot.turn.timeoutHandle).toBe(handle); + await new Promise(resolve => setTimeout(resolve, 30)); + expect(controller.signal.aborted).toBe(true); + expect(drained).toEqual(["Turn timed out"]); + }); + + test("announcing a start dispatches the revision and moves the hand-over to started", async () => { + const dispatched: unknown[] = []; + const { host } = setupHost(undefined, { catalog: { ...catalog(), dispatchWork: (...args: unknown[]) => { dispatched.push(args); } } as SessionCatalog }); + const slot = await openSlot(host, { sessionId: "session-1" }); + const changes: unknown[] = []; + spyOn(host.coordinator, "queueChanged", ((sessionId: string | null, change: unknown) => { changes.push([sessionId, change]); }) as never); + const work = recordingWork(); + const entry = queued("next", AUTHORIZATION, { work }); + slot.turn.handingOver = entry; + slot.turn.revision = 7; + announceTurnStart(slot, entry, 1234); + expect(slot.turn.startedAt).toBe(1234); + expect(dispatched).toEqual([["session-1", 7, "turn-1", "fake", 1234]]); + expect(changes).toEqual([["session-1", { started: { entry, turnId: "turn-1" } }]]); + expect(slot.turn.handingOver).toBeUndefined(); + expect(work.startedWith).toEqual(["turn-1"]); + }); +}); + +describe("one slot turn", () => { + test("a refused host check ends the slot with an error frame and settled work", async () => { + const { host, sent } = setupHost(makeFakeBackend({ id: "pi" })); + const slot = await openSlot(host, { requestId: "req-1" }); + const work = recordingWork("voice"); + const entry = queued("hi", AUTHORIZATION, { work }); + slot.releaseActive = entry.releaseAuthorization; + bindRequest(slot, entry, undefined); + expect(await runSlotTurn(slot, entry, undefined)).toBe("stop"); + expect(sent.some(frame => frame.type === "error")).toBe(true); + expect(work.settled[0]?.[0]).toBe("error"); + // The slot's close releases the lease, not the refused turn. + expect(entry.released).toBe(0); + }); + + test("a principal revoked during billing never reaches the backend", async () => { + let started = 0; + const { host } = setupHost(makeFakeBackend({ id: "fake", startTurn: async () => { started += 1; } })); + const slot = await openSlot(host); + const authorization = countedAuthorization(true); + const entry = queued("hi", authorization); + slot.releaseActive = entry.releaseAuthorization; + bindRequest(slot, entry, undefined); + spyOn(host, "expireAuthorizationContexts", (() => { (authorization as { valid: boolean }).valid = false; }) as never); + expect(await runSlotTurn(slot, entry, undefined)).toBe("revoked"); + expect(started).toBe(0); + expect(entry.released).toBe(1); + expect(slot.releaseActive).toBeUndefined(); + }); + + test("a turn that ran settles its work, releases its lease and reports idle", async () => { + const requests: unknown[] = []; + const { host, sent } = setupHost(makeFakeBackend({ id: "fake", startTurn: async (request) => { requests.push(request); } })); + const slot = await openSlot(host, { sessionId: "session-1" }); + const work = recordingWork(); + const entry = queued("hi", AUTHORIZATION, { work, requestId: "req-1" }); + slot.releaseActive = entry.releaseAuthorization; + bindRequest(slot, entry, undefined); + expect(await runSlotTurn(slot, entry, undefined)).toBe("ran"); + expect(requests).toEqual([expect.objectContaining({ prompt: "hi", sessionId: "session-1", turnId: "turn-1", applicationAuthority: "server" })]); + expect(work.settled).toEqual([["completed", { sessionId: "session-1" }]]); + expect(entry.released).toBe(1); + expect(slot.turn.retryRequest).toMatchObject({ type: "chat_message", text: "hi", requestId: "req-1" }); + expect(sent.at(-1)).toMatchObject({ type: "status", status: "idle", sessionId: "session-1" }); + }); +}); + +describe("backend entry and status", () => { + test("an ungoverned turn's request carries no sandbox, budget or worker hooks", () => { + const { host } = setupHost(); + const controller = new AbortController(); + const bridge = {} as never; + const request = turnRequest({ + host, turn: { turnId: "turn-1", sessionId: "session-1" }, current: { attachments: [], thinkingLevel: "high", work: recordingWork("voice") }, + abortController: controller, held: { referenceViews: null, referenceTurn: false, enteredBackend: false }, workerIdentity: undefined, + turnId: "turn-1", profileId: "fake", resumeId: "session-1", + } as unknown as TurnRun, "the prompt", bridge); + expect(request).toEqual({ + applicationAuthority: "server", prompt: "the prompt", attachments: [], sessionId: "session-1", profileId: "fake", + signal: controller.signal, turnBudgetMs: 5_000, bridge, turnId: "turn-1", thinkingLevel: "high", + posture: "voice", enforceAllowedTools: true, noGrantSurface: true, + } as never); + }); + + test("draft exchanges report whether each one was stored", async () => { + const { host, sent } = setupHost(undefined, { catalog: { ...catalog(), recordLocalExchange: async (_sid: string, exchange: { id: string }) => exchange.id === "kept" } as SessionCatalog }); + recordDraftExchanges(host, "session-1", [{ id: "kept" }, { id: "lost" }] as never); + await new Promise(resolve => setTimeout(resolve, 0)); + expect(sent.filter(frame => frame.type === "local_exchange_result")).toEqual([ + { type: "local_exchange_result", sessionId: "session-1", exchangeId: "kept", saved: true }, + { type: "local_exchange_result", sessionId: "session-1", exchangeId: "lost", saved: false, reason: "The server could not store it." }, + ] as never); + }); + + test("the slot status is cancelled before start, idle for a named session, and silent otherwise", () => { + const { host, sent } = setupHost(); + publishTurnStatus({ host, turn: { turnId: "turn-1", sessionId: null, requestId: "req-1" } as never }, { cancelledBeforeStart: true }); + publishTurnStatus({ host, turn: { turnId: "turn-1", sessionId: "session-1" } as never }, { cancelledBeforeStart: false }); + publishTurnStatus({ host, turn: { turnId: "turn-1", sessionId: null } as never }, { cancelledBeforeStart: false }); + expect(sent).toEqual([ + expect.objectContaining({ type: "status", status: "cancelled", detail: "Cancelled before starting", requestId: "req-1" }), + expect.objectContaining({ type: "status", status: "idle", sessionId: "session-1" }), + ] as never); + }); +}); diff --git a/scripts/measure-show-block.ts b/scripts/measure-show-block.ts index a8da0ba674..4fd815c58c 100644 --- a/scripts/measure-show-block.ts +++ b/scripts/measure-show-block.ts @@ -399,7 +399,7 @@ export function optionsFor(arm: ArmName, abortController: AbortController, alway return { cwd: BRAIN_PATH, // Production aborts a turn at this budget rather than letting it run on - // (`packages/ui-server/src/ws/run-session.ts:186`). Without it the harness + // (`timeoutHandle = setTimeout`, `packages/ui-server/src/ws/session-run/admission.ts:47`). Without it the harness // would score an answer no reader could ever have received: five turns of // an earlier run took 190-306 s. `maxTurns` bounds the conversation, not // the clock. From d1211758d794a15be020a6839c83ea6aa1305dfc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 01:24:03 +0000 Subject: [PATCH 3/5] chore(ui-server): changeset for the retained-session lifecycle stages Refs #1359 Co-Authored-By: Claude Opus 5.5 --- .changeset/retained-session-stages.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/retained-session-stages.md diff --git a/.changeset/retained-session-stages.md b/.changeset/retained-session-stages.md new file mode 100644 index 0000000000..d0700983a0 --- /dev/null +++ b/.changeset/retained-session-stages.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +A session's turns now run through named lifecycle stages: slot setup, host and governed admission, backend entry, outcome classification and teardown. Turn behaviour, ordering and the wire protocol are unchanged. From 27dba178a35547223ef9e038b2a312c272b36e40 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 02:41:45 +0000 Subject: [PATCH 4/5] fix(ui-server): keep the slot's state transitions in one synchronous step The base ran every state change between two awaits in one continuation. The first split added microtask ticks at the new function boundaries. `await openSessionSlot()` left a gap after the turn was registered but before the first request's revision was bound. Recovery read the session in that gap and saw no queued request: ws-session-recovery's "an acceptance that could not be recorded makes the session unknown, never its older success" failed 4 out of 4 runs, and passes on the base. - Routing's await stays inline in runRetainedSession. endStarting, registerSessionSlot (now synchronous) and the first bindRequest run in one step, so the session is never neither starting nor running. - confirmAdmission() is a separate synchronous check run after admitGovernedTurn resolves. The final abort and revocation check, the source record and the draft-exchange take stay atomic, as before. - runSlotTurn returns ran (with its outcome), revoked or denied. The slot runs each tail (error frame and work settle, lifecycle finish and lease release, the final status frame) in the same step as its next dequeue or its close. Refs #1359 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/managed-worktrees.md | 4 +- docs/decisions/session-principals.md | 6 +- .../plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 4 +- docs/plans/navigation-recovery.md | 2 +- packages/ui-server/src/ws/run-session.ts | 45 ++++++++-- .../ui-server/src/ws/session-run/admission.ts | 34 ++++--- .../src/ws/session-run/backend-entry.ts | 2 +- packages/ui-server/src/ws/session-run/slot.ts | 90 ++++++++++--------- .../ui-server/src/ws/session-run/teardown.ts | 4 +- packages/ui-server/src/ws/session-run/turn.ts | 34 +++---- 11 files changed, 136 insertions(+), 91 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 7262386706..5483a32d32 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -97,7 +97,7 @@ unknown; what happens next is in [hygiene and cleanup](#hygiene-and-cleanup). Each governed or strict turn whose journal is recording opens one worker generation, and every worker of that turn binds the generation's root-owned directory whole at `/tmp/brain-worktrees`, inside the turn's own `/tmp` -(`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/session-run/admission.ts:194-206`; +(`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/session-run/admission.ts:191-203`; `// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:852-863`). A granted worktree appears there as `/tmp/brain-worktrees//` on the worker's next path lookup; the worker cannot create entries beside it, and a @@ -199,7 +199,7 @@ The host side is `createReferenceTools` start, the host records its principal and what those workers bind: the public view, the principal's private view and the turn's worker generation, if one opened -(`// Reference tools (#2432): the turn's workers bind the principal's source`, `packages/ui-server/src/ws/session-run/admission.ts:207-213`). +(`// Reference tools (#2432): the turn's workers bind the principal's source`, `packages/ui-server/src/ws/session-run/admission.ts:204-210`). A call carries only a repository, a revision or a worktree identity. The bridge adds the turn's own principal, and a call for a turn the host did not prepare, or under another principal, refuses diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 9fc5facbe6..2da7ee3750 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -102,7 +102,7 @@ Both reviewers verified every row below against the source. | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | -| Follow-up queue | `QueuedFollowUp`, `ws/turns.ts:61-103`; `slot.queue.push(entry)`, `run-session.ts:225` | queued entries re-mint `turnId` in the same slot and may come from another socket | +| Follow-up queue | `QueuedFollowUp`, `ws/turns.ts:61-103`; `slot.queue.push(entry)`, `run-session.ts:260` | queued entries re-mint `turnId` in the same slot and may come from another socket | | Password login | `acquirePasswordVerification(key)`, `auth.ts:739` | argon2id verify, failure counting, in-flight reservation, then `issueSessionCookie` | | Passkey login | `issueLoginSession`, `packages/ui-server/src/middleware/passkeys.ts:441` | assertion verified, then `issueSessionCookie`; `row.id` is in scope | | Passkey **registration** | `INSERT INTO passkey_credentials`, `packages/ui-server/src/db/account-writes.ts:31-36` | inserts a credential; calls **neither** helper | @@ -178,8 +178,8 @@ ceremony in flight can mint a session for a credential deleted meanwhile. **5. Revocation is a boundary that outlives admission.** Closing a socket is not revocation: `onMessage` dispatches without re-checking (`ws/connection.ts:173`), turn startup awaits routing and billing before `startTurn` -(`resolveTurnTarget`, `ws/session-run/slot.ts:33`; `const billing = await resolveRunBilling`, -`ws/session-run/turn.ts:39`), and queued follow-ups execute later. Each connection holds a +(`resolveTurnTarget`, `ws/run-session.ts:105`; `const billing = await resolveRunBilling`, +`ws/session-run/turn.ts:35`), and queued follow-ups execute later. Each connection holds a server-resolved authorization context; revocation marks it invalid synchronously, refuses later frames, drops that principal's queued unstarted follow-ups, and leaves running work running (cancelling a slot would take other diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 3e0ea9c399..6b7c46b38a 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -256,7 +256,7 @@ Stated before the requirements because five of them derive from it. (`export function createTurnRecorder(`, `packages/ui-server/src/activity/recorder.ts:125-203`). - R25. **Autonomous work gets its own pool** (`MAX_AUTONOMOUS_RUNS`, default 2) — but a second counter alone does not deliver "interactive always wins". The host cap applies only when - starting WS sessions (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:436-448`), and an autonomous + starting WS sessions (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:471-483`), and an autonomous turn can hold a path write lock while an interactive turn waits or is denied at 30 seconds (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`). Required: an admission controller with reserved interactive capacity and hybrid yield at an explicit denial-risk diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 0c2b3cb955..1ef202dcae 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -156,7 +156,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. - **Share provenance/limits:** (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:101`) assigns the source in server code. (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2401`) bounds text, not binary uploads; extracted T1 context needs its own byte/token bound. -- **Interactive locks:** (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:436-448`) gates WS starts; +- **Interactive locks:** (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:471-483`) gates WS starts; (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`) owns tool locks. Shared-target priority and cooperative yield belong to the keyed lock and backend lifecycle. @@ -1274,7 +1274,7 @@ full-v1 enablement; predicates and schema tests cannot substitute for it. **Approach:** **hybrid — reserve capacity normally, yield only at denial risk.** `MAX_AUTONOMOUS_RUNS` (default 2) is necessary but not sufficient: the host cap applies only at -WS session start (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:436-448`) and an autonomous turn can hold a path write lock +WS session start (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:471-483`) and an autonomous turn can hold a path write lock while an interactive turn waits or is denied at 30s (`export function createTurnLockBinding(`, `packages/ui-backend-claude/src/turn-lock.ts:27-119`). diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index fe21b681e9..8a0608c5b3 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -399,7 +399,7 @@ implementation. Any PR moving these lines owns their citation repairs. - API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:912`). -- Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:202-247`). +- Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:237-282`). - Approval target: (`function mutateLastAssistant(`, `packages/ui-react/src/stores/chat-slices/buffers.ts:142-172`). diff --git a/packages/ui-server/src/ws/run-session.ts b/packages/ui-server/src/ws/run-session.ts index 5250ea2f40..49d1902ccc 100644 --- a/packages/ui-server/src/ws/run-session.ts +++ b/packages/ui-server/src/ws/run-session.ts @@ -18,7 +18,21 @@ import type { AuthorizationContext, HostWork, QueuedFollowUp, RunningTurn } from import { queuedBytes, queuedFollowUpBytes } from "./turns.js"; import type { WsHost } from "./host.js"; import { MAX_SESSION_QUEUE, QUEUE_MAX_BYTES, QUEUE_WARN_BYTES } from "./limits.js"; -import { bindRequest, closeSessionSlot, dequeueRequest, dropHandedOver, firstRequest, openSessionSlot, requestLifecycle } from "./session-run/slot.js"; +import { emitTurnError } from "./bridge.js"; +import { resolveTurnTarget } from "./routing.js"; +import { + beginSlotStart, + bindRequest, + closeSessionSlot, + dequeueRequest, + dropHandedOver, + firstRequest, + registerSessionSlot, + releaseActive, + reportRoutingFailure, + requestLifecycle, +} from "./session-run/slot.js"; +import { publishTurnStatus } from "./session-run/teardown.js"; import { runSlotTurn } from "./session-run/turn.js"; import type { HandoffHooks, RunSessionInput, TurnLifecycle } from "./session-run/types.js"; import { REVOKED_REASON } from "./turns.js"; @@ -75,7 +89,9 @@ export async function runSession(host: WsHost, initial: RunSessionInput): Promis * The slot's lifecycle: setup, then each request in queue order, then * teardown. Each request is bound to the slot, run as one turn * (`session-run/turn.ts`), and the slot advances to the session and profile - * that turn left behind. + * that turn left behind. Every state transition the slot makes between two + * awaits runs in one synchronous step here: routing's end and the turn's + * registration, and a turn's result and the next dequeue or the slot's close. */ async function runRetainedSession( host: WsHost, @@ -83,7 +99,17 @@ async function runRetainedSession( initialTurnId: string, initialLifecycle: TurnLifecycle | undefined ): Promise { - const slot = await openSessionSlot(host, initial, initialTurnId, initialLifecycle); + const starting = beginSlotStart(host, initial); + let target: Awaited>; + try { + target = await resolveTurnTarget(host.registry, host.catalog, initial.sessionId, initial.providerId); + } catch (err) { + reportRoutingFailure(host, initial, starting, err, initialLifecycle); + return; + } finally { + host.coordinator.endStarting(initial.sessionId, starting); + } + const slot = registerSessionSlot(host, initial, starting, target, initialTurnId); if (!slot) return; const { turn } = slot; let next: QueuedFollowUp | null = firstRequest(initial); @@ -102,12 +128,21 @@ async function runRetainedSession( } next = null; const result = await runSlotTurn(slot, current, lifecycle); - if (result === "stop") break; - if (result === "revoked") { + if (result.kind === "denied") { + const { error } = result; + lifecycle?.finish("denied", error instanceof Error ? error.message : String(error)); + emitTurnError(host, turn, error); + current.work?.settle("error", { reason: error instanceof Error ? error.message : String(error) }); + break; + } + if (result.kind === "revoked") { + lifecycle?.finish("cancelled", REVOKED_REASON); + releaseActive(slot); dropHandedOver(slot, current, REVOKED_REASON); next = dequeueRequest(turn); continue; } + publishTurnStatus(slot, result.outcome); // Subsequent (queued) turns resume the now-known session and keep its // pin. turn.providerId is the resolved profile (set from initial routing diff --git a/packages/ui-server/src/ws/session-run/admission.ts b/packages/ui-server/src/ws/session-run/admission.ts index e0d3d65724..fe311762a5 100644 --- a/packages/ui-server/src/ws/session-run/admission.ts +++ b/packages/ui-server/src/ws/session-run/admission.ts @@ -126,21 +126,18 @@ export function heldProfile(run: Pick): "governed" | "strict" { return run.held.governedHold!.sandbox.profile === "governed" ? "governed" : "strict"; } -export type GovernedAdmission = - | { - readonly kind: "admitted"; - /** The principal's profile preference for an interactive turn, which a draft's first send records. */ - readonly preference: "governed" | "strict" | undefined; - } - | { readonly kind: "revoked" }; +export interface GovernedAdmission { + /** The principal's profile preference for an interactive turn, which a draft's first send records. */ + readonly preference: "governed" | "strict" | undefined; +} /** * Governed admission, in order: the governed hold, the budget and its * warnings, the journal, a managed worktree generation (#2430), reference * tools (#2432) and per-turn scope caps. What it acquires is recorded on * {@link TurnRun.held} as it goes, so teardown releases it whichever way the - * turn ends. Throws a refusal or an abort; resolves `revoked` when the - * principal lost authority during the native awaits. + * turn ends. Throws a refusal or an abort. The caller confirms the turn's + * authority with {@link confirmAdmission} once this resolves. */ export async function admitGovernedTurn(run: TurnRun): Promise { const { host, slot, turn, backend, lifecycle, abortController, billing, recorder, held, stops, origin, profileId, resumeId } = run; @@ -212,11 +209,20 @@ export async function admitGovernedTurn(run: TurnRun): Promise): "admitted" | "revoked" { + run.abortController.signal.throwIfAborted(); + run.host.expireAuthorizationContexts(); + return run.turn.authorization.valid ? "admitted" : "revoked"; } /** Whether the backend's turn runs on the host inference relay. */ diff --git a/packages/ui-server/src/ws/session-run/backend-entry.ts b/packages/ui-server/src/ws/session-run/backend-entry.ts index c8041e2223..5852ca31aa 100644 --- a/packages/ui-server/src/ws/session-run/backend-entry.ts +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -51,7 +51,7 @@ function recordSource(run: TurnRun, sessionId: string): void { */ export async function openTurnBridge( run: TurnRun, - admission: Extract, + admission: GovernedAdmission, budget: TurnBudget | undefined ): Promise<{ prompt: string; bridge: BackendBridge }> { const { host, slot, turn, backend, current, recorder, failureRecording, billing, held, origin, profileId, resumeId } = run; diff --git a/packages/ui-server/src/ws/session-run/slot.ts b/packages/ui-server/src/ws/session-run/slot.ts index 4dc3065f8b..e9a6c0f4b5 100644 --- a/packages/ui-server/src/ws/session-run/slot.ts +++ b/packages/ui-server/src/ws/session-run/slot.ts @@ -1,6 +1,6 @@ import { createTurnLifecycle } from "../../activity/turn-lifecycle.js"; import type { WsHost } from "../host.js"; -import { resolveTurnTarget } from "../routing.js"; +import type { resolveTurnTarget } from "../routing.js"; import type { QueuedFollowUp, RunningTurn, StartingSession } from "../turns.js"; import { REVOKED_REASON } from "../turns.js"; import type { RunSessionInput, SessionSlot, TurnLifecycle } from "./types.js"; @@ -9,52 +9,62 @@ import type { RunSessionInput, SessionSlot, TurnLifecycle } from "./types.js"; export const SLOT_ENDED_REASON = "The session stopped before it ran."; /** - * Route a new slot and register its turn. Messages that arrive while routing - * queue on the starting session and become the turn's queue. Resolves - * undefined when the slot ends before any turn: routing failed (reported - * here), the start was cancelled, the host is closing, or the principal was - * revoked. + * Open a session start: messages that arrive while the slot routes queue on + * it, and become the turn's queue once the slot is registered. */ -export async function openSessionSlot( - host: WsHost, - initial: RunSessionInput, - initialTurnId: string, - initialLifecycle: TurnLifecycle | undefined -): Promise { - const { coordinator } = host; +export function beginSlotStart(host: WsHost, initial: RunSessionInput): StartingSession { const starting: StartingSession = { queue: [], cancelled: false, ...(initial.revision !== undefined ? { revision: initial.revision } : {}), }; - coordinator.beginStarting(initial.sessionId, starting); - let target: Awaited>; - try { - target = await resolveTurnTarget(host.registry, host.catalog, initial.sessionId, initial.providerId); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - initialLifecycle?.finish("error", message); - // No turn exists yet — routing failed before one was minted — so the - // report carries only the session identity the client asked for. - host.reportTurnFailed("BACKEND_ERROR", { sessionId: initial.sessionId }, message); - initial.work?.settle("error", { reason: message }); - // Messages queued behind this start have no runner now: settle their - // work and release their leases instead of stranding them. - for (const entry of starting.queue) entry.work?.settle("error", { reason: message }); - if (initial.sessionId) coordinator.dropStartingQueue(initial.sessionId, starting, message); - else for (const entry of starting.queue.splice(0)) entry.releaseAuthorization(); - host.sendToClients({ - type: "error", - code: "BACKEND_ERROR", - message, - ...(initial.sessionId ? { sessionId: initial.sessionId } : {}), - ...(initial.requestId ? { requestId: initial.requestId } : {}), - }); - return undefined; - } finally { - coordinator.endStarting(initial.sessionId, starting); - } + host.coordinator.beginStarting(initial.sessionId, starting); + return starting; +} +/** + * Routing failed before a turn was minted: report it with only the session + * identity the client asked for, and settle everything queued behind it. + */ +export function reportRoutingFailure( + host: WsHost, + initial: RunSessionInput, + starting: StartingSession, + err: unknown, + initialLifecycle: TurnLifecycle | undefined +): void { + const message = err instanceof Error ? err.message : String(err); + initialLifecycle?.finish("error", message); + host.reportTurnFailed("BACKEND_ERROR", { sessionId: initial.sessionId }, message); + initial.work?.settle("error", { reason: message }); + // Messages queued behind this start have no runner now: settle their + // work and release their leases instead of stranding them. + for (const entry of starting.queue) entry.work?.settle("error", { reason: message }); + if (initial.sessionId) host.coordinator.dropStartingQueue(initial.sessionId, starting, message); + else for (const entry of starting.queue.splice(0)) entry.releaseAuthorization(); + host.sendToClients({ + type: "error", + code: "BACKEND_ERROR", + message, + ...(initial.sessionId ? { sessionId: initial.sessionId } : {}), + ...(initial.requestId ? { requestId: initial.requestId } : {}), + }); +} + +/** + * Register a routed slot's turn, synchronously after its start ended so no + * message can find the session neither starting nor running. Resolves + * undefined when the slot ends before any turn: the start was cancelled, + * the host is closing, or the principal was revoked. + */ +export function registerSessionSlot( + host: WsHost, + initial: RunSessionInput, + starting: StartingSession, + target: Awaited>, + initialTurnId: string +): SessionSlot | undefined { + const { coordinator } = host; if (starting.cancelled || host.closing) { for (const entry of starting.queue.splice(0)) entry.releaseAuthorization(); return undefined; diff --git a/packages/ui-server/src/ws/session-run/teardown.ts b/packages/ui-server/src/ws/session-run/teardown.ts index 4ded1ba676..6ef248c8fd 100644 --- a/packages/ui-server/src/ws/session-run/teardown.ts +++ b/packages/ui-server/src/ws/session-run/teardown.ts @@ -68,9 +68,9 @@ export async function teardownTurn(run: TurnRun, outcome: TurnOutcome): Promise< turn.work = undefined; releaseActive(slot); // The recorder's writes, terminal included, commit off the event loop - // (#2814); recovery must see them before the final idle notification. + // (#2814); recovery must see them before the final idle notification, + // which the slot publishes with {@link publishTurnStatus}. await recorder?.settled(); - publishTurnStatus(run, outcome); } /** diff --git a/packages/ui-server/src/ws/session-run/turn.ts b/packages/ui-server/src/ws/session-run/turn.ts index 35c3b74983..0947098503 100644 --- a/packages/ui-server/src/ws/session-run/turn.ts +++ b/packages/ui-server/src/ws/session-run/turn.ts @@ -1,22 +1,24 @@ import { emitTurnError } from "../bridge.js"; import type { QueuedFollowUp } from "../turns.js"; -import { REVOKED_REASON } from "../turns.js"; import { recordPendingCancellations } from "./cancellations.js"; -import { admitGovernedTurn, admitWorkerHost, announceTurnStart, armTurnTimeout, createRunRecorder } from "./admission.js"; +import { admitGovernedTurn, admitWorkerHost, announceTurnStart, armTurnTimeout, confirmAdmission, createRunRecorder } from "./admission.js"; import { openTurnBridge, prepareRelayedEgress, turnRequest } from "./backend-entry.js"; import { resolveRunBilling } from "./billing.js"; import { budgetAttribution, budgetEvent, createTurnBudget, settleBudgetWrites } from "./budget.js"; import { AdmissionRevoked, classifyCompletedTurn, classifyFailedTurn, UNCLASSIFIED_OUTCOME, type TurnOutcome } from "./outcome.js"; -import { releaseActive } from "./slot.js"; import { teardownTurn } from "./teardown.js"; import type { SessionSlot, TurnLifecycle, TurnRun } from "./types.js"; /** * How one request of a slot ended: it `ran` (whatever its outcome), its - * principal was `revoked` before it reached admission, or the host refused - * it and the slot `stop`s. + * principal was `revoked` before it reached admission, or the host check + * `denied` it and the slot stops. The slot acts on each in the same + * synchronous run as its next dequeue or its close. */ -export type SlotTurnResult = "ran" | "revoked" | "stop"; +export type SlotTurnResult = + | { readonly kind: "ran"; readonly outcome: TurnOutcome } + | { readonly kind: "revoked" } + | { readonly kind: "denied"; readonly error: unknown }; /** Run the request the slot is bound to as one turn, from host admission to teardown. */ export async function runSlotTurn(slot: SessionSlot, current: QueuedFollowUp, lifecycle: TurnLifecycle | undefined): Promise { @@ -28,13 +30,7 @@ export async function runSlotTurn(slot: SessionSlot, current: QueuedFollowUp, li const abortController = new AbortController(); turn.abortController = abortController; const workerHost = await admitWorkerHost(host, backend, work); - if (workerHost.kind === "denied") { - const { error } = workerHost; - lifecycle?.finish("denied", error instanceof Error ? error.message : String(error)); - emitTurnError(host, turn, error); - work?.settle("error", { reason: error instanceof Error ? error.message : String(error) }); - return "stop"; - } + if (workerHost.kind === "denied") return { kind: "denied", error: workerHost.error }; const timeoutHandle = armTurnTimeout(host, turn, abortController); const billing = await resolveRunBilling(host.registry, backend.id, slot.profileId); const failureRecording = await host.failureReplay.begin(backend, slot.resumeId, turn.turnId, abortController.signal); @@ -58,9 +54,7 @@ export async function runSlotTurn(slot: SessionSlot, current: QueuedFollowUp, li // was revoked a moment later would erase the actor, not the turn. Drain // the buffer before leaving. recordPendingCancellations(host, turn, billing, lifecycle); - lifecycle?.finish("cancelled", REVOKED_REASON); - releaseActive(slot); - return "revoked"; + return { kind: "revoked" }; } const recorder = createRunRecorder(host, turn, lifecycle, billing, abortController, work); const mainModel = billing?.model ?? null; @@ -86,18 +80,17 @@ export async function runSlotTurn(slot: SessionSlot, current: QueuedFollowUp, li stops: {}, budgetWrites: new Set(), held: { referenceViews: null, referenceTurn: false, enteredBackend: false }, }; announceTurnStart(slot, current, run.startedAt); - await executeTurn(run); - return "ran"; + return { kind: "ran", outcome: await executeTurn(run) }; } /** Admit, enter the backend, classify the outcome and tear the turn down. */ -async function executeTurn(run: TurnRun): Promise { +async function executeTurn(run: TurnRun): Promise { const { host, turn, backend, lifecycle, abortController, recorder, held, stops } = run; let outcome: TurnOutcome = UNCLASSIFIED_OUTCOME; turn.backendStarted = false; try { const admission = await admitGovernedTurn(run); - if (admission.kind === "revoked") throw new AdmissionRevoked(); + if (confirmAdmission(run) === "revoked") throw new AdmissionRevoked(); const budget = host.budgets && held.governedHold ? createTurnBudget(run) : undefined; const { prompt, bridge } = await openTurnBridge(run, admission, budget); await prepareRelayedEgress(run, bridge, budget); @@ -148,4 +141,5 @@ async function executeTurn(run: TurnRun): Promise { } finally { await teardownTurn(run, outcome); } + return outcome; } From 01cc8a891a8b1073ed046f774c1fe304f5605575 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 02:41:45 +0000 Subject: [PATCH 5/5] test(ui-server): cover synchronous slot registration and admission confirmation directly Refs #1359 Co-Authored-By: Claude Opus 5.5 --- .../tests/session-run-stages.test.ts | 100 +++++++++++++----- 1 file changed, 76 insertions(+), 24 deletions(-) diff --git a/packages/ui-server/tests/session-run-stages.test.ts b/packages/ui-server/tests/session-run-stages.test.ts index 3ff36daf42..6d726858bc 100644 --- a/packages/ui-server/tests/session-run-stages.test.ts +++ b/packages/ui-server/tests/session-run-stages.test.ts @@ -5,6 +5,7 @@ import { BackendRequestError, type AgentBackend } from "@schlessera/brain-ui-sdk import { createStaticBackendRegistry, type BackendRegistry } from "../src/agent/backend"; import { BudgetExceeded, BudgetUnavailable } from "../src/brain/turn-budgets"; import { createRecordingObservability } from "../src/observability/index"; +import { resolveTurnTarget } from "../src/ws/routing"; import type { WSContext } from "../src/ws/clients"; import { WsHost } from "../src/ws/host"; import type { SessionCatalog } from "../src/ws/session-catalog"; @@ -24,9 +25,11 @@ import { closeSessionSlot, dequeueRequest, dropHandedOver, + beginSlotStart, firstRequest, - openSessionSlot, + registerSessionSlot, releaseActive, + reportRoutingFailure, SLOT_ENDED_REASON, } from "../src/ws/session-run/slot"; import { publishTurnStatus } from "../src/ws/session-run/teardown"; @@ -103,8 +106,16 @@ function spyOn(target: T, key: K, replaceme } afterEach(() => { while (restores.length) restores.pop()!(); }); -async function openSlot(host: WsHost, input: Partial[1]> = {}): Promise { - const slot = await openSessionSlot(host, { authorization: AUTHORIZATION, text: "hello", attachments: [], ...input }, "turn-1", undefined); +type SlotInput = Parameters[1]; + +/** Route and register a slot the way runRetainedSession does. */ +async function openSlot(host: WsHost, input: Partial = {}): Promise { + const initial: SlotInput = { authorization: AUTHORIZATION, text: "hello", attachments: [], ...input }; + const starting = beginSlotStart(host, initial); + let target: Awaited>; + try { target = await resolveTurnTarget(host.registry, host.catalog, initial.sessionId, initial.providerId); } + finally { host.coordinator.endStarting(initial.sessionId, starting); } + const slot = registerSessionSlot(host, initial, starting, target, "turn-1"); if (!slot) throw new Error("the slot did not open"); return slot; } @@ -250,21 +261,38 @@ describe("turn budget accounting", () => { }); describe("slot setup", () => { - test("a routing failure reports the error, settles the work and opens no slot", async () => { - const registry = { ...createStaticBackendRegistry([makeFakeBackend({ id: "fake" })], "fake"), getBackendForSession: async () => { throw new Error("no backend"); } } as unknown as BackendRegistry; - const { host, sent } = setupHost(undefined, { registry }); + test("a routing failure reports the error, settles queued work and releases the start's queue", () => { + const { host, sent } = setupHost(); const work = recordingWork(); - const slot = await openSessionSlot(host, { authorization: AUTHORIZATION, text: "hi", attachments: [], requestId: "req-1", work, sessionId: "session-1" }, "turn-1", undefined); - expect(slot).toBeUndefined(); - expect(sent.filter(frame => frame.type === "error")).toEqual([expect.objectContaining({ code: "BACKEND_ERROR", message: "no backend", sessionId: "session-1", requestId: "req-1" })] as never); - expect(work.settled[0]?.[0]).toBe("error"); + const initial: SlotInput = { authorization: AUTHORIZATION, text: "hi", attachments: [], requestId: "req-1", work }; + const starting = beginSlotStart(host, initial); + const waiting = queued("waiting", AUTHORIZATION, { work: recordingWork() }); + starting.queue.push(waiting); + reportRoutingFailure(host, initial, starting, new Error("no backend"), undefined); + host.coordinator.endStarting(initial.sessionId, starting); + expect(sent.filter(frame => frame.type === "error")).toEqual([expect.objectContaining({ code: "BACKEND_ERROR", message: "no backend", requestId: "req-1" })] as never); + expect(work.settled).toEqual([["error", { reason: "no backend" }]]); + expect((waiting.work as ReturnType).settled).toEqual([["error", { reason: "no backend" }]]); + expect(waiting.released).toBe(1); + expect(starting.queue).toEqual([]); expect(host.coordinator.startingSessions).toBe(0); }); - test("a revoked principal opens no slot", async () => { + test("a revoked principal or a cancelled start registers no turn and releases the queue", async () => { const { host } = setupHost(); - const revoked = countedAuthorization(false); - expect(await openSessionSlot(host, { authorization: revoked, text: "hi", attachments: [] }, "turn-1", undefined)).toBeUndefined(); + const target = await resolveTurnTarget(host.registry, host.catalog, undefined, undefined); + const revoked: SlotInput = { authorization: countedAuthorization(false), text: "hi", attachments: [] }; + const revokedStart = beginSlotStart(host, revoked); + const waiting = queued("waiting"); + revokedStart.queue.push(waiting); + host.coordinator.endStarting(undefined, revokedStart); + expect(registerSessionSlot(host, revoked, revokedStart, target, "turn-1")).toBeUndefined(); + expect(waiting.released).toBe(1); + const cancelled: SlotInput = { authorization: AUTHORIZATION, text: "hi", attachments: [] }; + const cancelledStart = beginSlotStart(host, cancelled); + cancelledStart.cancelled = true; + host.coordinator.endStarting(undefined, cancelledStart); + expect(registerSessionSlot(host, cancelled, cancelledStart, target, "turn-1")).toBeUndefined(); expect(host.coordinator.running.size).toBe(0); }); @@ -393,17 +421,19 @@ describe("host admission", () => { }); describe("one slot turn", () => { - test("a refused host check ends the slot with an error frame and settled work", async () => { + test("a refused host check is returned to the slot before anything is reported", async () => { const { host, sent } = setupHost(makeFakeBackend({ id: "pi" })); const slot = await openSlot(host, { requestId: "req-1" }); const work = recordingWork("voice"); const entry = queued("hi", AUTHORIZATION, { work }); slot.releaseActive = entry.releaseAuthorization; bindRequest(slot, entry, undefined); - expect(await runSlotTurn(slot, entry, undefined)).toBe("stop"); - expect(sent.some(frame => frame.type === "error")).toBe(true); - expect(work.settled[0]?.[0]).toBe("error"); - // The slot's close releases the lease, not the refused turn. + const result = await runSlotTurn(slot, entry, undefined); + expect(result.kind).toBe("denied"); + expect((result as { error: unknown }).error).toBeInstanceOf(BackendRequestError); + // The slot reports it, settles the work and releases the lease as it stops. + expect(sent.some(frame => frame.type === "error")).toBe(false); + expect(work.settled).toEqual([]); expect(entry.released).toBe(0); }); @@ -412,17 +442,38 @@ describe("one slot turn", () => { const { host } = setupHost(makeFakeBackend({ id: "fake", startTurn: async () => { started += 1; } })); const slot = await openSlot(host); const authorization = countedAuthorization(true); - const entry = queued("hi", authorization); + const entry = queued("hi", authorization, { revision: 2 }); slot.releaseActive = entry.releaseAuthorization; bindRequest(slot, entry, undefined); spyOn(host, "expireAuthorizationContexts", (() => { (authorization as { valid: boolean }).valid = false; }) as never); - expect(await runSlotTurn(slot, entry, undefined)).toBe("revoked"); + expect(await runSlotTurn(slot, entry, undefined)).toEqual({ kind: "revoked" }); + expect(started).toBe(0); + expect(slot.turn.revision).toBeUndefined(); + // The slot releases the lease in the same step as its next dequeue. + expect(entry.released).toBe(0); + }); + + test("a principal revoked during governed admission is cancelled before start", async () => { + let started = 0; + const { host, sent } = setupHost(makeFakeBackend({ id: "fake", startTurn: async () => { started += 1; } })); + const slot = await openSlot(host, { sessionId: "session-1" }); + const authorization = countedAuthorization(true); + const work = recordingWork(); + const entry = queued("hi", authorization, { work }); + slot.releaseActive = entry.releaseAuthorization; + bindRequest(slot, entry, undefined); + let checks = 0; + // Valid at the billing boundary, revoked by the time admission confirms. + spyOn(host, "expireAuthorizationContexts", (() => { checks += 1; if (checks === 2) (authorization as { valid: boolean }).valid = false; }) as never); + const result = await runSlotTurn(slot, entry, undefined); + expect(result).toEqual({ kind: "ran", outcome: expect.objectContaining({ delivery: "cancelled_before_start", work: "cancelled", reason: REVOKED_REASON }) }); expect(started).toBe(0); + expect(sent.some(frame => frame.type === "error")).toBe(false); + expect(work.settled).toEqual([["cancelled", { sessionId: "session-1", reason: REVOKED_REASON }]]); expect(entry.released).toBe(1); - expect(slot.releaseActive).toBeUndefined(); }); - test("a turn that ran settles its work, releases its lease and reports idle", async () => { + test("a turn that ran settles its work and releases its lease, leaving the status to the slot", async () => { const requests: unknown[] = []; const { host, sent } = setupHost(makeFakeBackend({ id: "fake", startTurn: async (request) => { requests.push(request); } })); const slot = await openSlot(host, { sessionId: "session-1" }); @@ -430,12 +481,13 @@ describe("one slot turn", () => { const entry = queued("hi", AUTHORIZATION, { work, requestId: "req-1" }); slot.releaseActive = entry.releaseAuthorization; bindRequest(slot, entry, undefined); - expect(await runSlotTurn(slot, entry, undefined)).toBe("ran"); + const result = await runSlotTurn(slot, entry, undefined); + expect(result).toEqual({ kind: "ran", outcome: expect.objectContaining({ lifecycle: "success", work: "completed", cancelledBeforeStart: false }) }); expect(requests).toEqual([expect.objectContaining({ prompt: "hi", sessionId: "session-1", turnId: "turn-1", applicationAuthority: "server" })]); expect(work.settled).toEqual([["completed", { sessionId: "session-1" }]]); expect(entry.released).toBe(1); expect(slot.turn.retryRequest).toMatchObject({ type: "chat_message", text: "hi", requestId: "req-1" }); - expect(sent.at(-1)).toMatchObject({ type: "status", status: "idle", sessionId: "session-1" }); + expect(sent.some(frame => frame.type === "status" && frame.status === "idle")).toBe(false); }); });