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
42 changes: 25 additions & 17 deletions src/incremental-lane.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,6 @@ function warnDroppedRequestParams(conversationId: string, request: Record<string
log("warn", `[incremental] ${conversationId}: request parameter(s) not in the forward allowlist were dropped: ${unwarned.join(", ")} — extend REQUEST_PARAM_KEYS (src/incremental-lane.ts) if they must reach the upstream (#3406)`);
}

/** Wire headers the client may contribute to the forwarded request. */
const PASSTHROUGH_HEADERS = ["authorization", "anthropic-version", "anthropic-beta"] as const;

/** Canonical prefix per conversation, in memory. Bounded LRU: cold entries
* rebuild from the unified messages table on demand (see loadCanonical). */
const CANONICAL_LIMIT = 16;
Expand Down Expand Up @@ -826,26 +823,37 @@ export async function handleIncrementalTurn(
}
const bodyBuf = laneBodyBuffer(body, itemsStr);

const headers: Record<string, string> = {
"content-type": "application/json",
"content-length": String(bodyBuf.length),
host: headerValue(req, "host") ?? "127.0.0.1",
// Session identity rides the CLIENT's own conversation header (the
// strongest signal in the pipeline) — see laneSessionId().
"x-bili-plugin": agent,
"x-bili-plugin-conversation": conversationId,
accept: headerValue(req, "accept") ?? "application/json",
};
// Re-enter the pipeline (forward → handleRequest → buildForwardHeaders) with a
// synthetic indistinguishable from the ORIGINAL client request, so egress
// normalization is the SAME code that serves full-resend traffic (#5658). This
// mirrors the marker-divert replay (handle.ts): copy the client's own headers
// and drop only the lane-intent marker — do NOT hand-roll a strip list, which
// diverges from the proven non-incremental surface and risks upstream rejection.
// The only extra corrections are forced by the REBUILT body: its length, and the
// encoding marker (an assembled turn body is always plain JSON, so any inbound
// content-encoding is stale). Lane identity is stamped below.
const headers: Record<string, string> = {};
for (const [k, v] of Object.entries(req.headers)) {
if (v === undefined) continue;
const lower = k.toLowerCase();
if (lower === INCREMENTAL_TURN_MARKER_HEADER.toLowerCase()) continue;
if (lower === "content-encoding") continue;
headers[k] = Array.isArray(v) ? v.join(", ") : v;
}
// Lane-owned values win, set explicitly (framing matches the assembled body;
// session identity rides the client's own conversation value — laneSessionId()).
headers["content-type"] = "application/json";
headers["content-length"] = String(bodyBuf.length);
headers["host"] = headerValue(req, "host") ?? "127.0.0.1";
headers["x-bili-plugin"] = agent;
headers["x-bili-plugin-conversation"] = conversationId;
headers["accept"] = headerValue(req, "accept") ?? "application/json";
// Plugin capability headers the client may contribute on the turn
// POST (context window / max output reports for the [window] clamp).
for (const h of ["x-bili-plugin-context-window", "x-bili-plugin-max-output"] as const) {
const v = headerValue(req, h);
if (v !== undefined) headers[h] = v;
}
for (const h of PASSTHROUGH_HEADERS) {
const v = headerValue(req, h);
if (v !== undefined) headers[h] = v;
}
if (model !== undefined) headers["x-bili-plugin-model"] = model;

