From fec8b15aea87328c22e4bbf4956b03380a34537a Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 11 Oct 2026 08:47:47 +0800 Subject: [PATCH] fix(pi-native): self-heal ACP tools dropped by a mid-session registry rebuild (#2708) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pi rebuilds its executable tool list per request from its tool registry (_refreshToolRegistry walks the live extension instances' tool maps into _toolRegistry; setActiveToolsByName filters active names through _toolRegistry.has(name) and silently drops any name it no longer holds). When that rebuild runs while our extension instance's map is empty (a runtime replacement / reload mid-session), the ACP tools leave both the registry and the active set while the transcript keeps declaring their names — so the model keeps calling tools pi rejects by name ("Tool compress not found") forever. registerTools() was gated once-per-sid (`if (sid === state.sid) return` plus the toolsFor guard), so nothing ever re-registered them: unrecoverable until a restart, and silent on both sides (no log). Fix: remember the tools we registered (state.registeredTools) and, on every provider request for an already-registered sid, probe the host's real registry via getAllTools() and re-assert any we dropped. registerTool is idempotent (dedup by name) and post-bind triggers a registry refresh, so the session self-heals on the next request cheaply. The same re-assert runs at the end of a successful registration to cover a same-id session_start whose register loop is skipped. Hosts without a registry query (older pi / omp) keep the once-per-sid behavior — the probe degrades to a no-op, and a throwing query never triggers a blind re-register. A console.warn names the dropped tools so the failure stops being silent. Tests: four regression cases in plugin-agent.test.ts (drop → self-heal + log; fast path does not re-register; no-query host stays inert; same-id session_start re-asserts during registration). --- src/agent/pi.ts | 43 +++++++++++++- tests/plugin-agent.test.ts | 117 +++++++++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+), 2 deletions(-) diff --git a/src/agent/pi.ts b/src/agent/pi.ts index 331b9875f1..3b1935e772 100644 --- a/src/agent/pi.ts +++ b/src/agent/pi.ts @@ -549,7 +549,34 @@ function noProxyWarning(agent: string): string { const RETRY_INTERVAL_MS = 10000; -type RegisterState = { sid?: string; toolsFor?: string; toolsReady?: boolean; pending?: Promise; retryAt?: number; identityAt?: string; carriedSids?: Set; retryIntervalMs: number; manifestPrime?: { base: string; tools: Promise } }; +type RegisterState = { sid?: string; toolsFor?: string; toolsReady?: boolean; pending?: Promise; retryAt?: number; identityAt?: string; carriedSids?: Set; retryIntervalMs: number; manifestPrime?: { base: string; tools: Promise }; 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; + 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 { let proxyBase = proxyBaseForCtx(ctx); @@ -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; @@ -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; @@ -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; diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index d7911d35d3..a52b98dfd7 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -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 { @@ -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 })), }; } @@ -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 = {}; + 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 = {}; + const h2: Record = {}; + 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 = {}; + 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