Skip to content
Closed
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
4 changes: 2 additions & 2 deletions src/agent/dsh-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScr
import { installNativeFetchIntercept, 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, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, type IncrementalWireMessage } from "./incremental-client.js";
import { clearIncrementalProbe, INCREMENTAL_TURN_MARKER_HEADER, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, wireMessagesLookAnthropic, type IncrementalWireMessage } from "./incremental-client.js";
export { sideShapedBody } from "./fork-adopt.js";

export const name = "bili-native";
Expand Down Expand Up @@ -1361,7 +1361,7 @@ export function apply(ctx: PluginContext): void {
} catch {
return;
}
if (!Array.isArray(parsed.messages) || typeof parsed.model !== "string") return; // anthropic wire only
if (typeof parsed.model !== "string" || !wireMessagesLookAnthropic(parsed.messages)) return; // anthropic wire only — OpenAI tool shapes (tool_calls / role:"tool") resend full (#3433)
const base = register.base ?? state.origin;
if (base === undefined) return;
if (!(await probeIncrementalTurns(base))) return;
Expand Down
3 changes: 2 additions & 1 deletion src/agent/pi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, INCREMENTAL_TURN_MARKER_HEADER, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, wireMessagesLookAnthropic, 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";
Expand Down Expand Up @@ -1206,6 +1206,7 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM
if (state.toolsReady !== true) return undefined; // no marker stamped → must not replace
const payload = event.payload as { messages?: unknown; system?: unknown } | undefined;
if (payload === null || typeof payload !== "object" || !Array.isArray((payload as { messages?: unknown }).messages)) return undefined;
if (!wireMessagesLookAnthropic(payload.messages)) return undefined; // anthropic wire only — OpenAI tool shapes resend full (#3433)
const sid = sessionIdOf(ctx);
if (sid === undefined || sid.length === 0) return undefined;
let proxyBase = proxyBaseForCtx(ctx);
Expand Down
14 changes: 14 additions & 0 deletions src/incremental-lane.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,19 @@ export function incrementalTurnBodyShape(raw: Buffer): boolean {
&& body.model === undefined;
}

/** Lane-side mirror of wireMessagesLookAnthropic (src/agent/incremental-client.ts — keep the two in sync): the lane ingests with anthropicToCore and re-emits with coreToAnthropic, so only the anthropic wire shape is convertible. OpenAI tool shapes (assistant.tool_calls, role:"tool"/"function", tool_call_id) would be silently dropped or mis-mapped into user text — reject loudly at the boundary instead of trusting every host to pre-filter (#3433). Empty lists PASS here: a pure sticky-system update carries no messages (the client-side predicate rejects them; the empty-without-system case is already a 400 below). */
function laneMessagesLookAnthropic(messages: unknown): boolean {
if (!Array.isArray(messages)) return false;
for (const m of messages) {
if (m === null || typeof m !== "object") return false;
const msg = m as { role?: unknown; content?: unknown; tool_calls?: unknown; tool_call_id?: unknown };
if (typeof msg.role !== "string" || msg.role === "tool" || msg.role === "function") return false;
if (msg.tool_calls !== undefined || msg.tool_call_id !== undefined) return false;
if (typeof msg.content !== "string" && !Array.isArray(msg.content)) return false;
}
return true;
}

const EXT_KEY_SYSTEM = "inc:system";
const EXT_KEY_CACHE_MARKS = "inc:cache-marks";
const EXT_KEY_BASE_SEQ = "inc:base-seq";
Expand Down Expand Up @@ -362,6 +375,7 @@ export async function handleIncrementalTurn(
if (typeof forwarded.model !== "string" || forwarded.model.length === 0) return jsonReply(res, 400, { error: "request.model is required" });
if (!Array.isArray(payload.messages)) return jsonReply(res, 400, { error: "messages must be an array (seed: full history; delta: everything after sinceSeq; empty allowed for a pure sticky-system update)" });
if (payload.messages.length === 0 && payload.system === undefined) return jsonReply(res, 400, { error: "messages must be a non-empty array (seed: full history; delta: everything after sinceSeq)" });
if (!laneMessagesLookAnthropic(payload.messages)) return jsonReply(res, 400, { error: 'messages must be anthropic wire shape — OpenAI tool shapes (assistant.tool_calls, role:"tool", tool_call_id) cannot ride the lane and stay on full resend', conversationId });
const deltaWire = payload.messages;

// Per-conversation turn lock: the ack contract is strictly sequential.
Expand Down
48 changes: 48 additions & 0 deletions tests/dsh-native.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,54 @@ test("#3370: dsh incremental conversion is atomic (marker + body on the same ini
}
});

