From 746dd65e698c493b61a66e3d1e27bdbf2c931e89 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 14:30:22 +0000 Subject: [PATCH 1/4] CONTRACT: fix host inference refusals reported as subscription auth failures --- .changeset/host-inference-refusal.md | 6 ++++ api-report/ui-sdk.txt | 2 +- docs/decisions/async-collaboration.md | 2 +- docs/decisions/claude-code-runtime.md | 2 +- docs/decisions/governed-writable-workers.md | 4 +-- docs/hosting/agent-workers.md | 2 +- .../paid-cli-provider-qualification.md | 4 +-- docs/integration-contract/wire.md | 10 ++++-- packages/ui-backend-claude/src/history.ts | 3 ++ .../ui-backend-claude/src/host-refusal.ts | 29 +++++++++++++++ .../ui-backend-claude/src/stream-adapter.ts | 7 +++- .../src/turn-inference-relay.ts | 3 ++ packages/ui-backend-claude/src/turn-runner.ts | 3 +- .../tests/api-failure.test.ts | 26 ++++++++++++++ .../tests/history-api-failure.test.ts | 9 ++++- .../tests/turn-units.test.ts | 34 ++++++++++++++++++ packages/ui-sdk/src/protocol.ts | 5 +-- packages/ui-sdk/src/server/egress-proxy.ts | 2 +- packages/ui-sdk/src/server/inference-relay.ts | 10 +++--- .../ui-sdk/tests/inference-egress.test.ts | 22 +++++++++++- .../ui-server/tests/runtime-record.test.ts | 36 +++++++++++++++++-- 21 files changed, 198 insertions(+), 23 deletions(-) create mode 100644 .changeset/host-inference-refusal.md create mode 100644 packages/ui-backend-claude/src/host-refusal.ts diff --git a/.changeset/host-inference-refusal.md b/.changeset/host-inference-refusal.md new file mode 100644 index 0000000000..d60b4d648d --- /dev/null +++ b/.changeset/host-inference-refusal.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-backend-claude": minor +--- + +Report host inference relay refusals as `host_refused` in live turns and replay, without subscription re-login instructions or authentication failure status. Include known host admission causes in the live failure message. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index e5c0f781ed..24078334a1 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -7820,7 +7820,7 @@ signatures (every public export and the types it is made of) entries: FileEntry[]; } FirstPartyFailureClass (packages/ui-sdk/src/protocol.ts) - type FirstPartyFailureClass = "authentication_failed" | "oauth_org_not_allowed" | "account_on_hold" | "verification_required" | "billing_error" | "subscription_required" | "auth_failure" | "rate_limit" | "overloaded" | "server_error" | "invalid_request" | "model_not_found" | "max_output_tokens" | "cloud_credential_error" | "worker_host_unsupported" | "session_too_large" | "worker_resource_limit" | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "safety_recording_unavailable" | "safety_recording_paused" | "safety_recording_chat_full" | "safety_recording_brain_full" | "unknown"; + type FirstPartyFailureClass = "authentication_failed" | "oauth_org_not_allowed" | "account_on_hold" | "verification_required" | "billing_error" | "subscription_required" | "host_refused" | "auth_failure" | "rate_limit" | "overloaded" | "server_error" | "invalid_request" | "model_not_found" | "max_output_tokens" | "cloud_credential_error" | "worker_host_unsupported" | "session_too_large" | "worker_resource_limit" | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "safety_recording_unavailable" | "safety_recording_paused" | "safety_recording_chat_full" | "safety_recording_brain_full" | "unknown"; FirstRequestCacheUsage (packages/ui-sdk/src/protocol.ts) export interface FirstRequestCacheUsage { inputTokens: number | null; diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index 549128de6f..45a7b4e456 100644 --- a/docs/decisions/async-collaboration.md +++ b/docs/decisions/async-collaboration.md @@ -306,7 +306,7 @@ costs or a provider-enforced spend ceiling. Narrower per-request relay accounting is not selected for v1. The current observer reports method, path, outcome and status, with no trusted token or cost bound (`InferenceRelayEvent`, -`packages/ui-sdk/src/server/inference-relay.ts:47-53`). Completed-response +`packages/ui-sdk/src/server/inference-relay.ts:47-55`). Completed-response snapshots cannot bound a pre-header continuation's input, output, cache usage or hidden requests. A smaller fraction, historical average, guessed zero or clipping below known spend would invent evidence. Revisit narrower accounting diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 8c25b6f8dc..070e9f9dc7 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -1318,7 +1318,7 @@ profile's `baseUrl` from `BRAIN_UI_CLAUDE_PROFILES`, else the server's `ANTHROPIC_BASE_URL`, else first-party inference. The relay forwards to that route, keeping its base path. Before the prompt is sent, the runner refuses a route whose origin is neither first-party nor listed -(`qualify(settings`, `packages/ui-backend-claude/src/turn-inference-relay.ts:108-133`). +(`qualify(settings`, `packages/ui-backend-claude/src/turn-inference-relay.ts:112-137`). Each dispatch checks the same list again before the credential is read. Native settings may repeat the server's route, compared as a canonical origin and base path, but never replace it. A discovered profile never carries a route or a diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 9c25a99843..b463bcfdcb 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -3279,7 +3279,7 @@ recipient only when it can record what the turn is shown (`const recipient = opt view is not on managed native storage, where the relay runs, is refused before this (#3314). The turn's relay is then held to that origin: it refuses to start toward any other -(`if (options.recipientOrigin`, `packages/ui-sdk/src/server/inference-relay.ts:79-81`), +(`if (options.recipientOrigin`, `packages/ui-sdk/src/server/inference-relay.ts:81-83`), pi refuses a changed endpoint before its credential is read, and a turn that has a recipient but no relay refuses to start. A model change inside a turn cannot leave the one relay socket the worker has. @@ -3409,7 +3409,7 @@ group, with setgid directories. Setgid sets only the group, though, and the kit creates its per-turn objects with private modes today. Runtime state (`export function createClaudeWorkerState`, `packages/ui-backend-claude/src/worker-state.ts:136`) and the inference relay -(`export function startInferenceRelay`, `packages/ui-sdk/src/server/inference-relay.ts:71`) +(`export function startInferenceRelay`, `packages/ui-sdk/src/server/inference-relay.ts:73`) both use `0700` directories and `0600` files or sockets. With a helper configured, the kit therefore creates these with explicit group ownership and group modes: diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 1495b92420..8214b8d7b3 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -833,7 +833,7 @@ the host root, `/home`, `/etc`, `/run`, `/var`, `/tmp` or an ancestor of the brain. No host home, stored login or `/run` socket is visible. The worker's only route out is the server-owned inference relay -(`export function startInferenceRelay(`, `packages/ui-sdk/src/server/inference-relay.ts:71-253`). +(`export function startInferenceRelay(`, `packages/ui-sdk/src/server/inference-relay.ts:73-261`). It is a Unix socket in a private `0700` directory, bind-mounted read-only at `/run/brain-inference`. It forwards only `POST` to the provider's inference routes, such as `/v1/messages` and `/v1/messages/count_tokens` for Anthropic, diff --git a/docs/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index 37c0836727..22860be026 100644 --- a/docs/hosting/paid-cli-provider-qualification.md +++ b/docs/hosting/paid-cli-provider-qualification.md @@ -91,9 +91,9 @@ providers refused rather than treated as first-party evidence. The current inference relay already strips inbound credentials, selects its fixed origin/routes and invokes host credentials for each dispatch -(`startInferenceRelay`, `packages/ui-sdk/src/server/inference-relay.ts:71-253`). +(`startInferenceRelay`, `packages/ui-sdk/src/server/inference-relay.ts:73-261`). Its event has outcome/status, not provider usage -(`InferenceRelayEvent`, `packages/ui-sdk/src/server/inference-relay.ts:47-53`). +(`InferenceRelayEvent`, `packages/ui-sdk/src/server/inference-relay.ts:47-55`). For these CLI consumers, the host would supply a non-secret transport projection and keep real keys outside the worker. A fixture key reaching a loopback upstream is not proof of that credential-free projection. diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 962702142a..fb18b5b748 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -946,7 +946,12 @@ SessionHistoryMessage.failure?: TurnFailure // on the assistant message the fa - **`errorClass`** uses the Claude Agent SDK's class names (`authentication_failed`, `rate_limit`, `overloaded`, `invalid_request`, `model_not_found`, `server_error`, …), plus `subscription_required` for a - turn the backend refused before sending it. `worker_host_unsupported` means + turn the backend refused before sending it. `host_refused` (additive in + 0.45.0, #3787) means the host inference relay refused the model request, + including cancelled admission (HTTP 499). It carries no `authAction` and + does not update subscription authentication status. Its message names a + known host denial cause; replay with only relay text claims no finer cause. + `worker_host_unsupported` means the host refused before runtime initialization because its required worker boundary probe failed; the message names the requirement and the verified Linux/qualifying WSL2 route. It creates no backend session or transcript. @@ -980,7 +985,8 @@ SessionHistoryMessage.failure?: TurnFailure // on the assistant message the fa It is free-form, so a new value is not a breaking change. `unknown` means the backend could not tell, and is never a guess. **`status`** is the provider's HTTP status. Absent means - unknown, not "no status". **`message`** is the runtime's own text. + unknown, not "no status". **`message`** is the runtime's own text, except `host_refused`, + which uses the host's explanation of the relay refusal. - **First-party diagnostic classes (#1619).** `FIRST_PARTY_FAILURE_CLASSES`, exported from `@schlessera/brain-ui-sdk` and `/protocol`, is an immutable registry whose keys and values are the first-party class names. Emitters diff --git a/packages/ui-backend-claude/src/history.ts b/packages/ui-backend-claude/src/history.ts index 515a57f3dc..dc9d876a8d 100644 --- a/packages/ui-backend-claude/src/history.ts +++ b/packages/ui-backend-claude/src/history.ts @@ -17,6 +17,7 @@ import { subscriptionAuthAction } from "@schlessera/brain-ui-sdk"; import type { SessionRetirement } from "@schlessera/brain-ui-sdk/internal"; import { listArchivedSessions, restoreArchivedSession, transcriptPaths } from "./transcript-archive.js"; import { isSessionId } from "./worker-state.js"; +import { hostRefusal } from "./host-refusal.js"; import { usageLimitText } from "./usage-limit.js"; import { statusFromText } from "./stream-adapter.js"; import { taskNotificationMessages } from "./task-notification-history.js"; @@ -367,6 +368,8 @@ export function apiErrorFailure(message: unknown, content: unknown[]): TurnFailu if (ABORTED_TEXT.test(text)) return null; const limitText = usageLimitText(message, content); if (limitText) return { errorClass: FIRST_PARTY_FAILURE_CLASSES.rate_limit, message: limitText }; + const refused = hostRefusal(text, statusFromText(text)); + if (refused) return refused; const known = API_ERROR_TEXTS.find(({ pattern }) => pattern.test(text)); if (!known) return null; const status = statusFromText(text); diff --git a/packages/ui-backend-claude/src/host-refusal.ts b/packages/ui-backend-claude/src/host-refusal.ts new file mode 100644 index 0000000000..ef811ca460 --- /dev/null +++ b/packages/ui-backend-claude/src/host-refusal.ts @@ -0,0 +1,29 @@ +import { FIRST_PARTY_FAILURE_CLASSES, type TurnFailure } from "@schlessera/brain-ui-sdk/protocol"; + +const DENIAL_DETAILS: Readonly> = { + safety_changed: "safety changed during admission", + max_bytes_per_turn: "the turn's network byte limit was reached", + call_not_admitted: "the host did not admit this connection", + destination_not_allowed: "the destination is not allowed by the host's network policy", + destination_port: "the destination port is not allowed", + unresolved_destination: "the destination could not be resolved", + private_destination: "the destination is a private address", + metadata_destination: "the destination is a metadata address", + outward_not_approved: "the outward connection was not approved", + turn_cancelled: "the turn was cancelled", + client_disconnected: "the request was cancelled", + inference_admission_refused: "network admission was refused", + inference_request_too_large: "the inference request exceeded the host's size limit", +}; + +/** Relay-owned signals, read only from a runtime error, never model prose. */ +export function hostRefusal(text: string, status: number | undefined, reason?: string): TurnFailure | null { + const fixed = /^(?:Failed to authenticate\. )?API Error: [1-5]\d\d (?:Inference network admission refused|Inference request refused|Inference request cancelled|Inference egress limit exceeded)\.?$/; + const body = /"type"\s*:\s*"brain_inference_refused"/.test(text); + if (!fixed.test(text) && !body) return null; + // Only first-party codes become prose; arbitrary host data is not disclosed. + const detail = reason && Object.hasOwn(DENIAL_DETAILS, reason) ? DENIAL_DETAILS[reason] : undefined; + return { errorClass: FIRST_PARTY_FAILURE_CLASSES.host_refused, + ...(status !== undefined ? { status } : {}), + message: `The host refused this model request${detail ? ` (${detail})` : ""}.` }; +} diff --git a/packages/ui-backend-claude/src/stream-adapter.ts b/packages/ui-backend-claude/src/stream-adapter.ts index 2bbe0416fd..478fe1966d 100644 --- a/packages/ui-backend-claude/src/stream-adapter.ts +++ b/packages/ui-backend-claude/src/stream-adapter.ts @@ -9,6 +9,7 @@ import type { } from "@schlessera/brain-ui-sdk/server"; import { subscriptionAuthAction } from "@schlessera/brain-ui-sdk/server"; import { usageLimitText } from "./usage-limit.js"; +import { hostRefusal } from "./host-refusal.js"; import { AUTH_ERROR_CLASSES } from "./subscription.js"; import { usageFromResult, CompletedResponseUsage } from "./usage.js"; @@ -148,7 +149,7 @@ export class StreamAdapter { .map((block) => (block.type === "text" ? block.text : "")) .join("") .trim(); - if (AUTH_ERROR_CLASSES.has(msg.error)) { + if (!hostRefusal(text, statusFromText(text)) && AUTH_ERROR_CLASSES.has(msg.error)) { this.report({ kind: "auth_failure", errorClass: msg.error, ...(text ? { message: text } : {}) }); } // The runtime's API-error message: its text arrives here and never @@ -410,6 +411,8 @@ export class StreamAdapter { } private failure(errorClass: string, message: string, status: number | undefined): TurnFailure { + const refused = hostRefusal(message, status, this.options.hostRefusalReason?.()); + if (refused) return refused; return { errorClass, ...(status !== undefined ? { status } : {}), @@ -424,6 +427,8 @@ export class StreamAdapter { } export interface StreamAdapterOptions { + /** Host-only denial cause; never added to provider history. */ + hostRefusalReason?: () => string | undefined; /** A fresh nonpersistent helper has no resumed history in its terminal totals. */ freshRuntimeUsage?: boolean; /** Restricted autonomous accounting; no additional client frames. */ diff --git a/packages/ui-backend-claude/src/turn-inference-relay.ts b/packages/ui-backend-claude/src/turn-inference-relay.ts index 9a77a9d223..4576a2181a 100644 --- a/packages/ui-backend-claude/src/turn-inference-relay.ts +++ b/packages/ui-backend-claude/src/turn-inference-relay.ts @@ -48,6 +48,8 @@ export class TurnInferenceRelay { readonly selectedUpstream: string; /** The worker's base URL: the relay's socket, at the selected route's path. */ baseUrl = "http://localhost"; + /** Latest relay denial, from this turn only. */ + refusalReason: string | undefined; routeInputs: Awaited> | undefined; #relay: InferenceRelay | undefined; #link: string | undefined; @@ -86,6 +88,7 @@ export class TurnInferenceRelay { if (!egress) return; this.#relay = startInferenceRelay({ upstream: this.selectedUpstream, routes: ANTHROPIC_INFERENCE_ROUTES, egress, ...(this.#recipient ? { recipientOrigin: this.#recipient.origin } : {}), + observe: event => { if (event.outcome === "refused") this.refusalReason = event.denialReason; }, credentials: async (signal, target) => { if (!this.#authorized) throw new Error("Native inference has not passed its prompt gate"); this.routeInputs?.assertUnchanged(); diff --git a/packages/ui-backend-claude/src/turn-runner.ts b/packages/ui-backend-claude/src/turn-runner.ts index e45fd53a2e..402ea0e619 100644 --- a/packages/ui-backend-claude/src/turn-runner.ts +++ b/packages/ui-backend-claude/src/turn-runner.ts @@ -216,7 +216,9 @@ async function startTurn(runner: TurnRunnerState, req: StartTurnRequest): Promis async function runAdmittedTurn(runner: TurnRunnerState, claim: ClaimedTurn): Promise { const { options } = runner; const { req, profile, abortController, input } = claim; + let relay: TurnInferenceRelay | undefined; const adapter = new StreamAdapter(req.bridge.activity, { + hostRefusalReason: () => relay?.refusalReason, subscriptionAuth: profile.billing !== "api", autonomousUsage: req.autonomous?.containment === "restricted", freshRuntimeUsage: req.autonomous?.persistence === "none" && req.sessionId === undefined, @@ -230,7 +232,6 @@ async function runAdmittedTurn(runner: TurnRunnerState, claim: ClaimedTurn): Pro const limits = new WorkerLimitReporter(reportActivity); const ackGrace: { timer?: ReturnType } = {}; let archiveEnv: Record | undefined; - let relay: TurnInferenceRelay | undefined; const phase = req.sessionId === undefined ? "start before prompt release" : "resume before prompt release"; const runtimeRequirements = claudeRuntimeRequirements(options.backend.versionRequirements, phase, profile.model); diff --git a/packages/ui-backend-claude/tests/api-failure.test.ts b/packages/ui-backend-claude/tests/api-failure.test.ts index 6b25741342..41dfeedff5 100644 --- a/packages/ui-backend-claude/tests/api-failure.test.ts +++ b/packages/ui-backend-claude/tests/api-failure.test.ts @@ -290,6 +290,32 @@ describe("a failed model call ends the turn as a failure", () => { }); }); +describe("host inference refusals", () => { + test("a known host cause is included, and an unknown cause is not invented", () => { + for (const [reason, detail] of [["safety_changed", " (safety changed during admission)"], ["unrecognized", ""]]) { + const adapter = new StreamAdapter(undefined, { subscriptionAuth: true, hostRefusalReason: () => reason }); + adapter.adapt({ ...(unsupportedModelError as object), error: "authentication_failed", message: { + content: [{ type: "text", text: 'API Error: 403 {"type":"error","error":{"type":"brain_inference_refused","message":"Inference request refused"}}' }], + } } as SDKMessage); + expect(adapter.pendingFailure()).toEqual({ errorClass: "host_refused", status: 403, + message: `The host refused this model request${detail}.` }); + } + }); + + test.each([403, 499])("relay %i overrides the runtime auth class without auth activity", status => { + const activity: unknown[] = []; + const adapter = new StreamAdapter(event => activity.push(event), { subscriptionAuth: true }); + adapter.adapt({ ...(unsupportedModelError as object), error: "authentication_failed", + message: { model: "", content: [{ type: "text", text: `Failed to authenticate. API Error: ${status} Inference network admission refused` }] }, + } as SDKMessage); + expect(adapter.pendingFailure()).toEqual({ errorClass: "host_refused", status, + message: "The host refused this model request." }); + expect(activity).toEqual([]); + const result = terminal(adapter.adapt({ ...answered.at(-1)!, is_error: true } as SDKMessage)); + expect(result.failure).toEqual(adapter.pendingFailure()!); + }); +}); + describe("StreamAdapter failure detection", () => { const result = (fields: Record) => ({ type: "result", session_id: SESSION, duration_ms: 1, num_turns: 1, modelUsage: {}, ...fields }) as unknown as SDKMessage; diff --git a/packages/ui-backend-claude/tests/history-api-failure.test.ts b/packages/ui-backend-claude/tests/history-api-failure.test.ts index 93387df4d9..df96e44490 100644 --- a/packages/ui-backend-claude/tests/history-api-failure.test.ts +++ b/packages/ui-backend-claude/tests/history-api-failure.test.ts @@ -24,6 +24,13 @@ const read = (entries: SessionMessage[]) => buildSessionHistory(SESSION, (async () => entries) as unknown as typeof getSessionMessages, import.meta.dir); describe("an API error replays as the turn's failure", () => { + test.each([403, 499])("a relay %i replays as host refusal without a login instruction", async status => { + const [, answer] = await read([userTurn("Continue"), syntheticEntry( + `${status === 403 ? "Failed to authenticate. " : ""}API Error: ${status} Inference network admission refused`)]); + expect(answer!.failure).toEqual({ errorClass: "host_refused", status, + message: "The host refused this model request." }); + expect(answer!.content).toBe(""); + }); test("the unsupported-model turn: an empty answer that failed, with the status its text states", async () => { const history = await read([userTurn("Test"), syntheticEntry(UNSUPPORTED_MODEL_TEXT)]); expect(history).toEqual([ @@ -143,7 +150,7 @@ describe("an API error replays as the turn's failure", () => { test("a 499 cancelled request stays a classified failure, not a notice", async () => { const text = "API Error: 499 Inference request cancelled"; const [, message] = await read([userTurn("hi"), syntheticEntry(text)]); - expect(message!.failure).toEqual({ errorClass: "unknown", status: 499, message: text }); + expect(message!.failure).toEqual({ errorClass: "host_refused", status: 499, message: "The host refused this model request." }); expect(message!.runtimeNotice).toBeUndefined(); expect(message!.content).toBe(""); }); diff --git a/packages/ui-backend-claude/tests/turn-units.test.ts b/packages/ui-backend-claude/tests/turn-units.test.ts index 01ef5c18f3..2e5d2e8ab4 100644 --- a/packages/ui-backend-claude/tests/turn-units.test.ts +++ b/packages/ui-backend-claude/tests/turn-units.test.ts @@ -9,6 +9,8 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { request } from "node:http"; +import { startEgressProxy } from "../../ui-sdk/src/server/egress-proxy"; import type { Query, SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import type { BackendActivityEvent, ServerMessage, StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; import { WorkerHostError, type WorkerLimitReport } from "@schlessera/brain-ui-sdk/internal"; @@ -199,6 +201,38 @@ describe("turn reporting", () => { }); describe("TurnInferenceRelay", () => { + test("the concrete host safety denial reaches the live failure without changing the relay body", async () => { + let epoch = "initial"; + const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 10000, + admissionSafety: { read: () => ({ evidenceRevision: "1", trustRevision: "1", authorityEpoch: epoch, + scope: "turn", policyHash: null, restricted: false, recordingAvailable: true, authorityCurrent: true }), + subscribe: () => () => {} }, + admitted: () => { epoch = "changed"; }, observe: () => {} }); + const relay = new TurnInferenceRelay({ req: { workerSandbox: { egress } } as unknown as StartTurnRequest, + profile: DEFAULT_PROFILES[0]!, turnEnvironment: { CLAUDE_CONFIG_DIR: tempDir() }, brainPath: tempDir() }); + try { + relay.start(); + const response = await new Promise<{ status: number; body: string }>((resolve, reject) => { + const req = request({ socketPath: join(egress.dir, "inference.sock"), path: "/v1/messages", method: "POST" }, res => { + let body = ""; + res.on("data", chunk => { body += chunk; }); + res.on("end", () => resolve({ status: res.statusCode!, body })); + res.on("error", reject); + }); + req.on("error", reject); req.end("{}"); + }); + expect(response.status).toBe(403); + expect(JSON.parse(response.body)).toEqual({ type: "error", error: { type: "brain_inference_refused", + message: "Inference network admission refused" } }); + expect(relay.refusalReason).toBe("safety_changed"); + const adapter = new StreamAdapter(undefined, { subscriptionAuth: true, hostRefusalReason: () => relay.refusalReason }); + adapter.adapt({ type: "assistant", error: "authentication_failed", message: { content: [{ type: "text", + text: `Failed to authenticate. API Error: ${response.status} Inference network admission refused` }] } } as SDKMessage); + expect(adapter.pendingFailure()).toEqual({ errorClass: "host_refused", status: 403, + message: "The host refused this model request (safety changed during admission)." }); + } finally { relay.stop(); relay.unlink(); egress.stop(); } + }); + function relayFor(env: Record = {}) { const config = tempDir(); const req = { workerSandbox: { egress: { dir: tempDir() } } } as unknown as StartTurnRequest; diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 6a81ec031d..3999b8683d 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -1368,7 +1368,7 @@ export interface TurnFailure { resetsAt?: number; /** Host budget scope; only a conversation block offers the reviewed handoff. */ budgetScope?: "turn" | "session" | "day"; - /** The failure as the runtime worded it. */ + /** Runtime failure text, or the host's explanation of its own refusal. */ message: string; /** * For a Claude subscription's auth failure: what the operator does about it @@ -1381,7 +1381,7 @@ export interface TurnFailure { type FirstPartyFailureClass = | "authentication_failed" | "oauth_org_not_allowed" | "account_on_hold" | "verification_required" | "billing_error" | "subscription_required" - | "auth_failure" | "rate_limit" | "overloaded" | "server_error" + | "host_refused" | "auth_failure" | "rate_limit" | "overloaded" | "server_error" | "invalid_request" | "model_not_found" | "max_output_tokens" | "cloud_credential_error" | "worker_host_unsupported" | "session_too_large" | "worker_resource_limit" | "worker_state_busy" | "worker_state_exceeded" | "worker_state_save_refused" | "journal_capacity" | "journal_unavailable" | "budget_exceeded" | "budget_unavailable" | "input_safety_unavailable" | "safety_recording_unavailable" | "safety_recording_paused" | "safety_recording_chat_full" | "safety_recording_brain_full" | "unknown"; @@ -1399,6 +1399,7 @@ export const FIRST_PARTY_FAILURE_CLASSES: Readonly<{ [Class in FirstPartyFailure verification_required: "verification_required", billing_error: "billing_error", subscription_required: "subscription_required", + host_refused: "host_refused", auth_failure: "auth_failure", rate_limit: "rate_limit", overloaded: "overloaded", diff --git a/packages/ui-sdk/src/server/egress-proxy.ts b/packages/ui-sdk/src/server/egress-proxy.ts index 02c2830cef..19bc72f529 100644 --- a/packages/ui-sdk/src/server/egress-proxy.ts +++ b/packages/ui-sdk/src/server/egress-proxy.ts @@ -458,7 +458,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { const abort = () => op.finish("cancelled", "client_disconnected"); signal.addEventListener("abort", abort, { once: true }); if (signal.aborted) abort(); - return { charge: op.charge, signal: op.signal, outcome: op.outcome, refusal: op.refusal, + return { charge: op.charge, signal: op.signal, outcome: op.outcome, refusal: op.refusal, reason: op.reason, admit: async () => !op.signal.aborted && await op.admit() && op.commit(), /** The concrete relay calls this again after its own final async waits. */ commit: op.commit, diff --git a/packages/ui-sdk/src/server/inference-relay.ts b/packages/ui-sdk/src/server/inference-relay.ts index 3215f53a5e..d65bc465ca 100644 --- a/packages/ui-sdk/src/server/inference-relay.ts +++ b/packages/ui-sdk/src/server/inference-relay.ts @@ -50,6 +50,8 @@ export interface InferenceRelayEvent { outcome: "forwarded" | "refused"; status: number; reason?: string; + /** Host-only admission cause; the HTTP body remains unchanged. */ + denialReason?: string; } export interface InferenceRelay { @@ -92,8 +94,8 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe const separateIdentity = Boolean(workerIdentityHelper()); chmodSync(dir, separateIdentity ? 0o750 : 0o700); const socketPath = join(dir, "relay.sock"); - const refuse = (method: string, path: string, status: number, reason: string): Response => { - options.observe?.({ method, path, outcome: "refused", status, reason }); + const refuse = (method: string, path: string, status: number, reason: string, denialReason?: string): Response => { + options.observe?.({ method, path, outcome: "refused", status, reason, ...(denialReason ? { denialReason } : {}) }); return Response.json({ type: "error", error: { type: "brain_inference_refused", message: reason } }, { status }); }; let server: ReturnType; @@ -118,12 +120,12 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe const signal = operation ? AbortSignal.any([request.signal, operation.signal]) : request.signal; const denied = (reason: string, status = 403): Response => { operation?.finish("denied", reason); - return refuse(request.method, path, status, reason === "max_bytes_per_turn" ? "Inference egress limit exceeded" : "Inference request refused"); + return refuse(request.method, path, status, reason === "max_bytes_per_turn" ? "Inference egress limit exceeded" : "Inference request refused", operation?.reason?.() ?? reason); }; if (operation && !await operation.admit()) { const cancelled = request.signal.aborted || operation.outcome() === "cancelled"; operation.finish(cancelled ? "cancelled" : "denied", "inference_admission_refused"); - return refuse(request.method, path, cancelled ? 499 : 403, "Inference network admission refused"); + return refuse(request.method, path, cancelled ? 499 : 403, "Inference network admission refused", operation.reason?.()); } const declared = Number(request.headers.get("content-length") ?? "0"); if (declared > MAX_INFERENCE_REQUEST_BYTES) return denied("inference_request_too_large", 413); diff --git a/packages/ui-sdk/tests/inference-egress.test.ts b/packages/ui-sdk/tests/inference-egress.test.ts index 86dd7060e0..4b0e52ce92 100644 --- a/packages/ui-sdk/tests/inference-egress.test.ts +++ b/packages/ui-sdk/tests/inference-egress.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test"; import { request } from "node:http"; -import { startEgressProxy, type EgressRecord } from "../src/server/egress-proxy"; +import { startEgressProxy, EgressAdmissionRefused, type EgressRecord } from "../src/server/egress-proxy"; import { startInferenceRelay } from "../src/server/inference-relay"; function deferred() { let resolve!: () => void; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; } @@ -153,3 +153,23 @@ test("parallel inference responses share the turn ceiling rather than independen expect(f.proxy.usedBytes()).toBe(f.records.reduce((sum, record) => sum + record.bytes, 0)); } finally { release.resolve(); for (const client of clients) client.destroy(); f.stop(); } }); + + +test("a relay denial keeps its host admission reason out of the unchanged wire body", async () => { + const records: EgressRecord[] = []; + const events: import("../src/server/inference-relay").InferenceRelayEvent[] = []; + const proxy = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 10000, + admitted: () => { throw new EgressAdmissionRefused(); }, observe: event => records.push(event) }); + const relay = startInferenceRelay({ upstream: "https://api.anthropic.com", routes: ["/v1/messages"], + egress: proxy, credentials: {}, observe: event => events.push(event) }); + try { + const response = await send(relay.socketPath, "/v1/messages"); + expect(response.status).toBe(403); + expect(JSON.parse(response.body)).toEqual({ type: "error", error: { + type: "brain_inference_refused", message: "Inference network admission refused" } }); + expect(records).toHaveLength(1); + expect(records[0]!.reason).toBe("call_not_admitted"); + expect(events).toEqual([{ method: "POST", path: "/v1/messages", outcome: "refused", status: 403, + reason: "Inference network admission refused", denialReason: "call_not_admitted" }]); + } finally { relay.stop(); proxy.stop(); } +}); diff --git a/packages/ui-server/tests/runtime-record.test.ts b/packages/ui-server/tests/runtime-record.test.ts index ebeb476a1b..566b7b0734 100644 --- a/packages/ui-server/tests/runtime-record.test.ts +++ b/packages/ui-server/tests/runtime-record.test.ts @@ -15,12 +15,12 @@ import { createRuntimeStatus } from "../src/activity/runtime-status"; import { createActivityStore, rowToRunRollup } from "../src/activity/store"; import { createUiDb } from "../src/db/client"; -function scripted(init: Record, account: AccountInfo, more: unknown[] = []): typeof query { +function scripted(init: Record, account: AccountInfo, more: unknown[] = [], isError = false): typeof query { return (() => { const stream = (async function* () { yield { type: "system", subtype: "init", session_id: "sess-1", ...init }; yield* more; - yield { type: "result", subtype: "success", session_id: "sess-1", total_cost_usd: 0, duration_ms: 1, num_turns: 1 }; + yield { type: "result", subtype: "success", is_error: isError, session_id: "sess-1", total_cost_usd: 0, duration_ms: 1, num_turns: 1 }; })(); return Object.assign(stream, { initializationResult: async () => ({ account }) }); }) as unknown as typeof query; @@ -174,3 +174,35 @@ describe("the run record", () => { expect(String(root.attrs["brain.billing_policy_violation"])).toContain("API credential"); }); }); + + +test("a host refusal leaves subscription auth history and re-login warnings untouched", async () => { + const logs: unknown[] = []; + const runtime = createRuntimeStatus(() => new Date("2026-07-12T12:00:00Z"), + { emit: event => { logs.push(event); }, enabled: () => true }); + runtime.authFailure({ kind: "auth_failure", errorClass: "authentication_failed", message: "Not logged in" }, "earlier"); + const before = runtime.snapshot().lastAuthFailure; + const subscriptionBefore = runtime.subscriptionAuthFailure(); + logs.length = 0; + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db, { writer: "test" }); + const recorder = createTurnRecorder({ store, runtime }, { turnId: "relay-refusal", sessionId: null }); + const frames: import("@schlessera/brain-ui-sdk").ServerMessage[] = []; + const backend = createClaudeBackend({ brainPath: "/brain", log: () => {}, queryFn: scripted({}, + { tokenSource: "CLAUDE_CODE_OAUTH_TOKEN", apiProvider: "firstParty" }, [{ type: "assistant", + error: "authentication_failed", parent_tool_use_id: null, message: { model: "", + content: [{ type: "text", text: "Failed to authenticate. API Error: 403 Inference network admission refused" }] } }], true) }); + await backend.startTurn({ prompt: "Continue", signal: new AbortController().signal, bridge: { + emit: frame => { frames.push(frame); recorder.observeFrame(frame); }, activity: event => recorder.observeActivity(event), + requestPermission: async () => ({ behavior: "allow" }), + } }); + recorder.finish("success"); + expect(runtime.snapshot().lastAuthFailure).toEqual(before); + expect(runtime.subscriptionAuthFailure()).toEqual(subscriptionBefore); + expect(logs).toEqual([]); + const result = frames.find(frame => frame.type === "result"); + expect(result?.type === "result" && result.failure?.errorClass).toBe("host_refused"); + expect(store.getSpan("relay-refusal:turn")!.outcome).toBe("error"); + } finally { db.close(); } +}); From a6e2fe8d09f729183f4759e3072221bbf312429a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 14:52:03 +0000 Subject: [PATCH 2/4] docs: align citations moved by relay refusal handling --- docs/decisions/answer-delivery.md | 2 +- docs/decisions/claude-code-runtime.md | 4 ++-- docs/plans/chat-history-deletion.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/decisions/answer-delivery.md b/docs/decisions/answer-delivery.md index b6dd28dae0..2c1999331f 100644 --- a/docs/decisions/answer-delivery.md +++ b/docs/decisions/answer-delivery.md @@ -256,7 +256,7 @@ whose turn was interrupted, it writes a reply of its own under its aborted.` for an aborted request. These replayed as the agent's words. They now replay as `SessionHistoryMessage.runtimeNotice` on the message they ended, after any partial answer (`export function runtimeNotice`, -`packages/ui-backend-claude/src/history.ts:339-350`). Recognition needs +`packages/ui-backend-claude/src/history.ts:340-351`). Recognition needs both the runtime's provenance and one of its two constant texts, read from the installed CLI, so the same words from the model or the user stay theirs. Only an aborted request names a cause, and neither notice says who stopped diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 070e9f9dc7..3001804657 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -111,7 +111,7 @@ than recalled: carries `claude_code_version` (`sdk.d.ts:5590`). The Claude backend already receives that message and keeps only a status line from it (`msg.subtype === "init"`, - `packages/ui-backend-claude/src/stream-adapter.ts:289-294`). + `packages/ui-backend-claude/src/stream-adapter.ts:290-295`). So the pair the measurements name — 2.1.280 with SDK 0.3.278 — is one the SDK never ships together. It can only arise when the binary is chosen separately @@ -544,7 +544,7 @@ subscription authenticates. successful turn with no text. That was #191's failure, and an auth failure is one of its cases. Since #575 the adapter reads `is_error` on either subtype (`msg.subtype === "success" && !msg.is_error`, - `packages/ui-backend-claude/src/stream-adapter.ts:247`) and ends the turn on a + `packages/ui-backend-claude/src/stream-adapter.ts:248`) and ends the turn on a `failure` carrying the class, the status and this text. - **`claude auth status` cannot detect it.** It reported `loggedIn: true`, `authMethod: "oauth_token"` for a bogus token, so it checks for presence, not diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index b320a19501..22bca3f5dd 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -166,7 +166,7 @@ must be tested through their installed runtime, not inferred from directory name - **Native Claude history.** Live JSONL, per-session subordinate files, titles, archive manifests/index/staged or conflict copies can contain readable text. History reads can restore archived files before reading the SDK transcript - (`createHistory`, `packages/ui-backend-claude/src/history.ts:45-103`; + (`createHistory`, `packages/ui-backend-claude/src/history.ts:46-104`; `restoreArchivedSession`, `packages/ui-backend-claude/src/transcript-archive.ts:179-207`). The live/archive roots are resolved by the backend (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:31-40`). From 104112ae8444ced3eaf99070d1c1857fa6aa6d81 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 15:27:14 +0000 Subject: [PATCH 3/4] CONTRACT: recognize bare retained inference refusal text --- packages/ui-backend-claude/src/host-refusal.ts | 2 +- packages/ui-backend-claude/tests/history-api-failure.test.ts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/ui-backend-claude/src/host-refusal.ts b/packages/ui-backend-claude/src/host-refusal.ts index ef811ca460..119ea573c5 100644 --- a/packages/ui-backend-claude/src/host-refusal.ts +++ b/packages/ui-backend-claude/src/host-refusal.ts @@ -18,7 +18,7 @@ const DENIAL_DETAILS: Readonly> = { /** Relay-owned signals, read only from a runtime error, never model prose. */ export function hostRefusal(text: string, status: number | undefined, reason?: string): TurnFailure | null { - const fixed = /^(?:Failed to authenticate\. )?API Error: [1-5]\d\d (?:Inference network admission refused|Inference request refused|Inference request cancelled|Inference egress limit exceeded)\.?$/; + const fixed = /^(?:(?:Failed to authenticate\. )?API Error: [1-5]\d\d )?(?:Inference network admission refused|Inference request refused|Inference request cancelled|Inference egress limit exceeded)\.?$/; const body = /"type"\s*:\s*"brain_inference_refused"/.test(text); if (!fixed.test(text) && !body) return null; // Only first-party codes become prose; arbitrary host data is not disclosed. diff --git a/packages/ui-backend-claude/tests/history-api-failure.test.ts b/packages/ui-backend-claude/tests/history-api-failure.test.ts index df96e44490..4d03433484 100644 --- a/packages/ui-backend-claude/tests/history-api-failure.test.ts +++ b/packages/ui-backend-claude/tests/history-api-failure.test.ts @@ -24,6 +24,10 @@ const read = (entries: SessionMessage[]) => buildSessionHistory(SESSION, (async () => entries) as unknown as typeof getSessionMessages, import.meta.dir); describe("an API error replays as the turn's failure", () => { + test("bare retained relay refusal text names the host without inventing a status or cause", async () => { + const [, answer] = await read([userTurn("Continue"), syntheticEntry("Inference network admission refused")]); + expect(answer!.failure).toEqual({ errorClass: "host_refused", message: "The host refused this model request." }); + }); test.each([403, 499])("a relay %i replays as host refusal without a login instruction", async status => { const [, answer] = await read([userTurn("Continue"), syntheticEntry( `${status === 403 ? "Failed to authenticate. " : ""}API Error: ${status} Inference network admission refused`)]); From 3931386f4bbfb4ed6c3cfcaba6fa0c542b5db050 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 18:37:53 +0000 Subject: [PATCH 4/4] CONTRACT: omit ambiguous inference refusal causes --- .changeset/host-inference-refusal.md | 2 +- docs/decisions/claude-code-runtime.md | 2 +- docs/integration-contract/wire.md | 3 ++- .../src/turn-inference-relay.ts | 9 ++++++--- .../tests/turn-units.test.ts | 20 ++++++++++++++----- 5 files changed, 25 insertions(+), 11 deletions(-) diff --git a/.changeset/host-inference-refusal.md b/.changeset/host-inference-refusal.md index d60b4d648d..dff22eea0e 100644 --- a/.changeset/host-inference-refusal.md +++ b/.changeset/host-inference-refusal.md @@ -3,4 +3,4 @@ "@schlessera/brain-backend-claude": minor --- -Report host inference relay refusals as `host_refused` in live turns and replay, without subscription re-login instructions or authentication failure status. Include known host admission causes in the live failure message. +Report host inference relay refusals as `host_refused` in live turns and replay, without subscription re-login instructions or authentication failure status. Include unambiguous host admission causes in the live failure message. diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 3001804657..c38aac6573 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -1318,7 +1318,7 @@ profile's `baseUrl` from `BRAIN_UI_CLAUDE_PROFILES`, else the server's `ANTHROPIC_BASE_URL`, else first-party inference. The relay forwards to that route, keeping its base path. Before the prompt is sent, the runner refuses a route whose origin is neither first-party nor listed -(`qualify(settings`, `packages/ui-backend-claude/src/turn-inference-relay.ts:112-137`). +(`qualify(settings`, `packages/ui-backend-claude/src/turn-inference-relay.ts:115-140`). Each dispatch checks the same list again before the credential is read. Native settings may repeat the server's route, compared as a canonical origin and base path, but never replace it. A discovered profile never carries a route or a diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 4ee73a942a..fe9c76f18e 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -955,7 +955,8 @@ SessionHistoryMessage.failure?: TurnFailure // on the assistant message the fa 0.45.0, #3787) means the host inference relay refused the model request, including cancelled admission (HTTP 499). It carries no `authAction` and does not update subscription authentication status. Its message names a - known host denial cause; replay with only relay text claims no finer cause. + known, unambiguous host denial cause; conflicting observed causes and replay + with only relay text claim no finer cause. `worker_host_unsupported` means the host refused before runtime initialization because its required worker boundary probe failed; the message names the requirement and the verified diff --git a/packages/ui-backend-claude/src/turn-inference-relay.ts b/packages/ui-backend-claude/src/turn-inference-relay.ts index 4576a2181a..9978a97ad7 100644 --- a/packages/ui-backend-claude/src/turn-inference-relay.ts +++ b/packages/ui-backend-claude/src/turn-inference-relay.ts @@ -48,8 +48,11 @@ export class TurnInferenceRelay { readonly selectedUpstream: string; /** The worker's base URL: the relay's socket, at the selected route's path. */ baseUrl = "http://localhost"; - /** Latest relay denial, from this turn only. */ - refusalReason: string | undefined; + /** Distinct causes cannot be associated with one runtime error's identical relay text. */ + #refusalReasons = new Set(); + get refusalReason(): string | undefined { + return this.#refusalReasons.size === 1 ? this.#refusalReasons.values().next().value : undefined; + } routeInputs: Awaited> | undefined; #relay: InferenceRelay | undefined; #link: string | undefined; @@ -88,7 +91,7 @@ export class TurnInferenceRelay { if (!egress) return; this.#relay = startInferenceRelay({ upstream: this.selectedUpstream, routes: ANTHROPIC_INFERENCE_ROUTES, egress, ...(this.#recipient ? { recipientOrigin: this.#recipient.origin } : {}), - observe: event => { if (event.outcome === "refused") this.refusalReason = event.denialReason; }, + observe: event => { if (event.outcome === "refused") this.#refusalReasons.add(event.denialReason); }, credentials: async (signal, target) => { if (!this.#authorized) throw new Error("Native inference has not passed its prompt gate"); this.routeInputs?.assertUnchanged(); diff --git a/packages/ui-backend-claude/tests/turn-units.test.ts b/packages/ui-backend-claude/tests/turn-units.test.ts index 2e5d2e8ab4..098bc9fdb3 100644 --- a/packages/ui-backend-claude/tests/turn-units.test.ts +++ b/packages/ui-backend-claude/tests/turn-units.test.ts @@ -10,7 +10,7 @@ import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { request } from "node:http"; -import { startEgressProxy } from "../../ui-sdk/src/server/egress-proxy"; +import { EgressAdmissionRefused, startEgressProxy } from "../../ui-sdk/src/server/egress-proxy"; import type { Query, SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import type { BackendActivityEvent, ServerMessage, StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; import { WorkerHostError, type WorkerLimitReport } from "@schlessera/brain-ui-sdk/internal"; @@ -201,18 +201,18 @@ describe("turn reporting", () => { }); describe("TurnInferenceRelay", () => { - test("the concrete host safety denial reaches the live failure without changing the relay body", async () => { - let epoch = "initial"; + test("the concrete host denial explains only unambiguous causes without changing the relay body", async () => { + let epoch = "initial", explicitRefusal = false; const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 10000, admissionSafety: { read: () => ({ evidenceRevision: "1", trustRevision: "1", authorityEpoch: epoch, scope: "turn", policyHash: null, restricted: false, recordingAvailable: true, authorityCurrent: true }), subscribe: () => () => {} }, - admitted: () => { epoch = "changed"; }, observe: () => {} }); + admitted: () => { if (explicitRefusal) throw new EgressAdmissionRefused(); epoch = "changed"; }, observe: () => {} }); const relay = new TurnInferenceRelay({ req: { workerSandbox: { egress } } as unknown as StartTurnRequest, profile: DEFAULT_PROFILES[0]!, turnEnvironment: { CLAUDE_CONFIG_DIR: tempDir() }, brainPath: tempDir() }); try { relay.start(); - const response = await new Promise<{ status: number; body: string }>((resolve, reject) => { + const send = () => new Promise<{ status: number; body: string }>((resolve, reject) => { const req = request({ socketPath: join(egress.dir, "inference.sock"), path: "/v1/messages", method: "POST" }, res => { let body = ""; res.on("data", chunk => { body += chunk; }); @@ -221,6 +221,7 @@ describe("TurnInferenceRelay", () => { }); req.on("error", reject); req.end("{}"); }); + const response = await send(); expect(response.status).toBe(403); expect(JSON.parse(response.body)).toEqual({ type: "error", error: { type: "brain_inference_refused", message: "Inference network admission refused" } }); @@ -230,6 +231,15 @@ describe("TurnInferenceRelay", () => { text: `Failed to authenticate. API Error: ${response.status} Inference network admission refused` }] } } as SDKMessage); expect(adapter.pendingFailure()).toEqual({ errorClass: "host_refused", status: 403, message: "The host refused this model request (safety changed during admission)." }); + // Another refusal may arrive before the runtime reports the earlier one. + // Identical wire texts cannot associate that earlier error with the latest cause. + explicitRefusal = true; + expect(await send()).toEqual(response); + const delayed = new StreamAdapter(undefined, { subscriptionAuth: true, hostRefusalReason: () => relay.refusalReason }); + delayed.adapt({ type: "assistant", error: "authentication_failed", message: { content: [{ type: "text", + text: `Failed to authenticate. API Error: ${response.status} Inference network admission refused` }] } } as SDKMessage); + expect(delayed.pendingFailure()).toEqual({ errorClass: "host_refused", status: 403, + message: "The host refused this model request." }); } finally { relay.stop(); relay.unlink(); egress.stop(); } });