const synthetic = Readable.from([bodyBuf]) as unknown as http.IncomingMessage;
Expand Down
5 changes: 5 additions & 0 deletions src/server/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ export const UPSTREAM_HOP_HEADERS = new Set([
"x-bili-pf-count",
"x-bili-pf-seq",
"x-bili-pf-tail-ids",
// #5658: incremental-lane turn correlation id — the native plugin stamps it
// on a diverted model request alongside x-bili-plugin-turn to correlate the
// applied-seq ack. Pure host↔bili bookkeeping; like the pf-* handshake
// headers above it must never reach a model endpoint, so strip at egress.
"x-bili-turn-id",
"te",
"trailer",
"upgrade",
Expand Down
11 changes: 11 additions & 0 deletions tests/e2e/e2e-native-pi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,17 @@ function piRun(
cwd: ctx.piCwd,
env: {
...cleanEnv(),
// This suite documents the SPAWN-posture package-native contract:
// instance record + proxy origin, per-request wire stamps, the
// shared-proxy delegate-child ACP channel (#2268), /__bili/plugin/status
// over HTTP. #5428 flipped the pi lane DEFAULT to inline (in-process
// engine, no instance record) and this suite was not updated with it:
// primary-lane tests then pass for the wrong reason while the
// instance-record and delegate-child stamp assertions fail structurally
// (CI sentinel incident, #4599). Pin the legacy posture so this
// coverage stays deterministic; inline posture is covered by
// tests/pi-inline-ws.test.ts and tests/pi-native.test.ts.
BILI_PI_INLINE: "0",
PI_CODING_AGENT_DIR: ctx.piAgentDir,
XDG_CONFIG_HOME: ctx.xdg.config,
XDG_CACHE_HOME: ctx.xdg.cache,
Expand Down
13 changes: 10 additions & 3 deletions tests/e2e/e2e-pi-codex-ws.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -722,7 +722,14 @@ test("E: two subagent-style sessions share one proxy — distinct state, identic
assert.ok(r.stdout.includes("WS_E2E_OK"));
};

ok("X warmup", await piRun(ctxX, "alpha marker ALPHA_X_SEED"));
// #5428 flipped the pi lane's DEFAULT posture to inline (in-process proxy):
// left unpinned, X's proxy would die with its pi process and unregister its
// instance record — nothing left to discover, nothing for Y to attach to.
// This scenario pins the legacy spawn/attach posture it was built on;
// scenarios A–D intentionally ride the new inline default.
const legacyPosture: NodeJS.ProcessEnv = { BILI_PI_INLINE: "0" };

ok("X warmup", await piRun(ctxX, "alpha marker ALPHA_X_SEED", { extraEnv: legacyPosture }));
const origin = proxyOriginOf(ctxX);
assert.ok(origin, "X's proxy origin discovered from its instance record");
// Y attaches to X's proxy (real subagent posture: inherited
Expand All @@ -733,7 +740,7 @@ test("E: two subagent-style sessions share one proxy — distinct state, identic

// Same tool args ({}) from both sessions, interleaved.
const [xStatus, yStatus] = await Promise.all([
piRun(ctxX, "WS_STATUS alpha status", { resume: true }),
piRun(ctxX, "WS_STATUS alpha status", { resume: true, extraEnv: legacyPosture }),
piRun(ctxY, "WS_STATUS beta status", { resume: true, extraEnv: yEnv }),
]);
ok("X status", xStatus);
Expand Down Expand Up @@ -763,7 +770,7 @@ test("E: two subagent-style sessions share one proxy — distinct state, identic

// Concurrent plain turns, same proxy, no cross-talk afterwards.
const [xFin, yFin] = await Promise.all([
piRun(ctxX, "concurrent X tail", { resume: true }),
piRun(ctxX, "concurrent X tail", { resume: true, extraEnv: legacyPosture }),
piRun(ctxY, "concurrent Y tail", { resume: true, extraEnv: yEnv }),
]);
ok("X concurrent", xFin);
Expand Down
10 changes: 9 additions & 1 deletion tests/event-loop-watchdog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,15 @@ test("wedged main loop trips the watchdog: warn + fatal forensic lines land in t
assert.ok(handle, "handle expected");
await sleep(50); // beats flowing — worker initialized
blockMainLoop(400); // synchronous spin: zero heartbeats reach the worker
await sleep(80); // deliver the queued trip message
// Deliver the queued trip message. Poll to a bounded deadline instead
// of one fixed grace sleep: under runner load, worker init or the
// postMessage hop can land past any small fixed window without the
// mechanism breaking (#4762; same load-flake family as #4161 — the
// 2026-11-04 windows-latest/node-24 shard-4 red fired exactly this
// line on green code). A genuinely dead trip path still fails — after
// the full budget.
const tripDeadline = Date.now() + 3_000;
while (typeof trippedWith !== "number" && Date.now() < tripDeadline) await sleep(20);
if (typeof trippedWith !== "number") throw new Error(`onTrip must fire after a continuous block past hardTimeoutMs (got ${String(trippedWith)})`);
assert.ok(trippedWith >= 150, `gap ${trippedWith} must reach the hard threshold`);
const content = fs.readFileSync(logFile, "utf8");
Expand Down
151 changes: 151 additions & 0 deletions tests/issue5658-incremental-credential-headers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import assert from "node:assert/strict";
import http from "node:http";
import { once } from "node:events";
import test from "node:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { defaultConfig } from "acp-kernel";
import { startServer } from "../src/server.ts";
import type { ProxyOptions } from "../src/config.ts";
import { SessionStore, _setStoreForTest } from "../src/persist.ts";
import { _resetPluginStateForTest } from "../src/plugin.ts";
import { _resetSessionsForTest } from "../src/session.ts";
import { _setForTest } from "../src/registry.ts";
import { resetToolRingForTest } from "../src/tool-ring.ts";
import { __resetIncrementalLaneForTests } from "../src/incremental-lane.ts";

// #5658: the delta lane rebuilt the outbound request with a positive header
// allowlist (authorization / anthropic-version / anthropic-beta), so any
// credential outside it — x-api-key above all — was silently dropped and the
// upstream answered 401 ("governor"), which DSH maps to an account sign-out.
// The fix forwards the client's own end-to-end headers (minus hop-by-hop and
// x-bili-* markers); these tests pin that credentials reach the upstream and
// lane markers do not.
process.env.NODE_ENV = "test";
const testRoot = mkdtempSync(join(tmpdir(), "bili-incr-cred-"));
test.after(() => rmSync(testRoot, { recursive: true, force: true }));

interface UpstreamHit {
headers: Record<string, string | string[] | undefined>;
body: unknown;
}

async function harness(): Promise<{
proxyUrl: string;
turn: (extraHeaders: Record<string, string>) => Promise<number>;
markerTurn: (extraHeaders: Record<string, string>) => Promise<number>;
hits: UpstreamHit[];
close: () => Promise<void>;
}> {
const dir = mkdtempSync(join(testRoot, "run-"));
const savedRollout = process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS;
for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) process.env[key] = dir;
process.env.BILI_STORAGE_UNIFIED = "full";
// The marker-divert entry gates on the pluginIncrementalTurns rollout feature.
process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS = "1";
_resetSessionsForTest();
_resetPluginStateForTest();
resetToolRingForTest();
__resetIncrementalLaneForTests();
const store = new SessionStore({ dir: dir + "/sessions", enabled: true, debounceMs: 60000 });
_setStoreForTest(store);
_setForTest({});
const hits: UpstreamHit[] = [];
const upstream = http.createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => chunks.push(chunk));
req.on("end", () => {
hits.push({ headers: req.headers, body: JSON.parse(Buffer.concat(chunks).toString("utf8")) });
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ id: "msg_test", role: "assistant", content: [{ type: "text", text: "answer" }], usage: { input_tokens: 10000, output_tokens: 10 } }));
});
});
upstream.listen(0, "127.0.0.1");
await once(upstream, "listening");
const addr = upstream.address();
assert(addr && typeof addr === "object");
const upstreamUrl = `http://127.0.0.1:${addr.port}`;
const proxy = await startServer({ port: 0, host: "127.0.0.1", upstream: upstreamUrl, routes: { [upstreamUrl]: { models: { "claude-test": { context: 400000 } } } }, modelContextLimit: 400000, kernelConfig: defaultConfig(400000), compress: { injectTool: true, injectNudge: false }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: false, debug: false, passthrough: false, autoUpdate: false, mitm: { enabled: false, domains: [] } } as ProxyOptions);
if (!(proxy as unknown as { listening?: boolean }).listening) await once(proxy, "listening");
const proxyUrl = `http://127.0.0.1:${(proxy.address() as { port: number }).port}`;
const path = "/v1/messages";
const seedBody = { conversationId: "conv-cred", sinceSeq: 0, path, request: { model: "claude-test", max_tokens: 1024 }, messages: [{ role: "user", content: "hello" }] };
// Direct /__bili/plugin/turn entry: the client carries its credentials on the
// turn POST exactly as it would on a full-resend request.
const turn = async (extraHeaders: Record<string, string>): Promise<number> => {
const response = await fetch(`${proxyUrl}/__bili/plugin/turn`, {
method: "POST",
headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "conv-cred", ...extraHeaders },
body: JSON.stringify(seedBody),
});
return response.status;
};
// Marker-divert entry: shaped turn posted on the ORDINARY model path with the
// x-bili-plugin-turn marker — the marker must NOT reach the upstream.
const markerTurn = async (extraHeaders: Record<string, string>): Promise<number> => {
const response = await fetch(`${proxyUrl}${path}`, {
method: "POST",
headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "conv-cred-marker", "x-acp-session": "conv-cred-marker", "x-bili-plugin-turn": "1", ...extraHeaders },
body: JSON.stringify({ conversationId: "conv-cred-marker", sinceSeq: 0, request: { model: "claude-test", max_tokens: 1024 }, messages: [{ role: "user", content: "hello" }] }),
});
return response.status;
};
const close = async (): Promise<void> => {
if (savedRollout === undefined) delete process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS;
else process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS = savedRollout;
await new Promise<void>((resolve) => proxy.close(() => resolve()));
store.closeQuietly();
await new Promise<void>((resolve) => upstream.close(() => resolve()));
};
return { proxyUrl, turn, markerTurn, hits, close };
}

