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/pi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -554,7 +554,7 @@ function manifestToTool(proxyBase: string, tool: ManifestTool, agent: string): T
description: tool.description,
parameters: tool.inputSchema,
loadMode: "essential",
execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
execute: async (toolCallId, params, signal, _onUpdate, ctx) => {
const conversationId = sessionIdOf(ctx) ?? "unknown";
try {
// #2416: read the LIVE base — a native respawn after a proxy
Expand All @@ -574,7 +574,7 @@ function manifestToTool(proxyBase: string, tool: ManifestTool, agent: string): T
// rebinding (onRoutedOriginObserved) converges env back to the
// observed routed origin.
const base = proxyBaseForCtx(ctx) ?? proxyBase;
const output = await forwardTool(base, conversationId, tool.name, params, signal, conversationId !== "unknown");
const output = await forwardTool(base, conversationId, tool.name, params, signal, conversationId !== "unknown", toolCallId);
// #2204: a business failure (e.g. a refused export) must reach
// the host as isError — rendering it as plain success text is
// what hid the #2204 write failures from OMP.
Expand Down
5 changes: 3 additions & 2 deletions src/agent/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,8 +334,9 @@ export async function reportRuntimeInfoOnChange(proxyBase: string | undefined, i
* partial note in `text`. Absent on legacy envelopes without the fields. */
export type ForwardedToolResult = { text: string; failed: boolean; outcome?: ToolOutcomeKind; blocksCreated?: number };

export async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal, nativeCaller: boolean = false): Promise<ForwardedToolResult> {
const body: { conversationId: string; tool: string; args: unknown; nativeCaller?: boolean } = { conversationId, tool, args: args ?? {} };
export async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal, nativeCaller: boolean = false, toolCallId?: string): Promise<ForwardedToolResult> {
const body: { conversationId: string; tool: string; args: unknown; nativeCaller?: boolean; toolCallId?: string } = { conversationId, tool, args: args ?? {} };
if (toolCallId !== undefined) body.toolCallId = toolCallId;
// #2072: host-native agents (pi / dsh / opencode) stamp a per-call id minted
// by the host's own session manager — declare it so a stale sibling witness
// can neither redirect nor fail-closed the call (ladder rung 0, #2024/#2016).
Expand Down
55 changes: 48 additions & 7 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,55 @@ const PLUGIN_REQUEST_AGENT_HEADER = "x-bili-plugin-agent";

const PLUGIN_PROTOCOL_VERSION = 1;

/** #1567: folds executed through POST /__bili/plugin/tool are minted this
* synthetic callId, which the client can never echo back — its own re-sent
* compress pair is the summary carrier for such blocks, so the kernel's
* in-place acp_summary anchor is redundant and must be stripped (#1567). */
/** #1567: legacy callers without a native tool-call id get a synthetic id.
* Their resent compress pair is recognized by range as a summary carrier. */
const PLUGIN_FOLD_CALLID_PREFIX = "plugin_";
export function isPluginFoldCallId(callId: string | undefined): boolean {
return typeof callId === "string" && callId.startsWith(PLUGIN_FOLD_CALLID_PREFIX);
}

/** Reconnect legacy plugin blocks before the kernel mistakes their live carriers for orphans. */
export function reconcilePluginFoldCallIds(session: Session, messages: CoreMessage[]): number {
const blocks = new Map<string, typeof session.state.blocks>();
for (const block of session.state.blocks) {
if (!block.active || !block.startRef || !block.endRef) continue;
const key = JSON.stringify([block.startRef, block.endRef]);
const sameRange = blocks.get(key) ?? [];
sameRange.push(block);
blocks.set(key, sameRange);
}
const calls = new Map<string, Set<string>>();
const results = new Map(messages.filter((m) => m.contentType === "tool-result" && m.toolCallId).map((m) => [m.toolCallId!, m.text ?? ""]));
for (const message of messages) {
if (message.contentType !== "tool-call" || message.toolName !== "compress" || !message.toolCallId) continue;
try {
const args = JSON.parse(message.text ?? "") as { content?: unknown; startId?: unknown; endId?: unknown };
for (const range of Array.isArray(args?.content) ? args.content : [args]) {
if (!range || typeof range.startId !== "string" || typeof range.endId !== "string") continue;
const key = JSON.stringify([range.startId, range.endId]);
if (!blocks.has(key)) continue;
const ids = calls.get(key) ?? new Set<string>();
ids.add(message.toolCallId);
calls.set(key, ids);
}
} catch { /* Invalid historical arguments cannot establish ownership. */ }
}
let changed = 0;
for (const [key, sameRange] of blocks) {
const block = sameRange[0]!;
if (sameRange.length !== 1 || !isPluginFoldCallId(block.compressCallId)) continue;
const ids = [...calls.get(key) ?? []].filter((id) => {
const receipt = results.get(id);
return receipt?.startsWith("[Compressed ") && receipt.split("\n").some((line) => line.startsWith(` · ${block.blockId} full summary `));
});
if (ids.length !== 1) continue;
block.compressCallId = ids[0]!;
changed++;
}
if (changed > 0) markDirty(session);
return changed;
}

const VERSION = (() => {
try {
const here = fileURLToPath(import.meta.url);
Expand Down Expand Up @@ -1597,9 +1637,9 @@ export async function handlePluginTool(
res: import("node:http").ServerResponse,
deps: PluginToolDeps,
): Promise<void> {
let parsed: { conversationId?: unknown; tool?: unknown; args?: unknown; expectedRevision?: unknown; nativeCaller?: unknown };
let parsed: { conversationId?: unknown; tool?: unknown; args?: unknown; expectedRevision?: unknown; nativeCaller?: unknown; toolCallId?: unknown };
try {
parsed = JSON.parse(payload) as { conversationId?: unknown; tool?: unknown; args?: unknown; expectedRevision?: unknown; nativeCaller?: unknown };
parsed = JSON.parse(payload) as { conversationId?: unknown; tool?: unknown; args?: unknown; expectedRevision?: unknown; nativeCaller?: unknown; toolCallId?: unknown };
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("expected tool object");
} catch {
res.writeHead(400, { "content-type": "application/json" });
Expand All @@ -1608,6 +1648,7 @@ export async function handlePluginTool(
}
const conversationId = typeof parsed.conversationId === "string" ? parsed.conversationId.trim() : "";
const tool = typeof parsed.tool === "string" ? parsed.tool : "";
if (parsed.toolCallId !== undefined && (typeof parsed.toolCallId !== "string" || !parsed.toolCallId.trim() || parsed.toolCallId.length > 512)) return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "toolCallId must be a non-empty string of at most 512 characters" });
if (parsed.expectedRevision !== undefined && (typeof parsed.expectedRevision !== "string" || !/^[a-f0-9]{64}$/.test(parsed.expectedRevision))) return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "expectedRevision must be a snapshot revision" });
if (parsed.expectedRevision !== undefined && !conversationId) return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "expectedRevision requires conversationId" });
// Explicit ids never yield to another session's outbound witness. A
Expand Down Expand Up @@ -1761,7 +1802,7 @@ export async function handlePluginTool(
// may still echo one — strip it before kernel arg parsing sees it (the
// witness hash in tool-ring.ts strips the same key).
delete args.conversation_id;
const callId = `${PLUGIN_FOLD_CALLID_PREFIX}${Date.now().toString(36)}`;
const callId = typeof parsed.toolCallId === "string" ? parsed.toolCallId : `${PLUGIN_FOLD_CALLID_PREFIX}${Date.now().toString(36)}`;
acquireInFlight(session);
let result: ProxyToolResult | undefined;
let retrievalExport: RetrievalExport | undefined;
Expand Down
2 changes: 2 additions & 0 deletions src/server/prepare-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { isStrictReasoningEcho, modelIdOf, normalizeStrictEchoResponsesInput } f
import { reconcileSystemAnchor } from "../system-anchor.js";
import { buildPromptForgeBody, buildTriggerForgeBody, carriesCodexLocalCompactionSummary, codexCompactGate, codexCompactGatePre, codexCompactMode, hasCompactionPrompt, hasCompactionTrigger, isCodexClient, mergeForgedSummaries, replaceBiliCompactionItems, stripBiliCompactionItems, CODEX_COMPACT_HEALTH_RATIO, CODEX_LOCAL_COMPACTION_MIN_MISSING } from "../codex-compact.js";
import type { ConversationIdentity } from "../session-id.js";
import { reconcilePluginFoldCallIds } from "../plugin.js";
import { logRawStripCounts, markerArtifactCount, stripRawStage } from "../marker/engine.js";
import { imageRescaleMaxDim, keepResponseId as knobKeepResponseId, noCompressPrompt as knobNoCompressPrompt, noInjectTool as knobNoInjectTool, renderNone as knobRenderNone } from "../knobs.js";
import { applyImageRescaleItems } from "../image-rescale.js";
Expand Down Expand Up @@ -264,6 +265,7 @@ export async function prepareResponses(
}
}
}
if (pluginMode && !isCompactionTrigger && !hasCompactionPrompt(parsed.input)) reconcilePluginFoldCallIds(session, msgs);
// [#1921] re-anchor fold coverage onto churned-but-same messages
// before the #1195 snapshot, so covered ids surviving a client
// re-serialization stay covered (src/fold-reconcile.ts).
Expand Down
6 changes: 3 additions & 3 deletions tests/plugin-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ test("proxyBaseFromEnv accepts BILLION_CONTEXT_PROXY, detectProxyBase honors kil

type FakeProxy = {
origin: string;
toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>;
toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean; toolCallId?: string }>;
registers: Array<{ conversationId: string; agent: string; identity: boolean; parentConversationId?: string }>;
runtimeInfos: Array<Record<string, unknown>>;
close(): Promise<void>;
Expand Down Expand Up @@ -752,7 +752,7 @@ test("pi extension registers manifest tools and stamps headers when proxied", as
assert.equal(out.isError, undefined);
// #2072: the pi host stamps its session-manager id as a confirmed
// native caller — the captured wire body carries the flag.
assert.deepEqual(proxy.toolCalls, [{ conversationId: "sess-42", tool: "compress", args: { content: [] }, nativeCaller: true }]);
assert.deepEqual(proxy.toolCalls, [{ conversationId: "sess-42", tool: "compress", args: { content: [] }, nativeCaller: true, toolCallId: "call-1" }]);
const errOut = await pi.tools[1]!.execute("call-2", {}, undefined, undefined, fakeCtx(proxy));
assert.match(errOut.content[0]!.text, /bili tool error:.*boom/);
assert.equal(errOut.isError, true);
Expand Down Expand Up @@ -814,7 +814,7 @@ test("#2416: registered tools track the respawned proxy origin — live re-read
out = await pi.tools[0]!.execute("call-2", { content: [] }, undefined, undefined, ctx);
assert.equal(out.isError, undefined, "the tool must reach the respawned proxy, not keep firing at the dead port");
assert.match(out.content[0]!.text, /\[Compressed/);
assert.deepEqual(newProxy.toolCalls, [{ conversationId: "sess-42", tool: "compress", args: { content: [] }, nativeCaller: true }]);
assert.deepEqual(newProxy.toolCalls, [{ conversationId: "sess-42", tool: "compress", args: { content: [] }, nativeCaller: true, toolCallId: "call-2" }]);
assert.equal(oldProxy.toolCalls.length, 1, "nothing further may hit the dead origin");
} finally {
if (prevEnv === undefined) delete process.env.BILLION_CONTEXT_PROXY;
Expand Down
Loading
Loading