// #3433: OpenAI wire shapes (assistant.tool_calls / role:"tool") must NOT be
// converted onto the incremental lane — the lane ingests with anthropicToCore
// and would silently drop the tool calls. They stay on full resend, exactly
// like omp/opencode do behind wireMessagesLookAnthropic.
test("#3433: dsh OpenAI tool shapes ride full resend; anthropic shapes still convert", async () => {
const proxy = await startMockProxy([], undefined, undefined, undefined, true);
const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-inc3433-"));
const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-inc3433-state-"));
try {
await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin, XDG_STATE_HOME: stateHome, BILI_PROVIDER_REWRITES: undefined, BILI_NATIVE_DSH: undefined, BILLION_CONTEXT_PLUGIN: undefined }, async () => {
_resetRegisterForTest(proxy.origin);
__resetIncrementalClientForTests();
const ctx = mockCtx();
ctx.setInitiator({ session: { id: "dsh-inc-3433" } });
apply(ctx);
await waitFor(() => ctx.registeredTools.length === 1, "manifest tool registration");
await _stateToolsReadyForTest();
const beforeSend = _stateBeforeSendForTest();
assert.ok(beforeSend, "conversion seam armed");
const url = `${proxy.origin}/v1/chat/completions`;

// OpenAI chat-completions shape: assistant.tool_calls + role:"tool"
const openaiMsgs = [
{ role: "user", content: "list the files" },
{ role: "assistant", content: null, tool_calls: [{ id: "call_1", type: "function", function: { name: "ls", arguments: "{}" } }] },
{ role: "tool", tool_call_id: "call_1", content: "a.txt b.txt" },
{ role: "user", content: "now read a.txt" },
];
const original = JSON.stringify({ model: "gpt-test", max_tokens: 64, messages: openaiMsgs });
const init: RequestInit = { method: "POST", body: original };
await beforeSend(url, init);
assert.equal(init.body, original, "OpenAI tool shape rides full resend (body untouched)");
assert.equal(new Headers(init.headers ?? {}).get("x-bili-plugin-turn"), null, "no marker on the untouched body");

// control: the anthropic wire shape still converts (guard does not over-block)
const init2: RequestInit = { method: "POST", body: JSON.stringify({ model: "claude-test", max_tokens: 64, messages: [{ role: "user", content: [{ type: "text", text: "hello" }] }] }) };
await beforeSend(url, init2);
const body2 = JSON.parse(init2.body as string) as { conversationId?: string };
assert.equal(body2.conversationId, "dsh-inc-3433", "anthropic shape still converts to a lane turn");
assert.equal(new Headers(init2.headers).get("x-bili-plugin-turn"), "1", "marker stamped on the anthropic turn");
});
} finally {
proxy.close();
rmrf(home);
rmrf(stateHome);
}
});

import { rmrf } from "./tmp-rm.ts";

// #1797: drain ALL in-flight attach/recovery chains after each test — defense-in-depth
Expand Down
30 changes: 30 additions & 0 deletions tests/incremental-lane.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,3 +476,33 @@ test("incrementalTurnBodyShape accepts the incremental payload and rejects anthr
const badSeq = Buffer.from(JSON.stringify({ conversationId: "c1", sinceSeq: "3", messages: [] }));
assert.equal(incrementalTurnBodyShape(badSeq), false, "sinceSeq must be an integer");
});

// #3433: the lane ingests with anthropicToCore and re-emits with coreToAnthropic,
// so non-anthropic message shapes must be rejected LOUDLY at the boundary —
// converting them would silently drop assistant.tool_calls or mis-map
// role:"tool" into user text. The client-side mirror is
// wireMessagesLookAnthropic; this is the trust-boundary enforcement.
test("#3433: lane rejects non-anthropic message shapes with 400, never half-converts them", async () => {
const h = await harness("full");
try {
const toolRole = await h.turn({ sinceSeq: 0, resync: true, messages: [
{ role: "user", content: "hi" },
{ role: "tool", tool_call_id: "c1", content: "out" },
] });
assert.equal(toolRole.status, 400);
assert.match((toolRole.body as { error?: string }).error ?? "", /anthropic wire shape/);

const toolCalls = await h.turn({ sinceSeq: 0, resync: true, messages: [
{ role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "f", arguments: "{}" } }] },
] });
assert.equal(toolCalls.status, 400);
assert.match((toolCalls.body as { error?: string }).error ?? "", /anthropic wire shape/);

// the rejections applied nothing — a valid anthropic seed still lands
const seed = await h.turn({ sinceSeq: 0, resync: true, messages: [{ role: "user", content: "hello" }] });
assert.equal(seed.status, 200);
assert.equal(seed.headers.get("x-bili-applied-seq"), "1");
} finally {
await h.close();
}
});
133 changes: 133 additions & 0 deletions tests/issue3433-pi-incremental-guard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// #3433: pi (and pi-native, which inherits this wiring by design) must apply
// the same anthropic-wire guard as omp/opencode before converting an outgoing
// payload onto the incremental lane — pi supports openai/responses/google
// provider APIs, so OpenAI tool shapes (assistant.tool_calls / role:"tool")
// reach before_provider_request and would be silently dropped by the lane's
// anthropicToCore ingest. They stay on full resend.
import assert from "node:assert/strict";
import http from "node:http";
import { once } from "node:events";
import test, { after } 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 { createBiliPlugin } from "../src/agent/pi.ts";
import { __resetIncrementalClientForTests } from "../src/agent/incremental-client.js";