const CREDENTIALS: [string, string][] = [
["authorization", "Bearer TEST-AUTH"],
["x-api-key", "sk-TEST-XAPIKEY"],
["x-goog-api-key", "goog-TEST"],
["api-key", "vendor-TEST"],
];

function hitHasCredential(h: UpstreamHit, name: string, value: string): boolean {
const v = h.headers[name.toLowerCase()];
return v === value || (Array.isArray(v) && v.includes(value));
}

test("#5658 direct turn: every credential header reaches the upstream, no x-bili marker leaks", async () => {
const h = await harness();
try {
const status = await h.turn({ ...Object.fromEntries(CREDENTIALS), "x-custom-gateway": "gw-TEST", "x-bili-turn-id": "turn-direct-TEST" });
assert.equal(status, 200);
assert.equal(h.hits.length, 1);
const hit = h.hits[0];
for (const [name, value] of CREDENTIALS) {
assert.ok(hitHasCredential(hit, name, value), `credential header ${name} must reach the upstream`);
}
// Full-resend parity (#5658): the lane forwards the client's OWN end-to-end
// headers verbatim (buildForwardHeaders downstream), never an allowlist — an
// arbitrary non-credential client header must ride through as well.
assert.ok(hitHasCredential(hit, "x-custom-gateway", "gw-TEST"), "an arbitrary client end-to-end header must reach the upstream");
assert.equal(hit.headers["x-bili-turn-id"] ?? null, null, "lane turn-id bookkeeping must not be forwarded verbatim");
} finally {
await h.close();
}
});

test("#5658 marker divert: credentials reach the upstream, x-bili-plugin-turn marker is stripped", async () => {
const h = await harness();
try {
const status = await h.markerTurn({ ...Object.fromEntries(CREDENTIALS), "x-bili-turn-id": "turn-divert-TEST" });
assert.equal(status, 200);
assert.equal(h.hits.length, 1);
const hit = h.hits[0];
for (const [name, value] of CREDENTIALS) {
assert.ok(hitHasCredential(hit, name, value), `credential header ${name} must reach the upstream`);
}
assert.equal(hit.headers["x-bili-plugin-turn"] ?? null, null, "the divert marker must never ride onto the upstream request");
assert.equal(hit.headers["x-bili-turn-id"] ?? null, null, "lane turn-id bookkeeping must not be forwarded verbatim");
} finally {
await h.close();
}
});
Loading
Loading