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
43 changes: 41 additions & 2 deletions src/agent/pi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,34 @@ function noProxyWarning(agent: string): string {

const RETRY_INTERVAL_MS = 10000;

type RegisterState = { sid?: string; toolsFor?: string; toolsReady?: boolean; pending?: Promise<void>; retryAt?: number; identityAt?: string; carriedSids?: Set<string>; retryIntervalMs: number; manifestPrime?: { base: string; tools: Promise<ManifestTool[] | undefined> } };
type RegisterState = { sid?: string; toolsFor?: string; toolsReady?: boolean; pending?: Promise<void>; retryAt?: number; identityAt?: string; carriedSids?: Set<string>; retryIntervalMs: number; manifestPrime?: { base: string; tools: Promise<ManifestTool[] | undefined> }; registeredTools?: ManifestTool[] };

// #2708: pi rebuilds its executable tool list per request — _refreshToolRegistry() walks
// the live extension instances' tool maps into _toolRegistry, and setActiveToolsByName()
// filters the active names through _toolRegistry.has(name), silently dropping any name it
// no longer holds. If that rebuild runs while our instance's map is empty (a runtime
// replacement / reload mid-session), the ACP tools leave the registry + active set while the
// transcript keeps declaring them — the model then calls tools pi rejects by name forever,
// and the once-per-sid gate below would never re-register them. Self-heal by probing the
// host's real registry and re-asserting vanished tools: registerTool is idempotent (dedup by
// name) and post-bind triggers a registry refresh, so a per-request re-assert is cheap and
// safe. No registry query (older pi / omp) or a throwing query → no-op, never a blind re-register.
function reassertDroppedTools(pi: ExtensionAPI, state: RegisterState, agent: string, proxyBase: string): void {
const tools = state.registeredTools;
if (tools === undefined || tools.length === 0) return;
const probe = (pi as { getAllTools?: () => Array<{ name?: unknown }> }).getAllTools;
if (typeof probe !== "function") return;
let present: Set<string>;
try {
present = new Set(probe.call(pi).map((t) => (typeof t?.name === "string" ? t.name : "")).filter((n): n is string => n.length > 0));
} catch {
return; // query rejected (e.g. stale ctx) — never re-register blindly
}
const missing = tools.map((t) => t.name).filter((name) => !present.has(name));
if (missing.length === 0) return;
console.warn(`bili-plugin(${agent}): ${missing.length} bili tool(s) dropped from the host registry (${missing.join(", ")}) — re-registering (#2708)`);
for (const t of tools) pi.registerTool(manifestToTool(proxyBase, t, agent));
}

async function registerTools(pi: ExtensionAPI, ctx: Ctx, state: RegisterState, agent: string, awaitNativeOrigin = true): Promise<void> {
let proxyBase = proxyBaseForCtx(ctx);
Expand All @@ -559,7 +586,12 @@ async function registerTools(pi: ExtensionAPI, ctx: Ctx, state: RegisterState, a
// so a successful registration is not re-fetched on every provider
// request — the manifest is session-independent anyway.
const sid = sessionIdOf(ctx) ?? "";
if (sid === state.sid) return;
if (sid === state.sid) {
// #2708: already registered for this sid — but pi may have rebuilt its
// registry since and dropped our tools. Re-assert if they vanished.
reassertDroppedTools(pi, state, agent, proxyBase);
return;
}
if (state.pending !== undefined) return state.pending;
if (state.retryAt !== undefined && Date.now() < state.retryAt) return;
const wait = state.retryIntervalMs;
Expand Down Expand Up @@ -588,6 +620,9 @@ async function registerTools(pi: ExtensionAPI, ctx: Ctx, state: RegisterState, a
if (state.toolsFor !== sid) {
for (const t of tools) pi.registerTool(manifestToTool(proxyBase, t, agent));
state.toolsFor = sid;
// #2708: remember what we put in the host registry so the
// per-request re-assert can detect a later drop.
state.registeredTools = tools;
}
state.toolsReady = true;
state.retryAt = undefined;
Expand Down Expand Up @@ -618,6 +653,10 @@ async function registerTools(pi: ExtensionAPI, ctx: Ctx, state: RegisterState, a
}
}
state.sid = sid;
// #2708: a same-id session_start skips the register loop above
// (toolsFor already === sid), so re-assert here too — otherwise a
// drop during that window wouldn't heal until the next request.
reassertDroppedTools(pi, state, agent, proxyBase);
} catch (err) {
state.sid = undefined;
state.toolsFor = undefined;
Expand Down
117 changes: 117 additions & 0 deletions tests/plugin-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,9 @@ type FakePi = {
registerTool: (tool: RecordedTool) => void;
registerCommand: (name: string, options: RecordedCommand) => void;
registerProvider?: (name: string, config: { baseUrl: string }) => void;
// #2708: real pi exposes the registry contents; the plugin probes it to
// detect a mid-session drop. Optional so a host without it can be modeled.
getAllTools?: () => Array<{ name: string }>;
};

function makeFakePi(): FakePi {
Expand Down Expand Up @@ -246,6 +249,10 @@ function makeFakePi(): FakePi {
registerProvider: (name, config) => {
providers.set(name, config.baseUrl);
},
// #2708: mirrors real pi's ExtensionAPI.getAllTools() — returns the
// registry contents by name. The test drops tools from `tools` directly
// to simulate pi rebuilding its registry with an empty instance map.
getAllTools: () => tools.map((t) => ({ name: t.name })),
};
}

Expand Down Expand Up @@ -856,6 +863,116 @@ test("before_provider_headers stamps after a session_start prewarm too", async (
}
});

test("#2708: a mid-session registry rebuild that drops bili tools self-heals on the next request", async () => {
const proxy = await startFakeProxy();
try {
const pi = makeFakePi();
biliPlugin(pi as never);
await pi.events.get("session_start")!({}, fakeCtx(proxy));
await waitForTools(pi, 2);
assert.equal(pi.tools.length, 2, "baseline: both manifest tools registered");
const before = pi.registerCalls;

const warns: string[] = [];
const origWarn = console.warn;
const headers: Record<string, string> = {};
console.warn = (...args: unknown[]) => { warns.push(args.map(String).join(" ")); };
try {
// pi rebuilds its registry while our instance's tool map is empty
// (runtime replacement / reload): the ACP tools vanish from the
// executable list, but our plugin still believes they're registered.
pi.tools.length = 0;
await pi.events.get("before_provider_headers")!({ headers }, fakeCtx(proxy));
} finally {
console.warn = origWarn;
}

assert.equal(pi.tools.length, 2, "the dropped tools were re-registered");
assert.ok(pi.tools.some((t) => t.name === "compress"), "compress restored");
assert.equal(headers["x-bili-plugin"], "pi", "ownership header still stamped after recovery");
assert.equal(headers["x-bili-plugin-conversation"], "sess-42");
assert.equal(pi.registerCalls, before + 2, "exactly the two dropped tools were re-asserted");
assert.ok(warns.some((w) => w.includes("dropped from the host registry")), "the silent drop is now logged");
assert.ok(warns.some((w) => w.includes("compress")), "the dropped tool name is named in the log");
} finally {
await proxy.close();
}
});

test("#2708: the fast path skips re-registration when nothing was dropped", async () => {
const proxy = await startFakeProxy();
try {
const pi = makeFakePi();
biliPlugin(pi as never);
await pi.events.get("session_start")!({}, fakeCtx(proxy));
await waitForTools(pi, 2);
const before = pi.registerCalls;

const warns: string[] = [];
const origWarn = console.warn;
const h1: Record<string, string> = {};
const h2: Record<string, string> = {};
console.warn = (...args: unknown[]) => { warns.push(args.map(String).join(" ")); };
try {
await pi.events.get("before_provider_headers")!({ headers: h1 }, fakeCtx(proxy));
await pi.events.get("before_provider_headers")!({ headers: h2 }, fakeCtx(proxy));
} finally {
console.warn = origWarn;
}

assert.equal(pi.registerCalls, before, "no redundant re-registration when the tools are intact");
assert.equal(warns.filter((w) => w.includes("dropped from the host registry")).length, 0, "no spurious drop warning");
assert.equal(h1["x-bili-plugin"], "pi");
assert.equal(h2["x-bili-plugin"], "pi");
} finally {
await proxy.close();
}
});

test("#2708: a host without a registry query keeps the once-per-sid behavior", async () => {
const proxy = await startFakeProxy();
try {
const pi = makeFakePi();
delete pi.getAllTools; // older pi / omp: no registry query surface
biliPlugin(pi as never);
await pi.events.get("session_start")!({}, fakeCtx(proxy));
await waitForTools(pi, 2);
const before = pi.registerCalls;
// Drop the tools from the host registry. With no query available the
// plugin cannot detect it and must NOT crash or guess-re-register.
pi.tools.length = 0;
const headers: Record<string, string> = {};
await pi.events.get("before_provider_headers")!({ headers }, fakeCtx(proxy));
assert.equal(pi.registerCalls, before, "no blind re-registration without a registry query");
assert.equal(pi.tools.length, 0, "nothing re-registered on a host that exposes no query");
assert.equal(headers["x-bili-plugin"], "pi", "ownership claim is independent of the probe");
} finally {
await proxy.close();
}
});

test("#2708: a same-id session_start after a drop re-asserts during registration", async () => {
const proxy = await startFakeProxy();
try {
const pi = makeFakePi();
biliPlugin(pi as never);
await pi.events.get("session_start")!({}, fakeCtx(proxy));
await waitForTools(pi, 2);
// pi drops the tools, then a same-id session_start (resume/reload) fires.
// Its register loop is skipped (toolsFor already === sid), so healing
// depends on the post-registration re-assert, not the loop.
pi.tools.length = 0;
assert.equal(pi.tools.length, 0, "precondition: tools dropped from the registry");
await pi.events.get("session_start")!({}, fakeCtx(proxy));
// Recovery runs inside the async registration block (manifest fetch),
// so poll rather than asserting synchronously.
await waitForTools(pi, 2);
assert.ok(pi.tools.some((t) => t.name === "compress"), "tools re-asserted on same-id session_start");
} finally {
await proxy.close();
}
});

test("#1217: launcher-mode manifest fetch is primed at extension load time", async () => {
// Correctness of the -p first-request stamp under ANY latency is #1228's
// awaited ownership claim; this prime is the latency half: the manifest
Expand Down
Loading