diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index f886d852e6..b02623c203 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -50,7 +50,7 @@ import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; import { APIG_RESIGN_SCHEME, unresolvedRefusals } from "../apig-resign.js"; import { adminRelayEnabled, resolveResignSettings } from "../config.js"; import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, singleFlight } from "./native-bootstrap.js"; -import { installNativeFetchIntercept, liveStateSlotEffect, noteRoutedOrigin, observeRoutedOrigin, type GateVerdict, type NativeInterceptState } from "./native-intercept.js"; +import { fetchMethodOf, installNativeFetchIntercept, liveStateSlotEffect, noteRoutedOrigin, observeRoutedOrigin, type GateVerdict, type NativeInterceptState } from "./native-intercept.js"; import { asciiHeaderValue, fetchManifest, fetchProxyVersion, fetchStatus, fetchStatusLatest, forwardTool, reportRuntimeInfo, waitForProxyVersion, type ManifestTool } from "./shared.js"; import { createForkAdopter, sideShapedBody } from "./fork-adopt.js"; import { clearIncrementalProbe, INCREMENTAL_TURN_MARKER_HEADER, INCREMENTAL_TURN_ID_HEADER, newIncrementalTurnId, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, sweepStale, type IncrementalWireMessage } from "./incremental-client.js"; @@ -1628,6 +1628,9 @@ export function apply(ctx: PluginContext): void { // pipeline — dropping it is a separate follow-up, not this PR. const INC_PENDING_TTL_MS = 30_000; // matches omp-native / opencode-native const incPendingAcks = new Map(); + // #3304: original (body, headers) per swapped init — the give-up restore + // guard looks the init object back up by identity when the proxy dies. + const incOriginals = new WeakMap(); async function maybeIncrementalNative(url: string, init: RequestInit | undefined): Promise { if (!register.toolsReady || init === undefined) return; const attr = attributionOf(ctx); @@ -1664,6 +1667,7 @@ export function apply(ctx: PluginContext): void { if (pending.url === url && Date.now() - pending.at < INC_PENDING_TTL_MS) { inflight = true; break; } } if (inflight) return; + incOriginals.set(init, { body, headers: new Headers(init.headers) }); init.body = (plan as { body: string }).body; const turnId = newIncrementalTurnId(); const headers = new Headers(init.headers); @@ -1672,6 +1676,16 @@ export function apply(ctx: PluginContext): void { init.headers = headers; incPendingAcks.set(turnId, { sid, url, messages: parsed.messages as IncrementalWireMessage[], system: "system" in parsed ? parsed.system : undefined, base, at: Date.now() }); } + // #3304: when the proxy dies and this request falls back to a direct + // send, restore the ORIGINAL payload instead of shipping the lane + // envelope a bare upstream cannot parse. + state.directGuard = (url, input, guardInit) => { + if (guardInit === undefined) return undefined; + const orig = incOriginals.get(guardInit); + if (orig === undefined) return undefined; + incOriginals.delete(guardInit); + return { input: url, init: { ...guardInit, method: fetchMethodOf(input, guardInit), body: orig.body, headers: orig.headers } }; + }; state.onResponse = (_url, response, headers) => { const turnId = headers?.[INCREMENTAL_TURN_ID_HEADER]; if (turnId === undefined) return; // not an incremental dispatch — nothing to attribute (#3329) diff --git a/src/agent/incremental-client.ts b/src/agent/incremental-client.ts index 92a53b21f4..dbd21dc5ff 100644 --- a/src/agent/incremental-client.ts +++ b/src/agent/incremental-client.ts @@ -291,10 +291,45 @@ export function clearIncrementalProbe(proxyBase: string): void { probeCache.delete(proxyBase); } +// #3304: pi-lane original-payload ledger backing the give-up restore guard. +// The swap happens in the extension's before_provider_request handler while +// the guard runs in the bootstrap's fetch intercept — same bundle (the +// package.json "pi" manifest loads dist/agent/pi-native.js, which inlines +// pi.ts), so this module-level state is shared between them. Keyed per +// conversation id: pi sends strictly sequentially per session, and the +// writer clears the entry whenever a turn leaves WITHOUT a swap (or its +// response lands), so at fetch time an entry exists iff THE CURRENT request +// was swapped. TTL bounds memory for sessions whose response never comes. +const PI_ORIGINAL_TTL_MS = 30_000; +const piOriginals = new Map(); + +export function notePiIncrementalOriginal(conversationId: string, payload: unknown): void { + sweepStale(piOriginals, PI_ORIGINAL_TTL_MS); + piOriginals.set(conversationId, { payload, at: Date.now() }); +} + +export function clearPiIncrementalOriginal(conversationId: string): void { + piOriginals.delete(conversationId); +} + +/** Consume (and forget) the original payload of the current swapped turn. + * Absent when nothing is pending or the entry expired. */ +export function consumePiIncrementalOriginal(conversationId: string): unknown { + const entry = piOriginals.get(conversationId); + if (entry === undefined) return undefined; + if (Date.now() - entry.at >= PI_ORIGINAL_TTL_MS) { + piOriginals.delete(conversationId); + return undefined; + } + piOriginals.delete(conversationId); + return entry.payload; +} + export function __resetIncrementalClientForTests(): void { convs.clear(); probeCache.clear(); rejectionCircuit.clear(); droppedParamWarned.clear(); droppedParamWarnPairs = 0; + piOriginals.clear(); } diff --git a/src/agent/native-intercept.ts b/src/agent/native-intercept.ts index 98be6dbb5e..36de123cc5 100644 --- a/src/agent/native-intercept.ts +++ b/src/agent/native-intercept.ts @@ -22,6 +22,14 @@ import { APIG_RESIGN_HEADER, APIG_RESIGN_CREDENTIAL_HEADER, APIG_RESIGN_SCHEME, * context window. */ export type GateVerdict = boolean | "refuse-oversized"; +/** #3304: a (input, init) pair ready for a direct send — either the host's + * original pair or a lane-restored one carrying the ORIGINAL payload. */ +type DirectSendPair = { input: string | URL | Request; init?: RequestInit }; + +/** #3304: directGuard verdicts — replace the outgoing pair, refuse locally, + * or leave it untouched (nothing was swapped). */ +type DirectGuardVerdict = DirectSendPair | "refuse" | undefined; + export interface NativeInterceptState { /** Proxy origin ("http://127.0.0.1:PORT") once the bootstrap resolved. * Written by the owner (pi-native.ts); read synchronously on each call. */ @@ -63,6 +71,16 @@ export interface NativeInterceptState { * (headersFor returns nothing) still pass through it — the hook itself * gates on its own conditions. */ beforeSend?: (url: string, init: RequestInit | undefined) => Promise; + /** #3304: consulted at EVERY exit that sends a model request DIRECT — + * proxy death (give-up), bootstrap failure, unattributed passthrough. + * Lane adapters arm it to restore the ORIGINAL payload when they + * swapped the outgoing body (incremental turns): a rewritten envelope + * must never leave the process toward a bare upstream. Return a + * replacement (input, init) pair, `"refuse"` for a local protocol- + * shaped refusal, or undefined when nothing was swapped. A throwing + * guard fails closed (local refusal) — it must never degrade to + * sending the possibly-rewritten body. */ + directGuard?: (url: string, input: string | URL | Request, init?: RequestInit) => DirectGuardVerdict | Promise; /** #3248 incremental turns: response hook — fired with the routed * Response BEFORE it is returned to the host, so response headers are * readable without consuming the stream. Native hosts use it to read @@ -276,8 +294,9 @@ function fetchUrlOf(input: string | URL | Request): string | undefined { /** HTTP method of a fetch call, uppercased: init.method wins (spec: init * overrides a Request-object input), then the Request object's own method, - * then the fetch default GET. */ -function fetchMethodOf(input: string | URL | Request, init?: RequestInit): string { + * then the fetch default GET. Exported for #3304 directGuard restorers, + * which must rebuild the outgoing pair with the SAME effective method. */ +export function fetchMethodOf(input: string | URL | Request, init?: RequestInit): string { const m = init?.method; if (typeof m === "string") return m.toUpperCase(); try { @@ -409,6 +428,58 @@ function oversizeRefusal(url: string): Response { return new Response(JSON.stringify({ error: { type: "server_error", code: "bili_gate_oversize_refusal", message, retryable: false } }), { status: 422, headers }); } +/** #3304: protocol-shaped local refusal for the give-up fallback when the + * outstanding request carries a lane payload that cannot be restored. 503 + * retryable (transient infrastructure failure — the next turn re-plans + * against the respawned proxy), NOT 4xx (the request itself is fine; a 4xx + * would teach hosts the payload was wrong). */ +function giveUpRestoreRefusal(url: string): Response { + const message = + "billion-context refused this request locally: the bili proxy died mid-session and this request carries an incremental payload that cannot be safely sent uncompressed — failing closed instead of shipping a rewritten body the upstream cannot parse (#3304). Retry the turn."; + const headers = { "content-type": "application/json", "x-bili-gate": "giveup-restore-refusal", "retry-after": "1" }; + if (url.endsWith("/messages")) { + return new Response(JSON.stringify({ type: "error", error: { type: "api_error", message } }), { status: 503, headers }); + } + return new Response(JSON.stringify({ error: { type: "server_error", code: "bili_gate_giveup_restore_refusal", message, retryable: true } }), { status: 503, headers }); +} + +/** #3304: the single choke point every exit that sends a model request + * DIRECT (proxy death, bootstrap failure, unattributed passthrough) must + * consult before sending. When a lane swapped the outgoing body + * (incremental turns), the ORIGINAL payload must travel instead of the + * rewritten envelope — or the request fails locally. Returns: + * - a Response: a local refusal (ship NOTHING); + * - a DirectSendPair: the caller must send exactly this pair; + * - undefined: nothing was swapped — the caller keeps its OWN default + * pair construction (each exit builds its target differently, e.g. + * makeTarget vs verbatim input), which stays byte-identical to the + * pre-fix behavior. + * A guard error fails closed too: an unknown state must never be resolved + * by shipping a possibly-rewritten body. */ +/** "refuse" never leaves this helper — it becomes the local refusal + * Response — so callers only ever see pair / refusal / undefined. */ +async function directGuardVerdict( + state: NativeInterceptState, + url: string, + input: string | URL | Request, + init?: RequestInit, +): Promise { + const guard = state.directGuard; + if (guard === undefined) return undefined; + let verdict: DirectGuardVerdict; + try { + verdict = await guard(url, input, init); + } catch (err) { + logHostEvent("error", "[native-client]", `bili-native: directGuard failed (${err instanceof Error ? err.message : String(err)}) — refusing instead of shipping a possibly-rewritten body (#3304)`); + verdict = "refuse"; + } + if (verdict === "refuse") { + state.onDispatch?.(url, "refused"); + return giveUpRestoreRefusal(url); + } + return verdict; +} + async function withTimeout(p: Promise, ms: number): Promise { let timer: ReturnType | undefined; const timeout = new Promise((resolve) => { @@ -745,7 +816,10 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState): return oversizeRefusal(url); } if (verdict !== true) { - const stamped = withHeaders(input, init, { [BILI_PASSTHROUGH_HEADER]: "1" }); + const gv = await directGuardVerdict(state, url, input, init); + if (gv instanceof Response) return gv; + const pair = gv ?? { input, init }; + const stamped = withHeaders(pair.input, pair.init, { [BILI_PASSTHROUGH_HEADER]: "1" }); state.onDispatch?.(url, "direct"); return send(stamped.input, stamped.init); } @@ -830,7 +904,10 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState): warned = true; logHostEvent("error", "[native-client]", `bili-native: no live proxy — model requests go direct (uncompressed): ${routedTarget}`); } + const gv = await directGuardVerdict(state, routedTarget, input, init); + if (gv instanceof Response) return gv; state.onDispatch?.(routedTarget, "direct"); + if (gv !== undefined) return send(gv.input, gv.init); return send(makeTarget(routedTarget), init); } } @@ -887,8 +964,11 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState): return new Response(refusal.body, { status: refusal.status, headers: { "content-type": refusal.contentType, "x-bili-resign": "unavailable" } }); } clearSignedRefusal(signedScheme); + const gv = await directGuardVerdict(state, url, input, init); + if (gv instanceof Response) return gv; noteSignedDirect(url, signedScheme, "built-in passthrough opt-in (#1884) — byte-untouched, no compression"); state.onDispatch?.(url, "direct"); + if (gv !== undefined) return send(gv.input, gv.init); return send(input, init); } resignExtra = { @@ -935,7 +1015,10 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState): state.onDispatch?.(url, "refused"); return oversizeRefusal(url); } + const gv = await directGuardVerdict(state, url, input, init); + if (gv instanceof Response) return gv; state.onDispatch?.(url, "direct"); + if (gv !== undefined) return send(gv.input, gv.init); return send(input, init); } } @@ -948,7 +1031,10 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState): warned = true; logHostEvent("error", "[native-client]", `bili-native: proxy not ready — model request goes direct (uncompressed): ${url}`); } + const gv = await directGuardVerdict(state, url, input, init); + if (gv instanceof Response) return gv; state.onDispatch?.(url, "direct"); + if (gv !== undefined) return send(gv.input, gv.init); return send(input, init); } // Attach mode rewrites exactly like spawn mode (#809 semantics — @@ -1012,7 +1098,10 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState): warned = true; logHostEvent("error", "[native-client]", `bili-native: proxy respawn failed — model requests go direct (uncompressed): ${url}`); } + const gv = await directGuardVerdict(state, url, input, init); + if (gv instanceof Response) return gv; state.onDispatch?.(url, "direct"); + if (gv !== undefined) return send(gv.input, gv.init); return send(input, init); } throw err; diff --git a/src/agent/omp-native.ts b/src/agent/omp-native.ts index 2b959fc47d..3f713b1d11 100644 --- a/src/agent/omp-native.ts +++ b/src/agent/omp-native.ts @@ -24,7 +24,7 @@ import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; import { createBiliPlugin } from "./pi.js"; import { applyOmpFirstEventTimeout, markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, setNativeOriginWaiter, singleFlight } from "./native-bootstrap.js"; -import { installNativeFetchIntercept, noteRoutedOrigin, observeRoutedOrigin, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; +import { fetchMethodOf, installNativeFetchIntercept, noteRoutedOrigin, observeRoutedOrigin, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; import { clearIncrementalProbe, INCREMENTAL_TURN_MARKER_HEADER, INCREMENTAL_TURN_ID_HEADER, newIncrementalTurnId, noteIncrementalAck, noteIncrementalRejection, planIncrementalTurn, probeIncrementalTurns, sweepStale, wireMessagesLookAnthropic, type IncrementalWireMessage } from "./incremental-client.js"; import { fetchProxyVersion, waitForProxyVersion } from "./shared.js"; import { logHostEvent } from "./host-log.js"; @@ -104,6 +104,10 @@ const incPendingOmp = new Map(); * (#3329): attribution is exact per turn id. Mirrors opencode. */ const INC_PENDING_TTL_MS = 30_000; +// #3304: original (body, headers) per swapped init — the give-up restore +// guard looks the init object back up by identity when the proxy dies. +const incOriginalsOmp = new WeakMap(); + /** Test hook: drop all planned turns (module state across suites). */ export function __resetOmpIncrementalForTests(): void { incPendingOmp.clear(); @@ -140,6 +144,7 @@ export async function ompIncrementalBeforeSend(url: string, init: RequestInit | if (pending.url === url && Date.now() - pending.at < INC_PENDING_TTL_MS) { inflight = true; break; } } if (inflight) { return; } + incOriginalsOmp.set(init, { body: init.body, headers: new Headers(init.headers) }); init.body = plan.body; const headers = new Headers(init.headers); headers.set("x-bili-plugin", "omp"); @@ -156,6 +161,17 @@ export async function ompIncrementalBeforeSend(url: string, init: RequestInit | state.beforeSend = ompIncrementalBeforeSend; +// #3304: when the proxy dies and this request falls back to a direct +// send, restore the ORIGINAL payload instead of shipping the lane +// envelope a bare upstream cannot parse. +state.directGuard = (url, input, guardInit) => { + if (guardInit === undefined) return undefined; + const orig = incOriginalsOmp.get(guardInit); + if (orig === undefined) return undefined; + incOriginalsOmp.delete(guardInit); + return { input: url, init: { ...guardInit, method: fetchMethodOf(input, guardInit), body: orig.body, headers: orig.headers } }; +}; + export function ompIncrementalOnResponse(_url: string, response: Response, headers?: Record): void { const turnId = headers?.[INCREMENTAL_TURN_ID_HEADER]; if (turnId === undefined) return; // not an incremental dispatch — nothing to attribute (#3329) @@ -382,6 +398,11 @@ export function _stateRespawnForTest(): (() => Promise) | un return state.respawn; } +/** Test hook (#3304): expose the armed give-up restore guard. */ +export function _directGuardForTest(): NativeInterceptState["directGuard"] { + return state.directGuard; +} + /** Test hook (#1365): record routed-channel evidence without the fetch patch. */ export function _noteRoutedForTest(url: string): void { noteRoutedOrigin(state, url); diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index 387c38bf59..644ba037c4 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -876,8 +876,10 @@ export async function maybeIncrementalOpencode(e: V2HttpRequestEvent, s: V2State if (pending.url === url && Date.now() - pending.at < INC_PENDING_TTL_MS) { inflight = true; break; } } if (inflight) return; + const oldReq = req; const turnId = newIncrementalTurnId(); replaceRequestPayload(e, plan.body, { [INCREMENTAL_TURN_MARKER_HEADER]: "1", [INCREMENTAL_TURN_ID_HEADER]: turnId }); + if (e.request !== oldReq) incOriginalRequestsOpencode.set(e.request as Request, oldReq); incPendingOpencode.set(turnId, { sid, url, messages: b.messages as IncrementalWireMessage[], system: b.system as unknown, base, at: Date.now() }); } catch { // never break the host's request on adapter failure @@ -907,6 +909,12 @@ const INC_PENDING_TTL_MS = 30_000; * same-URL entries — see maybeIncrementalOpencode. */ const incPendingOpencode = new Map(); +// #3304: the ORIGINAL Request per swapped Request (replaceRequestPayload +// mints a fresh object; the original's body stream stays untouched because +// planning reads a clone). The give-up restore guard looks it back up by +// identity when the proxy dies. +const incOriginalRequestsOpencode = new WeakMap(); + /** Test hook: drop all planned turns (the map is module state across suites). */ export function __resetOpencodeIncrementalForTests(): void { incPendingOpencode.clear(); @@ -959,3 +967,30 @@ export function opencodeIncrementalOnResponse(_url: string, response: Response, } state.onResponse = opencodeIncrementalOnResponse; + +/** Test hook (#3304): expose the armed give-up restore guard (mirrors omp/pi). */ +export function _directGuardForTest(): NativeInterceptState["directGuard"] { + return state.directGuard; +} + +// #3304: when the proxy dies and this request falls back to a direct send, +// restore the ORIGINAL request instead of shipping the lane envelope a bare +// upstream cannot parse. The original's body stream was never consumed +// (planning reads a clone), so it can travel verbatim. +state.directGuard = (url, input) => { + if (!(input instanceof Request)) return undefined; + const orig = incOriginalRequestsOpencode.get(input); + if (orig === undefined) return undefined; + incOriginalRequestsOpencode.delete(input); + if (orig.bodyUsed) return "refuse"; + try { + const init: RequestInit & { duplex?: "half" } = { method: orig.method, headers: new Headers(orig.headers) }; + if (orig.body !== null) { + init.body = orig.body; + init.duplex = "half"; + } + return { input: url, init }; + } catch { + return "refuse"; + } +}; diff --git a/src/agent/pi-native.ts b/src/agent/pi-native.ts index 295a3ccc66..349c08727f 100644 --- a/src/agent/pi-native.ts +++ b/src/agent/pi-native.ts @@ -33,7 +33,8 @@ import { createBiliPlugin } from "./pi.js"; import { isLegacyBcpEntry, markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, setNativeOriginWaiter, singleFlight } from "./native-bootstrap.js"; import { loadConfigFile } from "../config.js"; import { getInlineEngine, INLINE_ORIGIN } from "../inline-engine.js"; -import { installNativeFetchIntercept, noteRoutedOrigin, observeRoutedOrigin, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; +import { consumePiIncrementalOriginal, INCREMENTAL_TURN_MARKER_HEADER } from "./incremental-client.js"; +import { fetchMethodOf, installNativeFetchIntercept, noteRoutedOrigin, observeRoutedOrigin, readyOrigin, type NativeInterceptState } from "./native-intercept.js"; import { installInlineTransport } from "./pi-inline.js"; import { installNativeWebSocketIntercept } from "./native-ws-intercept.js"; import { fetchProxyVersion, fetchStatus, waitForProxyVersion } from "./shared.js"; @@ -214,6 +215,28 @@ const plan = planNativePi(process.env, loadConfigFile().pi?.inline === true); export function armNativePi(p: typeof plan): void { if (p.mode === "off") return; markNativeHost(process.env, "pi"); + // #3304: when the proxy dies and this request falls back to a direct + // send, put the ORIGINAL payload back on the wire instead of shipping + // the lane envelope a bare upstream cannot parse. The extension's swap + // (pi.ts, same bundle) notes the original per conversation id; the sid + // here is read off the outgoing x-bili-plugin-conversation header. + state.directGuard = (url, input, guardInit) => { + const src = guardInit?.headers !== undefined ? guardInit.headers : input instanceof Request ? input.headers : undefined; + if (src === undefined) return undefined; + let sid: string | null; + try { + sid = new Headers(src).get("x-bili-plugin-conversation"); + } catch { + return undefined; + } + if (sid === null || sid.length === 0) return undefined; + const payload = consumePiIncrementalOriginal(sid); + if (payload === undefined) return undefined; + const outHeaders = new Headers(src); + outHeaders.delete(INCREMENTAL_TURN_MARKER_HEADER); + const init: RequestInit = { ...guardInit, method: fetchMethodOf(input, guardInit), body: JSON.stringify(payload), headers: outHeaders }; + return { input: url, init }; + }; if (p.mode === "attach") { state.attach = true; const attachOrigin = p.attachOrigin; @@ -307,6 +330,11 @@ export function _stateRespawnForTest(): (() => Promise) | un return state.respawn; } +/** Test hook (#3304): expose the armed give-up restore guard. */ +export function _directGuardForTest(): NativeInterceptState["directGuard"] { + return state.directGuard; +} + /** Test hook (#1365): record routed-channel evidence without the fetch patch. */ export function _noteRoutedForTest(url: string): void { noteRoutedOrigin(state, url); diff --git a/src/agent/pi.ts b/src/agent/pi.ts index 2b3a56059f..7a971fe13f 100644 --- a/src/agent/pi.ts +++ b/src/agent/pi.ts @@ -14,7 +14,7 @@ import { disposeSubagentSelfReg, selfRegisterForSession, type SubagentSelfRegSta import { isModelApiUrl, nativeInterceptInstalled } from "./native-intercept.js"; import { wirePiSubagents } from "./pi-subagents.js"; import { wireToolGuardrails } from "./tool-guardrails.js"; -import { clearIncrementalProbe, INCREMENTAL_TURN_MARKER_HEADER, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, type IncrementalWireMessage } from "./incremental-client.js"; +import { clearIncrementalProbe, clearPiIncrementalOriginal, INCREMENTAL_TURN_MARKER_HEADER, noteIncrementalRejection, noteIncrementalAck, notePiIncrementalOriginal, planIncrementalTurn, probeIncrementalTurns, type IncrementalWireMessage } from "./incremental-client.js"; import { asciiHeaderValue, detectProxyBase, destinationRoutedThroughProxy, fetchManifest, forwardTool, fetchStatus, fetchProxyVersion, postIdentityRegister, reportRuntimeInfoOnChange, armedIdleNotice, noSessionWarning, nonHttpProvidersFromEnv, type ForwardedToolResult, type ManifestTool } from "./shared.js"; import { createForkAdopter } from "./fork-adopt.js"; import { logHostEvent } from "./host-log.js"; @@ -1239,6 +1239,10 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM }); if (plan.mode === "skip") return undefined; pendingIncrementalAcks.set(sid, { messages: payload.messages as IncrementalWireMessage[], system: "system" in payload ? payload.system : undefined, base: proxyBase }); + // #3304: remember the ORIGINAL payload so the give-up restore + // guard (bootstrap bundle, same module state) can put it back on + // the wire if the proxy dies before this request lands. + notePiIncrementalOriginal(sid, event.payload); return JSON.parse((plan as { body: string }).body) as unknown; } async function maybeAdoptForkChild(event: unknown, ctx: Ctx): Promise { @@ -1319,6 +1323,11 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM } catch (err) { logHostEvent("error", "[native-client]", `bili-plugin(${agent}): incremental turn skipped (${err instanceof Error ? err.message : String(err)}) — full resend this turn`); } + // #3304: this request leaves UN-swapped (full resend) — drop any + // stale original so the give-up guard cannot restore a PREVIOUS + // turn's payload onto this one. + const noSwapSid = sessionIdOf(ctx); + if (noSwapSid !== undefined && noSwapSid.length > 0) clearPiIncrementalOriginal(noSwapSid); } return stampPromptCacheKey(event, ctx, agent); }); @@ -1349,6 +1358,8 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM return; } pendingIncrementalAcks.delete(sid); + // #3304: the swapped turn completed — its original is spent. + clearPiIncrementalOriginal(sid); if (status === 200) { noteIncrementalAck(sid, Number(seq), pending.messages, pending.system); return; diff --git a/tests/issue3304-giveup-restore.test.ts b/tests/issue3304-giveup-restore.test.ts new file mode 100644 index 0000000000..e934187d71 --- /dev/null +++ b/tests/issue3304-giveup-restore.test.ts @@ -0,0 +1,399 @@ +// #3304 — give-up restore guard. When the bili proxy dies mid-session the +// fetch intercept degrades to a DIRECT send of the model request. If an +// incremental lane had already swapped that request's body into its envelope +// (seed/delta/resync), the bare upstream cannot parse it — the old code +// shipped the rewritten body anyway (silent content corruption). This suite +// pins the fix at every layer: +// 1. intercept level — every direct-send exit consults state.directGuard: +// a restored pair travels verbatim, "refuse" and a throwing guard both +// fail closed with a local 503 (x-bili-gate:giveup-restore-refusal), +// and an unswapped request is byte-identical to pre-fix behavior; +// 2. lane level — omp / opencode / pi capture their originals at swap time +// and their armed guards restore them (consumed on read). +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import type { V2HttpRequestEvent, V2State } from "../src/agent/opencode-v2.ts"; + +process.env.NODE_TEST_CONTEXT = "1"; + +const STATE_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "bili-issue3304-state-")); +const PREV_XDG_STATE_HOME = process.env.XDG_STATE_HOME; +process.env.XDG_STATE_HOME = STATE_ROOT; +after(() => { + if (PREV_XDG_STATE_HOME === undefined) delete process.env.XDG_STATE_HOME; + else process.env.XDG_STATE_HOME = PREV_XDG_STATE_HOME; + fs.rmSync(STATE_ROOT, { recursive: true, force: true }); +}); + +const DEAD_ORIGIN = "http://127.0.0.1:40001"; +const UPSTREAM_URL = "http://127.0.0.1:8199/v1/messages"; +// Captured BEFORE any withIntercept cycle: each cycle's reset re-anchors the +// fetch property against ITS OWN fake downstream, so the lanes' probes (real +// HTTP to the fake lane server) must run against this pristine fetch. +const PRISTINE_FETCH = globalThis.fetch; + +/** Undo the last intercept cycle's residual fetch state for the lane-level + * tests below (their probes use real HTTP). */ +async function ensureRealFetch(): Promise { + const ni = await import("../src/agent/native-intercept.ts"); + ni._resetForTest(); + globalThis.fetch = PRISTINE_FETCH; +} + +interface Hit { url: string; bodyText?: string; headerRecord: Record } + +/** Downstream fake: proxy-origin URLs die with a connection TypeError (the + * dead proxy); everything else lands on the "upstream" sink verbatim. */ +function fakeFetch(sinks: { proxy: Hit[]; upstream: Hit[] }): typeof fetch { + return (async (input: string | URL | Request, init?: RequestInit) => { + const u = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + const recordHeaders = (src: unknown): Record => { + if (src === undefined) return {}; + try { + const out: Record = {}; + for (const [k, v] of new Headers(src as string[][] | Record | Headers)) out[k.toLowerCase()] = v; + return out; + } catch { + return {}; + } + }; + const bodyText = async (): Promise => { + if (init?.body !== undefined && typeof init.body === "string") return init.body; + if (input instanceof Request) { + try { return await input.clone().text(); } catch { return undefined; } + } + return undefined; + }; + if (u.startsWith(DEAD_ORIGIN)) { + sinks.proxy.push({ url: u, bodyText: await bodyText(), headerRecord: recordHeaders(init?.headers !== undefined ? init.headers : input instanceof Request ? input.headers : undefined) }); + throw new TypeError("fetch failed"); + } + sinks.upstream.push({ url: u, bodyText: await bodyText(), headerRecord: recordHeaders(init?.headers !== undefined ? init.headers : input instanceof Request ? input.headers : undefined) }); + return new Response("{}", { status: 200 }); + }) as typeof fetch; +} + +async function withIntercept(state: Record, fn: (ctx: { proxy: Hit[]; upstream: Hit[]; gaveUp: () => boolean }) => Promise): Promise<{ result: T; proxy: Hit[]; upstream: Hit[]; gaveUp: boolean }> { + const saved = globalThis.fetch; + const proxy: Hit[] = []; + const upstream: Hit[] = []; + let giveUps = 0; + const fullState = { ...state, onGiveUp: () => { giveUps++; }, respawn: async () => undefined } as never; + const { _resetForTest, installNativeFetchIntercept } = await import("../src/agent/native-intercept.ts"); + _resetForTest(); + globalThis.fetch = fakeFetch({ proxy, upstream }); + try { + assert.equal(installNativeFetchIntercept(fullState), true); + const result = await fn({ proxy, upstream, gaveUp: () => giveUps > 0 }); + return { result, proxy, upstream, gaveUp: giveUps > 0 }; + } finally { + globalThis.fetch = saved; + _resetForTest(); + } +} + +const ORIGINAL_BODY = JSON.stringify({ model: "claude-test", max_tokens: 512, system: "be terse", messages: [{ role: "user", content: "hello" }] }); +const ENVELOPE_BODY = JSON.stringify({ conversationId: "conv-1", sinceSeq: 0, path: "/v1/messages", resync: true, request: { model: "claude-test" }, messages: [{ role: "user", content: "hello" }] }); +const MARKER = "x-bili-plugin-turn"; + +test("#3304 rewrite give-up: swapped body is restored before the direct send", async () => { + const originals = new WeakMap(); + const state: Record = { + origin: DEAD_ORIGIN, + ready: Promise.resolve(DEAD_ORIGIN), + beforeSend: (_url: string, init: RequestInit | undefined) => { + if (init === undefined || typeof init.body !== "string") return Promise.resolve(); + originals.set(init, { body: init.body, headers: new Headers(init.headers) }); + init.body = ENVELOPE_BODY; + const h = new Headers(init.headers); + h.set(MARKER, "1"); + init.headers = h; + return Promise.resolve(); + }, + directGuard: (url: string, _input: string | URL | Request, guardInit?: RequestInit) => { + if (guardInit === undefined) return undefined; + const orig = originals.get(guardInit); + if (orig === undefined) return undefined; + originals.delete(guardInit); + return { input: url, init: { ...guardInit, method: "POST", body: orig.body, headers: orig.headers } }; + }, + }; + const init: RequestInit = { method: "POST", headers: { authorization: "Bearer sk-test", "content-type": "application/json" }, body: ORIGINAL_BODY }; + const { result, proxy, upstream, gaveUp } = await withIntercept(state, async ({ proxy: p, upstream: u }) => ({ res: await globalThis.fetch(UPSTREAM_URL, init), p, u })); + assert.equal(gaveUp, true, "give-up fired"); + assert.equal(proxy.length, 1, "the dead proxy saw the routed attempt"); + assert.equal(proxy[0].url, `${DEAD_ORIGIN}/bili/${UPSTREAM_URL}`); + assert.equal(proxy[0].bodyText, ENVELOPE_BODY, "the proxy attempt carried the swapped envelope"); + assert.equal(upstream.length, 1, "exactly one direct send reached the upstream"); + assert.equal(upstream[0].url, UPSTREAM_URL); + assert.equal(upstream[0].bodyText, ORIGINAL_BODY, "the ORIGINAL payload traveled, not the envelope"); + assert.equal(upstream[0].headerRecord["authorization"], "Bearer sk-test", "original headers survive the restore"); + assert.equal(upstream[0].headerRecord[MARKER], undefined, "no marker header on the restored request"); + void result; +}); + +test("#3304 unswapped request: byte-identical to pre-fix behavior (regression anchor)", async () => { + const state: Record = { + origin: DEAD_ORIGIN, + ready: Promise.resolve(DEAD_ORIGIN), + directGuard: () => undefined, + }; + const init: RequestInit = { method: "POST", headers: { authorization: "Bearer sk-test" }, body: ORIGINAL_BODY }; + const { upstream, gaveUp } = await withIntercept(state, async () => globalThis.fetch(UPSTREAM_URL, init)); + assert.equal(gaveUp, true); + assert.equal(upstream.length, 1); + assert.equal(upstream[0].url, UPSTREAM_URL); + assert.equal(upstream[0].bodyText, ORIGINAL_BODY); + assert.equal(upstream[0].headerRecord["authorization"], "Bearer sk-test"); +}); + +test("#3304 refuse verdict: local protocol-shaped 503, nothing ships", async () => { + const state: Record = { + origin: DEAD_ORIGIN, + ready: Promise.resolve(DEAD_ORIGIN), + directGuard: () => "refuse", + }; + const { result, upstream } = await withIntercept(state, async () => globalThis.fetch(UPSTREAM_URL, { method: "POST", body: ENVELOPE_BODY })); + const res = result as Response; + assert.equal(res.status, 503, "retryable class — transient infrastructure failure, not a request error"); + assert.equal(res.headers.get("x-bili-gate"), "giveup-restore-refusal"); + assert.equal(res.headers.get("retry-after"), "1"); + const json = (await res.json()) as { type?: string; error?: { type?: string; message?: string } }; + assert.equal(json.type, "error", "anthropic envelope for a /messages URL"); + assert.equal(json.error?.type, "api_error"); + assert.match(json.error?.message ?? "", /#3304/); + assert.equal(upstream.length, 0, "nothing left the process"); +}); + +test("#3304 refusing guard throws: fails closed with the same local 503", async () => { + const state: Record = { + origin: DEAD_ORIGIN, + ready: Promise.resolve(DEAD_ORIGIN), + directGuard: () => { throw new Error("boom"); }, + }; + const { result, upstream } = await withIntercept(state, async () => globalThis.fetch(UPSTREAM_URL, { method: "POST", body: ENVELOPE_BODY })); + const res = result as Response; + assert.equal(res.status, 503); + assert.equal(res.headers.get("x-bili-gate"), "giveup-restore-refusal"); + assert.equal(upstream.length, 0, "an unknown state never resolves by shipping the possibly-rewritten body"); +}); + +test("#3304 routed give-up: overlay-baked URLs restore too", async () => { + const originals = new WeakMap(); + const state: Record = { + origin: DEAD_ORIGIN, + ready: Promise.resolve(DEAD_ORIGIN), + beforeSend: (_url: string, init: RequestInit | undefined) => { + if (init === undefined || typeof init.body !== "string") return Promise.resolve(); + originals.set(init, { body: init.body, headers: new Headers(init.headers) }); + init.body = ENVELOPE_BODY; + return Promise.resolve(); + }, + directGuard: (url: string, _input: string | URL | Request, guardInit?: RequestInit) => { + if (guardInit === undefined) return undefined; + const orig = originals.get(guardInit); + if (orig === undefined) return undefined; + originals.delete(guardInit); + return { input: url, init: { ...guardInit, method: "POST", body: orig.body, headers: orig.headers } }; + }, + }; + const init: RequestInit = { method: "POST", headers: { authorization: "Bearer sk-routed" }, body: ORIGINAL_BODY }; + const { upstream, gaveUp } = await withIntercept(state, async () => globalThis.fetch(`${DEAD_ORIGIN}/bili/${UPSTREAM_URL}`, init)); + assert.equal(gaveUp, true); + assert.equal(upstream.length, 1); + assert.equal(upstream[0].url, UPSTREAM_URL, "the embedded upstream target travels"); + assert.equal(upstream[0].bodyText, ORIGINAL_BODY); + assert.equal(upstream[0].headerRecord["authorization"], "Bearer sk-routed"); +}); + +test("#3304 bootstrap-failure exit: pre-swapped (opencode shape) request restores", async () => { + // opencode swaps BEFORE fetch (V2 hook chain), so the body is already the + // envelope when the intercept sees a not-ready origin. + const originals = new WeakMap(); + const state: Record = { + origin: undefined, + ready: Promise.resolve(undefined), + directGuard: (url: string, _input: string | URL | Request, guardInit?: RequestInit) => { + if (guardInit === undefined) return undefined; + const orig = originals.get(guardInit); + if (orig === undefined) return undefined; + originals.delete(guardInit); + return { input: url, init: { ...guardInit, method: "POST", body: orig.body, headers: orig.headers } }; + }, + }; + const init: RequestInit = { method: "POST", headers: { authorization: "Bearer sk-boot", [MARKER]: "1" }, body: ENVELOPE_BODY }; + originals.set(init, { body: ORIGINAL_BODY, headers: new Headers({ authorization: "Bearer sk-boot" }) }); + const { upstream } = await withIntercept(state, async () => globalThis.fetch(UPSTREAM_URL, init)); + assert.equal(upstream.length, 1); + assert.equal(upstream[0].bodyText, ORIGINAL_BODY); + assert.equal(upstream[0].headerRecord[MARKER], undefined); +}); + +test("#3304 unattributed gate-fail exit: pre-swapped (opencode shape) request restores", async () => { + // Same shape as the bootstrap failure, but the origin IS up and the + // attribution gate refuses the caller — the third direct-send exit that + // can carry a pre-swapped envelope (opencode swaps before fetch). + const originals = new WeakMap(); + const state: Record = { + origin: DEAD_ORIGIN, + ready: Promise.resolve(DEAD_ORIGIN), + takeoverGate: async () => false, + directGuard: (url: string, _input: string | URL | Request, guardInit?: RequestInit) => { + if (guardInit === undefined) return undefined; + const orig = originals.get(guardInit); + if (orig === undefined) return undefined; + originals.delete(guardInit); + return { input: url, init: { ...guardInit, method: "POST", body: orig.body, headers: orig.headers } }; + }, + }; + const init: RequestInit = { method: "POST", headers: { authorization: "Bearer sk-unattr", [MARKER]: "1" }, body: ENVELOPE_BODY }; + originals.set(init, { body: ORIGINAL_BODY, headers: new Headers({ authorization: "Bearer sk-unattr" }) }); + const { proxy, upstream } = await withIntercept(state, async () => globalThis.fetch(UPSTREAM_URL, init)); + assert.equal(proxy.length, 0, "the gate refused attribution — nothing rode the proxy"); + assert.equal(upstream.length, 1); + assert.equal(upstream[0].bodyText, ORIGINAL_BODY); + assert.equal(upstream[0].headerRecord[MARKER], undefined); +}); + +// --- lane level: the real adapters' capture + armed guards ----------------- + +async function fakeLane(enabled: boolean): Promise<{ base: string; close: () => Promise }> { + const srv = createServer((req, res) => { + if (req.method === "GET" && req.url === "/__bili/plugin/turn") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true, protocol: 1, feature: "pluginIncrementalTurns", enabled })); + return; + } + res.writeHead(404); res.end("{}"); + }); + await new Promise((r) => srv.listen(0, "127.0.0.1", r)); + const { port } = srv.address() as AddressInfo; + return { base: `http://127.0.0.1:${port}`, close: () => new Promise((r) => srv.close(() => r())) }; +} + +test("#3304 omp lane: swap captures the original; the armed guard restores and consumes", async () => { + const { __resetIncrementalClientForTests } = await import("../src/agent/incremental-client.ts"); + const mod = await import("../src/agent/omp-native.ts"); + await ensureRealFetch(); + __resetIncrementalClientForTests(); + mod.__resetOmpIncrementalForTests(); + const lane = await fakeLane(true); + try { + mod._setOmpOriginForTest(lane.base); + const original = { model: "claude-test", max_tokens: 512, prompt_cache_key: "omp-3304-a", messages: [{ role: "user", content: "hi omp" }] }; + const init: RequestInit = { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(original) }; + await mod.ompIncrementalBeforeSend(UPSTREAM_URL, init); + const swappedJson = JSON.parse(init.body as string) as { conversationId?: string }; + assert.equal(swappedJson.conversationId, "omp-3304-a", "swap happened (lane envelope replaces the body)"); + assert.equal((init.headers as Headers).get(MARKER), "1"); + + const guard = mod._directGuardForTest(); + assert.notEqual(guard, undefined, "guard armed"); + const verdict = await guard!(UPSTREAM_URL, UPSTREAM_URL, init); + if (verdict === undefined || verdict === "refuse") throw new Error(`expected a restored pair, got ${String(verdict)}`); + const restoredBody = verdict.init?.body as string; + assert.deepEqual(JSON.parse(restoredBody), original, "original payload restored byte-for-byte"); + const restoredHeaders = new Headers(verdict.init?.headers); + assert.equal(restoredHeaders.get(MARKER), null, "marker stripped by the restore"); + assert.equal(restoredHeaders.get("content-type"), "application/json"); + assert.equal(await guard!(UPSTREAM_URL, UPSTREAM_URL, init), undefined, "consumed on read"); + } finally { + mod._setOmpOriginForTest(undefined); + await lane.close(); + } +}); + +test("#3304 opencode lane: pre-fetch swap restores the original Request", async () => { + const { __resetIncrementalClientForTests } = await import("../src/agent/incremental-client.ts"); + const mod = await import("../src/agent/opencode-native.ts"); + await ensureRealFetch(); + __resetIncrementalClientForTests(); + mod.__resetOpencodeIncrementalForTests(); + const lane = await fakeLane(true); + try { + const original = { model: "claude-test", max_tokens: 512, system: "s", messages: [{ role: "user", content: "hi oc" }] }; + const req = new Request(UPSTREAM_URL, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer sk-oc" }, body: JSON.stringify(original) }); + const e = { request: req, sessionID: "oc-3304-a" } as unknown as V2HttpRequestEvent; + await mod.maybeIncrementalOpencode(e, { proxyBase: lane.base } as unknown as V2State); + const swapped = e.request as Request; + assert.notEqual(swapped, req, "the request object was replaced"); + const swappedJson = JSON.parse(await swapped.clone().json().then((j) => JSON.stringify(j))) as { conversationId?: string }; + assert.equal(swappedJson.conversationId, "oc-3304-a", "swap happened (lane envelope)"); + + const guard = mod._directGuardForTest(); + assert.notEqual(guard, undefined); + const verdict = await guard!(swapped.url, swapped); + if (verdict === undefined || verdict === "refuse") throw new Error(`expected a restored pair, got ${String(verdict)}`); + const stream = verdict.init?.body as unknown as ReadableStream; + const reader = stream.getReader(); + const chunks: Uint8Array[] = []; + for (;;) { + const r = await reader.read(); + if (r.done) break; + chunks.push(r.value); + } + const restoredBody = Buffer.concat(chunks).toString("utf8"); + assert.deepEqual(JSON.parse(restoredBody), original, "original payload restored"); + const restoredHeaders = new Headers(verdict.init?.headers); + assert.equal(restoredHeaders.get("authorization"), "Bearer sk-oc", "original headers preserved"); + assert.equal(restoredHeaders.get(MARKER), null); + assert.equal(await guard!(swapped.url, swapped), undefined, "consumed on read"); + } finally { + await lane.close(); + } +}); + +test("#3304 pi ledger: note/consume/clear/expiry semantics", async () => { + const { notePiIncrementalOriginal, clearPiIncrementalOriginal, consumePiIncrementalOriginal, __resetIncrementalClientForTests } = await import("../src/agent/incremental-client.ts"); + __resetIncrementalClientForTests(); + const payload = { model: "claude-test", messages: [{ role: "user", content: "pi" }] }; + assert.equal(consumePiIncrementalOriginal("sid-a"), undefined, "absent before any note"); + notePiIncrementalOriginal("sid-a", payload); + assert.deepEqual(consumePiIncrementalOriginal("sid-a"), payload, "consume returns the original"); + assert.equal(consumePiIncrementalOriginal("sid-a"), undefined, "and forgets it"); + notePiIncrementalOriginal("sid-a", payload); + clearPiIncrementalOriginal("sid-a"); + assert.equal(consumePiIncrementalOriginal("sid-a"), undefined, "clear wins"); + notePiIncrementalOriginal("sid-b", payload); + const realNow = Date.now; + try { + Date.now = () => realNow() + 61_000; + assert.equal(consumePiIncrementalOriginal("sid-b"), undefined, "expired entries are absent (TTL bounds memory)"); + } finally { + Date.now = realNow; + } +}); + +test("#3304 pi-native guard: sid from x-bili-plugin-conversation restores the noted payload", async () => { + const { notePiIncrementalOriginal, consumePiIncrementalOriginal, __resetIncrementalClientForTests, INCREMENTAL_TURN_MARKER_HEADER } = await import("../src/agent/incremental-client.ts"); + const mod = await import("../src/agent/pi-native.ts"); + __resetIncrementalClientForTests(); + const guard = mod._directGuardForTest(); + assert.notEqual(guard, undefined, "guard armed at module load (spawn posture)"); + const payload = { model: "claude-test", max_tokens: 512, messages: [{ role: "user", content: "pi wire" }] }; + notePiIncrementalOriginal("pi-sid-3304", payload); + const init: RequestInit = { + method: "POST", + headers: { "x-bili-plugin-conversation": "pi-sid-3304", [INCREMENTAL_TURN_MARKER_HEADER]: "1", "content-type": "application/json" }, + body: ENVELOPE_BODY, + }; + const verdict = await guard!(UPSTREAM_URL, UPSTREAM_URL, init); + if (verdict === undefined || verdict === "refuse") throw new Error(`expected a restored pair, got ${String(verdict)}`); + assert.equal(verdict.input, UPSTREAM_URL); + assert.equal(verdict.init?.body, JSON.stringify(payload), "original payload re-serialized onto the wire"); + const restoredHeaders = new Headers(verdict.init?.headers); + assert.equal(restoredHeaders.get(INCREMENTAL_TURN_MARKER_HEADER), null, "marker stripped by the restore"); + assert.equal(restoredHeaders.get("x-bili-plugin-conversation"), "pi-sid-3304", "attribution header untouched"); + assert.equal(await guard!(UPSTREAM_URL, UPSTREAM_URL, init), undefined, "consumed on read"); + assert.equal(consumePiIncrementalOriginal("pi-sid-3304"), undefined, "ledger drained"); + // no conversation header → miss, nothing consumed + notePiIncrementalOriginal("pi-sid-other", payload); + assert.equal(await guard!(UPSTREAM_URL, UPSTREAM_URL, { method: "POST", body: ENVELOPE_BODY }), undefined); + assert.notEqual(consumePiIncrementalOriginal("pi-sid-other"), undefined, "miss consumes nothing"); + __resetIncrementalClientForTests(); +});