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
45 changes: 45 additions & 0 deletions src/agent/pi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@ type ExtensionAPI = {
// #2322: current session name (pi /name); optional because older hosts
// lack it (the session_info_changed event is the primary channel).
getSessionName?: () => string | undefined;
// #3542: the ACTIVE tool loadout — the set pi declares to the model and
// its dispatcher checks, distinct from the registry (getAllTools). pi's
// /tree rewind resets it from the transcript, so a registered tool can be
// missing from it; optional because older hosts lack it.
getActiveTools?: () => string[];
setActiveTools?: (toolNames: string[]) => void;
};

function agentName(override: string | undefined): string {
Expand Down Expand Up @@ -653,6 +659,42 @@ function reassertDroppedTools(pi: ExtensionAPI, state: RegisterState, agent: str
for (const t of tools) pi.registerTool(manifestToTool(proxyBase, t, agent));
}

// #3542: a pi /tree rewind (navigateTree) resets the ACTIVE tool loadout to what
// the surviving transcript system entries declare (_restoreToolsFromTranscript),
// discarding the entry that declared our tools whenever it sits after the rewind
// target — the normal case, since the manifest handshake is async and lands after
// the first turn's declaration. The definitions stay in the registry, so #2708's
// probe sees nothing missing, but pi dispatches on the loadout: every later call
// fails with "Tool X not found" until restart. session_tree fires right after the
// reset and before the next _startRun, so re-assert there. Additive-only (names
// the host currently holds are never removed), mirroring pi's own reload()
// precedent of re-activating all extension tools. No loadout query/setter (older
// pi / omp) or a throwing query → no-op, never a blind set.
function reassertLoadoutAfterTree(pi: ExtensionAPI, state: RegisterState, agent: string): void {
const tools = state.registeredTools;
if (tools === undefined || tools.length === 0) return;
const getActive = pi.getActiveTools;
const setActive = pi.setActiveTools;
if (typeof getActive !== "function" || typeof setActive !== "function") return;
let active: string[];
try {
const names = getActive.call(pi);
if (!Array.isArray(names)) return;
active = names.filter((n): n is string => typeof n === "string");
} catch {
return; // stale ctx — same guard as reassertDroppedTools
}
const present = new Set(active);
const missing = tools.map((t) => t.name).filter((name) => !present.has(name));
if (missing.length === 0) return;
try {
setActive.call(pi, [...active, ...missing]);
} catch {
return; // setter rejected — never break the navigation
}
logHostEvent("warn", "[native-client]", `bili-plugin(${agent}): ${missing.length} bili tool(s) dropped from the active loadout by a tree navigation (${missing.join(", ")}) — re-asserting (#3542)`);
}

async function registerTools(pi: ExtensionAPI, ctx: Ctx, state: RegisterState, agent: string, awaitNativeOrigin = true): Promise<void> {
let proxyBase = proxyBaseForCtx(ctx);
if (proxyBase === undefined && awaitNativeOrigin) proxyBase = await awaitNativeProxyOrigin();
Expand Down Expand Up @@ -1417,6 +1459,9 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM
pi.on("session_shutdown", () => {
disposeSubagentSelfReg(subagentReg);
});
// #3542: a /tree rewind resets the active loadout from the transcript —
// re-assert ours right after the reset (see reassertLoadoutAfterTree).
pi.on("session_tree", () => reassertLoadoutAfterTree(pi, state, agent));
// omp fires session_compact on in-session native compaction (sid does
// not rotate), so the proxy reuses stale state — notify it to archive
// the now-unreachable blocks (#395). Fire-and-forget: a failed
Expand Down
122 changes: 122 additions & 0 deletions tests/plugin-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,19 +214,32 @@ type FakePi = {
// #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 }>;
// #3542: real pi exposes the ACTIVE loadout (distinct from the registry);
// the plugin re-asserts it after a tree navigation. Optional so a host
// without it can be modeled.
activeTools: string[];
setActiveCalls: unknown[][];
getActiveTools?: () => string[];
setActiveTools?: (toolNames: string[]) => void;
};

function makeFakePi(): FakePi {
const events = new Map<string, (event: unknown, ctx: unknown) => unknown>();
const tools: RecordedTool[] = [];
const commands = new Map<string, RecordedCommand>();
const providers = new Map<string, string>();
// #3542: the active loadout, separate from the registry `tools` — a test
// can reset it (as pi's /tree does) while the registrations survive.
const activeTools: string[] = [];
const setActiveCalls: unknown[][] = [];
let registerCallCount = 0;
return {
events,
tools,
commands,
providers,
activeTools,
setActiveCalls,
get registerCalls() { return registerCallCount; },
on: (event, handler) => {
// Real pi dispatches each event to ALL registered handlers in
Expand All @@ -253,6 +266,13 @@ function makeFakePi(): FakePi {
// 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 })),
// #3542: mirrors real pi's ExtensionAPI.getActiveTools()/setActiveTools().
// setActiveTools dedupes like pi (_setActiveTools via [...new Set(...)]).
getActiveTools: () => [...activeTools],
setActiveTools: (toolNames) => {
setActiveCalls.push([...toolNames]);
activeTools.splice(0, activeTools.length, ...new Set(toolNames));
},
};
}

Expand Down Expand Up @@ -980,6 +1000,108 @@ test("#2708: a same-id session_start after a drop re-asserts during registration
}
});

test("#3542: a /tree rewind that resets the active loadout self-heals on session_tree", async () => {
const proxy = await startFakeProxy();
const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), "bc-plugin-agent-log-"));
try {
const pi = makeFakePi();
biliPlugin(pi as never);
await pi.events.get("session_start")!({}, fakeCtx(proxy));
await waitForTools(pi, 2);
pi.activeTools.splice(0, pi.activeTools.length, "bash", "read", "compress", "acp_status");
const before = pi.registerCalls;

await withEnv({ XDG_STATE_HOME: stateHome }, async () => {
// pi's navigateTree() rewinds past the entry that declared our tools
// and _restoreToolsFromTranscript() resets the loadout to what
// survives — the definitions stay in the registry, only the loadout
// loses them (the exact shape #2708's probe cannot see).
pi.activeTools.splice(0, pi.activeTools.length, "bash", "read");
assert.deepEqual([...pi.getAllTools!().map((t) => t.name)].sort(), ["acp_status", "compress"], "precondition: definitions still registered");
await pi.events.get("session_tree")!({ type: "session_tree", newLeafId: null, oldLeafId: "leaf-1" }, undefined);
});

assert.deepEqual([...pi.activeTools].sort(), ["acp_status", "bash", "compress", "read"], "the dropped tools are back in the active loadout");
assert.equal(pi.registerCalls, before, "no re-registration needed — the definitions never left the registry");
const dropLogPath = path.join(stateHome, "billion-context", "bili.log");
const dropLines = (fs.existsSync(dropLogPath) ? fs.readFileSync(dropLogPath, "utf8") : "").split("\n").filter((l) => l.length > 0 && l.includes("dropped from the active loadout"));
assert.ok(dropLines.length >= 1, `the silent loadout reset is logged in bili.log, got: ${JSON.stringify(dropLines)}`);
assert.ok(dropLines.some((l) => l.includes("compress")), "the dropped tool name is named in the log");
} finally {
await proxy.close();
fs.rmSync(stateHome, { recursive: true, force: true });
}
});

