Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
58ffea8
test(responses): pin the combo replay on a paced source, and only the…
lidge-jun Nov 13, 2026
274c36f
fix(responses): a combo child's required-tool check keeps whether the…
lidge-jun Nov 13, 2026
d66eecd
fix(link): end every relayed request's traffic flow through one guard…
lidge-jun Nov 13, 2026
840e0d4
fix(link): a throwing stall observer never breaks a relayed body
lidge-jun Nov 13, 2026
7eb3614
test(link): a parsed create stays with its own request when a fallbac…
lidge-jun Nov 13, 2026
72395f1
docs(link): note that a link create's parsed body shares its nested i…
lidge-jun Nov 13, 2026
57e5f78
feat(link): the Home counts each link WebSocket in its per-link traff…
lidge-jun Nov 13, 2026
2e8b3f3
test(link): the RSS acceptance announces a stall only after a quiet w…
lidge-jun Nov 13, 2026
b7c8018
docs(link): only the settled acceptance runs count, and how the quiet…
lidge-jun Nov 13, 2026
18dc680
docs(link): the Home counts link sockets in the Child's units, and sa…
lidge-jun Nov 13, 2026
92729db
docs(link): the traffic counters' comments cover a link socket's mess…
lidge-jun Nov 13, 2026
3240b58
docs(responses): the required-tool check keeps its tool declarations …
lidge-jun Nov 13, 2026
9abe4ef
test(link): a refused or failed link upgrade counts nothing in the Ho…
lidge-jun Nov 13, 2026
fbea506
style(link): drop the trailing blank line from the gate and the RSS f…
lidge-jun Nov 13, 2026
1ba512b
docs(link): the quiet window's timers are the only ones that change a…
lidge-jun Nov 13, 2026
cc9f3b9
test(link): the failed-upgrade case proves the gate reached server.up…
lidge-jun Nov 13, 2026
4767667
Merge remote-tracking branch 'origin/dev' into fix/link-websocket-rea…
lidge-jun Nov 13, 2026
a083956
test(responses): the workflow ceiling test's hand-made socket carries…
lidge-jun Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/test-layout/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -1991,6 +1991,6 @@
"responses-claude-preflight-lease.test.ts": "responses",
"injection-routing-drift.test.ts": "codex-integration", "injection-routing-healer.test.ts": "codex-integration",
"injection-routing-heal-apply.test.ts": "codex-integration", "cli-start-routing-heal-wiring.test.ts": "cli",
"cli-status-codex-routing-drift.test.ts": "cli", "advisor-settings.test.ts": "advisor", "advisor-context.test.ts": "advisor", "advisor-state.test.ts": "advisor", "advisor-guard.test.ts": "advisor", "advisor-consult.test.ts": "advisor", "advisor-plan.test.ts": "advisor", "advisor-responses-wiring.test.ts": "advisor", "advisor-routes.test.ts": "server", "advisor-internal-authority.test.ts": "advisor", "advisor-core-boundary.test.ts": "advisor", "advisor-continuation-limit.test.ts": "advisor", "advisor-authority-transport.test.ts": "advisor", "advisor-evidence.test.ts": "advisor", "advisor-budget.test.ts": "advisor", "advisor-adaptive.test.ts": "advisor", "advisor-scope-transport.test.ts": "advisor", "local-credentials.test.ts": "cli", "local-credential-fence.test.ts": "config", "local-credential-generation.test.ts": "config", "link-websocket-upgrade.test.ts": "server", "link-websocket-gate.test.ts": "server", "link-websocket-drain.test.ts": "server", "link-websocket-pump.test.ts": "server", "link-websocket-rss.test.ts": "e2e-style", "link-websocket-holds.test.ts": "server", "link-ws-activity-holds.test.ts": "clients", "link-websocket-fingerprints.test.ts": "server", "link-activity-holds-routes.test.ts": "server", "link-ws-activity-holds-operator.test.ts": "clients", "cli-link-activity.test.ts": "cli", "link-child-ops-ignore-activity.test.ts": "clients", "link-request-log-fields.test.ts": "server", "link-websocket-transport-status.test.ts": "server", "link-websocket-release-gate.test.ts": "e2e-style"
"cli-status-codex-routing-drift.test.ts": "cli", "advisor-settings.test.ts": "advisor", "advisor-context.test.ts": "advisor", "advisor-state.test.ts": "advisor", "advisor-guard.test.ts": "advisor", "advisor-consult.test.ts": "advisor", "advisor-plan.test.ts": "advisor", "advisor-responses-wiring.test.ts": "advisor", "advisor-routes.test.ts": "server", "advisor-internal-authority.test.ts": "advisor", "advisor-core-boundary.test.ts": "advisor", "advisor-continuation-limit.test.ts": "advisor", "advisor-authority-transport.test.ts": "advisor", "advisor-evidence.test.ts": "advisor", "advisor-budget.test.ts": "advisor", "advisor-adaptive.test.ts": "advisor", "advisor-scope-transport.test.ts": "advisor", "local-credentials.test.ts": "cli", "local-credential-fence.test.ts": "config", "local-credential-generation.test.ts": "config", "link-websocket-upgrade.test.ts": "server", "link-websocket-gate.test.ts": "server", "link-websocket-drain.test.ts": "server", "link-websocket-pump.test.ts": "server", "link-websocket-rss.test.ts": "e2e-style", "link-websocket-holds.test.ts": "server", "link-websocket-traffic.test.ts": "server", "link-ws-activity-holds.test.ts": "clients", "link-websocket-fingerprints.test.ts": "server", "link-activity-holds-routes.test.ts": "server", "link-ws-activity-holds-operator.test.ts": "clients", "cli-link-activity.test.ts": "cli", "link-child-ops-ignore-activity.test.ts": "clients", "link-request-log-fields.test.ts": "server", "link-websocket-transport-status.test.ts": "server", "link-websocket-release-gate.test.ts": "e2e-style"
}
}
21 changes: 13 additions & 8 deletions src/link/traffic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,11 @@
* it is written, even when the Home reads only part of it. A Home's hub-link listener (`src/server/index/link-relay-sessions.ts`) counts the
* response-body bytes it streams back and, for requests, each declared Content-Length (it cannot
* wrap Bun's native request without losing its identity); a request body without one is counted in
* `toHomeUncounted` instead. Neither counts HTTP headers, the relay-auth challenge, SSH or TCP
* framing, or what any relay between the machines adds.
* `toHomeUncounted` instead. A link WebSocket is one request in either book, in the same units: message payload bytes
* each way (the Child once its socket write completed and per complete message from the Home; the Home per message
* received and per message Bun took for the socket). The Home counts it complete when any close frame ended it; the Child
* also counts its own overload, binary and protocol closes as incomplete. Neither counts HTTP headers, WebSocket framing or control
* frames, the relay-auth challenge, SSH or TCP framing, or what any relay between the machines adds.
*/
export const MAX_LINKS = 256;

Expand All @@ -42,21 +45,23 @@ export interface LinkTrafficCounters {
epoch: string;
/** Changes every time this link's counters start from zero within one epoch; compare two reads only when epoch and generation match. */
generation: number;
/** Relayed requests on this link. */
/** Relayed requests on this link, a link socket counting as one. */
requests: number;
/**
* Of those, requests that ended before their response body did (abort, cancel, error, refusal),
* and on a Child also requests whose request-body upload did not finish.
* and on a Child also requests whose request-body upload did not finish; a link socket counts when
* it ended without a close frame (and on a Child also after its own overload, binary or protocol close).
*/
incomplete: number;
/**
* Request-body bytes toward the Home. Child: bytes whose socket write completed, a lower bound
* while `incomplete` > 0. Home: the declared Content-Length of each request.
* Request-body bytes toward the Home, or a link socket's message payloads toward it. Child: bytes
* whose socket write completed, a lower bound while `incomplete` > 0. Home: the declared
* Content-Length of each relayed request, or the payload of each message a link socket received.
*/
toHomeBytes: number;
/** Response-body bytes from the Home. */
/** Response-body bytes from the Home, or a link socket's message payloads from it. */
fromHomeBytes: number;
/** How toHomeBytes was measured: socket writes completed (Child) or declared Content-Length (Home). */
/** How toHomeBytes was measured for relayed HTTP: socket writes completed (Child) or declared Content-Length (Home); a link socket's message payloads count the same on both. */
toHomeSource: "relayed" | "content-length";
/** Requests whose body bytes toHomeBytes could not include (a Home request without Content-Length). */
toHomeUncounted: number;
Expand Down
2 changes: 2 additions & 0 deletions src/server/index/link-listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ export function createLinkListenerLifecycle<T>(deps: LinkListenerDeps = {}): Lin
// The same lifecycle-owned book relayed HTTP turns count in, so restart gates see link sockets.
activity,
holds,
// The same per-link traffic book as the relayed HTTP requests: a link socket is one request in it.
traffic,
enabled: websocketEnabled,
policy: () => startContext!.responsesWebsocket!.policy(),
authorized: identity => fingerprintsFor(identity.keyId, identity.linkId).includes(identity.fingerprint),
Expand Down
21 changes: 12 additions & 9 deletions src/server/index/link-relay-sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,8 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) {
try { decideObservation = options.observeResponsesRequest?.(sessionLink, req) ?? undefined; } catch { /* observation never blocks the request */ }
}
let flow: ReturnType<LinkTrafficBook["begin"]> | undefined;
// Accounting never keeps a lease: every path ends its flow through here and goes on to release.
const endFlow = (complete: boolean): void => { try { flow?.end(complete); } catch { /* the request's own outcome is the one reported */ } };
try {
flow = sessionLink !== null ? options.traffic?.begin(sessionLink) : undefined;
if (flow) {
Expand All @@ -201,21 +203,21 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) {
} catch (error) {
// Accounting that fails before dispatch still decides a pending body observation and returns the lease.
decideObservation?.(false);
try { flow?.end(false); } catch { /* the original failure is the one reported */ } finally { release(); }
endFlow(false); release();
throw error;
}
// Socket cancellation before headers is terminal too; an upstream handler that is
// settling its own cleanup cannot keep a dead transport's listener lease forever.
// An abort before headers also decides a pending body observation (not accepted) and drops its unclaimed turn token.
const beforeHeadersAbort = () => { decideObservation?.(false); flow?.end(false); release(); };
const beforeHeadersAbort = () => { decideObservation?.(false); endFlow(false); release(); };
req.signal.addEventListener("abort", beforeHeadersAbort, { once: true });
if (req.signal.aborted) beforeHeadersAbort();
try {
const response = await dispatch(req, server);
decideObservation?.(response.status < 400 && !req.signal.aborted);
req.signal.removeEventListener("abort", beforeHeadersAbort);
if (countsActivity && sessionLink === null && response.status < 400 && !req.signal.aborted) beginActivity();
if (!response.body || req.method === "HEAD") { flow?.end(true); release(); return response; }
if (!response.body || req.method === "HEAD") { endFlow(true); release(); return response; }
const reader = response.body.getReader();
const catalogHash = options.catalogServed && req.method === "GET" && url.pathname === "/v1/catalog" && url.search === ""
&& response.status === 200 ? createHash("sha256") : null;
Expand All @@ -234,7 +236,8 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) {
// Test-only stall signal (link-websocket-limits.ts): set from each chunk handed over until the reader asks again.
const waitObserver = sessionLink !== null ? linkRelayWaitObserver() : null;
let waiting = false;
const stopWaiting = (): void => { if (waiting) { waiting = false; waitObserver?.(false); } };
const tellWaiting = (value: boolean): void => { try { waitObserver?.(value); } catch { /* a test observer never breaks the relay */ } };
const stopWaiting = (): void => { if (waiting) { waiting = false; tellWaiting(false); } };
const finish = () => {
if (ended) return;
ended = true;
Expand All @@ -244,7 +247,7 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) {
};
const cancel = async (reason?: unknown) => {
cancelled = true;
flow?.end(false);
endFlow(false);
try { await reader.cancel(reason); } finally { finish(); }
};
const aborted = () => { void cancel(req.signal.reason).catch(() => {}); };
Expand All @@ -255,19 +258,19 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) {
stopWaiting();
try {
const next = await reader.read();
if (next.done) { flow?.end(!cancelled); finish(); controller.close(); if (!cancelled) reportCatalog(); }
if (next.done) { endFlow(!cancelled); finish(); controller.close(); if (!cancelled) reportCatalog(); }
else {
catalogHash?.update(next.value); flow?.fromHome(next.value.byteLength); controller.enqueue(next.value);
if (waitObserver && !ended) { waiting = true; waitObserver(true); }
if (waitObserver && !ended) { waiting = true; tellWaiting(true); }
}
} catch (error) { flow?.end(false); finish(); controller.error(error); }
} catch (error) { endFlow(false); finish(); controller.error(error); }
},
cancel,
}, { highWaterMark: 0 });
return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
} catch (error) {
decideObservation?.(false); req.signal.removeEventListener("abort", beforeHeadersAbort);
try { flow?.end(false); } catch { /* the original failure is the one reported */ } finally { release(); }
endFlow(false); release();
throw error;
}
},
Expand Down
13 changes: 12 additions & 1 deletion src/server/index/link-websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { sessionLaneIdFromRequest } from "../request-log-conversation";
import { classifyUsageClient } from "../../usage/client";
import type { LinkActivity, LinkSocketActivity } from "../../link/child-activity";
import type { ActivityHolds, FingerprintMark, StoredMark } from "../../link/ws-activity-holds";
import type { LinkTrafficBook } from "../../link/traffic";
import type { LinkWsCloseReason, LinkWsCounters, LinkWsRefusal } from "../../link/status-projection";
import type { LinkTurnObserver } from "../link-turn";
import { resultKeysOf } from "../../codex/websocket-activity";
Expand Down Expand Up @@ -125,6 +126,12 @@ export interface LinkWebsocketGateDeps {
activity?: LinkActivity;
/** Durable holds: a busy close leaves one, and the crash fence is armed before the first upgrade. */
holds?: ActivityHolds;
/**
* The Home's per-link traffic book (the HTTP relay's): each link socket is one request in it, counted from open to close
* in the Child's units (message payload bytes each way); complete when any close frame ended it, where the Child also
* counts its own overload, binary and protocol closes as incomplete.
*/
traffic?: LinkTrafficBook;
}

