diff --git a/.changeset/3613-approved-owner-read-resolution.md b/.changeset/3613-approved-owner-read-resolution.md new file mode 100644 index 0000000000..664498f97f --- /dev/null +++ b/.changeset/3613-approved-owner-read-resolution.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Bind immutable read identity evidence to independently published Settings owner approval. Record unavailable qualification for missing or mismatched approval, repository transfer/name reuse and replaced policy roots, and recheck inside the write transaction after waits. Bind publication to the qualified native filesystem and live-brain subvolume UUID, preserving ordinary restart while refusing recreated roots and unqualified hosts. Source trust remains disabled. diff --git a/.changeset/egress-upstream-socket-ownership.md b/.changeset/egress-upstream-socket-ownership.md new file mode 100644 index 0000000000..c9eec440ba --- /dev/null +++ b/.changeset/egress-upstream-socket-ownership.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-sdk": patch +--- + +Give each cleartext HTTP proxy operation its own non-pooled upstream connection so a stale same-origin socket cannot produce a spurious 502. Preserve cancellation, admission fences and byte accounting without retrying requests. diff --git a/.changeset/exact-origin-trust.md b/.changeset/exact-origin-trust.md new file mode 100644 index 0000000000..557d93dae6 --- /dev/null +++ b/.changeset/exact-origin-trust.md @@ -0,0 +1,73 @@ +--- +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-react": minor +--- + +Enforce prospective exact-origin and explicit-tunnel source trust with separate restricted-recipient permission. This pre-1.0 semantic break lets qualified future inputs avoid unresolved triggers while retaining their historical rule, policy hash and revision. Removing a rule fences active admissions and interrupts trusted input streams; repository trust remains unavailable. Existing triggers, independent controls and provider history are preserved. + +Bind pending Network approvals to actual transport identity and record the hash of freshly verified valid policy bytes even when trust rules are unchanged. + +Enforce canonical bracketed IPv6 tunnels, retain last-valid live trust on bounded policy read failures, and prove DNS subdomains cannot inherit parent trust. + +Classify live trust observations consistently: stable invalid or unreadable policy retains last-valid rules with an error, verification races fence, and unchanged chunks use metadata generation checks instead of full policy reads. Refresh rechecks after its durable write. + +Normalize all transport host identities, recheck send authority on every HTTP write/end and tunnel chunk, and retain explicit recipient approvals independently of source trust. + +Validate complete trusted admission variants on the wire, avoid absent-approval and unchanged-stream evidence scans with live change counters, and let independent readers recover after projection publication races. + +Record unmatched source hash and revision from the same live snapshot used for matching, and display IPv6 provenance with bracketed authorities. + +Preserve absolute DNS authorities during resolution/dialing separately from comparison keys, and retain the version-1 detector ID contract while strictly validating admission evidence. + +Cancel queued turn-start trust refreshes with the turn signal, and distinguish budget, safety and unavailable charge results across proxy, inference/provider relays and managed reference acquisition. + +Revalidate only an active input’s admitted source rule across trust revisions, unify source revocation audit/safety results, and reject invalid byte counts before either charge counter changes. + +Retire source-rule instances durably across independent publishers, preserve typed commit/charge failures on managed streams, and classify post-write source revocation identically to notification and send fences. + +Allow HTTP and tunnel completion exactly at the byte ceiling while preserving terminal safety checks and refusing bytes beyond it. + +Separate preparation byte charging from dispatch notification and contacted-host grants, classify initial recording loss as unavailable, and preserve historical IPv6 session grants through canonical host lookup. + +Capture one immutable typed refusal per egress operation before abort, preserve it through every caller and audit record, and fence outward exemptions with the active call-classification generation. + +Guard the concrete proxy lifecycle through pending, admitted, dispatched and terminal states; distinguish exhausted new dispatch from exact-cap stream completion, fence closed wait continuations, and release all per-operation admission keys after terminal evidence. + +Validate destination provenance through the wire schema before durable writes, cancel every upstream cleanup/request with its operation and deadline, and preserve unavailable classifications through repeated inference admission. + +Capture relay error causes before terminal signal cleanup, preserve failed versus cancelled receipts and statuses across every response path, and release caller listeners from every operation termination path. + +Preserve provider cancellation reasons, fence sends after preparation observers, and meter Files cleanup response headers. + +Keep provider receipt status as upstream evidence and fence buffered response release at EOF. + +Share relay response metering and EOF fencing across normal, Files, redirect and cleanup paths. + +Separate preparation from actual dispatch facts and fence streaming delivery in the same synchronous handoff. + +Fence upstream HTTP request construction and prove in-place selector edits retire source instances. + +Require remaining allowance on every governed web/relay route and debit received overflow consistently across proxy and relay traffic. + +Preserve ordinary upstream-failure classification for synchronous transport handoff errors. + +Meter raw proxy header pairs and all observable Fetch headers before forwarding filters; clarify the conservative HTTP wire bound. + +Publish dispatched exposure and contacted-host grants only after the transport constructor or fetch call returns successfully; synchronous construction failures remain upstream failures without granting recipient permission. + +Bind recipient receipts to the final dispatch authority and share verified, bounded admission validation between durable ingestion, projection and history, including retained provenance after pruning. + +Meter relay worker request headers before filtering and cover upstream credential/header growth with the same shared head meter. + +Add remainingBytes as an optional SDK route reader, preserving older operation-only routes with a documented 32 MiB per-request compatibility ceiling; host builders require it internally. Meter informational HTTP response heads before the final response. + +Require a confirmed durable occurrence before trusted dispatch; false or failed source writes refuse the affected operation as recording unavailable, including permanently restricted turns and legacy recorder adapters. + +Keep an approved connection valid across the occurrence and initial collection writes of every peer admitted under that same Network card. Independent evidence still fences dispatch. Restore safety-changed 403 for peer recorder loss or independent pending input while preserving operation-specific recorder-unavailable 503. Preserve the fixed inference refusal wire message and its stored-history classification, keeping detailed causes in host-only denialReason. Document all optional egress receipt fields. + +Preserve a committed explicit session recipient grant across later input without relaxing the first-dispatch fence. Keep outward callback payloads compatible and align peer-loss audit/status assertions and received-header byte-cap expectations with their contract. + +Keep shared-card peer admissions usable with the real governance writer: exclude only their exact owned local/durable pending reservations from approval freshness and recording-availability fences. Independent pending input, recorder failures and capacity remain enforced; global safety projections and history remain unchanged. + +Preserve typed refusal causes through session-binding settlement: revoked authority answers 403 safety_changed, an aborted wait is cancelled, and genuinely pending/failed/missing binding remains 503 unavailable. Native Pi credential-error assertions follow the existing 502 failed-attempt contract without changing the relay. diff --git a/.changeset/full-journal-receipt-recovery.md b/.changeset/full-journal-receipt-recovery.md new file mode 100644 index 0000000000..de1900599e --- /dev/null +++ b/.changeset/full-journal-receipt-recovery.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Keep the host available when a full journal defers startup receipt recovery. Retain unchanged recovery rows, record the cause in journal cleanup status, and retry on the next open with headroom. diff --git a/.changeset/trust-refresh-admission.md b/.changeset/trust-refresh-admission.md new file mode 100644 index 0000000000..a653fbf8e3 --- /dev/null +++ b/.changeset/trust-refresh-admission.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Keep turn admission independent of a running index when the verified policy hash already matches the healthy durable trust projection. Changed or unavailable policy still refreshes under the cancellable brain lock. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 3e802f9b38..781890c091 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1394,7 +1394,10 @@ export "./internal" (./src/internal.ts) type CompiledWorkerCommandPolicy DEFAULT_TURN_TEMP_BYTES EgressAdmissionRefused + type EgressChargeFailure + type EgressChargeResult type EgressDestinationPolicy + type EgressFailureReason type EgressRecord type EgressRefusal FIRST_PARTY_PROVIDER_RECIPIENTS @@ -1504,6 +1507,7 @@ export "./internal" (./src/internal.ts) assertManagedTurnStartupView assertScratchMaskAsync bashCommand + canonicalEgressHost canonicalModelId claudeMaskFilename claudeReportedMaskPath @@ -1523,6 +1527,7 @@ export "./internal" (./src/internal.ts) describeClient egressAddressRefusal egressBootstrapEntry + egressChargeRefusal envMaskedPaths execWrapperSpawnOptions handleTurnTemp @@ -1600,6 +1605,9 @@ export "./internal" (./src/internal.ts) runMaintenanceWorker runMaintenanceWorkerSync safetyAdmissionRefusal + safetyAdmissionSchema + safetyOccurrenceAdmissionSchema + safetyRecordSchema sameSafetyAdmission sessionPromptContext sessionPromptContextLocation @@ -1611,6 +1619,7 @@ export "./internal" (./src/internal.ts) stripHostContextFromTitle turnTempLimit turnTempSpace + validatedEgressProvenance verifiedWorkerIdentity webSearchBrief webSearchKeySource @@ -15411,6 +15420,7 @@ signatures (every public export and the types it is made of) export interface WebModelEgress { dir: string; inference(method: string, target: URL, signal: AbortSignal): unknown; + remainingBytes?(): number; } WebModelGrant (packages/ui-sdk/src/tool-contracts/web.ts) export interface WebModelGrant { @@ -16385,6 +16395,7 @@ signatures (every public export and the types it is made of) }>; }, z.core.$strict>, z.ZodObject<{ cursor: z.ZodOptional>; + includeAdmissions: z.ZodOptional>; includeEntries: z.ZodOptional>; limit: z.ZodOptional; requestId: z.ZodString; @@ -16551,6 +16562,7 @@ signatures (every public export and the types it is made of) clientSafetyReadSchema (packages/ui-sdk/src/safety.ts) const clientSafetyReadSchema: z.ZodObject<{ cursor: z.ZodOptional>; + includeAdmissions: z.ZodOptional>; includeEntries: z.ZodOptional>; limit: z.ZodOptional; requestId: z.ZodString; @@ -21425,6 +21437,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -21571,6 +21594,17 @@ signatures (every public export and the types it is made of) }, z.core.$strict>; safetyRecordSchema (packages/ui-sdk/src/safety.ts) const safetyRecordSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + admission: z.ZodOptional; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -22068,6 +22102,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -27160,6 +27205,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -27318,6 +27374,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -27997,6 +28064,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; @@ -28171,6 +28249,17 @@ signatures (every public export and the types it is made of) unresolvedCount: z.ZodNumber; }, z.core.$strict>; records: z.ZodArray; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 5f49e16bef..d0362b5f2a 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -699,7 +699,15 @@ signatures (every public export and the types it is made of) connectionId: z.ZodOptional; credentialMs: z.ZodOptional; dispatchMs: z.ZodOptional; + dispatched: z.ZodOptional; durationMs: z.ZodNumber; + failureReason: z.ZodOptional>; firstChunkMs: z.ZodOptional; headersMs: z.ZodOptional; host: z.ZodString; @@ -718,6 +726,16 @@ signatures (every public export and the types it is made of) port: z.ZodNumber; provider: z.ZodOptional>; reason: z.ZodOptional; + recipientAdmission: z.ZodOptional; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + }, z.core.$strict>>; + recipientApproved: z.ZodOptional>; + standingRecipient: z.ZodOptional>; + trustedSource: z.ZodOptional>; }, z.core.$strict>; version: number; }; @@ -1100,11 +1118,17 @@ signatures (every public export and the types it is made of) payload: z.ZodObject<{ detail: z.ZodNullable; occurrence: z.ZodOptional; - trustRevision: z.ZodLiteral<"0">; + trustRevision: z.ZodString; trusted: z.ZodLiteral; - }, z.core.$strict>>; + }, z.core.$strict>, z.ZodObject<{ + collectionRevision: z.ZodString; + policyHash: z.ZodString; + ruleId: z.ZodString; + trustRevision: z.ZodString; + trusted: z.ZodLiteral; + }, z.core.$strict>], "trusted">>; detector: z.ZodEnum<{ attachment_input: "attachment_input"; compute_input: "compute_input"; diff --git a/docs/decisions/async-collaboration.md b/docs/decisions/async-collaboration.md index 45a7b4e456..2f43d7bbb3 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-55`). Completed-response +`packages/ui-sdk/src/server/inference-relay.ts:55-63`). 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/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index bd152e50cf..263a826ae1 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -714,7 +714,7 @@ the key and forwards it as the turn's own egress (G5). A key goes only to its built-in first-party origin, or to an exact origin the operator lists for that key in `BRAIN_UI_CLI_PROVIDER_ORIGINS`, under the 2026-10-23 ruling on #1673; the backends' origin rulings grant the CLI nothing by analogy -(`startProviderRelay`, `packages/ui-sdk/src/server/provider-relay.ts:329-334`). +(`startProviderRelay`, `packages/ui-sdk/src/server/provider-relay.ts:336-341`). The inference relay's placeholder is not a key: the launcher names a key that holds it as withheld, so a relayed Claude API-key turn's `anthropic-haiku` reaches the host's key instead of failing authentication. The `jev` reranker @@ -2688,7 +2688,7 @@ so nothing in them can be recorded or limited. **The design.** A `governed` or `strict` worker gets `--unshare-net` and a server-owned egress proxy, bind-mounted as a Unix socket in the same way as the inference relay. The relay's `observe` hook already exists but is not -connected (`observe?(event`, `packages/ui-sdk/src/server/inference-relay.ts:38`). +connected (`observe?(event`, `packages/ui-sdk/src/server/inference-relay.ts:46`). Inside the worker, a small loopback listener forwards to the socket, and `HTTPS_PROXY`, `HTTP_PROXY` and `ALL_PROXY` point at it. @@ -2749,7 +2749,7 @@ reports which applies as `governed.egress`. Making the relay work without managed storage is follow-up work. Each connection is recorded as a governance event, and a recording failure ends the turn. Without a governance recorder the policy still applies and only the records are absent (`prepareTurnEgress`, -`packages/ui-server/src/brain/turn-egress.ts:86-216`). The note says egress is +`packages/ui-server/src/brain/turn-egress.ts:94-389`). The note says egress is recorded only when the backend actually routed the worker through the proxy. API-key Claude profiles (2026-10-22) and pi turns (2026-10-23) are routed too. A pi turn whose credential the relay cannot carry is refused rather than @@ -3771,7 +3771,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:81-83`), +(`if (options.recipientOrigin`, `packages/ui-sdk/src/server/inference-relay.ts:89-91`), 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. @@ -3901,7 +3901,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:73`) +(`export function startInferenceRelay`, `packages/ui-sdk/src/server/inference-relay.ts:81`) 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: @@ -4365,7 +4365,7 @@ outward host skips the card only while every classified call in progress is a visible read, or an approved outward action that names that host. A GitHub write names the GitHub API hosts, and a push or HTTP write names its target's host. Any unknown or opaque call in progress withholds the exception -(`createOutwardCalls`, `packages/ui-server/src/brain/turn-egress.ts:62-84`). +(`createOutwardCalls`, `packages/ui-server/src/brain/turn-egress.ts:67-89`). A background process left by an earlier call can still connect inside such a window; the proxy records it either way. @@ -4379,7 +4379,7 @@ listen on other ports: `gmail.googleapis.com`, `graph.microsoft.com`, `smtp.sendgrid.net`, `api.mailgun.net`, `api.eu.mailgun.net`, `smtp.mailgun.org`, `smtp.eu.mailgun.org`, `api.postmarkapp.com`, `smtp.postmarkapp.com`, `api.resend.com` and `smtp.resend.com` -(`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:22-25`). +(`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:25-28`). Microsoft Graph and Exchange Online carry more than mail, so their reads by an opaque script also wait on the card. The coordinator chose this list for #1665; the maintainer may override it. @@ -4409,7 +4409,7 @@ and a documented "no GitHub here" were both rejected. The rest of the ruling: approves a write, and autonomous turns have no write surface. - **The Network card stays.** An unclassified connection to an outward GitHub host keeps its `Network` approval card (`approveOutward`, - `packages/ui-server/src/brain/turn-egress.ts:256-263`); it is not refused + `packages/ui-server/src/brain/turn-egress.ts:386-393`); it is not refused outright. The hosted report behind #3791 was a compound shell command that ended in `curl` to `api.github.com`. The classifier reads such a command as opaque, so no visible-read exception covers it. Its `CONNECT` was held for @@ -4542,7 +4542,7 @@ rules (maintainer ruling, 2026-10-22). Historically the first source was the session's one `taint` event; the collection supersession above now records every signal. A write that fails stops the turn rather than leaving its outward rules loose. Binding, duplicate checks and the write share a SQLite transaction -(`recordFirstTaint`, `packages/ui-server/src/governance/session-taint.ts:21-27`). +(`recordFirstTaint`, `packages/ui-server/src/governance/session-taint.ts:22-28`). The hosted server runs that transaction on its write worker (`insertGovernanceEvent`, `packages/ui-server/src/governance/events.ts:380`; [#2850](https://github.com/schlessera/brain-kit/issues/2850)). A taint counts @@ -4569,7 +4569,7 @@ charges only after admission); otherwise it is refused and recorded as an `egress_denial` with reason `taint_allowlist` (an interactive turn asks first since 2026-11-03, see [below](#tainted-destinations-ask)). The taint list narrows and never widens: deny and `allowlist` mode still apply first (`prepareTurnEgress`, -`packages/ui-server/src/brain/turn-egress.ts:86-242`). Hosts without managed +`packages/ui-server/src/brain/turn-egress.ts:94-389`). Hosts without managed native storage have no proxy, so the Bash classifier remains their shell rule and nothing narrows their egress. @@ -4614,18 +4614,18 @@ turn's connection passes deny, `allowlist` mode and the byte ceiling but matches neither `taint.egress.allow` nor a contacted host, the proxy asks through the turn's tool-permission card (`toolName: "Network"`, `kind: "command"`, never remembered as a tool grant) before refusing -(`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:198-203`). The +(`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:390-395`). The card names the destination, the session's first taint source and the consequence of allowing it -(`taintedDestinationDescription`, `packages/ui-server/src/brain/turn-egress.ts:41-46`). +(`taintedDestinationDescription`, `packages/ui-server/src/brain/turn-egress.ts:46-51`). Concurrent connections to the same host share one card. An allowed connection's admission adds its host to the turn's contacted hosts, and its charged `egress_connection` record carries the host into the session's later turns, so it is not asked for again; a different host still asks -(`const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:172-183`). +(`const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:273-284`). A decline refuses: the record stays an `egress_denial` with reason `taint_allowlist`, and the 403 carries a short reason the tool can print (`function describeRefusal`, -`packages/ui-sdk/src/server/egress-proxy.ts:88-104`). Stopping the turn while the +`packages/ui-sdk/src/server/egress-proxy.ts:205-221`). Stopping the turn while the card is pending cancels the connection, and a late allow admits nothing. Voice turns, which have no grant surface, and autonomous turns, which have no turn proxy, refuse without a card as before; deny and `allowlist` mode still refuse first. Maintainer @@ -4709,14 +4709,14 @@ with a status text and a body that name it: the deny list, `allowlist` mode, the byte ceiling, an unapproved outward host, or a tainted session's host outside its allow-list, with the session's first taint source and what the user can do (`function describeRefusal`, -`packages/ui-sdk/src/server/egress-proxy.ts:88-104`; the source wording, -`cause: () =>`, `packages/ui-server/src/brain/turn-egress.ts:207`). The status +`packages/ui-sdk/src/server/egress-proxy.ts:205-221`; the source wording, +`cause: () =>`, `packages/ui-server/src/brain/turn-egress.ts:320`). The status line carries the reason because `curl -v`, `git` and `egress-connect` print only that line for a refused CONNECT. The provider relay passes the proxy's reason through as the refusal body's `error.message` and an additive `error.reason`, using the `egress_denial` reason words plus `outward_not_approved` (`const refuse`, -`packages/ui-sdk/src/server/provider-relay.ts:392-397`). The OpenAI image +`packages/ui-sdk/src/server/provider-relay.ts:399-404`). The OpenAI image provider no longer appends its account hint to a relay refusal (`const relayRefusal`, `packages/module-images/src/providers/openai.ts:258-259`). A cancelled connection keeps its bare 403. The system prompt's turn-lifecycle @@ -4811,11 +4811,11 @@ authorization, the byte ceilings, budget admission, cancellation and accounting. It keeps its own `egress_connection` record, which carries `provider: true` and never `inference: true`. The exemption belongs to the operation, never to a hostname. Only the relay's validated routes reach the proxy's provider -admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:338`), and +admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:618`), and worker HTTP and `CONNECT` traffic cannot claim it, even to a provider's host -(`narrowed`, `packages/ui-sdk/src/server/egress-proxy.ts:196`). Turn egress +(`narrowed`, `packages/ui-sdk/src/server/egress-proxy.ts:389`). Turn egress records neither a taint nor a contacted host for the operation -(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:216-221`). So in a +(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:329-334`). So in a tainted session, the worker's own traffic stays narrowed away from the provider's host. @@ -4823,9 +4823,9 @@ A later turn rebuilds its contacted hosts from the session's earlier `egress_connection` records, and a provider record there would look like a worker's. So the maintainer added the optional `provider: true` tag, mirroring `inference: true`, on the record of every validated provider-relay operation -(`finish`, `packages/ui-sdk/src/server/egress-proxy.ts:159-166`). The rebuild +(`observe`, `packages/ui-sdk/src/server/egress-proxy.ts:318-324`). The rebuild excludes those records (`contactedHosts`, -`packages/ui-server/src/governance/session-taint.ts:34-40`), so a provider +`packages/ui-server/src/governance/session-taint.ts:35-48`), so a provider request never gives the worker's own `CONNECT` a contacted-host pass, in the same turn or a later one. Records written before the tag existed stay unmarked, so they can still count for a session that already has them. That is diff --git a/docs/decisions/proportionate-containment.md b/docs/decisions/proportionate-containment.md index 366b834dbb..bb82f87ac0 100644 --- a/docs/decisions/proportionate-containment.md +++ b/docs/decisions/proportionate-containment.md @@ -12,10 +12,10 @@ Ruled by the maintainer on 2026-11-09 (#3812). Tracked under #3813. A hosted instance refused every turn in every chat. One turn's safety-recording write had failed, and the guard reacted by setting one durable flag for the whole brain (`latchSafety`, -`packages/ui-server/src/governance/safety-store.ts:115-125`). From then on, turn +`packages/ui-server/src/governance/safety-store.ts:118-128`). From then on, turn admission threw for every chat, including new chats that had never seen untrusted input (`beginSafetyCollection`, -`packages/ui-server/src/governance/safety-store.ts:193-202`). The error that +`packages/ui-server/src/governance/safety-store.ts:196-205`). The error that set the flag was recorded as "capacity" while the store was at a fraction of a percent of its limits, and its real cause was never stored. The only way back was to stop the server and run `recoverSafetyRecording` from a script, a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 871fc437a9..93eba5f80c 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -191,7 +191,7 @@ reclamation is observed. The concrete access owner (`createGitHubReferenceAccess`, `packages/ui-server/src/brain/github-reference-access.ts:19-189`) uses the fixed transport (`createGitHubReferenceWire`, -`packages/ui-server/src/brain/github-reference-wire.ts:19-254`). +`packages/ui-server/src/brain/github-reference-wire.ts:20-257`). The host-only GitHub access service binds one canonical repository and short branch/tag to a bounded acquisition. Anonymous metadata precedes a private @@ -436,3 +436,48 @@ names together before recording. A changed or missing observation refuses that read; a fresh call can acquire again. Old receipts remain historical evidence, including across restart, and cannot establish current identity or source trust. Approved-owner rule evaluation remains independently required. + +## Approved-owner resolution for immutable reads + +The host read service resolves each actual transport observation against the +Settings' existing live-policy interpretation, its matching durable trust +projection and operation-bound approved-owner evidence. No independent policy +parser or live cache selects owner rules. The policy root's directory identity is +captured with a no-follow directory descriptor and qualified against the native +manager's filesystem ID and fixed live-brain subvolume UUID. The kernel Btrfs +identity is read from that already held descriptor, including across native +library startup waits; lexical replacement before qualification completes +withholds the result. Holding the directory descriptor prevents live inode +reuse, and each read still checks the named root against that descriptor's +identity. Publication records filesystem ID and subvolume UUID from this host +qualification. Ordinary restart requalifies the same native brain and preserves +approval; recreation at the same path, inode and policy bytes has a different +subvolume UUID and cannot inherit it. An unqualified host or legacy proof without +that native binding withholds qualification. Replaced roots, verification races, incoherent projection data +and missing/malformed publication proof produce unavailable qualification. Stable +invalid/unreadable policy retains Settings' last-valid rules and records its +honest error; they do not prevent an otherwise authorized untrusted read. + +Exact repository approval requires the freshly observed stable repository ID, +current canonical owner and the independently approved owner ID. A same-owner +repository rename can qualify only from that new transport observation. Transfer, +repository name reuse and owner namespace reassignment cannot borrow approval. +Owner rules deliberately include future repositories currently in that same +canonical namespace and stable owner ID. A validated policy permits at most one +matching repository and one matching owner rule. Other policy edits do not erase +a retained approval of the same selector, and bounded operation-receipt pruning +or approving-login deletion does not erase the durable owner evidence. It +is interpreted only against a freshly qualified native brain after restart. + +Resolution runs provisionally before recording and again inside the acquired +SQLite writer transaction against the host snapshot and current metadata +generation and durable projection. A generation change during the queue wait +withholds only this qualification; a later read uses a new live Settings +snapshot. The recorded operation ID, policy hash/revision, +approved owner, selector and publication operation/proof hash are historical +qualification evidence. They are separate from the original acquisition and the +prepared/observed/unknown delivery state. Removal affects later resolutions and +retains earlier read evidence. This is neither a trust-at-admission decision nor +a private-access, recipient, Git-write or mutable-content grant. Every read still +produces workspace input; standing-rule enforcement and review targets remain +separately qualified work. diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 21a59ad210..ccf8097141 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -96,7 +96,7 @@ The explicitly prepared ordinary egress proxy follows that same helper selection. Its directory and socket remain owned by the server and use its shared primary group, with exact `0750`/`0660` modes; a setgid temporary parent cannot choose another IPC group (`const separateIdentity`, -`packages/ui-sdk/src/server/egress-proxy.ts:132-138`). Without a helper they retain +`packages/ui-sdk/src/server/egress-proxy.ts:275-281`). Without a helper they retain owner-only `0700`/`0600` modes. Before mounting the proxy, the launcher checks canonical paths, server ownership, the expected helper group, exact modes and socket type. Missing entries, symlinks and widened permissions refuse before @@ -869,7 +869,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:73-261`). +(`export function startInferenceRelay(`, `packages/ui-sdk/src/server/inference-relay.ts:81-254`). 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, @@ -1749,7 +1749,7 @@ wrappers do not borrow that exemption (`commandTaintSource`, `packages/ui-server/src/activity/command-taint.ts:2-27`). The first source is kept as a session `taint` governance event, using the same SQLite transaction for the existing-source check and write -(`recordFirstTaint`, `packages/ui-server/src/governance/session-taint.ts:21-27`). +(`recordFirstTaint`, `packages/ui-server/src/governance/session-taint.ts:22-28`). The recorder waits for a tool result and excludes known denied calls; failed calls can still return untrusted partial output. It records the source kind and tool name, without copying command text or content into the payload. If diff --git a/docs/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index da0d4abd4c..7b9254eac5 100644 --- a/docs/hosting/paid-cli-provider-qualification.md +++ b/docs/hosting/paid-cli-provider-qualification.md @@ -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:73-261`). +(`startInferenceRelay`, `packages/ui-sdk/src/server/inference-relay.ts:81-254`). Its event has outcome/status, not provider usage -(`InferenceRelayEvent`, `packages/ui-sdk/src/server/inference-relay.ts:47-55`). +(`InferenceRelayEvent`, `packages/ui-sdk/src/server/inference-relay.ts:55-63`). 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/http-api.md b/docs/http-api.md index 3330e65536..1dc71ee50a 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -165,10 +165,10 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/journal/configuration-coverage` | S | Read the brain's current untraced configuration-input set | Latest complete inventoried turn only; explicit `unknown`, never an empty list. | | GET | `/api/agent-policy` | I | Read shared admission policy and reported enforcing limits | Read-only Devices & agents facts; no editor or duplicate policy cache. | | GET | `/api/policy-proposals/:turnId/:requestId` | I | Read one principal-owned policy request receipt | Same-request reconciliation only; never writes or reactivates approval. | -| GET | `/api/trust-settings` | I | Read trust policy data and publication availability | Paired Security settings transport (#3608); live password-mode human owners only; runtime trust remains disabled. | +| GET | `/api/trust-settings` | I | Read trust policy data and publication availability | Paired Security settings transport (#3608); live password-mode human owners only; exact origin/tunnel enforcement is advertised independently from unavailable repository enforcement. | | GET | `/api/trust-settings/:request` | I | Read one owner-bound trust publication receipt and review | Same-request reconciliation only; never republishes or resolves a taint trigger. | | POST | `/api/trust-settings/prepare` | I | Prepare one exact-base trust change | Paired Security settings transport; same-origin JSON and live owner authority; repository create/edit independently verifies host metadata. | -| POST | `/api/trust-settings/commit` | I | Publish the exact owner-reviewed trust change | Shared descriptor-bound publisher; bounded durable receipt; saved policy does not imply runtime enforcement. | +| POST | `/api/trust-settings/commit` | I | Publish the exact owner-reviewed trust change | Shared descriptor-bound publisher; bounded durable receipt; enforced origin/tunnel publication joins live admission fences, while repository publication remains unavailable. | | GET | `/api/sessions/:id/safety` | S | Read bounded revisioned host safety evidence | Authenticated principal of the history owner's account (#3952); immutable records, snapshot aggregate/high-water, scoped cursor, explicit coverage/unavailable, no mutation (#3604). | | POST | `/api/sessions/:id/safety/reviews/prepare` | S | Prepare review of one finalized safety occurrence | Live password-mode human owner, exact Origin and bounded JSON; host-issued body/brain/principal/generation-bound handle (#3603). | | POST | `/api/sessions/:id/safety/reviews/:requestId/commit` | S | Commit or read back one individual safe verdict | Live owner rechecked on the acquired FULL transaction and final response; immutable receipt plus fresh aggregate, no bulk clear or standing rule (#3603). | @@ -1942,7 +1942,7 @@ read by any authenticated principal. | Kind | Version | Fields | Meaning | | --- | --- | --- | --- | | `safety_admission_expired` | 1 | `toolUseId`, `evidenceRevision`, `trustRevision`, `authorityEpoch`, `reason` | A waiting or claimed safety-bound approval was withdrawn before dispatch. The server commits this terminal fact before settling the backend wait or publishing the coordinator's `expired` result. Revisions describe the card's original host snapshot; `reason` is `safety_changed`, `turn_ended` or `grant_storage_failed`. Storage failure stops the turn with an explicit failed terminal outcome, without claiming durable withdrawal. This grants no replay and changes no historical approval. | -| `egress_connection` | 1 | `connectionId` (optional), `host`, `port`, `method`, `path` (optional), `bytes`, `accounting`, `durationMs`, optional inference clocks (`admitMs`, `bodyMs`, `credentialMs`, `dispatchMs`, `headersMs`, `firstChunkMs`, `loopLagMaxMs`), optional provider usage (`inputTokens`, `cacheReadTokens`, `cacheCreationTokens`), `outcome`, `inference` (optional), `provider` (optional, #3246), `managedReference` (optional, #3613), `reason` (optional) | A completed, denied, failed or cancelled proxy connection. HTTP has a path and conservative wire accounting; opaque CONNECT has no path or plaintext claim. Only the concrete inference relay sets `inference: true`, only a validated provider-relay operation sets `provider: true`, and only the fixed host GitHub acquisition wire sets `managedReference: true`. Each operation supplies its own exclusive tag. These host records grant no contacted-host authority to a tainted session's worker traffic. Managed acquisition retains ordinary recipient restrictions and claims no model-content delivery or repository trust. Headers, query strings and content are absent. | +| `egress_connection` | 1 | `connectionId` (optional), `dispatched` (optional), `failureReason` (optional), `recipientAdmission` (optional), `recipientApproved` (optional), `standingRecipient` (optional), `trustedSource` (optional), `host`, `port`, `method`, `path` (optional), `bytes`, `accounting`, `durationMs`, optional inference clocks (`admitMs`, `bodyMs`, `credentialMs`, `dispatchMs`, `headersMs`, `firstChunkMs`, `loopLagMaxMs`), optional provider usage (`inputTokens`, `cacheReadTokens`, `cacheCreationTokens`), `outcome`, `inference` (optional), `provider` (optional, #3246), `managedReference` (optional, #3613), `reason` (optional) | A completed, denied, failed or cancelled proxy connection. HTTP has a path and conservative wire accounting; opaque CONNECT has no path or plaintext claim. Only the concrete inference relay sets `inference: true`, only a validated provider-relay operation sets `provider: true`, and only the fixed host GitHub acquisition wire sets `managedReference: true`. Each operation supplies its own exclusive tag. These host records grant no contacted-host authority to a tainted session's worker traffic. Managed acquisition retains ordinary recipient restrictions and claims no model-content delivery or repository trust. Headers, query strings and content are absent. | | `steering_change` | 1 | `path`, `sequence`, `beforeHash`, `afterHash`, `taintSourceEventId`, `overlappingTurnIds`, `tainted` (optional) | One observed steering change, attributed to its turn. Hashes identify retained regular-file versions or are `null`; the source is the current unresolved taint event or `null`. New observations may carry `tainted: true` for effective restriction, including unknown coverage without an attributable source. Historical rows retain their original attribution. Shared windows remain shared, not exclusive writer claims. | | `policy_change` | 1 | `requestId`, `baseHash`, `proposedHash`, `sections`, `outcome` | Explicit user-approved policy publication. Actor is `user`; outcome is `updated`; hashes identify the exact reviewed and written bytes. | | `scratch_overage` | 1 | `bytes`, `pinnedFiles`, `pinnedBytes`, `overageBytes` | Scratch remains above its cap after a prune that preserved retained links. Counts are remaining bytes and pinned files/bytes; `overageBytes` is the excess. A background pass has actor `server` and no session or turn; unbound retention applies. | diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 37ab9eaf0d..7e907cfe86 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -675,8 +675,7 @@ The version 1 governance taint payload optionally adds strict host occurrence metadata; the source enum adds `legacy_unknown`. Every input/output/path/mark signal is independent, including later signals from the same source. Exact host-key retries deduplicate; changed identity/payload retries refuse. Admission -records `trusted: false`, the admitted policy hash (or `null`) and trust revision -`"0"`. Runtime source trust remains disabled. Verified proxy provenance records +records the host admission decision. Unmatched input retains `trusted:false` and the policy hash (or `null`) and trust revision from the same live projection snapshot used for matching. Since #3609, verified exact-origin/tunnel matches retain `trusted:true`, `ruleId`, exact trust policy hash, `trustRevision` and `collectionRevision`; these immutable facts survive rule removal and detail pruning. The wire validator discriminates `trusted:true` (all evidence fields required, non-null hash) from `trusted:false` (no rule ID or collection revision); malformed trusted evidence is refused rather than shown as trusted. The existing v1 detector field continues accepting any valid ID; admission negotiation does not narrow it. Trusted admissions remain inspectable and do not contribute unresolved triggers. Unknown or independent signals stay restrictive. Verified proxy provenance records only the actual web origin or opaque tunnel authority; worker tool arguments never establish transport or repository provenance. The proxy's optional `connectionId` relates its admission and receipt, without guessing a tool call. @@ -894,9 +893,10 @@ stored events keep their recorded sources. behind the proxy, a connection to a host outside `taint.egress.allow` and the session's contacted hosts now raises the existing tool-permission request before it is refused: `toolName: "Network"`, `kind: "command"`, `input` of -`{ host, port, method, target }` with `target` as `host:port`, and a +`{ host, port, method, protocol, managedReference, target }` with `target` as +`host:port` (bracketed for IPv6), and a `description` naming what tainted the session and what allowing does. No -request field, kind or card variant is added. An allowed connection records +new card kind or variant is added. An allowed connection records `egress_connection` as any admitted one does; a declined one records `egress_connection` with `reason: "taint_not_approved"` and the existing `egress_denial` with `reason: "taint_allowlist"`. A turn stopped while the card @@ -1525,3 +1525,129 @@ Authenticated `GET /api/status` adds `journalCleanup`: `retained` contains `retrying: true` at the time it was recorded. The historical cause survives recovery and restart; it does not assert a currently blocked turn. Current charges remain separate in `retained`. No field changes public `/health`. + + +### Prospective origin enforcement (breaking before 1.0, #3609) + +The composed host enables incoming-source and explicit restricted-recipient +rules for verified exact web origins and explicitly selected opaque tunnel +authorities. Repository enforcement stays unavailable pending its independent +read qualification. A CONNECT authority never asserts HTTPS or a Git path. +Redirects and concurrent traffic receive independent decisions; scheme, port +and subdomain cannot borrow another selector's permission. + +Standing recipient permission bypasses only the taint-network card. Source-only +trust grants no recipient permission after unrelated input restricts a chat. +Egress evidence retains `trustedSource` and/or `standingRecipient` markers; a standing recipient decision also records `recipientAdmission` with its rule ID, exact policy hash, trust revision and collection revision. A standing capability alone creates no legacy hostname grant. An explicit +Network card approval independently records `recipientApproved:true` and +retains its legacy session grant, including when source trust also matched. +Transport receipt hosts use lowercase DNS or canonical bare IP literals. +Deny/allowlists, byte ceilings, provider credentials and outward-action approval +remain independent. Removing a standing capability affects future admissions; +source streams revalidate their admitted incoming-content rule when trust changes. +They stop before later bytes if that same rule no longer matches; unrelated +recipient edits alone do not revoke that source decision. Historical admission +facts remain unchanged, and independent recipient/approval fences still apply. +Approval and recording waits recheck live authority and recipient permission at +final dispatch. No earlier trigger, verdict or provider message is rewritten. + + +Origin admission also fences a valid disk/projection mismatch while publication +is being durably projected. The other protected policy publisher joins the same +trust refresh before reporting its update; each qualified proxy turn refreshes +this slice before starting. Invalid policy retains last-valid rules and an +honest error. No ordinary admitted governance setting reloads live. + +Both taint-network and outward cards bind committed evidence, independent +pending/coverage state, trust and authority through later writes and connection +setup. Only the exact connection's own immutable occurrence may be excluded +from its marker; another signal never borrows that exclusion. Cancellation +destroys both tunnel sockets before a delayed connect callback can return 200. +Managed HTTPS reference traffic carries a host-only verified transport tag for +recipient matching and audit, independently of its opaque wire accounting; it +cannot borrow a raw CONNECT selector or grant source/private/write authority. + +Pending network cards coalesce only for the same destination and immutable live +approval context; later evidence cannot join an earlier card. Fork reconstruction +copies unresolved untrusted occurrences only, with identical admission handling +before and after detail pruning. CONNECT and relay rechecks revalidate every time +but notify the host's committed observer exactly once per operation. + +Mixed history groups count trusted admissions and human safe verdicts separately. +An unresolved group names an actually unresolved input for review; a trusted or +reviewed row cannot supply that label. Historical source trust is not relabelled +as a human decision, and a human verdict is not relabelled as source trust. + + +## Egress charge failures + +Egress charge refusals retain their cause. Before response headers, a changed +safety/authority decision reports 403 (including `safety_changed`), and unavailable +recording/admission reports 503 with `egress_unavailable`. These never claim a +network byte limit was exhausted. A byte ceiling retains its existing refusal. +A stream which already began terminates; its relay error and connection evidence +retain the corresponding safety, unavailable or budget classification. + + +Source trust revocation uses one path whether a publication notification or a +send fence or post-write admission check observes it first: connection evidence records `source_trust_changed` +and subsequent charge results classify it as safety, never turn cancellation +or unavailable recording. The turn and unrelated connections remain active. + +Active trusted inputs retain a durable source-rule instance (rule ID plus its +creation revision). Removing, disabling or retargeting that source retires the +instance even if another publisher restores the same ID before the next chunk. +Recipient-only edits preserve the source instance. Instance metadata stays out +of Settings responses and never grants trust independently of policy files. + +New egress records carry optional `dispatched` evidence. Charged preparation +with `dispatched:false` never grants contacted-host permission in later turns; +older records without the field retain their existing interpretation. Historical +contacted hosts use the same canonical comparison key as current destinations, +including legacy bracketed IPv6 literals. This operation's recording +unavailability is 503 `egress_unavailable`, including initial admission. +Another recorder's loss or an independent pending input is a safety change, +403 `safety_changed`. + +A shared Network card excludes every occurrence admitted under that exact +card from its approval-evidence marker, including completed peers, their +initial collection metadata, and their exact in-flight write reservation IDs. +The host tracks reservation ownership through occurrence IDs; both local +overlays and durable pending rows are excluded from only that group's pending +count, recording-pending reason and recording-availability send fence. Global +projection/history reads, failures and capacity are unchanged. Host-only read +arguments are additive and optional; callers that omit them retain the global +view. Independent inputs, cards, human decisions and +authority or trust changes still invalidate the pending approval. These host +exclusions never remove occurrences from safety history or effective taint. +Inference refusal wire messages retain their existing fixed text (including +`Inference network admission refused`); the specific cause stays in the host's +`denialReason`, preserving runtime classification and stored-history readers. + +Egress audit records add optional `failureReason` with the stored terminal +category: `budget`, `safety_changed`, `policy_denied`, `unavailable` or +`cancelled`. This category is captured before abort listeners run and is shared +by every caller; reading it never retries admission or recomputes a cause. +Outward approval markers include the active call-classification generation, +so a covering call ending or an opaque call starting withdraws its exemption +even across a durable occurrence write. + +Malformed proxy destination fields return HTTP 400 before recording input +evidence. They cannot poison a safety-history page or stop later valid +requests in the turn. Authority loss while settling a binding reports 403 +`safety_changed`; an aborted wait reports 499/cancelled. Only pending, failed +or missing session binding reports 503 `egress_unavailable`, on both initial +and repeated inference admission. A cancelled cleanup cannot +send its credentialed DELETE, and cancellation interrupts an in-flight DELETE. + +A credential resolver or upstream transport failure is a failed attempt, not +cancellation caused by the proxy closing its own signal. Before response +headers it reports 502; cancellation reports 499 and existing admission +refusals retain their typed cause. Provider receipts keep 0 when no upstream +HTTP status was observed, or the observed status for interrupted responses. + +`egress_connection.accounting: "http_wire_bound"` counts received headers before +hop-by-hop filtering. The Node proxy meters `rawHeaders`, its actual HTTP start +line and framing; Fetch relays meter all unfiltered header pairs exposed by +Fetch with a runtime framing allowance. The bound is not an exact TLS/wire-byte +measurement and does not reconstruct formatting that Fetch does not expose. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 95dbee7cc9..d577b7d761 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -109,7 +109,27 @@ The internal turn proxy has a first-party `managedReference(target, signal)` operation for fixed GitHub HTTPS acquisition and a `remainingBytes()` counter. It retains ordinary G6 recipient narrowing, final admission fences and byte accounting; it cannot grant a contacted-host allowance. No worker -header selects it. The internal entry also exports the existing +header selects it. Network approval destinations carry `protocol` and the +host-owned `managedReference` identity; pending approvals never coalesce a +managed HTTPS acquisition with an opaque CONNECT to the same authority. +CONNECT accepts explicit bracketed IPv6 authorities as well as canonical DNS +and IPv4 hosts. `canonicalEgressHost` supplies one lowercase DNS or canonical bare +IP comparison identity for host checks, cards and receipts. Resolution/dialing +preserves the requested URL hostname, including a DNS root dot; destination +policy resolves that exact hostname before pinning a checked IP. Settings selectors +retain URL brackets for IPv6; the trust matcher adapts that schema boundary. +Absent approvals never request an approval revision. Unchanged safety reads, +approval markers and taint/projection reads use local-write, external SQLite +change and pending/loss counters; changed evidence revalidates the scoped +marker, including the exact own-occurrence exception. +Every upstream write/end and tunnel chunk uses the same current authority, +recipient, source-trust, approval-freshness and byte-budget fence. +Live trust reads and durable refresh share one policy observation state machine. +Stable invalid or unreadable policy retains last-valid rules/hash with an error; +a changed-file or ancestry verification mismatch fences. Unchanged-file chunk +fences compare ancestry/file metadata generations without reading policy bytes +or querying SQLite. Refresh rechecks the generation after its durable write. +The internal entry also exports the existing `egressAddressRefusal` validator so the fixed acquisition wire validates every DNS address before connecting to a checked IP. These are implementation sharing, with no supported public transport extension seam (#3613). @@ -476,7 +496,7 @@ admitted model as its backend lends it on the host, and `handleWebTool` takes it as an optional fifth argument, `model`. `WebModelAccess` is `{ provider, model, open(egress, signal?) }`; `open` starts a host relay for exactly that model into a web executor's egress route (`WebModelEgress`: -`{ dir, inference }`) and resolves to `{ grant, stop() }`. `WebModelGrant` +`{ dir, inference, remainingBytes? }`) and resolves to `{ grant, stop() }`. `WebModelGrant` (`{ provider, model, credential: "api_key" | "oauth", basePath, socket }`) is everything the executor is told, and never holds a credential. A backend that does not set `model` behaves as before. @@ -5680,7 +5700,7 @@ capability, HTTP endpoint, history DTO or provider conversation changes here. The optional owner-only `/api/trust-settings` HTTP surface is a policy-publication building block. `GET /api/trust-settings` reads the current trust-only revision, exact policy hash, `origins`, `repositories`, repository-identity availability, -and disabled runtime enforcement capabilities. +and independently advertised runtime enforcement capabilities. The composed host enables origin/recipient enforcement; repository enforcement remains unavailable. `POST /api/trust-settings/prepare` accepts strict version-1 JSON with `expectedTrustRevision`, `expectedPolicyHash` and exactly one `change`: `{action:create|edit,rule}` or `{action:remove,ruleId}`. The host issues the @@ -5729,12 +5749,10 @@ only read the original outcome; changed data conflicts. Expired handles can never create operations. Prepared/readback text survives stale-base refusal. The receipt stages are `prepared|file_published|committed|partial|unknown|refused`; -`committed` is an internal publication-completion stage, never proof of live -runtime enforcement. Current responses use `partial` for saved policy because -`enforcement:unavailable` remains truthful until the admission implementation. +`committed` with `enforcement:enforced` reports a qualified origin/tunnel publication only after the live revision and active input fences have updated. Repository publication and hosts without origin enforcement continue to return `partial` with `enforcement:unavailable`. `currentRule:present|removed|changed|unknown` is refreshed on reads, independently of historical publication proof. Readback loads the durable operation and policy -projection within the same brain lock after any in-progress commit finishes. No removal receipt claims an enforcing fence. +projection within the same brain lock after any in-progress commit finishes. An enforced origin removal has already fenced later active-turn admission and interrupted affected source streams. No agent turn, provider message or ordinary governance snapshot is changed. The journal awaits asynchronous metadata and publication before releasing its Settings observation window. It records intervening changes with their ordinary attribution before @@ -5745,7 +5763,9 @@ The live trust projection retains last-valid rules on invalid policy, reports an error, and increments its decimal uint64 revision only for trust-list changes. Exhausted revisions refuse both new reviews and publication of retained reviews before any protected policy write; request revisions above uint64 also refuse. -It is supplied for future admission integration; runtime capabilities remain off. +The composed host shares its live trust revision with proxy and backend admission. The protected policy proposal publisher refreshes the same projection under the shared brain lock before reporting updated; qualified turn preparation refreshes it too. A synchronous anchored trust-list check refuses stale disk/projection matches during that refresh gap. Invalid policy retains last-valid rules with an error. Ordinary turn budgets, commands and profiles retain their admitted snapshots. + +`OriginTrust.refresh` returns without the brain lock when the observed policy hash equals the durable projection's hash and the projection carries no error; otherwise it queues the lock as before, cancellable on turn abort. The HTTP boundary admits at most 32 concurrent requests per principal and 256 for the served brain, including lock waiters; excess requests return retryable @@ -6051,3 +6071,181 @@ for every interactive session, so a new session's retained append contains the bullet. A session retained earlier keeps its append byte for byte. The same-commit API report records the additive types. See [the MCP component](mcp.md#raw-connections-to-githubs-api-0450-3799). + + +### Historical origin admission evidence (#3609) + +Safety occurrence DTOs add optional `admission` with `trusted`, `policyHash` +and `trustRevision`; a true decision also carries `ruleId` and +`collectionRevision`. A trusted admission requires the proxy detector and verified +HTTP-origin or tunnel provenance; both revisions are bounded unsigned 64-bit +decimal strings. Recorder ingestion, projection and history share this schema. +It is host-owned historical evidence, never client +permission or a human verdict. Older payloads without it retain conservative +interpretation. The aggregate excludes trusted admissions from unresolved +counts while keeping unrelated occurrences, coverage gaps and recording failures +restrictive. Pruning preserves these minimal admission facts and their verified provenance. The UI names +historical source trust separately and offers no safe-verdict action for it. +Provider history remains byte-identical as an earlier prefix. + + +## Turn egress charge and cancellation + +Each cleartext HTTP proxy operation uses its own non-pooled upstream connection, matching its `Connection: close` request header. A closed socket from an earlier operation is never reused, and transport failures do not automatically replay the request. Application-byte accounting and the final admission fence run once per send. CONNECT already owns a distinct upstream socket; inference and provider relays retain their separate Fetch transports. + +The concrete turn proxy's `charge(bytes)` returns `{ok:true}` or +`{ok:false,reason:"budget"|"safety_changed"|"policy_denied"|"unavailable"|"cancelled"}`. Callers preserve that +classification. Each terminal decision stores its typed reason before notifying +abort listeners; `failure()` reads that immutable decision without charging or +consulting live state. Callers never call `charge(0)` to classify an operation +that already refused. `prepare()` runs preparation observers without publishing a +dispatch fact. After charging, `dispatch(send)` runs the final typed fence and +calls the synchronous transport handoff. Only after the transport constructor or fetch call returns successfully does +it publish dispatched state and the committed/contacted notification, once. +The final fence returns the recipient authority it used (the exact rule instance, +explicit approval or independent allowance). Only that decision feeds the +dispatch receipt; preparation never supplies recipient evidence. +A refused preparation or fence never grants contacted-host access. A started +send still counts if it later fails. Preparation observers may revoke; fact +observers run after send and cannot erase bytes already handed to transport. A zero-byte terminal decision can complete at the exact byte ceiling while +still revalidating safety. `bytes` must be a nonnegative safe integer; invalid counts +throw RangeError before changing either the turn or connection byte counter. +Only budget refusal is byte exhaustion; authority/source or +approval changes are `safety_changed`, denied recipient/destination policy is +`policy_denied`, unverifiable recording/admission is `unavailable`, and turn or +client cancellation is `cancelled`. Their statuses are 403, 403, 503 and 499 +respectively; disconnected transports may have no response status. Inference/provider uploads, headers, streams and managed GitHub +wire metering consume this result. `OriginTrust.refresh(signal?)` cancels a +queued brain-lock acquisition on turn abort; it never releases another holder. `OriginTrust.refresh` returns without the brain lock when the observed policy hash equals the durable projection's hash and the projection carries no error; otherwise it queues the lock as before, cancellable on turn abort. +Turn startup rechecks abort before creating egress resources and normal turn +teardown releases its own governed hold and concurrency slot. + +The concrete operation lifecycle is pending → admitted → dispatched → finished +or aborted. Admission after a terminal transition is a no-op. A new dispatch +requires remaining byte capacity, including after approval or DNS waits; the +zero-byte ceiling exception applies only to an already-dispatched stream. +Admission effects already started are joined before terminal observation and +cleanup. Proxy `settled()` joins those effects before the host joins its durable +records. Each operation owns and releases all of its per-connection keys once. + +Proxy destination admission and server occurrence provenance use the history +record schema itself: host names fit 253 UTF-8 bytes and ports are integers +from 1 through 65535. Invalid destinations are refused before admission effects +or durable occurrence writes. Relay retries use the same stored-failure +classification as initial admission. All upstream requests use operation +cancellation together with their existing request/deadline signal, and check +cancellation again after observer callbacks immediately before dispatch. + +Relay failure classification snapshots the failure site before terminal +cleanup aborts the operation signal. Credential or upstream request failures +return 502, actual cancellation returns 499, and a previously decided policy +or safety refusal retains its typed status. Interrupted streams keep their +already-sent HTTP status and terminate with failed or cancelled evidence. +Caller-signal listeners belong to the operation lifecycle and are released +by every terminal transition, including internal admit/charge/dispatch refusals. + +Provider relay cancellation preserves `cancelled` in both the refusal observer +and `error.reason`. Preparation observers run before a final typed send fence; +a synchronous authority or recording change refuses the upstream request. +Files cleanup responses charge their headers against the same turn ceiling as +ordinary provider responses, with a budget refusal if those headers exceed it. + +Provider receipt `status` is exclusively the observed upstream HTTP status, +including cancellation and cleanup; it stays 0 until a response arrives. +Local refusal status remains in the caller response. Governed buffered Files +answers and streaming scrubber tails revalidate safety at EOF before exposing +held bytes or registering upload URLs and handles. + +Inference and provider relays share response accounting: observed headers debit +before redirect/status handling, every observed chunk debits before response +size checks, and EOF revalidates live admission before completion. Incoming +bytes beyond the remaining turn allowance consume the available allowance and +refuse the excess. Files cleanup drains through the same metered reader. + +`WebModelEgress.remainingBytes()` and the reader on governed relay `egress` +options are optional additive minor-version fields. Existing operation-only +adapters still compile and run. Without a reader, each relay operation uses a +32 MiB compatibility ceiling (the existing per-request limit) across its +accounted request and response bytes, while the route's own charge/admission +checks still apply. This fallback cannot know or saturate an older adapter's +remaining shared turn allowance; adapters should supply the reader for exact +shared accounting. Host web-model routes require it through an internal type, +and Pi forwards it unchanged. Ungoverned relays without an egress route +retain their existing behavior. Received proxy HTTP/CONNECT bytes and both +relay uploads/responses share the same saturating allowance accounting. + +Preparation and exposure notifications are separate: proxy `preparing` and +provider relay `preparing` run before the last send fence; `committed` and +provider `observe({outcome:"dispatched",...})` report an actual transport start. +Relayed operations expose `prepare()` and `dispatch(send)` in place of this +change's provisional `commit()` method. A pending terminal decision during a +synchronous transport handoff joins its final dispatched fact before audit only +if the handoff returns successfully. +Streaming read results carry a delivery closure that revalidates and enqueues +in one synchronous call. No awaited continuation separates that final check +from chunk delivery or scrubber-tail release. + +An upstream HTTP request constructor starts a connection attempt. The proxy +constructs it inside `dispatch(send)` after the final fence, even if the +client's body is still pending. That connection attempt is dispatched and +contacted exposure; later cancellation cannot erase it. Subsequent writes and +end still revalidate through the same send fence. + +A synchronous transport-handoff throw is classified by the same caller path +as an asynchronous upstream rejection. A synchronous throw publishes no +dispatched fact or contacted-host grant. Dispatch does not abort or store an +admission refusal before the caller classifies +that transport error. Both report failed upstream attempts (502 before response +headers), with provider receipt status 0 when no upstream response was seen. +The final fence and transport invocation remain synchronous. Proxy HTTP and +CONNECT use their ordinary upstream-failure handler for either failure order. + +Received HTTP heads are metered by the shared reader before forwarding filters. +The Node proxy supplies the actual HTTP version/status or request line and every +`rawHeaders` pair, including duplicate and Connection-nominated fields. Fetch +relays supply every unfiltered header pair exposed by Fetch, including repeated +Set-Cookie entries in the installed runtime. Counts cover all exposed name/value +bytes and CRLF framing plus the existing runtime allowance. `http_wire_bound` +is conservative application-level accounting: it does not claim exact TLS, +transport wire bytes, or original header formatting discarded by Fetch. This +clarifies the existing bound; forwarding policy never determines received cost. + +Relay request accounting charges the unfiltered worker head before any body read, +forwarding filter or credential injection. The logical request head costs at +least the larger of that received head and the constructed upstream head, +including the framing allowance; upstream growth is charged before dispatch. +The local relay hop does not count the same logical head twice. Generated +cleanup requests have no worker head and charge their constructed upstream head. + +The native HTTP proxy also meters every informational response head (including +100 Continue and 103 Early Hints) through the same raw-head meter, before the +final response. A 101 upgrade head is also metered; this HTTP route refuses +protocol switching and closes that socket. An interim refusal cannot be overwritten by a final head that +arrives in the same packet. + +A proxy input cannot use source trust until its occurrence write confirms a +durable commit. A false result or failed write refuses that operation with +503 egress_unavailable even if permanent-gap coverage reports recording +available. No trusted source fact or terminal exposure is published for a +missing occurrence. Legacy recorder adapters await their write result; an +otherwise unacknowledged trusted write must be present in the safety ledger. + +Network approval markers exclude only the approved operation’s own occurrence +and, when it creates the turn’s first collection, that same collection-start +metadata. Independent inputs, pending writes, failures, bindings and authority +changes still invalidate the decision. An unknown collection does not become +clean through this exclusion. + +An operation-specific recorder failure is 503 egress_unavailable. A different +recorder’s loss or an independent pending input changes the safety context and +refuses with 403 safety_changed. The internal optional +AdmissionSafetySnapshot.operationRecordingAvailable distinguishes the two; +legacy snapshots without that detail retain conservative unavailable behavior. + +Once a successfully dispatched explicit Network approval has become the session +contacted-host grant, later independent input does not revoke that recipient +grant or truncate the approved stream. Pre-dispatch approval freshness, source +rule removal, authority, recorder availability, outward permission and byte +ceilings remain independently fenced. Outward callbacks retain their original +{host, port, method} shape; transport metadata is confined to source/recipient +matching and the corresponding Network-card identity. diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 860f454888..3d3fe2c954 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -3656,3 +3656,13 @@ the existing `error` outcome and the named `git_publication_discarded` reason; the recorded child exit code is unchanged. Other discard conditions retain the normal command outcome and carry their cause in this optional metadata. No existing outcome or reason enum gains a value. This ships in a minor. + +### Historical admission evidence (additive, #3609) + +A server advertising `sessionSafetyAdmissionEvidence:true` accepts optional +`includeAdmissions:true` on `safety_read`. Only opted-in snapshot pages and +their subscriptions include occurrence `admission` evidence. Cursor continuation +pins this choice alongside entry correlation; changing it requires a fresh +snapshot. Older readers retain their strict record shape and conservative +interpretation. New clients omit the field when the server capability is absent. +HTTP readers explicitly opt in with `admissions=1`; repeated/invalid query values are refused. This affects host UI sidecars only; it never changes provider history. diff --git a/docs/plans/extraction-classifier.md b/docs/plans/extraction-classifier.md index 414dfa5bba..7cdde2bf3f 100644 --- a/docs/plans/extraction-classifier.md +++ b/docs/plans/extraction-classifier.md @@ -39,8 +39,8 @@ It is advisory and narrow: - An `allow` may relax exactly one thing, the #3430 card for a host the tainted session has not contacted - (`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:280-285`; - `const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:172-183`). + (`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:390-395`; + `const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:273-284`). Because the proxy cannot tell which process opened a connection, that relaxation can only cover the hosts a readable call names while it is in progress, as the outward exception already does. An opaque call withholds @@ -85,7 +85,7 @@ Each is deterministic and was scored alone | Taint host | A destination's site appears among the hosts the tainting content named. | | Encoded blob | A base64 or hex token of at least twelve characters in subdomain, path, query or body; an undecodable one must be twenty characters with a digit. `encodedText`: the blob decodes to readable text. | | Volume | A query of 120 characters or data of 512 bytes to a host the session has not contacted. | -| Write-shaped | Paste, webhook, request-bin, form, upload and collect hosts, the built-in outward mail hosts (`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:22`), a writing method to a submit, issue, comment, gist or message path, a beacon path, or an MCP tool named send, create, post, upload, comment, write, update, append or share. | +| Write-shaped | Paste, webhook, request-bin, form, upload and collect hosts, the built-in outward mail hosts (`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:25`), a writing method to a submit, issue, comment, gist or message path, a beacon path, or an MCP tool named send, create, post, upload, comment, write, update, append or share. | | Fan-out | Five earlier calls, or three distinct hosts, to one site the session had not used before its taint. | | Method | A writing method, or a tool the policy classifies outward or opaque. | diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 5f57f1cc9e..18442bb7a1 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -25,7 +25,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. - Taint recording retains every independently observed signal and reads a durable revisioned aggregate, including pending/failure and explicit unknown coverage (`safetyProjection`, - `packages/ui-server/src/governance/safety-store.ts:418-423`). Legacy rows prove + `packages/ui-server/src/governance/safety-store.ts:429-434`). Legacy rows prove their own event, never a complete history. Owner review transport and its mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, @@ -36,13 +36,13 @@ public design or its fixtures. Fictional examples use the Odysseus world. never prove finalized delivery or complete coverage. - The turn proxy records each admitted non-provider connection and terminal exposure observation (`prepareTurnEgress`, - `packages/ui-server/src/brain/turn-egress.ts:86-295`). Relay admissions join + `packages/ui-server/src/brain/turn-egress.ts:94-389`). Relay admissions join this proxy's submitted terminal observations and its own announced session binding before reading fresh safety (`settleTurnSessionBinding`, - `packages/ui-server/src/ws/bridge-session-binding.ts:14-28`), without excluding + `packages/ui-server/src/ws/bridge-session-binding.ts:15-32`), without excluding independent pending input. A raw CONNECT reveals only an authority and opaque bytes, not a repository path or inner protocol - (`startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:200-435`). + (`startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:264-608`). - Outward decisions read session taint at admission (`prepareOutwardPlan`, `packages/ui-sdk/src/server/outward-policy.ts:47-94`). Existing historical steering attribution must remain attribution at the time of a write. diff --git a/docs/supported-inputs.md b/docs/supported-inputs.md index 5b9fdf3fb6..04f7f893cc 100644 --- a/docs/supported-inputs.md +++ b/docs/supported-inputs.md @@ -110,11 +110,13 @@ repeated hyphens; repository tokens are 1–100 ASCII alphanumeric/`_.-` bytes, excluding `.` and `..`. Stable provider IDs are nonzero decimal strings of at most 20 digits. A parsed worker remote never proves provider identity. -These are policy data and pure candidate matching only. All runtime origin, -recipient and repository rule capabilities remain **disabled**, with an -explicit reason in the internal availability facts. There is no new Settings -writer, transport, admission exemption, historical reclassification or safe -verdict. Incoming-only rules cannot authorize a restricted destination; repo +Schema parsing and pure candidate matching alone enable no runtime authority. +The data-only availability defaults remain disabled. Since #3609, the composed +host independently advertises qualified exact-origin/tunnel source and recipient +enforcement; repository enforcement remains disabled. See the +[admission contract](integration-contract/http.md#prospective-origin-enforcement-breaking-before-10-3609) +and [owner Settings publication](integration-contract/package-api.md#human-trust-settings-publication). +No rule retrospectively reclassifies a trigger or supplies a safe verdict. Incoming-only rules cannot authorize a restricted destination; repo rules cannot authorize a generic host, outward write or private acquisition. The existing `taint.egress.allow` list is not populated from these entries. diff --git a/packages/ui-backend-pi/src/host-inference.ts b/packages/ui-backend-pi/src/host-inference.ts index 4590457a86..9173fd51e8 100644 --- a/packages/ui-backend-pi/src/host-inference.ts +++ b/packages/ui-backend-pi/src/host-inference.ts @@ -244,7 +244,7 @@ export async function preparePiHostInference(options: { /** The origin turn admission proved the recipient from (#2695); any other endpoint refuses before a credential is read. */ recipientOrigin?: string; /** The turn proxy's private directory; the relay socket is linked into it. */ - egress: { dir: string; inference: NonNullable[0]["egress"]>["inference"] }; + egress: { dir:string } & NonNullable[0]["egress"]>; environment: Readonly>; signal?: AbortSignal; received?: Parameters[0]["received"]; diff --git a/packages/ui-backend-pi/tests/fixtures/native-host-auth-probe.ts b/packages/ui-backend-pi/tests/fixtures/native-host-auth-probe.ts index 9edf00486f..008f2f4a75 100644 --- a/packages/ui-backend-pi/tests/fixtures/native-host-auth-probe.ts +++ b/packages/ui-backend-pi/tests/fixtures/native-host-auth-probe.ts @@ -159,7 +159,7 @@ try { unix: relay.socketPath, } as RequestInit); const body = await response.text(); - assert.equal(response.status, 503); + assert.equal(response.status, 502); assert(!body.includes(errorSecret)); assert(!body.includes("odysseus-refresh-cancel")); assert(body.includes("Inference credentials unavailable")); diff --git a/packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts b/packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts index ce55365e03..2146b3c3f1 100644 --- a/packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts +++ b/packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts @@ -73,7 +73,7 @@ test("installed native auth reads current credentials, serializes refresh, cance hostAuthUnchanged: true, }); expect(result.nativeAuthErrorRedaction).toEqual({ - status: 503, + status: 502, secretAbsent: true, namedRefusal: true, }); diff --git a/packages/ui-react/src/components/chat/safety-indicator.tsx b/packages/ui-react/src/components/chat/safety-indicator.tsx index 8cd6349a14..f5f896f7af 100644 --- a/packages/ui-react/src/components/chat/safety-indicator.tsx +++ b/packages/ui-react/src/components/chat/safety-indicator.tsx @@ -7,6 +7,8 @@ import { activeChat, useChatStore } from "../../stores/chat-store.js"; import { entryEvidence, safetyEvidence, type SafetyEvidence } from "../../lib/safety-evidence.js"; import { createSafetyReviewer, type SafetyReviewProgress } from "../../lib/safety-reviewer.js"; +const formatAuthority = ({host,port}:{host:string;port:number}) => `${host.includes(":") && !host.startsWith("[") ? `[${host}]` : host}:${port}`; + const sources:Record={web_fetch:"Web fetch",web_search:"Web search",staged_share:"Shared input",chat_attachment:"Chat attachment", workspace_read:"Workspace read",mcp_document:"External tool input",user_marked:"Marked untrusted",fetching_command:"Fetching command",unclassified_command:"Unclassified command", compute_output:"Compute output",apify_result:"Apify result",github_result:"GitHub result",egress_connection:"Network input",legacy_unknown:"Legacy input evidence"}; @@ -70,9 +72,17 @@ function SafetyIndicator({entries:currentEntries}:{entries:SafetyEvidence[]}) { const entries=allowed?(currentEntries.length?currentEntries:open||readStatus!=="ready"?held.current.entries:[]):[]; useEffect(()=>{if(!allowed)setOpen(false);},[allowed]); useEffect(()=>{setOpen(false);},[scope,auth]); - const unresolved=entries.filter(e=>!e.decision).length,unknown=entries.some(e=>e.occurrence.detailPruned||e.occurrence.source==="legacy_unknown"); - const name=unresolved?`Safety restrictions: ${unresolved} unresolved trigger${unresolved===1?"":"s"}`:`Marked safe by you${entries.length>1?`: ${entries.length} triggers`:""}: show details`; - const reason=unresolved?`${sources[entries.find(e=>!e.decision)!.occurrence.source]} · Only this trigger can be reviewed`:"Human decision retained; content remains in the model context"; + const unresolvedEntries=entries.filter(e=>!e.decision&&!e.occurrence.admission?.trusted); + const unresolved=unresolvedEntries.length,unknown=entries.some(e=>e.occurrence.detailPruned||e.occurrence.source==="legacy_unknown"); + const trusted=entries.filter(e=>e.occurrence.admission?.trusted).length,reviewed=entries.filter(e=>e.decision).length; + const accepted=[...(trusted?[`${trusted} trusted at admission`]:[]),...(reviewed?[`${reviewed} marked safe by you`]:[])].join("; "); + const name=unresolved?`Safety restrictions: ${unresolved} unresolved trigger${unresolved===1?"":"s"}${accepted?`; ${accepted}`:""}` + :trusted===entries.length&&!reviewed?`Trusted at admission${entries.length>1?`: ${entries.length} inputs`:""}: show details` + :reviewed===entries.length&&!trusted?`Marked safe by you${entries.length>1?`: ${entries.length} triggers`:""}: show details` + :`Safety history: ${accepted}: show details`; + const reason=unresolved?`${sources[unresolvedEntries[0]!.occurrence.source]} · Only this trigger can be reviewed` + :trusted&&reviewed?"Historical source trust and human decisions retained; current rules may differ" + :trusted?"Historical source trust retained; current rules may differ":"Human decision retained; content remains in the model context"; useLayoutEffect(()=>{ if(!open)return; const place=()=>{const r=trigger.current?.getBoundingClientRect();if(r)setPosition({left:Math.max(12,Math.min(r.left,innerWidth-Math.min(384,innerWidth-24)-12)),top:Math.max(12,Math.min(r.bottom+4,innerHeight-Math.min(520,innerHeight*.65)-12))});}; @@ -108,18 +118,19 @@ function SafetyTrigger({entry}:{entry:SafetyEvidence}) { useEffect(()=>{if(state.status!=="ready"||!state.capabilities?.review||auth!=="active")setReview(false);},[state.status,state.capabilities?.review,auth]); const r=entry.occurrence,session=state.identity&&"sessionId" in state.identity?state.identity:null; const readable=state.status==="ready"&&!!session,owner=state.capabilities?.review===true&&auth==="active"; - const canReview=readable&&owner&&entry.exposure==="finalized"&&!entry.decision&&!state.projection?.pendingCount&&!state.projection?.reasons.includes("recording_failed"); + const canReview=readable&&owner&&entry.exposure==="finalized"&&!entry.decision&&!r.admission?.trusted&&!state.projection?.pendingCount&&!state.projection?.reasons.includes("recording_failed"); const busy=progress?.stage==="pending",unknown=progress?.stage==="unknown"; - const provenance=r.provenance?.kind==="web_origin"?`${r.provenance.origin.scheme}://${r.provenance.origin.host}:${r.provenance.origin.port}`: - r.provenance?.kind==="tunnel_authority"?`${r.provenance.authority.host}:${r.provenance.authority.port}`:"Source provenance unavailable"; + const provenance=r.provenance?.kind==="web_origin"?`${r.provenance.origin.scheme}://${formatAuthority(r.provenance.origin)}`: + r.provenance?.kind==="tunnel_authority"?formatAuthority(r.provenance.authority):"Source provenance unavailable"; return
-

{entry.decision?"Marked safe by you":"Safety restrictions enabled"}

+

{r.admission?.trusted?"Trusted at admission":entry.decision?"Marked safe by you":"Safety restrictions enabled"}

{sources[r.source]} ·

{r.summary}

{provenance}

+ {r.admission?.trusted&&

Source rule {r.admission.ruleId} · trust revision {r.admission.trustRevision}. This historical decision grants no current recipient permission.

} {r.detailPruned&&

Some source detail has expired. The trigger and any decision remain recorded.

} {entry.decision&&

Marked safe by you ·

} - {!entry.decision&&entry.exposure!=="finalized"&&

{entry.exposure==="open"?"Input is still arriving. Mark as safe is unavailable until delivery is finalized.":"Delivery could not be confirmed. This trigger cannot be marked safe."}

} - {!owner&&!entry.decision&&

Only the authenticated owner can mark this trigger safe.

} + {!r.admission?.trusted&&!entry.decision&&entry.exposure!=="finalized"&&

{entry.exposure==="open"?"Input is still arriving. Mark as safe is unavailable until delivery is finalized.":"Delivery could not be confirmed. This trigger cannot be marked safe."}

} + {!r.admission?.trusted&&!owner&&!entry.decision&&

Only the authenticated owner can mark this trigger safe.

} {!readable&&

Current evidence is unavailable or incomplete. Read it again before reviewing.

} {canReview&&!review&&!progress&&