test("#3542: the re-assert is additive-only — names the host holds are never removed", 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);
// Host keeps its own tools plus one of ours active; the rewind drops
// only acp_status from the loadout.
pi.activeTools.splice(0, pi.activeTools.length, "bash", "read", "compress");
await pi.events.get("session_tree")!({ type: "session_tree", newLeafId: null, oldLeafId: "leaf-1" }, undefined);
assert.equal(pi.setActiveCalls.length, 1, "exactly one setter call");
assert.deepEqual(pi.setActiveCalls[0], ["bash", "read", "compress", "acp_status"], "previously-active names kept, missing ones appended");
assert.deepEqual(pi.activeTools, ["bash", "read", "compress", "acp_status"]);
} finally {
await proxy.close();
}
});

test("#3542: the fast path leaves the loadout untouched 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);
pi.activeTools.splice(0, pi.activeTools.length, "bash", "read", "compress", "acp_status");
const before = pi.registerCalls;
await pi.events.get("session_tree")!({ type: "session_tree", newLeafId: null, oldLeafId: "leaf-1" }, undefined);
assert.equal(pi.setActiveCalls.length, 0, "no setter call when the loadout is intact");
assert.equal(pi.registerCalls, before, "no re-registration either");
} finally {
await proxy.close();
}
});

test("#3542: a host without a loadout query/setter keeps working", async () => {
const proxy = await startFakeProxy();
try {
const pi = makeFakePi();
delete pi.getActiveTools;
delete pi.setActiveTools; // older pi / omp: no loadout surface
biliPlugin(pi as never);
await pi.events.get("session_start")!({}, fakeCtx(proxy));
await waitForTools(pi, 2);
pi.activeTools.splice(0, pi.activeTools.length, "bash", "read");
await pi.events.get("session_tree")!({ type: "session_tree", newLeafId: null, oldLeafId: "leaf-1" }, undefined);
assert.equal(pi.setActiveCalls.length, 0, "no blind set without a loadout surface");
assert.deepEqual(pi.activeTools, ["bash", "read"], "loadout untouched");
} finally {
await proxy.close();
}
});

test("#3542: a throwing loadout query degrades to a no-op", 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.getActiveTools = () => { throw new Error("ctx is stale"); };
await pi.events.get("session_tree")!({ type: "session_tree", newLeafId: null, oldLeafId: "leaf-1" }, undefined);
assert.equal(pi.setActiveCalls.length, 0, "never sets blindly after a failed query");
} 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