/** What the gate keeps per open link socket. */
Expand Down Expand Up @@ -512,6 +519,7 @@ export function createLinkWebsocketGate(deps: LinkWebsocketGateDeps) {
const owed = pending.get(link) ?? null;
pending.delete(link);
track(ws, link.linkId);
link.traffic = deps.traffic?.begin(link.linkId);
base.open?.(ws);
const state: SocketState = {
openedAt: now(), idleSince: null, drainingSince: null, closeAfterTurn: false,
Expand Down Expand Up @@ -587,6 +595,8 @@ export function createLinkWebsocketGate(deps: LinkWebsocketGateDeps) {
},
message(ws, raw) {
const link = ws.data.link;
// Every message that reached the Home counts, as the Child counts every write that completed, fenced or not.
link?.traffic?.toHome(typeof raw === "string" ? Buffer.byteLength(raw) : raw.byteLength);
if (!link || link.fenced) return;
// S3: every message, of any type, before the shared handler can admit a turn.
if (!authorized(link)) { fence(ws, LINK_WS_REVOKED_CLOSE); return; }
Expand Down Expand Up @@ -620,6 +630,8 @@ export function createLinkWebsocketGate(deps: LinkWebsocketGateDeps) {
const entry = tally(link.linkId, false);
const why: LinkWsCloseReason = fencedBy.get(link) ?? (code === 1000 || code === 1001 ? "client" : code === 1006 ? "dropped" : "other");
if (entry) entry.closes[why] = (entry.closes[why] ?? 0) + 1;
// Complete when a close ended it, from either side; a socket dropped without one (1006, 1015) is incomplete.
try { link.traffic?.end(code !== 1006 && code !== 1015); } catch { /* accounting never keeps a lease */ }
link.leases.closed();
}
}
Expand Down Expand Up @@ -678,4 +690,3 @@ export function createLinkWebsocketGate(deps: LinkWebsocketGateDeps) {
}

export type LinkWebsocketGate = ReturnType<typeof createLinkWebsocketGate>;

2 changes: 2 additions & 0 deletions src/server/index/websocket-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,8 @@ export function createWebsocketHandler(
baseHeaders.forEach((value, key) => fwd.set(key, value));
// A Remote Link socket hands the pipeline the create it parsed (#8600): serializing it into the request and
// parsing it back would hold two more request-sized copies for the turn. Local sockets keep the request body.
// turnBody is a shallow copy: preparation's in-place edits to nested input reach frame.input too, which the
// socket's activity book reads again later, for the array's identity and each result's type and ids only.
const turnBody = { ...payload, stream: true };
const linkSocket = ws.data.link !== undefined;
const req = new Request("http://localhost/v1/responses", {
Expand Down
4 changes: 3 additions & 1 deletion src/server/responses/combo-required-tool-fulfillments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ export function requiredToolFulfillments(
const identity = record(normalize({ ...substitution, type: "function_call" }));
if (identity && intendedClient(identity) && wire?.hosted.has(substitution.callType)) hosted.add(substitution.callType);
}
// Read once here: the predicate lives as long as the stream, so it keeps this answer and the wire declarations, never the parsed body (#8601).
const deniesAll = request !== undefined && (!outbound || outbound.tool_choice === "none");
return (item, clientCall) => {
if (request && (outbound?.tool_choice === "none" || !outbound)) return false;
if (deniesAll) return false;
if (!clientCall) return hosted.has(String(item.type)) && (!wire || wire.hosted.has(String(item.type)));
// Sparse calls keep the existing uncertain-name policy; explicit identities must be declared.
if (typeof item.name !== "string") return !wire || wire.clients.length > 0;
Expand Down
6 changes: 6 additions & 0 deletions src/server/ws-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { ResponsesTerminalStatus } from "../bridge";
import type { DataPlaneAdmission } from "./auth-cors";
import type { AdmissionLease, AdmissionReservation } from "../lib/admission";
import { BoundedSseFrameBuffer, MAX_CLIENT_SSE_FRAME_BYTES } from "./sse-frame-buffer";
import type { LinkTrafficFlow } from "../link/traffic";
import { sseDataPayload as parseSseBlock } from "./sse-payload-rewrite";
import { safeResponseHeaders } from "./safe-response-headers";
import type { AudioSocketTarget } from "./audio-dictation";
Expand Down Expand Up @@ -103,6 +104,8 @@ export interface LinkSocketBinding {
readonly leases: { closed(): void };
/** Set by the link pump while it waits for Bun's drain; the link handler calls it on drain and close. */
drained?: () => void;
/** This socket's flow in the Home's per-link traffic book: message payload bytes each way (link-websocket.ts). */
traffic?: LinkTrafficFlow;
}

export interface LiveSidebandUpstreamFailure {
Expand Down Expand Up @@ -220,6 +223,9 @@ export function sendTextFrame(ws: ServerWebSocket<WsData>, payload: string): voi
const result = ws.send(payload);
if (result === 0) throw new WsSendDroppedError();
// Bun returns -1 when queued with backpressure. That is accepted; a later 0 is the hard failure.
// A link socket counts what Bun took, queued or written; a local socket has no flow and pays one property read.
const flow = ws.data.link?.traffic;
if (flow) flow.fromHome(Buffer.byteLength(payload));
}

export function sendJsonFrame(ws: ServerWebSocket<WsData>, payload: Record<string, unknown>): void {
Expand Down
Loading
Loading