From e84978e1c704d576db9b8ee1d6688a73b588199a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Thu, 12 Nov 2026 08:53:29 +0000 Subject: [PATCH 1/2] CONTRACT: feat(backends,ui-sdk,ui-server): admit each web provider request for the calling turn Every external recipient a Pi web call reaches is admitted for its turn: a named provider before dispatch, and every request the executor sends to a provider's API host while the call runs, extraction fallbacks and nested model calls included. Data routing follows Apify consent's rules over the conversation's recorded exposures, a blocked budget scope refuses, and each admitted request counts as unknown spend, never zero. A connection with no call in flight is refused, and the executor opens one connection per request so a reused tunnel carries nothing unadmitted. Adds the web tool error codes policy_denied and budget_exceeded. Closes #3687 Co-Authored-By: Claude Opus 5.5 --- .changeset/3687-web-call-admission.md | 7 ++ api-report/ui-sdk.txt | 3 +- docs/decisions/governed-writable-workers.md | 51 +++++++++++++ docs/integration-contract/mcp.md | 15 +++- packages/ui-backend-pi/README.md | 6 ++ .../ui-backend-pi/src/web-executor-entry.ts | 7 +- packages/ui-sdk/src/internal.ts | 2 +- packages/ui-sdk/src/server/egress-proxy.ts | 21 +++++- packages/ui-sdk/src/tool-contracts/web.ts | 2 + packages/ui-server/src/brain/turn-budgets.ts | 15 ++++ packages/ui-server/src/web-tools/broker.ts | 70 +++++++++++++++-- packages/ui-server/src/web-tools/host.ts | 47 ++++++++++-- .../ui-server/src/web-tools/recipients.ts | 71 ++++++++++++++++++ packages/ui-server/src/web-tools/routing.ts | 27 +++++++ .../src/ws/bridge-capabilities/web.ts | 33 +++++++- packages/ui-server/src/ws/bridge.ts | 2 +- .../ui-server/tests/fixtures/web-pi-worker.ts | 4 + .../tests/provider-relay-budgets.test.ts | 16 ++++ .../ui-server/tests/web-pi-delivery.test.ts | 9 +++ .../ui-server/tests/web-pi-executor.test.ts | 75 ++++++++++++++++++- .../tests/web-tools-admission.test.ts | 72 ++++++++++++++++++ .../ui-server/tests/web-tools-broker.test.ts | 19 +++++ 22 files changed, 548 insertions(+), 26 deletions(-) create mode 100644 .changeset/3687-web-call-admission.md create mode 100644 packages/ui-server/src/web-tools/recipients.ts create mode 100644 packages/ui-server/src/web-tools/routing.ts create mode 100644 packages/ui-server/tests/web-tools-admission.test.ts diff --git a/.changeset/3687-web-call-admission.md b/.changeset/3687-web-call-admission.md new file mode 100644 index 0000000000..4bf9c0df6e --- /dev/null +++ b/.changeset/3687-web-call-admission.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-backend-pi": minor +--- + +Admit each web provider request for the calling turn. Pi's web tools now check the conversation's provider policy and the turn's budgets before a named provider is called, and again for every request the web executor sends to a provider's API, including extraction fallbacks and nested model calls. A refusal answers `policy_denied` or `budget_exceeded`, and each admitted request counts as unknown spend in the turn, conversation and day budgets, never as zero. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index f815c90599..1623fbd2ec 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1264,6 +1264,7 @@ export "./internal" (./src/internal.ts) type CleanupReconcilerOptions type CompiledWorkerCommandPolicy DEFAULT_TURN_TEMP_BYTES + EgressAdmissionRefused type EgressDestinationPolicy type EgressRecord type EgressRefusal @@ -12989,7 +12990,7 @@ signatures (every public export and the types it is made of) WEB_TOOL_CONTRACTS (packages/ui-sdk/src/tool-contracts/web.ts) const WEB_TOOL_CONTRACTS: readonly ToolContract[]; WEB_TOOL_ERROR_CODES (packages/ui-sdk/src/tool-contracts/web.ts) - const WEB_TOOL_ERROR_CODES: readonly ["invalid_input", "unsupported", "provider_not_admitted", "unavailable", "unknown_handle", "replayed_call", "busy", "request_too_large", "response_too_large", "cancelled", "deadline", "executor_died", "failed"]; + const WEB_TOOL_ERROR_CODES: readonly ["invalid_input", "unsupported", "provider_not_admitted", "unavailable", "unknown_handle", "replayed_call", "busy", "request_too_large", "response_too_large", "cancelled", "deadline", "executor_died", "failed", "policy_denied", "budget_exceeded"]; WEB_TOOL_LIMITS (packages/ui-sdk/src/tool-contracts/web.ts) const WEB_TOOL_LIMITS: Readonly<{ domainChars: 253; diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 3a9f905242..b8e6018665 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -4762,6 +4762,57 @@ choice from the host's configuration and its pinned code. The executor's copy of the configuration sets `ssrf.trustEnvProxy`, so the extension leaves name resolution to the route. +#### Per-call admission of the executor's recipients — built in #3687 + +Item 4 of the bridge design reuses the admission a turn already has. Each +forwarded call carries its turn's authority (`createWebAccess`, +`packages/ui-server/src/ws/bridge-capabilities/web.ts`), built from the +turn's frozen policy, the conversation's recorded exposures and the turn +budgets, never from anything the worker or the executor says: + +- **Recipients.** A web provider is a recipient in the provider policy's + sense, as Apify is. Curated provider ids and the pinned extension's API + hosts name one (`webHostRecipient`, `packages/ui-server/src/web-tools/recipients.ts`). + Vendors that also serve inference keep their inference names, so Gemini is + `google` and OpenAI is `openai`. A host-configured `exaBaseUrl` or + `firecrawlBaseUrl` names its provider too. +- **Where it applies.** A provider the call names is admitted before anything + is dispatched. Every connection the executor opens is attributed to the call + in flight, and one to a provider host is admitted again for that turn + (`admitConnection`, `packages/ui-server/src/web-tools/host.ts`). That covers + the automatic chain, extraction fallbacks such as Jina's reader, and nested + model calls such as Gemini's URL context, which no call field names. A + connection with no call in flight, or one that could belong to two turns, + is refused. The executor opens one connection per request, so a reused TLS + tunnel cannot carry a request the host did not admit. +- **Data routing (G2).** The rules are Apify consent's: nothing leaves for a + recipient from a conversation that has shown it a provider folder the policy + keeps from it, and an exposure the host cannot judge refuses + (`webRoutingRefusal`, `packages/ui-server/src/web-tools/routing.ts`). This + extends ruling 3 of #2695, under which G2 governed only the inference + recipient: a web provider receives text the model wrote, which can quote + any folder the model was shown. +- **Budget.** A blocked scope refuses the request. Each admitted provider + request is recorded as a dispatched relayed attempt with no usage + (`observeWebProvider`, `packages/ui-server/src/brain/turn-budgets.ts`), so + the receipt counts it in `unknownRuns` for the turn, conversation and day, + and never as zero. No web provider reports a price, so none is ever settled. +- **Taint and attribution.** These were already in place since #3685: each + call taints the session before it runs and its result is recorded before + the model receives it, through the turn's input-safety collector, and the + owner sees both in the chat's safety history. Call receipts carry the + principal, session, turn and tool-call id. +- **Outward actions.** The executor performs none. Its configuration turns off + every workflow, command and model mode that would act. A provider request + sends a query or a URL, and a page fetch reads. + +What stays unmetered, stated rather than hidden: pages the call fetches are +egress-policy territory (G5), checked by the route for address, port and +bytes but not for routing; a provider configured by hand outside the curated +catalog is reached as a page, so its routing is not checked and its spend is +not counted; and the receipt's `coverage` text keeps saying that other +provider and tool spend is not metered. + #### Approved host OAuth refresh placement (2026-10-16) The #1665/#1666 maintainer ruling moves stored-login Claude OAuth refresh to diff --git a/docs/integration-contract/mcp.md b/docs/integration-contract/mcp.md index 373e97cea3..b919387902 100644 --- a/docs/integration-contract/mcp.md +++ b/docs/integration-contract/mcp.md @@ -1391,7 +1391,20 @@ message, feature? } }` as a tool error. `text` is external content. The codes (`WEB_TOOL_ERROR_CODES`) are `invalid_input`, `unsupported`, `provider_not_admitted`, `unavailable`, `unknown_handle`, `replayed_call`, `busy`, `request_too_large`, `response_too_large`, `cancelled`, `deadline`, -`executor_died` and `failed`. +`executor_died`, `failed`, and, since #3687, `policy_denied` and +`budget_exceeded`. + +Since #3687 every external recipient a call reaches is admitted for the +calling turn: a provider the call names before anything is dispatched, and +each request the executor sends to a provider's API host while the call runs, +whether a search, an extraction fallback or a nested model call. A +conversation that has shown a provider folder to its model sends no recipient +the provider policy keeps that folder from (`policy_denied`; an exposure the +host cannot judge is refused too), and a blocked budget scope refuses the +request (`budget_exceeded`). Each admitted provider request counts toward the +turn, conversation and day as unknown spend in the budget receipt's +`unknownRuns`, never as zero. Pages the call fetches are checked by the egress +route, not the provider policy. A `responseId` is an opaque handle the host issues. It is scoped to the calling principal and session and to the executor session that stored the diff --git a/packages/ui-backend-pi/README.md b/packages/ui-backend-pi/README.md index 0d30043d87..1387e15a2b 100644 --- a/packages/ui-backend-pi/README.md +++ b/packages/ui-backend-pi/README.md @@ -350,6 +350,12 @@ are refused, and the session's bytes are bounded (64 MiB). The proxy does not intercept TLS, so a guard inside the executor keeps provider keys from following a redirect to another origin. Refused connections are logged with their host, port and reason. A host without bubblewrap has no web executor. + +Each request to a provider's API is admitted for the turn whose call is in +flight, against that conversation's provider policy and the turn's budgets, +and counts as unknown spend. A connection with no call in flight is refused. +The executor opens one connection per request, so a reused tunnel cannot +carry a request the host did not admit. Per-call admission is #3687's second part; subscription and current-model search is #3688. diff --git a/packages/ui-backend-pi/src/web-executor-entry.ts b/packages/ui-backend-pi/src/web-executor-entry.ts index 8889c2cc3d..39cab56619 100644 --- a/packages/ui-backend-pi/src/web-executor-entry.ts +++ b/packages/ui-backend-pi/src/web-executor-entry.ts @@ -50,7 +50,12 @@ const send = (frame: unknown): void => { process.stdout.write(redact(JSON.string let hostConfig: unknown = {}; try { hostConfig = JSON.parse(readFileSync(join(agentDir, "web-search.json"), "utf8")); } catch { /* The executor runs with forced defaults. */ } const credentialNames = WEB_SEARCH_PROVIDERS.flatMap(provider => provider.envVar ? [provider.envVar] : []); -globalThis.fetch = Object.assign(guardCredentialRedirects(globalThis.fetch.bind(globalThis), webCredentialValues(resolveWebSearchEnv(), credentialNames, hostConfig)), +// One request per connection (#3687): the host admits and counts each +// provider request as its egress route admits the connection, and a reused +// TLS tunnel would carry a second request it never saw. +const native = globalThis.fetch.bind(globalThis); +const fresh = (input: string | URL | Request, init?: RequestInit) => native(input, { ...init, keepalive: false }); +globalThis.fetch = Object.assign(guardCredentialRedirects(fresh, webCredentialValues(resolveWebSearchEnv(), credentialNames, hostConfig)), { preconnect: globalThis.fetch.preconnect }) as typeof fetch; const settingsManager = SettingsManager.inMemory({ retry: { enabled: false }, compaction: { enabled: false }, cacheWarming: "off" }); diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index df5defa65b..c6134afef1 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -22,7 +22,7 @@ export { execWrapperSpawnOptions, workerExecHelpers } from "./server/exec-wrappe export { assertScratchMask, assertScratchMaskAsync } from "./server/bridge-tools/mask.js"; export { startInferenceRelay, ANTHROPIC_INFERENCE_ROUTES, INFERENCE_PLACEHOLDER, WORKER_INFERENCE_SOCKET } from "./server/inference-relay.js"; export type { InferenceRelay, InferenceRelayEvent } from "./server/inference-relay.js"; -export { startEgressProxy, egressBootstrapEntry, WORKER_EGRESS_DIR, WORKER_EGRESS_TRANSPORT_ENV } from "./server/egress-proxy.js"; +export { startEgressProxy, egressBootstrapEntry, EgressAdmissionRefused, WORKER_EGRESS_DIR, WORKER_EGRESS_TRANSPORT_ENV } from "./server/egress-proxy.js"; export { startProviderRelay, parseCliProviderOrigins, relayedProviderKeys, heldCustomProviderKeys, PROVIDER_RELAY_KEYS_NAME, providerUsage, FIRST_PARTY_PROVIDER_RECIPIENTS, PROVIDER_RELAY_SOCKET_NAME, WORKER_PROVIDER_RELAY_SOCKET, MAX_PROVIDER_REQUEST_BYTES, type ProviderRelay, type ProviderRelayOptions, type ProviderRelayReceipt, type ProviderRelayRefusal, type ProviderUsage, type ProviderOperation } from "./server/provider-relay.js"; export { hostProviderCredential, hostComputeCredential } from "./config/env.js"; export type { EgressDestinationPolicy, EgressRecord, EgressRefusal } from "./server/egress-proxy.js"; diff --git a/packages/ui-sdk/src/server/egress-proxy.ts b/packages/ui-sdk/src/server/egress-proxy.ts index 3accd457a2..356542d771 100644 --- a/packages/ui-sdk/src/server/egress-proxy.ts +++ b/packages/ui-sdk/src/server/egress-proxy.ts @@ -63,7 +63,8 @@ export interface EgressProxyOptions { /** * A destination passed every check; called before its first upstream byte. * A returned promise is awaited first, so a durable record it makes commits - * before any byte flows; its rejection refuses the connection. + * before any byte flows; its rejection refuses the connection, as + * `call_not_admitted` when it is an {@link EgressAdmissionRefused}. */ admitted?(destination: { host: string; port: number; method: string; inference: boolean; provider: boolean; connectionId: string; protocol?: string }): unknown; /** Synchronous notification only after final admission, immediately before dispatch. */ @@ -137,7 +138,8 @@ function matches(host: string, patterns: readonly string[]): boolean { * appears in either. */ export interface EgressRefusal { - cause: "denied_host" | "not_allowlisted" | "byte_cap" | "taint_allowlist" | "outward_not_approved" | "private_destination" | "destination_port"; + cause: "denied_host" | "not_allowlisted" | "byte_cap" | "taint_allowlist" | "outward_not_approved" | "private_destination" | "destination_port" + | "call_not_admitted"; message: string; } function describeRefusal(reason: string | undefined, host: string, denied: boolean, tainted: string | null | undefined): EgressRefusal | undefined { @@ -156,6 +158,8 @@ function describeRefusal(reason: string | undefined, host: string, denied: boole message: `Blocked: a connection to ${host} acts outside the brain in the user's name, and it was not approved. Do not retry it; say what you needed it for.` }; case "private_destination": case "metadata_destination": case "unresolved_destination": return { cause: "private_destination", message: `Blocked: ${host} is not a public web address. Do not retry it; tell the user.` }; + case "call_not_admitted": return { cause: "call_not_admitted", + message: `Blocked: this call may not send anything to ${host} under this conversation's provider policy or budget. Do not retry it; tell the user.` }; case "destination_port": return { cause: "destination_port", message: `Blocked: ${host} was reached on a port the web route does not allow. Do not retry it; tell the user.` }; default: return undefined; @@ -167,7 +171,17 @@ const REFUSAL_STATUS: Readonly> = { byte_cap: "Forbidden - turn network byte limit reached", taint_allowlist: "Forbidden - untrusted session, host not allowed", outward_not_approved: "Forbidden - outward connection not approved", private_destination: "Forbidden - not a public web address", destination_port: "Forbidden - destination port not allowed", + call_not_admitted: "Forbidden - not admitted for this call", }; + +/** + * Thrown by `admitted` to refuse one connection on the host's own authority + * (#3687): recorded as `denied` with reason `call_not_admitted`, where any + * other failure of the hook is `failed` with `proxy_error`. + */ +export class EgressAdmissionRefused extends Error { + constructor(message = "The host did not admit this connection.") { super(message); this.name = "EgressAdmissionRefused"; } +} /** One refused connection's 403, with its reason when it has one. */ function refusalHead(refusal: EgressRefusal | undefined, reason: string | undefined): { status: string; body: string } | undefined { if (!refusal) return undefined; @@ -291,7 +305,8 @@ export async function startEgressProxy(options: EgressProxyOptions) { } if (!await narrowing()) return false; // A recorder failure aborts the turn through its own signal; it cannot admit. - try { await options.admitted?.({ host, port, method, inference, provider, connectionId, protocol:url.protocol }); } catch { finish("failed", "proxy_error"); return false; } + try { await options.admitted?.({ host, port, method, inference, provider, connectionId, protocol:url.protocol }); } + catch (error) { if (error instanceof EgressAdmissionRefused) finish("denied", "call_not_admitted"); else finish("failed", "proxy_error"); return false; } if (stopped || controller.signal.aborted) { finish("cancelled", "turn_cancelled"); return false; } return true; }; diff --git a/packages/ui-sdk/src/tool-contracts/web.ts b/packages/ui-sdk/src/tool-contracts/web.ts index b1023ae3b7..220044d74f 100644 --- a/packages/ui-sdk/src/tool-contracts/web.ts +++ b/packages/ui-sdk/src/tool-contracts/web.ts @@ -71,6 +71,8 @@ export const WEB_TOOL_LIMITS = Object.freeze({ export const WEB_TOOL_ERROR_CODES = [ "invalid_input", "unsupported", "provider_not_admitted", "unavailable", "unknown_handle", "replayed_call", "busy", "request_too_large", "response_too_large", "cancelled", "deadline", "executor_died", "failed", + // The calling turn's authority refused a recipient (#3687). + "policy_denied", "budget_exceeded", ] as const; export type WebToolErrorCode = (typeof WEB_TOOL_ERROR_CODES)[number]; diff --git a/packages/ui-server/src/brain/turn-budgets.ts b/packages/ui-server/src/brain/turn-budgets.ts index 8f9c8e4f1c..dcb04d9d91 100644 --- a/packages/ui-server/src/brain/turn-budgets.ts +++ b/packages/ui-server/src/brain/turn-budgets.ts @@ -448,6 +448,21 @@ export function createTurnBudgets(db: Database, pricing: RollupPricing, clock: ( return call("observeProvider", turnId, turn?.policy ?? null, attempt, { costUsd: priced.costUsd, estimate: priced.estimate, tokens: priced.tokens }, now, turn ? apifyReading(turnId, now) : null); }, + /** + * One admitted web provider request (#3687): a search, extraction fallback + * or nested model call the host web executor sent for this turn. Its price + * is never reported, so it is recorded as a dispatched relayed attempt + * with no usage: unknown spend in the turn, its session and its day, + * never zero, and never settled into a price. + */ + observeWebProvider(turnId: string, attempt: { attemptId: string; host: string }): Promise { + const turn = active.get(turnId); + const now = clock(); + const recorded = { attemptId: attempt.attemptId, family: "web", operation: "web", origin: `https://${attempt.host}`, model: null, + outcome: "dispatched", status: 0, usage: null, inlineMedia: false }; + return call("observeProvider", turnId, turn?.policy ?? null, recorded, + { costUsd: null, estimate: null, tokens: null }, now, turn ? apifyReading(turnId, now) : null); + }, /** * Hosted external compute (#3108). `reserve` runs under core's admission * lock, after every budget write submitted before it, against the turn's diff --git a/packages/ui-server/src/web-tools/broker.ts b/packages/ui-server/src/web-tools/broker.ts index 322a65dc52..cdf547da83 100644 --- a/packages/ui-server/src/web-tools/broker.ts +++ b/packages/ui-server/src/web-tools/broker.ts @@ -18,6 +18,12 @@ * after the turn stopped being current, is discarded. Each settled call * and each ended executor session leaves a receipt. * + * - Admission (#3687): before a call is dispatched, each provider it names + * is put to the calling turn's own authority (data routing and budget). + * While it runs, every connection its executor opens can be put to the same + * authority through `inFlight`; a refusal there settles the call with the + * authority's code, whatever the executor made of the failed connection. + * * Provider credentials and configuration stay with the executor; the broker * knows only which provider ids the host admits. */ @@ -25,6 +31,7 @@ import { randomBytes } from "node:crypto"; import { parseWebToolInput, webToolProviders, type WebToolCall, type WebToolEnvelope, type WebToolErrorCode, type WebToolName, } from "@schlessera/brain-ui-sdk/tool-contracts"; +import { webProviderRecipient } from "./recipients.js"; /** The authenticated turn's identity for one call, captured by the ws bridge. */ export interface WebCallScope { @@ -36,6 +43,31 @@ export interface WebCallScope { policyRevision: string | null; } +/** Why the calling turn's authority refused a recipient: a web call error code and the words for the model. */ +export interface WebCallRefusal { code: "policy_denied" | "budget_exceeded" | "unavailable"; message: string } + +/** + * The calling turn's own admission for the external recipients one web call + * reaches (#3687). Built by the ws bridge from the authenticated turn, never + * from anything the worker or executor says, and never sent to the executor. + */ +export interface WebCallAuthority { + /** Data routing (G2) and budget admission for one recipient, by its policy name. */ + admit(recipient: string): Promise; + /** One admitted provider request, attributed to the turn: unknown cost, never zero. */ + attempt(event: { recipient: string; host: string; callId: string }): void; +} + +/** A dispatched call, as an executor connection is attributed to it. */ +export interface WebInFlightCall { + callId: string; + tool: WebToolName; + scope: WebCallScope; + authority: WebCallAuthority | undefined; + /** Settle the call as refused by its authority; the first refusal wins. */ + refuse(refusal: WebCallRefusal): void; +} + /** One call as the executor receives it: validated input, host scope, upstream handle substituted. */ export interface WebExecutorRequest { /** Broker-issued, unique per call. */ @@ -131,8 +163,13 @@ interface WebBrokerOptions { } export interface WebBroker { - /** `current` reports whether the calling turn still holds authority. */ - call(scope: WebCallScope, call: WebToolCall, signal: AbortSignal, current: () => boolean): Promise; + /** + * `current` reports whether the calling turn still holds authority; + * `authority` is that turn's admission for the recipients the call reaches. + */ + call(scope: WebCallScope, call: WebToolCall, signal: AbortSignal, current: () => boolean, authority?: WebCallAuthority): Promise; + /** The calls one principal's session has dispatched and not settled, for attributing its executor's connections. */ + inFlight(owner: { principalId: string; sessionId: string }): readonly WebInFlightCall[]; /** Close every executor session and refuse further calls. */ close(): Promise; /** For tests and diagnostics: counts only, no content. */ @@ -150,6 +187,8 @@ interface Owned { idle?: ReturnType; /** Opaque handle -> executor handle, insertion ordered. */ handles: Map; + /** Calls dispatched to this executor session and not yet settled. */ + inFlight: Map; ended: boolean; } @@ -205,6 +244,7 @@ export function createWebBroker(options: WebBrokerOptions): WebBroker { entry.ended = true; if (entry.idle) clearTimeout(entry.idle); entry.handles.clear(); + entry.inFlight.clear(); if (owned.get(entry.key) === entry) owned.delete(entry.key); receipt({ kind: "executor", owner: entry.owner, generation: entry.generation, calls: entry.calls, exit }); wake(); @@ -232,7 +272,7 @@ export function createWebBroker(options: WebBrokerOptions): WebBroker { if (owned.has(key)) return owned.get(key)!; } const entry: Owned = { key, owner, generation: ++generation, session: options.executor.open(owner, lifetime.signal), active: 0, calls: 0, - lastUsed: now(), handles: new Map(), ended: false }; + lastUsed: now(), handles: new Map(), inFlight: new Map(), ended: false }; owned.set(key, entry); entry.session.then(session => session.ended.then(exit => end(entry, exit)), () => end(entry, { reason: "start_failed", pid: null, code: null, signal: null, exited: false })); @@ -246,7 +286,7 @@ export function createWebBroker(options: WebBrokerOptions): WebBroker { return handle; } - async function run(scope: WebCallScope, call: WebToolCall, signal: AbortSignal, current: () => boolean): Promise<{ envelope: WebToolEnvelope; callId: string | null; requestBytes: number; responseBytes: number; queuedMs: number; startedAt: number }> { + async function run(scope: WebCallScope, call: WebToolCall, signal: AbortSignal, current: () => boolean, authority: WebCallAuthority | undefined): Promise<{ envelope: WebToolEnvelope; callId: string | null; requestBytes: number; responseBytes: number; queuedMs: number; startedAt: number }> { const tool = call.tool; const fail = (code: WebToolErrorCode, message: string, feature?: string): WebToolEnvelope => ({ ok: false, tool, error: { code, message, ...(feature ? { feature } : {}) } }); const started = now(); @@ -264,6 +304,14 @@ export function createWebBroker(options: WebBrokerOptions): WebBroker { seen.add(replayKey); while (seen.size > limits.replayWindow) seen.delete(seen.values().next().value!); if (signal.aborted || !current()) return { ...base, requestBytes, envelope: fail("cancelled", "The turn is no longer current.") }; + // Each provider the call names is admitted before anything is queued or sent. + for (const provider of webToolProviders(parsed.input)) { + let refusal: WebCallRefusal | null; + try { refusal = authority ? await authority.admit(webProviderRecipient(provider)) : null; } + catch { refusal = { code: "unavailable", message: "The host could not check this web call's admission; nothing was sent." }; } + if (refusal) return { ...base, requestBytes, envelope: fail(refusal.code, refusal.message) }; + } + if (signal.aborted || !current()) return { ...base, requestBytes, envelope: fail("cancelled", "The turn is no longer current.") }; const owner = { principalId: scope.principalId, sessionId: scope.sessionId }; const key = ownerKey(owner); @@ -278,6 +326,7 @@ export function createWebBroker(options: WebBrokerOptions): WebBroker { catch (error) { return { ...base, requestBytes, envelope: error instanceof Settled ? fail(error.code, error.message) : fail("failed", "The call could not be admitted.") }; } const queuedMs = now() - started; let entry: Owned | undefined; + let dispatched: (() => WebCallRefusal | undefined) | undefined; const callId = `wc_${randomBytes(12).toString("base64url")}`; const controller = new AbortController(); let outcome: Settled | undefined; @@ -292,6 +341,10 @@ export function createWebBroker(options: WebBrokerOptions): WebBroker { return { ...base, callId, requestBytes, queuedMs, envelope: fail("unknown_handle", "That stored web result is no longer available. Run the search or fetch again.") }; } entry.active++; entry.calls++; entry.lastUsed = now(); + let refused: WebCallRefusal | undefined; + const inFlight: WebInFlightCall = { callId, tool, scope, authority, refuse: refusal => { refused ??= refusal; } }; + entry.inFlight.set(callId, inFlight); + dispatched = () => refused; if (entry.idle) clearTimeout(entry.idle); let session: WebExecutorSession; try { session = await entry.session; } @@ -306,6 +359,8 @@ export function createWebBroker(options: WebBrokerOptions): WebBroker { const result = await Promise.race([session.call({ callId, tool, input, scope }, controller.signal), stopped]); // No late or cross-turn result: re-check liveness before any data returns. if (outcome) throw outcome; + const refusal = dispatched?.(); + if (refusal) return { ...base, callId, requestBytes, queuedMs, envelope: fail(refusal.code, refusal.message) }; if (signal.aborted || !current()) throw new Settled("cancelled", "The turn stopped being current before the result returned; it was discarded."); if (!result.ok) return { ...base, callId, requestBytes, queuedMs, envelope: fail(result.code, result.message, result.feature) }; const responseBytes = bytes(result.text); @@ -331,14 +386,14 @@ export function createWebBroker(options: WebBrokerOptions): WebBroker { signal.removeEventListener("abort", onAbort); controller.abort(new Settled("cancelled", "settled")); active--; - if (entry) { entry.active--; entry.lastUsed = now(); scheduleIdle(entry); } + if (entry) { if (dispatched) entry.inFlight.delete(callId); entry.active--; entry.lastUsed = now(); scheduleIdle(entry); } wake(); } } return { - async call(scope, call, signal, current) { - const ran = await run(scope, call, signal, current); + async call(scope, call, signal, current, authority) { + const ran = await run(scope, call, signal, current, authority); receipt({ kind: "call", callId: ran.callId, tool: call.tool, scope, outcome: ran.envelope.ok ? "completed" : ran.envelope.error.code, requestBytes: ran.requestBytes, responseBytes: ran.responseBytes, queuedMs: ran.queuedMs, durationMs: now() - ran.startedAt }); return ran.envelope; @@ -349,6 +404,7 @@ export function createWebBroker(options: WebBrokerOptions): WebBroker { for (const waiter of queue.splice(0)) waiter.reject(new Settled("unavailable", "The host closed its web tools.")); await Promise.allSettled([...owned.values()].map(entry => retire(entry, "closed"))); }, + inFlight: owner => [...owned.get(ownerKey(owner))?.inFlight.values() ?? []], stats: () => ({ active, queued: queue.length, sessions: owned.size, handles: [...owned.values()].reduce((sum, entry) => sum + entry.handles.size, 0) }), }; } diff --git a/packages/ui-server/src/web-tools/host.ts b/packages/ui-server/src/web-tools/host.ts index 45078c1d26..0d36703dee 100644 --- a/packages/ui-server/src/web-tools/host.ts +++ b/packages/ui-server/src/web-tools/host.ts @@ -12,10 +12,18 @@ * An explicit `provider` is admitted only when it is in the host's configured * chain (or override) and has a credential the executor can use: the same * set the Settings card and the brief report. + * + * Every connection the executor opens is attributed to the call in flight + * (#3687). With none in flight it is refused: nothing the executor sends then + * belongs to a turn. A connection to a provider's API host, a search, an + * extraction fallback or a nested model call alike, is put to that call's + * authority, which checks data routing and budget and counts it at unknown + * cost; a refusal settles the call with the authority's code. */ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs"; -import { startEgressProxy, webSearchBrief, type EgressDestinationPolicy, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; -import { createWebBroker, type WebBroker, type WebBrokerLimits, type WebReceipt } from "./broker.js"; +import { EgressAdmissionRefused, startEgressProxy, webSearchBrief, type EgressDestinationPolicy, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; +import { createWebBroker, type WebBroker, type WebBrokerLimits, type WebCallRefusal, type WebReceipt } from "./broker.js"; +import { configuredWebHosts, webHostRecipient } from "./recipients.js"; import { createChildWebExecutor } from "./child-executor.js"; /** What ui-server uses of the pi backend's internal entry, mirrored structurally. */ @@ -73,19 +81,47 @@ function admittedWebProviders(config: Record, env: Readonly provider.id); } +/** + * Admit one executor connection for the call it belongs to. Calls of one + * session normally share its turn; a connection that could belong to two + * turns is attributed to neither and refused. + */ +/** @internal Exported for its unit test. */ +export async function admitConnection(broker: WebBroker, owner: { principalId: string; sessionId: string }, host: string, configured: ReadonlyMap): Promise { + const calls = broker.inFlight(owner); + if (!calls.length) throw new EgressAdmissionRefused("No web call is running for this conversation."); + const recipient = webHostRecipient(host, configured); + // A page the call fetches: its address and bytes are the route's to check. + if (recipient === undefined) return; + if (new Set(calls.map(call => call.scope.turnId)).size !== 1) throw new EgressAdmissionRefused("This connection could belong to more than one turn."); + const [call] = calls as [typeof calls[number]]; + if (!call.authority) return; + let refusal: WebCallRefusal | null; + try { refusal = await call.authority.admit(recipient); } + catch { refusal = { code: "unavailable", message: "The host could not check this web call's admission; nothing more was sent." }; } + if (refusal) { + for (const each of calls) each.refuse(refusal); + throw new EgressAdmissionRefused(refusal.message); + } + call.authority.attempt({ recipient, host, callId: call.callId }); +} + export function createHostWebTools(options: HostWebToolsOptions): WebBroker { // A crash leaves session directories behind; nothing can still own them now. rmSync(options.root, { recursive: true, force: true }); mkdirSync(options.root, { recursive: true, mode: 0o700 }); const credentialEnv = Object.fromEntries(Object.entries(options.env).filter(([name]) => !["PI_CODING_AGENT_DIR", "XDG_CONFIG_HOME", "HOME"].includes(name))); - return createWebBroker({ + const broker: WebBroker = createWebBroker({ executor: createChildWebExecutor({ - launch: async () => { + launch: async owner => { const configPath = options.hostConfigPath(); + const config = readHostConfig(configPath); + const providerHosts = configuredWebHosts(config); // The executor's whole network: a host proxy that resolves and checks every destination. const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: options.maxEgressBytes ?? DEFAULT_MAX_EGRESS_BYTES, - destinations: { allowRanges: hostAllowRanges(readHostConfig(configPath)), ...(options.lookup ? { lookup: options.lookup } : {}), + destinations: { allowRanges: hostAllowRanges(config), ...(options.lookup ? { lookup: options.lookup } : {}), ...(options.egressPorts ? { ports: options.egressPorts } : {}) }, + admitted: destination => admitConnection(broker, owner, destination.host, providerHosts), observe: record => { try { options.onEgress?.(record); } catch { /* A recorder cannot hold a connection open. */ } } }); try { const state = options.module.prepareWebExecutorState({ root: options.root, hostConfigPath: configPath, credentialEnv, path: options.path }); @@ -102,4 +138,5 @@ export function createHostWebTools(options: HostWebToolsOptions): WebBroker { ...(options.limits ? { limits: options.limits } : {}), ...(options.onReceipt ? { onReceipt: options.onReceipt } : {}), }); + return broker; } diff --git a/packages/ui-server/src/web-tools/recipients.ts b/packages/ui-server/src/web-tools/recipients.ts new file mode 100644 index 0000000000..e8581e0012 --- /dev/null +++ b/packages/ui-server/src/web-tools/recipients.ts @@ -0,0 +1,71 @@ +/** + * Who receives what a web call sends (#3687): the provider policy's name for + * each curated web provider, and for each API host the pinned extension + * reaches on its behalf. + * + * A web search sends the model's query, and an extraction fallback sends the + * URL, to a third party. That party is a recipient in the provider policy's + * sense (G2), as Apify is (`APIFY_RECIPIENT`): a conversation that has shown + * it a provider folder it may not receive sends it nothing. Vendors that also + * serve inference keep the names the inference recipients use + * (`FIRST_PARTY_RECIPIENT_ORIGINS`), so one policy rule names one company. + * + * Every other host a call reaches is a page the call fetches. Pages are + * egress-policy territory (G5): the route checks their addresses and bytes, + * not their routing. A provider the curated catalog does not list, configured + * by hand, is reached as a page too; its spend is not counted and its routing + * is not checked, and the decision record says so. + */ + +/** Curated provider id (`WEB_SEARCH_PROVIDERS`) to provider-policy recipient. */ +const PROVIDER_RECIPIENTS: Readonly> = Object.freeze({ + exa: "exa", duckduckgo: "duckduckgo", brave: "brave", jina: "jina", perplexity: "perplexity", tavily: "tavily", + openai: "openai", gemini: "google", firecrawl: "firecrawl", kagi: "kagi", +}); + +/** + * The API hosts of the pinned extension (pi-web-access 0.41.0) for those + * providers and its extraction fallbacks, to their recipient. Exact names: + * a page on a vendor's other hosts is still a page. + */ +const HOST_RECIPIENTS: Readonly> = Object.freeze({ + "api.exa.ai": "exa", "mcp.exa.ai": "exa", + "html.duckduckgo.com": "duckduckgo", + "api.search.brave.com": "brave", + // Jina search, and the reader the extraction fallback sends a page's URL to. + "s.jina.ai": "jina", "r.jina.ai": "jina", + "api.perplexity.ai": "perplexity", + "api.tavily.com": "tavily", + "api.openai.com": "openai", + // Gemini search, URL context and PDF extraction: nested model calls. + "generativelanguage.googleapis.com": "google", + // Kagi's API shares its host with its site: every connection there counts as Kagi's. + "kagi.com": "kagi", +}); + +/** Host config keys that move a provider's API to another origin; Firecrawl has no default one. */ +const BASE_URL_RECIPIENTS: Readonly> = Object.freeze({ exaBaseUrl: "exa", firecrawlBaseUrl: "firecrawl" }); + +/** The recipient a curated provider id names. An id outside the table names itself, which no policy rule allows by accident. */ +export function webProviderRecipient(provider: string): string { + return Object.hasOwn(PROVIDER_RECIPIENTS, provider) ? PROVIDER_RECIPIENTS[provider]! : provider; +} + +const hostName = (host: string) => host.toLowerCase().replace(/\.$/u, ""); + +/** The API hosts the host-owned configuration moves a provider to, by recipient. */ +export function configuredWebHosts(config: Readonly>): ReadonlyMap { + const hosts = new Map(); + for (const [key, recipient] of Object.entries(BASE_URL_RECIPIENTS)) { + const value = config[key]; + if (typeof value !== "string") continue; + try { hosts.set(hostName(new URL(value).hostname), recipient); } catch { /* Not a URL: the extension refuses it too. */ } + } + return hosts; +} + +/** The recipient an executor connection's host is, or undefined for a page. */ +export function webHostRecipient(host: string, configured: ReadonlyMap = new Map()): string | undefined { + const name = hostName(host); + return configured.get(name) ?? (Object.hasOwn(HOST_RECIPIENTS, name) ? HOST_RECIPIENTS[name] : undefined); +} diff --git a/packages/ui-server/src/web-tools/routing.ts b/packages/ui-server/src/web-tools/routing.ts new file mode 100644 index 0000000000..148d8da39d --- /dev/null +++ b/packages/ui-server/src/web-tools/routing.ts @@ -0,0 +1,27 @@ +/** + * Data routing (G2) for one web recipient (#3687), by the rules Apify's + * consent applies (`routingGate`, `packages/common/src/apify/consent.ts`): + * nothing leaves for a recipient from a conversation that has shown it a + * provider folder the policy does not let it receive. A recipient no rule + * restricts is admitted; one whose exposure cannot be judged here is refused, + * since an unknown never becomes clean. + */ +import type { EffectiveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import { exposureConflicts, providerDeniedFolders, unsupportedProviderSelectors, type ProviderExposure } from "../brain/governance-policy.js"; +import type { WebCallRefusal } from "./broker.js"; + +export function webRoutingRefusal(policy: Pick, typeFolders: Readonly> | undefined, + exposures: readonly ProviderExposure[] | undefined, recipient: string): WebCallRefusal | null { + const restricting = policy.providers.filter(rule => !rule.allow.includes(recipient)); + if (!restricting.length) return null; + const selectsTypes = restricting.some(rule => rule.types?.length); + // A selector no folder mask can express cannot be checked against exposures either. + if (!exposures || unsupportedProviderSelectors({ providers: restricting }).length || (selectsTypes && !typeFolders)) { + return { code: "policy_denied", message: `The provider policy restricts folders for ${recipient}, and this conversation's exposure to them is unknown here, so nothing was sent to it.` }; + } + const denied = providerDeniedFolders(policy, typeFolders ?? {}, recipient); + if (exposureConflicts(exposures, denied).length) { + return { code: "policy_denied", message: `This conversation has shown folders the provider policy does not allow ${recipient} to receive, so nothing was sent to it. Start a new conversation for this web work, or use another provider.` }; + } + return null; +} diff --git a/packages/ui-server/src/ws/bridge-capabilities/web.ts b/packages/ui-server/src/ws/bridge-capabilities/web.ts index 31e53cb907..0a49d020a4 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/web.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/web.ts @@ -1,5 +1,8 @@ import type { BridgeContext, BridgeSlice, MakeBridgeOptions } from "./context.js"; import type { TurnTranscript } from "./emission.js"; +import { BudgetExceeded } from "../../brain/turn-budgets.js"; +import type { WebCallAuthority, WebCallRefusal } from "../../web-tools/broker.js"; +import { webRoutingRefusal } from "../../web-tools/routing.js"; /** * The host-owned web tools (#3685): Pi's governed and strict interactive @@ -8,12 +11,36 @@ import type { TurnTranscript } from "./emission.js"; * cancellation signal are this turn's, captured here; the call carries its tool, parsed input and the model's call id. * Liveness is checked by the live-authority wrapper before dispatch and by * the broker again before any result returns. + * + * Each call also carries this turn's authority over the recipients it + * reaches (#3687): data routing under the turn's frozen provider policy and + * the conversation's recorded exposures, then the turn's budgets, which + * refuse once a scope is blocked and count each admitted provider request at + * unknown cost. A turn without a frozen policy admits no recipient. */ export function createWebAccess(ctx: Pick, - transcript: Pick, governance: MakeBridgeOptions["governance"]): Partial> { + transcript: Pick, governance: MakeBridgeOptions["governance"], + providerMasks?: MakeBridgeOptions["providerMasks"]): Partial> { const { host, turn, turnId, principalId, signal, backendId, workerProfile, current, recordingAvailable } = ctx; const broker = host.webTools; if (!broker || backendId !== "pi") return {}; + const authority = (sessionId: string): WebCallAuthority => ({ + async admit(recipient): Promise { + if (!governance) return { code: "policy_denied", message: "This turn has no frozen governance policy, so no web provider could be admitted." }; + const exposures = host.governedTurns ? await host.governedTurns.exposures([sessionId]) : undefined; + const routed = webRoutingRefusal(governance.policy.policy, providerMasks?.typeFolders, exposures, recipient); + if (routed) return routed; + if (!host.budgets) return null; + try { + const blocked = await host.budgets.providerAdmission(turnId, governance.policy.policy); + return blocked ? { code: "budget_exceeded", message: new BudgetExceeded(blocked, "mid_turn").message } : null; + } catch { return { code: "unavailable", message: "Budget accounting is unavailable for this turn, so nothing was sent." }; } + }, + attempt(event) { + // A failed write leaves the turn's accounting to refuse its next admission. + void host.budgets?.observeWebProvider(turnId, { attemptId: `web:${event.callId}:${crypto.randomUUID()}`, host: event.host }).catch(() => {}); + }, + }); return { async webAccess(call) { const sessionId = transcript.collectedSessionId ?? turn.sessionId ?? null; @@ -23,8 +50,8 @@ export function createWebAccess(ctx: Pick current() && recordingAvailable()); + // qualified input recording must both still hold when a result returns. + call, signal, () => current() && recordingAvailable(), authority(sessionId)); }, }; } diff --git a/packages/ui-server/src/ws/bridge.ts b/packages/ui-server/src/ws/bridge.ts index 575c5d0144..bcb16c78b0 100644 --- a/packages/ui-server/src/ws/bridge.ts +++ b/packages/ui-server/src/ws/bridge.ts @@ -74,7 +74,7 @@ export async function makeBridge(host: WsHost, turn: RunningTurn, options: MakeB if (host.referenceTools) bridge.referenceAccess = call => host.referenceTools!.call(ctx.turnId, ctx.principalId, call, ctx.signal); applyExternalServices(ctx, bridge, transcript, options.governance); Object.assign(bridge, createAttachmentRead(ctx, transcript)); - Object.assign(bridge, createWebAccess(ctx, transcript, options.governance)); + Object.assign(bridge, createWebAccess(ctx, transcript, options.governance, options.providerMasks)); guardMaskedRecords(ctx, bridge); if (ctx.backendId === "claude" || ctx.backendId === "pi") applyLiveAuthority(ctx, bridge); if (host.activity?.governanceDb) { diff --git a/packages/ui-server/tests/fixtures/web-pi-worker.ts b/packages/ui-server/tests/fixtures/web-pi-worker.ts index acbf7280a7..9038f8f2e9 100644 --- a/packages/ui-server/tests/fixtures/web-pi-worker.ts +++ b/packages/ui-server/tests/fixtures/web-pi-worker.ts @@ -47,6 +47,10 @@ async function run(mode: string, detail: string) { if (found?.responseId) await call(1, "get_search_content", { responseId: found.responseId, queryIndex: 0 }); await call(2, "fetch_content", { url: detail }); await call(3, "source_check", { claim: "The raft reaches Ithaca at dawn" }); + } else if (mode === "host-explicit") { + // A provider named outright (#3687), then a page. + await call(0, "web_search", { query: "Odysseus mast", provider: "exa" }); + await call(1, "fetch_content", { url: detail }); } else if (mode === "host-slow") await call(0, "web_search", { query: "slow Odysseus mast" }); else if (mode === "forged") await call(0, "web_search", { query: "Odysseus mast" }, true); else if (mode === "unsupported") { diff --git a/packages/ui-server/tests/provider-relay-budgets.test.ts b/packages/ui-server/tests/provider-relay-budgets.test.ts index cc1049ca2d..d1ee05dafa 100644 --- a/packages/ui-server/tests/provider-relay-budgets.test.ts +++ b/packages/ui-server/tests/provider-relay-budgets.test.ts @@ -160,3 +160,19 @@ test("an attempt that settles after midnight counts toward the day it settled in expect((await f.budgets.providerAdmission(null, policy()))?.scope, "SETTLED_ATTEMPT_ON_ITS_SETTLEMENT_DAY").toBe("day"); } finally { f.close(); } }); + +test("an admitted web provider request is unknown spend in every scope, never zero and never priced (#3687)", async () => { + const f = fixture(); + try { + await f.budgets.begin("athena", "ithaca", policy()); + const before = f.budgets.receipt("athena").scopes.map(scope => scope.unknownRuns); + const result = (await f.budgets.observeWebProvider("athena", { attemptId: "web:call-1:a", host: "api.exa.ai" }))!; + expect(result.receipt.scopes.map(scope => scope.unknownRuns), "WEB_PROVIDER_UNKNOWN_SPEND").toEqual(before.map(count => count + 1)); + expect(result.receipt.scopes.map(scope => scope.costUsd), "WEB_PROVIDER_NOT_ZERO").toEqual([null, null, null]); + // The same attempt recorded twice still counts once. + expect(await f.budgets.observeWebProvider("athena", { attemptId: "web:call-1:a", host: "api.exa.ai" })).toBeUndefined(); + expect(f.budgets.receipt("athena").scopes[0]!.unknownRuns).toBe(before[0]! + 1); + // Unknown spend never blocks by itself: the next request is admitted. + expect(await f.budgets.providerAdmission("athena", policy())).toBeUndefined(); + } finally { f.close(); } +}); diff --git a/packages/ui-server/tests/web-pi-delivery.test.ts b/packages/ui-server/tests/web-pi-delivery.test.ts index c02f7c5991..ba6a9c4747 100644 --- a/packages/ui-server/tests/web-pi-delivery.test.ts +++ b/packages/ui-server/tests/web-pi-delivery.test.ts @@ -20,6 +20,7 @@ import { openSqliteWriter } from "../src/db/write-worker"; import { createGovernanceWrites } from "../src/governance/event-writes"; import { createSafetyCollector } from "../src/governance/safety-collector"; import { safetyCatalogCreated, safetyRecords } from "../src/governance/safety-store"; +import { SafetyHistory } from "../src/governance/safety-history"; import { createWebBroker } from "../src/web-tools/broker"; import { createChildWebExecutor } from "../src/web-tools/child-executor"; import { createWebAccess } from "../src/ws/bridge-capabilities/web"; @@ -97,6 +98,14 @@ test("installed Pi records a forwarded web result before the next provider reque expect(safetyRecords(db, "ithaca").filter(record => record.kind === "occurrence").map(record => (record.payload as { source: string; tool: string })), "WEB_RESULT_TAINTS_SESSION").toEqual([expect.objectContaining({ source: "web_search", tool: "web_search" })]); expect(writes.safety(null, "ithaca").coverage.state, "WEB_RECORDING_COVERAGE_COMPLETE").toBe("complete"); + // The owner sees it where every other taint shows: the chat's safety history (#3687). + const history = new SafetyHistory(db, () => true, () => writer.idle()); + try { + const page = await history.read({ id: "odysseus" } as never, { sessionId: "ithaca" }); + expect(page.records.filter(record => record.kind === "occurrence").map(record => ({ detector: (record as { detector?: string }).detector, source: (record as { source?: string }).source })), + "WEB_TAINT_IN_SAFETY_HISTORY").toEqual([{ detector: "tool_web_input", source: "web_search" }]); + expect(page.projection.restriction, "WEB_TAINT_RESTRICTS_THE_SESSION").toBe("restricted"); + } finally { history.close(); } } finally { controller.abort(); for (const session of sessions) { await session.abort(); session.dispose(); } diff --git a/packages/ui-server/tests/web-pi-executor.test.ts b/packages/ui-server/tests/web-pi-executor.test.ts index 8c6b4b92bf..9664a20fbb 100644 --- a/packages/ui-server/tests/web-pi-executor.test.ts +++ b/packages/ui-server/tests/web-pi-executor.test.ts @@ -102,7 +102,9 @@ function executorPids(): number[] { }); } -async function piTurn(prompt: string, options: { abortWhen?: () => boolean; onTick?: () => void } = {}) { +/** What the turn's authority reads (#3687): its frozen provider policy, the conversation's exposures and the budgets. */ +interface TurnAuthority { providers?: unknown[]; exposures?: unknown[]; budgets?: unknown } +async function piTurn(prompt: string, options: { abortWhen?: () => boolean; onTick?: () => void; authority?: TurnAuthority } = {}) { const previous = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = join(root, "agent"); const controller = new AbortController(), frames: ServerMessage[] = []; @@ -121,9 +123,13 @@ async function piTurn(prompt: string, options: { abortWhen?: () => boolean; onTi try { const backend = createPiBackend({ brainPath: brain, sessionDir: join(root, "sessions") }); const turnId = `odysseus-web-${Math.random().toString(36).slice(2)}`; - const web = createWebAccess({ host: { webTools: broker }, turn: { sessionId: "s-ithaca" }, turnId, principalId: "p-penelope", signal: controller.signal, + const authority = options.authority ?? {}; + const host = { webTools: broker, ...(authority.exposures ? { governedTurns: { exposures: async () => authority.exposures } } : {}), + ...(authority.budgets ? { budgets: authority.budgets } : {}) }; + const web = createWebAccess({ host, turn: { sessionId: "s-ithaca" }, turnId, principalId: "p-penelope", signal: controller.signal, backendId: "pi", workerProfile: { origin: "interactive", actualProfile: "governed" }, current: () => !controller.signal.aborted, - recordingAvailable: () => true } as never, { collectedSessionId: "s-ithaca" }, { policy: { hash: "rev-odyssey" } } as never); + recordingAvailable: () => true } as never, { collectedSessionId: "s-ithaca" }, + { policy: { hash: "rev-odyssey", policy: { providers: authority.providers ?? [] } } } as never); await backend.startTurn({ prompt, signal: controller.signal, turnId, workerSandbox: { brain, profile: "governed", restricted: false, areas: [], scratchAliasesRemoved: [] }, bridge: { @@ -257,3 +263,66 @@ test("redirects to metadata or private addresses are refused at the route, and a // An ordinary search on the same session still works. expect((await call("after", "web_search", { query: "Odysseus mast" })).ok).toBe(true); }); + +/** The turn budgets as the web authority uses them: admission, then each provider request at unknown cost. */ +function recordingBudgets(blocked?: Record) { + const attempts: Array<{ turnId: string; host: string; attemptId: string }> = []; + return { attempts, budgets: { + providerAdmission: async () => blocked, + observeWebProvider: async (turnId: string, attempt: { attemptId: string; host: string }) => { attempts.push({ turnId, ...attempt }); return undefined; }, + } }; +} +/** A provider rule that keeps `notes/` from every web recipient, and a conversation whose earlier turn showed `notes/` to its model. */ +const NOTES_FOR_NO_ONE = { providers: [{ paths: ["notes/**"], allow: ["anthropic"] }], + exposures: [{ recipient: "anthropic", visible: ["notes"], hidden: [] }] }; + +test("each provider request is admitted for its turn and counted at unknown cost; a page is not a provider request (#3687)", async () => { + startBroker(); + const { attempts, budgets } = recordingBudgets(); + const envelopes = await piTurn(`host\n${pagesOrigin()}/ithaca/log`, { authority: { budgets } }); + expect(envelopes.map(envelope => `${envelope.tool}:${envelope.ok}`)).toEqual(["web_search:true", "get_search_content:true", "fetch_content:true", "source_check:true"]); + // Every request the provider received was admitted and recorded first, and nothing else was. + expect(providerRequests.length).toBeGreaterThanOrEqual(2); + expect(attempts.map(attempt => attempt.host), "WEB_PROVIDER_REQUESTS_COUNTED").toEqual(providerRequests.map(() => "exa.odysseus.test")); + expect(new Set(attempts.map(attempt => attempt.turnId)).size, "WEB_PROVIDER_REQUESTS_ATTRIBUTED_TO_THE_TURN").toBe(1); + expect(attempts[0]!.turnId).toStartWith("odysseus-web-"); + expect(new Set(attempts.map(attempt => attempt.attemptId)).size).toBe(attempts.length); + // The page was reached, and is not counted as provider spend. + expect(egress.some(record => record.host === "harbour.odysseus.test" && record.outcome === "completed")).toBe(true); +}); + +test("a conversation that showed a folder to its model sends no web provider what the policy keeps from it (#3687)", async () => { + startBroker(); + const { attempts, budgets } = recordingBudgets(); + const envelopes = await piTurn(`host\n${pagesOrigin()}/ithaca/log`, { authority: { ...NOTES_FOR_NO_ONE, budgets } }); + const search = envelopes.find(envelope => envelope.tool === "web_search"); + // The automatic chain reaches Exa from inside the executor: refused at the connection, before a byte. + expect(search?.error?.code, "WEB_ROUTING_REFUSED_AT_CONNECTION").toBe("policy_denied"); + expect(search?.error?.message).toContain("exa"); + expect(providerRequests, "WEB_ROUTING_NOTHING_SENT").toEqual([]); + expect(attempts).toEqual([]); + expect(egress.some(record => record.host === "exa.odysseus.test" && record.outcome === "denied" && record.reason === "call_not_admitted")).toBe(true); + // A page is the route's to check, not the provider policy's. + expect(envelopes.find(envelope => envelope.tool === "fetch_content")?.ok, "WEB_ROUTING_PAGES_UNAFFECTED").toBe(true); +}); + +test("an explicitly named provider is refused before anything is dispatched (#3687)", async () => { + startBroker(); + const envelopes = await piTurn(`host-explicit\n${pagesOrigin()}/ithaca/log`, { authority: NOTES_FOR_NO_ONE }); + expect(envelopes[0]?.error?.code, "WEB_ROUTING_REFUSED_BEFORE_DISPATCH").toBe("policy_denied"); + expect(receipts.find(receipt => receipt.kind === "call" && receipt.tool === "web_search"), "no call id: nothing was dispatched") + .toMatchObject({ outcome: "policy_denied", callId: null }); + expect(providerRequests).toEqual([]); +}); + +test("a blocked budget scope refuses the next provider request with the budget's own words (#3687)", async () => { + startBroker(); + const blocked = { scope: "turn", costUsd: 2, blockUsd: 1, tokens: 900, blockTokens: 1_000, blocked: true }; + const { attempts, budgets } = recordingBudgets(blocked); + const envelopes = await piTurn(`host\n${pagesOrigin()}/ithaca/log`, { authority: { budgets } }); + const search = envelopes.find(envelope => envelope.tool === "web_search"); + expect(search?.error?.code, "WEB_BUDGET_REFUSED").toBe("budget_exceeded"); + expect(search?.error?.message).toContain("Turn inference budget reached"); + expect(providerRequests).toEqual([]); + expect(attempts).toEqual([]); +}); diff --git a/packages/ui-server/tests/web-tools-admission.test.ts b/packages/ui-server/tests/web-tools-admission.test.ts new file mode 100644 index 0000000000..c61a159562 --- /dev/null +++ b/packages/ui-server/tests/web-tools-admission.test.ts @@ -0,0 +1,72 @@ +/** + * Web call admission (#3687): who receives a web call's content, whether the + * conversation may send it there (G2), and how an executor connection is + * attributed to the call in flight. The real executor proves the same rules + * end to end (`web-pi-executor.test.ts`); these are the cases it cannot reach. + */ +import { expect, test } from "bun:test"; +import { EgressAdmissionRefused } from "@schlessera/brain-ui-sdk/internal"; +import type { WebBroker, WebCallAuthority, WebCallRefusal, WebCallScope, WebInFlightCall } from "../src/web-tools/broker.js"; +import { admitConnection } from "../src/web-tools/host.js"; +import { configuredWebHosts, webHostRecipient, webProviderRecipient } from "../src/web-tools/recipients.js"; +import { webRoutingRefusal } from "../src/web-tools/routing.js"; + +test("each curated provider and its API hosts name one recipient; anything else is a page", () => { + expect(["exa", "duckduckgo", "brave", "jina", "perplexity", "tavily", "openai", "gemini", "firecrawl", "kagi"].map(webProviderRecipient)) + .toEqual(["exa", "duckduckgo", "brave", "jina", "perplexity", "tavily", "openai", "google", "firecrawl", "kagi"]); + expect(webProviderRecipient("serper"), "an uncatalogued id names itself, which no rule allows by accident").toBe("serper"); + expect(webHostRecipient("api.exa.ai")).toBe("exa"); + expect(webHostRecipient("R.JINA.AI."), "WEB_READER_FALLBACK_IS_JINA").toBe("jina"); + expect(webHostRecipient("generativelanguage.googleapis.com"), "WEB_NESTED_MODEL_IS_GOOGLE").toBe("google"); + expect(webHostRecipient("harbour.ithaca.example")).toBeUndefined(); + expect(webHostRecipient("exa.ai"), "a vendor's other host is a page").toBeUndefined(); + const configured = configuredWebHosts({ exaBaseUrl: "https://exa.odysseus.test:8443", firecrawlBaseUrl: "https://crawl.odysseus.test", jinaApiKey: "x" }); + expect(webHostRecipient("exa.odysseus.test", configured), "WEB_CONFIGURED_BASE_URL").toBe("exa"); + expect(webHostRecipient("crawl.odysseus.test", configured)).toBe("firecrawl"); + expect(configuredWebHosts({ exaBaseUrl: "not a url" }).size).toBe(0); +}); + +test("data routing: unrestricted, allowed, unproven and conflicting recipients", () => { + const rule = { paths: ["notes/**"], allow: ["anthropic", "exa"] }; + const shown = [{ recipient: "anthropic", visible: ["notes"], hidden: [] }]; + expect(webRoutingRefusal({ providers: [] }, undefined, undefined, "brave"), "no rule restricts anything").toBeNull(); + expect(webRoutingRefusal({ providers: [rule] }, undefined, shown, "exa"), "a recipient the rule allows").toBeNull(); + expect(webRoutingRefusal({ providers: [rule] }, undefined, shown, "brave")?.code, "WEB_ROUTING_CONFLICT").toBe("policy_denied"); + expect(webRoutingRefusal({ providers: [rule] }, undefined, [{ recipient: "anthropic", visible: ["notes"], hidden: ["notes"] }], "brave"), + "a folder that stayed masked was never shown").toBeNull(); + expect(webRoutingRefusal({ providers: [rule] }, undefined, [], "brave"), "nothing shown yet").toBeNull(); + // An unknown never becomes clean. + expect(webRoutingRefusal({ providers: [rule] }, undefined, undefined, "brave")?.code, "WEB_ROUTING_EXPOSURE_UNKNOWN").toBe("policy_denied"); + expect(webRoutingRefusal({ providers: [{ paths: ["notes/*.md"], allow: [] }] }, undefined, [], "brave")?.code, "WEB_ROUTING_UNEXPRESSIBLE_SELECTOR").toBe("policy_denied"); + expect(webRoutingRefusal({ providers: [{ paths: [], types: ["journal"], allow: [] }] }, undefined, [], "brave")?.code, "WEB_ROUTING_TYPES_UNTRANSLATED").toBe("policy_denied"); + expect(webRoutingRefusal({ providers: [{ paths: [], types: ["journal"], allow: [] }] }, { journal: ["journal"] }, shown, "brave")).toBeNull(); +}); + +const scope = (turnId: string): WebCallScope => ({ principalId: "p-penelope", sessionId: "s-ithaca", turnId, toolCallId: "t1", profile: "governed", policyRevision: null }); +function inFlight(turnId: string, refusal: WebCallRefusal | null, log: string[]): WebInFlightCall { + const authority: WebCallAuthority = { admit: async recipient => { log.push(`admit:${recipient}`); return refusal; }, attempt: event => { log.push(`attempt:${event.host}:${event.callId}`); } }; + return { callId: `call-${turnId}`, tool: "web_search", scope: scope(turnId), authority, refuse: given => { log.push(`refused:${given.code}`); } }; +} +const brokerWith = (calls: WebInFlightCall[]) => ({ inFlight: () => calls }) as unknown as WebBroker; +const owner = { principalId: "p-penelope", sessionId: "s-ithaca" }; + +test("an executor connection belongs to the call in flight, or is refused", async () => { + const log: string[] = []; + await expect(admitConnection(brokerWith([]), owner, "harbour.ithaca.example", new Map()), "WEB_NO_CALL_NO_CONNECTION").rejects.toBeInstanceOf(EgressAdmissionRefused); + await admitConnection(brokerWith([inFlight("turn-1", null, log)]), owner, "harbour.ithaca.example", new Map()); + expect(log, "a page asks no authority").toEqual([]); + await admitConnection(brokerWith([inFlight("turn-1", null, log), inFlight("turn-1", null, log)]), owner, "api.exa.ai", new Map()); + expect(log, "WEB_PROVIDER_ADMITTED_AND_COUNTED_ONCE").toEqual(["admit:exa", "attempt:api.exa.ai:call-turn-1"]); + log.length = 0; + await expect(admitConnection(brokerWith([inFlight("turn-1", null, log), inFlight("turn-2", null, log)]), owner, "api.exa.ai", new Map()), + "WEB_AMBIGUOUS_TURN_REFUSED").rejects.toBeInstanceOf(EgressAdmissionRefused); + expect(log).toEqual([]); + const denied = { code: "budget_exceeded" as const, message: "Turn inference budget reached." }; + await expect(admitConnection(brokerWith([inFlight("turn-1", denied, log), inFlight("turn-1", denied, log)]), owner, "api.exa.ai", new Map())).rejects.toBeInstanceOf(EgressAdmissionRefused); + expect(log, "WEB_REFUSAL_SETTLES_EVERY_CALL_IN_FLIGHT").toEqual(["admit:exa", "refused:budget_exceeded", "refused:budget_exceeded"]); + log.length = 0; + const broken = inFlight("turn-1", null, log); + broken.authority!.admit = async () => { throw new Error("ledger closed"); }; + await expect(admitConnection(brokerWith([broken]), owner, "api.exa.ai", new Map())).rejects.toBeInstanceOf(EgressAdmissionRefused); + expect(log, "WEB_ADMISSION_FAILURE_REFUSES").toEqual(["refused:unavailable"]); +}); diff --git a/packages/ui-server/tests/web-tools-broker.test.ts b/packages/ui-server/tests/web-tools-broker.test.ts index 6ddfb45143..f86683d2c5 100644 --- a/packages/ui-server/tests/web-tools-broker.test.ts +++ b/packages/ui-server/tests/web-tools-broker.test.ts @@ -210,3 +210,22 @@ test("closing the broker ends every executor session and refuses further calls", expect(executorReceipts().every(receipt => receipt.exit.exited && groupGone(receipt.exit.pid!)), "WEB_CLOSE_EXITS").toBe(true); expect(await call(scope(), "web_search", { query: "Odysseus" })).toMatchObject({ ok: false, error: { code: "unavailable" } }); }); + +test("a dispatched call is in flight for its executor's connections until it settles, and its authority's refusal is the answer (#3687)", async () => { + const at = scope(); + const owner = { principalId: at.principalId, sessionId: at.sessionId }; + const seen: string[] = []; + const authority = { admit: async () => null, attempt: () => {} }; + const running = broker.call(at, { tool: "web_search", input: { query: "slow Odysseus mast" }, toolCallId: at.toolCallId }, new AbortController().signal, () => true, authority); + await until(() => broker.inFlight(owner).length === 1, "the call was never in flight"); + const [flight] = broker.inFlight(owner); + expect(flight!.scope, "WEB_IN_FLIGHT_CARRIES_THE_TURN").toEqual(at); + expect(flight!.authority).toBe(authority); + expect(broker.inFlight({ principalId: "p-suitor", sessionId: at.sessionId }), "WEB_IN_FLIGHT_IS_PER_OWNER").toEqual([]); + flight!.refuse({ code: "policy_denied", message: "Not for this recipient." }); + flight!.refuse({ code: "budget_exceeded", message: "later" }); + seen.push(JSON.stringify(await running)); + expect(JSON.parse(seen[0]!), "WEB_AUTHORITY_REFUSAL_IS_THE_ANSWER").toEqual({ ok: false, tool: "web_search", error: { code: "policy_denied", message: "Not for this recipient." } }); + expect(broker.inFlight(owner), "WEB_SETTLED_CALL_LEAVES_FLIGHT").toEqual([]); + expect(receipts.find(receipt => receipt.kind === "call")).toMatchObject({ outcome: "policy_denied" }); +}); From 4e46e0dacb21c122696f24d3004912cebfaff102 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 13 Nov 2026 12:01:40 +0000 Subject: [PATCH 2/2] test: give the web-access governance fixtures a frozen provider policy Admission now routes each web recipient under the turn's frozen provider policy (#3687), so a stand-in governance without policy.providers refused every call. The Pi worker runtime proof (PI_HOST_WEB_FOUR_TOOLS_EXECUTE) went red on CI; the three ui-server stand-ins get the same real shape. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/web-pi-delivery.test.ts | 2 +- packages/ui-server/tests/web-pi-worker.test.ts | 2 +- packages/ui-server/tests/ws-web-access.test.ts | 2 +- tests/fixtures/pi-worker-probe.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/web-pi-delivery.test.ts b/packages/ui-server/tests/web-pi-delivery.test.ts index ba6a9c4747..d8393a3949 100644 --- a/packages/ui-server/tests/web-pi-delivery.test.ts +++ b/packages/ui-server/tests/web-pi-delivery.test.ts @@ -64,7 +64,7 @@ test("installed Pi records a forwarded web result before the next provider reque // The ws web slice as makeBridge composes it for a governed Pi turn. const web = createWebAccess({ host: { webTools: broker }, turn: { sessionId: "ithaca" }, turnId: "voyage", principalId: "odysseus", signal: controller.signal, backendId: "pi", workerProfile: { origin: "interactive", actualProfile: "governed" }, current: () => !controller.signal.aborted, - recordingAvailable: () => true } as never, { collectedSessionId: "ithaca" }, { policy: { hash: "rev-odyssey" } } as never); + recordingAvailable: () => true } as never, { collectedSessionId: "ithaca" }, { policy: { hash: "rev-odyssey", policy: { providers: [] } } } as never); expect(web.webAccess, "WEB_SLICE_PRESENT_FOR_GOVERNED_PI").toBeFunction(); const turn = createTurnContext(); turn.bridge = { emit() {}, requestPermission: async () => ({ behavior: "allow" }), webAccess: web.webAccess } as never; diff --git a/packages/ui-server/tests/web-pi-worker.test.ts b/packages/ui-server/tests/web-pi-worker.test.ts index c322976337..0945431c99 100644 --- a/packages/ui-server/tests/web-pi-worker.test.ts +++ b/packages/ui-server/tests/web-pi-worker.test.ts @@ -56,7 +56,7 @@ async function piTurn(mode: string) { // What makeBridge composes for a governed Pi turn: the scope is this turn's, never the call's. const web = createWebAccess({ host: { webTools: broker }, turn: { sessionId: "s-ithaca" }, turnId, principalId: "p-penelope", signal: controller.signal, backendId: "pi", workerProfile: { origin: "interactive", actualProfile: "governed" }, current: () => !controller.signal.aborted, - recordingAvailable: () => true } as never, { collectedSessionId: "s-ithaca" }, { policy: { hash: "rev-odyssey" } } as never); + recordingAvailable: () => true } as never, { collectedSessionId: "s-ithaca" }, { policy: { hash: "rev-odyssey", policy: { providers: [] } } } as never); await backend.startTurn({ prompt: mode, signal: controller.signal, turnId, workerSandbox: { brain, profile: "governed", restricted: false, areas: [], scratchAliasesRemoved: [] }, bridge: { diff --git a/packages/ui-server/tests/ws-web-access.test.ts b/packages/ui-server/tests/ws-web-access.test.ts index f00d0f5a24..6f3860d0b7 100644 --- a/packages/ui-server/tests/ws-web-access.test.ts +++ b/packages/ui-server/tests/ws-web-access.test.ts @@ -11,7 +11,7 @@ function slice(overrides: Record = {}, collected: string | null const broker = { call: async (scope: WebCallScope, call: { tool: string }) => { scopes.push(scope); return { ok: true, tool: call.tool, text: "" }; } } as unknown as WebBroker; const ctx = { host: { webTools: broker }, turn: { sessionId: null }, turnId: "t-voyage", principalId: "p-penelope", signal: new AbortController().signal, backendId: "pi", workerProfile: { origin: "interactive", actualProfile: "strict" }, work: undefined, current: () => true, recordingAvailable: () => true, ...overrides }; - return { scopes, web: createWebAccess(ctx as never, { collectedSessionId: collected }, { policy: { hash: "rev-7" } } as never) }; + return { scopes, web: createWebAccess(ctx as never, { collectedSessionId: collected }, { policy: { hash: "rev-7", policy: { providers: [] } } } as never) }; } test("the slice exists only for Pi's turns, typed or voice, on a host with a broker", () => { diff --git a/tests/fixtures/pi-worker-probe.ts b/tests/fixtures/pi-worker-probe.ts index b436500068..8c87746979 100644 --- a/tests/fixtures/pi-worker-probe.ts +++ b/tests/fixtures/pi-worker-probe.ts @@ -336,7 +336,7 @@ const maskBridge = await makeBridge(host, maskTurn, { promptText: "Odysseus work } as TurnRecorder, applicationPolicy: backend.brainApplicationPolicy!({})! }); const webAccess = webBroker ? createWebAccess({ host: { webTools: webBroker }, turn: { sessionId: "s-ithaca" }, turnId: "worker-turn", principalId: "odysseus", signal: controller.signal, backendId: "pi", workerProfile: { origin: "interactive", actualProfile: "governed" }, current: () => !controller.signal.aborted, - recordingAvailable: () => true } as never, { collectedSessionId: "s-ithaca" }, { policy: { hash: "rev-odyssey" } } as never).webAccess : undefined; + recordingAvailable: () => true } as never, { collectedSessionId: "s-ithaca" }, { policy: { hash: "rev-odyssey", policy: { providers: [] } } } as never).webAccess : undefined; const activeBridge = scenario.startsWith("mask-") ? { ...bridge, requestMask: maskBridge.requestMask, ...(scenario !== "mask-no-route" ? { applyImageMask: maskBridge.applyImageMask } : {}) } : webAccess ? { ...bridge, webAccess } : bridge; if (scenario === "failed-host") workerHostBoundary.probe = () => ({ ok: false, requirement: "fixture missing namespaces" });