Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/3687-web-call-admission.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion api-report/ui-sdk.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1264,6 +1264,7 @@ export "./internal" (./src/internal.ts)
type CleanupReconcilerOptions
type CompiledWorkerCommandPolicy
DEFAULT_TURN_TEMP_BYTES
EgressAdmissionRefused
type EgressDestinationPolicy
type EgressRecord
type EgressRefusal
Expand Down Expand Up @@ -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<WebToolName>[];
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;
Expand Down
51 changes: 51 additions & 0 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 14 additions & 1 deletion docs/integration-contract/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions packages/ui-backend-pi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 6 additions & 1 deletion packages/ui-backend-pi/src/web-executor-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" });
Expand Down
2 changes: 1 addition & 1 deletion packages/ui-sdk/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
21 changes: 18 additions & 3 deletions packages/ui-sdk/src/server/egress-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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 {
Expand All @@ -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;
Expand All @@ -167,7 +171,17 @@ const REFUSAL_STATUS: Readonly<Record<EgressRefusal["cause"], string>> = {
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;
Expand Down Expand Up @@ -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;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/ui-sdk/src/tool-contracts/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];

Expand Down
15 changes: 15 additions & 0 deletions packages/ui-server/src/brain/turn-budgets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,21 @@ export function createTurnBudgets(db: Database, pricing: RollupPricing, clock: (
return call<BudgetObservationResult | undefined>("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<BudgetObservationResult | undefined> {
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<BudgetObservationResult | undefined>("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
Expand Down
Loading
Loading