process.env.NODE_ENV = "test";
const testRoot = mkdtempSync(join(tmpdir(), "bili-incr3433-"));
after(() => rmSync(testRoot, { recursive: true, force: true }));

type FakePi = { events: Map<string, (event: unknown, ctx: unknown) => unknown>; tools: Array<{ name: string }>; on: (event: string, handler: (event: never, ctx: never) => unknown) => void; registerTool: (tool: { name: string }) => void };

function makeFakePi(): FakePi {
const events = new Map<string, (event: unknown, ctx: unknown) => unknown>();
const tools: Array<{ name: string }> = [];
return {
events,
tools,
on: (event, handler) => {
const h = handler as (event: unknown, ctx: unknown) => unknown;
const prev = events.get(event);
events.set(event, prev ? ((e, c) => { prev(e, c); return h(e, c); }) : h);
},
registerTool: (tool) => {
const i = tools.findIndex((t) => t.name === tool.name);
if (i >= 0) tools[i] = tool;
else tools.push(tool);
},
};
}

/** Real proxy with the lane LIVE (unified storage + rollout forced on) so the
* probe passes and the guard — not the probe — is what decides conversion. */
async function harness(): Promise<{ origin: string; close: () => Promise<void> }> {
const dir = mkdtempSync(join(testRoot, "run-"));
const savedXdg: Record<string, string | undefined> = {};
const savedRollout = process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS;
const savedProxy = process.env.BILLION_CONTEXT_PROXY;
for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) {
savedXdg[key] = process.env[key];
process.env[key] = dir;
}
process.env.BILI_STORAGE_UNIFIED = "full";
process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS = "1";
_resetSessionsForTest();
_resetPluginStateForTest();
resetToolRingForTest();
__resetIncrementalClientForTests();
const store = new SessionStore({ dir: dir + "/sessions", enabled: true, debounceMs: 60000 });
_setStoreForTest(store);
_setForTest({});
const upstream = http.createServer((req, res) => {
req.resume();
req.on("end", () => {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ id: "msg_test", role: "assistant", content: [{ type: "text", text: "answer" }], usage: { input_tokens: 100, 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 origin = `http://127.0.0.1:${(proxy.address() as { port: number }).port}`;
process.env.BILLION_CONTEXT_PROXY = origin;
return {
origin,
close: async () => {
for (const [key, v] of Object.entries(savedXdg)) {
if (v === undefined) delete process.env[key];
else process.env[key] = v;
}
if (savedRollout === undefined) delete process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS;
else process.env.BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS = savedRollout;
if (savedProxy === undefined) delete process.env.BILLION_CONTEXT_PROXY;
else process.env.BILLION_CONTEXT_PROXY = savedProxy;
await new Promise<void>((resolve) => proxy.close(() => resolve()));
store.closeQuietly();
await new Promise<void>((resolve) => upstream.close(() => resolve()));
},
};
}

test("#3433: pi OpenAI tool shapes ride full resend; anthropic shapes still convert", async () => {
const h = await harness();
try {
const pi = makeFakePi();
createBiliPlugin("pi")(pi as never);
const handler = pi.events.get("before_provider_request");
assert.ok(handler, "before_provider_request handler registered");
const ctx = { sessionManager: { getSessionId: () => "pi-inc-3433" }, model: { id: "claude-test", contextWindow: 400000, baseUrl: h.origin }, cwd: "/tmp" };

// OpenAI chat-completions shape: assistant.tool_calls + role:"tool"
const openaiBody = { model: "gpt-test", max_tokens: 64, stream: false, messages: [
{ role: "user", content: "list the files" },
{ role: "assistant", content: null, tool_calls: [{ id: "call_1", type: "function", function: { name: "ls", arguments: "{}" } }] },
{ role: "tool", tool_call_id: "call_1", content: "a.txt b.txt" },
] };
const out = await handler({ payload: openaiBody }, ctx);
assert.ok(pi.tools.length > 0, "tools registered — the readiness gate passed, so the shape guard is what skipped the conversion");
assert.equal(out, undefined, "OpenAI tool shape: no replacement — the host keeps its full-resend payload");

// control: the anthropic wire shape DOES convert in the same live-lane environment
const anthropicBody = { model: "claude-test", max_tokens: 64, system: "sys", messages: [{ role: "user", content: [{ type: "text", text: "hello" }] }] };
const replaced = (await handler({ payload: anthropicBody }, ctx)) as { conversationId?: string; sinceSeq?: number; messages?: unknown[] } | undefined;
assert.ok(replaced !== undefined, "anthropic shape converts (guard does not over-block)");
assert.equal(replaced?.conversationId, "pi-inc-3433");
assert.equal(replaced?.sinceSeq, 0, "first turn seeds the lane");
assert.equal(replaced?.messages?.length, 1);
} finally {
await h.close();
}
});
Loading