Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
746dd65
CONTRACT: fix host inference refusals reported as subscription auth f…
schlessera Nov 15, 2026
4197b1a
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
a6e2fe8
docs: align citations moved by relay refusal handling
schlessera Nov 15, 2026
d54969c
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
f52664e
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
104112a
CONTRACT: recognize bare retained inference refusal text
schlessera Nov 15, 2026
741a4f2
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
931756a
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
42db918
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
abe5edf
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
f090d26
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
3931386
CONTRACT: omit ambiguous inference refusal causes
schlessera Nov 15, 2026
31f205b
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
ddc6bf8
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
41bccd4
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
2e02847
Merge remote-tracking branch 'origin/main' into fix/3787-inference-re…
schlessera Nov 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/host-inference-refusal.md
Original file line number Diff line number Diff line change
@@ -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 unambiguous host admission causes in the live failure message.
2 changes: 1 addition & 1 deletion api-report/ui-sdk.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8042,7 +8042,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;
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/answer-delivery.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/async-collaboration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions docs/decisions/claude-code-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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: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
Expand Down
4 changes: 2 additions & 2 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -3400,7 +3400,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.
Expand Down Expand Up @@ -3530,7 +3530,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:

Expand Down
2 changes: 1 addition & 1 deletion docs/hosting/agent-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -851,7 +851,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,
Expand Down
4 changes: 2 additions & 2 deletions docs/hosting/paid-cli-provider-qualification.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,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.
Expand Down
11 changes: 9 additions & 2 deletions docs/integration-contract/wire.md
Original file line number Diff line number Diff line change
Expand Up @@ -951,7 +951,13 @@ 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, 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
Linux/qualifying WSL2 route. It creates no backend session or transcript.
Expand Down Expand Up @@ -985,7 +991,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
Expand Down
4 changes: 2 additions & 2 deletions docs/plans/chat-history-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,10 @@ 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:180-213`).
The live/archive roots are resolved by the backend
(`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:31-40`).
(`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:32-41`).
Archive movement and crash recovery must join the same lifecycle fence
(`archiveIdleSessions`, `packages/ui-backend-claude/src/transcript-archive.ts:267-327`).
Delete all owned branches/subagents/copies, not just the displayed branch.
Expand Down
3 changes: 3 additions & 0 deletions packages/ui-backend-claude/src/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand Down
29 changes: 29 additions & 0 deletions packages/ui-backend-claude/src/host-refusal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { FIRST_PARTY_FAILURE_CLASSES, type TurnFailure } from "@schlessera/brain-ui-sdk/protocol";

const DENIAL_DETAILS: Readonly<Record<string, string>> = {
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})` : ""}.` };
}
7 changes: 6 additions & 1 deletion packages/ui-backend-claude/src/stream-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 } : {}),
Expand All @@ -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. */
Expand Down
6 changes: 6 additions & 0 deletions packages/ui-backend-claude/src/turn-inference-relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +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";
/** Distinct causes cannot be associated with one runtime error's identical relay text. */
#refusalReasons = new Set<string | undefined>();
get refusalReason(): string | undefined {
return this.#refusalReasons.size === 1 ? this.#refusalReasons.values().next().value : undefined;
}
routeInputs: Awaited<ReturnType<typeof retainNativeRouteInputs>> | undefined;
#relay: InferenceRelay | undefined;
#link: string | undefined;
Expand Down Expand Up @@ -86,6 +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.#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();
Expand Down
3 changes: 2 additions & 1 deletion packages/ui-backend-claude/src/turn-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,9 @@ async function startTurn(runner: TurnRunnerState, req: StartTurnRequest): Promis
async function runAdmittedTurn(runner: TurnRunnerState, claim: ClaimedTurn): Promise<void> {
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,
Expand All @@ -230,7 +232,6 @@ async function runAdmittedTurn(runner: TurnRunnerState, claim: ClaimedTurn): Pro
const limits = new WorkerLimitReporter(reportActivity);
const ackGrace: { timer?: ReturnType<typeof setTimeout> } = {};
let archiveEnv: Record<string, string | undefined> | 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);

Expand Down
26 changes: 26 additions & 0 deletions packages/ui-backend-claude/tests/api-failure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: "<synthetic>", 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<string, unknown>) =>
({ type: "result", session_id: SESSION, duration_ms: 1, num_turns: 1, modelUsage: {}, ...fields }) as unknown as SDKMessage;
Expand Down
Loading
Loading