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
2,141 changes: 2,108 additions & 33 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,14 @@
"zod": "4.1.8"
},
"devDependencies": {
"@earendil-works/pi-coding-agent": "0.83.0",
"@earendil-works/pi-tui": "0.83.0",
"@types/node": "^22.0.0",
"@types/node-forge": "^1.3.14",
"@types/semver": "^7.7.1",
"@types/ws": "8.18.2",
"acp-kernel": "file:./kernel",
"billion-context-pi-subagents": "0.1.1",
"esbuild": "^0.27.0",
"fzstd": "0.1.1",
"jsonc-parser": "^3.3.1",
Expand Down
2 changes: 2 additions & 0 deletions reference/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ billion-context/
│ │ ├── opencode-native.ts # opencode native bootstrap gate
│ │ ├── opencode-legacy.ts # Legacy DCP hooks table
│ │ ├── pi.ts # pi plugin factory (session derivation, #1333/#1362)
│ │ ├── pi-subagents.ts # Inlined acp_delegate sub-agent surface (markEmbedded wiring, #2186)
│ │ ├── pi-host-stub.ts # esbuild alias stub for @earendil-works/pi-coding-agent (→ ".pi" fallback, #2186)
│ │ ├── pi-native.ts # pi native bootstrap gate
│ │ ├── omp.ts # omp plugin = createBiliPlugin("omp") re-export of pi factory
│ │ ├── omp-native.ts # omp native bootstrap gate
Expand Down
9 changes: 9 additions & 0 deletions src/agent/pi-host-stub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// #2186: esbuild alias target for the single runtime host import inside the
// inlined billion-context-pi-subagents bundle. The package's config-dir
// module namespace-imports @earendil-works/pi-coding-agent only to read
// CONFIG_DIR_NAME and falls back to ".pi" when the export is absent — the
// documented degradation for hosts that alias the pi package to their own
// build. Leaving the import resolvable would force a runtime dependency on
// the full pi agent; aliasing it to this empty module keeps dist/agent/pi.js
// dependency-free, preserving bili's zero-runtime-dependency contract.
export {};
177 changes: 177 additions & 0 deletions src/agent/pi-subagents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
// #2186: acp_delegate surface for bili's pi lane, inlined from
// billion-context-pi-subagents (exact devDependency, tsup-bundled the same
// way acp-kernel is — see AGENTS.md §2.1). The package ships its own
// standalone factory (createSubagentsExtension); bili re-wires the building
// blocks instead so the surface rides bili's registration lifecycle, stays
// out of omp (no buildContextEntries), and stands down when another embedder
// (billion-context-pi, or a standalone install that claimed first) already
// owns it for this process.

import type { ExtensionAPI as PiExtensionAPI, ExtensionContext as PiExtensionContext } from "@earendil-works/pi-coding-agent";
import type { KeyId } from "@earendil-works/pi-tui";
import {
ACP_DELEGATE_PROMPT,
DEFAULT_DELEGATE_POLICY,
DELEGATE_STAND_DOWN_MESSAGE,
delegateStatusWidget,
findPiSubagentsInstalls,
loadSubagentsUserConfig,
makeDelegateCancelTool,
makeDelegateTool,
makeDelegateWaitTool,
markDelegateResultRead,
markDelegateRunReadByCommand,
markEmbedded,
openFleetInspector,
resetDelegateUsage,
resolveAgentDir,
resolveDelegate,
runningRunsSnapshot,
setDelegateDefaults,
setDelegateDisplayUsage,
setDelegateNotifyIfRead,
setDelegatePolicy,
setDebugEnabled,
type DelegatePolicy,
} from "billion-context-pi-subagents";
import type { ExtensionAPI, ToolDefinition } from "./pi.js";

const EMBEDDED_GLOBAL_KEY = Symbol.for("acp-delegate.embedded");

function embeddedClaimed(): boolean {
return (globalThis as Record<symbol, unknown>)[EMBEDDED_GLOBAL_KEY] === true;
}

// Same check as the package's host.ts isPiHost: the delegate tools need Pi's
// buildContextEntries() session API. Structural on purpose — forks that
// reached this lane without the API get the same refusal as omp, not a crash.
function hasBuildContextEntries(ctx: unknown): boolean {
const sm = (ctx as { sessionManager?: unknown } | undefined)?.sessionManager as { buildContextEntries?: unknown } | undefined;
return typeof sm?.buildContextEntries === "function";
}

function normalizeSystemPrompt(input: string | string[] | undefined): string {
if (input === undefined) return "";
if (Array.isArray(input)) return input.join("\n");
return input;
}

export function wirePiSubagents(pi: ExtensionAPI, agent: string): void {
// omp never gets the delegate surface: it lacks buildContextEntries, the
// exact host gap the package's UNSUPPORTED_HOST_MESSAGE describes.
if (agent !== "pi") return;
// The embedded marker decides process-wide ownership of acp_delegate.
// Whoever claims first wires it; a second embedder registering the same
// tool names, prompt section and widgets would double-render. Cross-
// extension factory load order is undefined, so check before claiming.
if (embeddedClaimed()) return;
markEmbedded();

const piCast = pi as unknown as PiExtensionAPI;
const state = { policy: DEFAULT_DELEGATE_POLICY as DelegatePolicy, stoodDown: false, delegatePrompt: undefined as string | null | undefined };
let standDownWarned = false;
let fleetCommandRegistered = false;

// Read-tracking for completion notifications (notifyIfRead: "skip"): when
// the model reads a delegate's result file, mark the run as read so the
// notification is skipped if the run finishes after that read.
pi.on("tool_result", (rawEvent) => {
const event = rawEvent as unknown as { isError?: unknown; toolName?: unknown; input?: unknown };
if (event.isError) return;
if (event.toolName === "read") {
const p = (event.input as { path?: unknown } | undefined)?.path;
if (typeof p === "string") markDelegateResultRead(p);
} else if (event.toolName === "bash") {
const cmd = (event.input as { command?: unknown } | undefined)?.command;
if (typeof cmd === "string") markDelegateRunReadByCommand(cmd);
}
});

pi.on("session_start", async (_event, ctx) => {
// /acp-fleet registers once per process (not per session): the host
// command table is process-global.
if (fleetCommandRegistered === false) {
fleetCommandRegistered = true;
pi.registerCommand?.("acp-fleet", {
description: "Inspect acp_delegate sub-agent runs: live list + transcript overlay (TUI), text snapshot elsewhere.",
handler: async (_args, c) => {
if (!state.policy.enabled) {
c.ui?.notify?.("acp_delegate is not enabled in this session's config.");
return;
}
await openFleetInspector(c as unknown as PiExtensionContext);
},
});
}
if (!hasBuildContextEntries(ctx)) return;
const cwd = ctx.cwd ?? process.cwd();
resetDelegateUsage();
setDelegateDisplayUsage("separate");
setDelegatePolicy(DEFAULT_DELEGATE_POLICY);
state.stoodDown = false;
try {
// Delegate config lives in pi's own acp.json (the package's
// loader) — deliberately NOT in bili's config surface.
const user = await loadSubagentsUserConfig(cwd);
if (user.debug !== undefined) setDebugEnabled(user.debug === true);
state.policy = resolveDelegate(user);
state.delegatePrompt = user.delegatePrompt;
setDelegateDisplayUsage(state.policy.displayUsage);
setDelegatePolicy(state.policy);
setDelegateDefaults({ thinkingLevel: state.policy.thinkingLevel, agents: state.policy.agents });
setDelegateNotifyIfRead(state.policy.notifyIfRead);
// Third-party pi-subagents overlap guard (#415, same contract as
// the standalone package): a PROJECT-scope install stands
// acp_delegate down unless delegate.forceEnable opts back in; a
// USER-scope-only install stays active (warn-only there too, but
// silently here — bili's lane already reports overlap through its
// own log surface).
if (state.policy.enabled && !state.policy.forceEnable) {
const scopes = findPiSubagentsInstalls(resolveAgentDir(), cwd);
if (scopes.project[0] !== undefined) {
state.stoodDown = true;
if (!standDownWarned) {
standDownWarned = true;
ctx.ui?.notify?.(DELEGATE_STAND_DOWN_MESSAGE, "warning");
}
}
}
} catch (err) {
// Config load failure keeps the defaults — delegate stays enabled,
// but a broken acp.json must not vanish silently (the standalone
// package logs this via logThrow; bili's lane has no such channel).
console.error(`bili-plugin(pi): subagents user config unreadable, using defaults: ${err instanceof Error ? err.message : String(err)}`);
}
if (state.policy.enabled && !state.stoodDown) {
// The package's ToolDefinition carries typed params + its own
// update-callback shape; bili's registration surface is the
// minimal structural one. Compatible at runtime (pi duck-types
// the execute contract); the cast crosses the two static shapes.
pi.registerTool(makeDelegateTool(piCast) as unknown as ToolDefinition);
pi.registerTool(makeDelegateWaitTool(piCast) as unknown as ToolDefinition);
pi.registerTool(makeDelegateCancelTool(piCast) as unknown as ToolDefinition);
if (typeof pi.registerShortcut === "function" && state.policy.fleetShortcut !== "") {
pi.registerShortcut(state.policy.fleetShortcut as KeyId, {
description: "Inspect acp_delegate runs (live list + transcript)",
handler: (c) => {
void openFleetInspector(c as unknown as PiExtensionContext);
},
});
}
}
delegateStatusWidget.setContext(ctx as unknown as PiExtensionContext, runningRunsSnapshot, state.policy.fleetShortcut, "billion-context");
});

pi.on("session_shutdown", () => {
delegateStatusWidget.dispose();
});

pi.on("before_agent_start", (rawEvent) => {
if (!state.policy.enabled || state.stoodDown) return;
const event = rawEvent as unknown as { systemPrompt?: string | string[] };
const text = state.delegatePrompt !== undefined ? state.delegatePrompt : ACP_DELEGATE_PROMPT;
if (typeof text !== "string") return;
const base = normalizeSystemPrompt(event.systemPrompt);
return { systemPrompt: `${base}\n\n${text}` };
});
}
16 changes: 16 additions & 0 deletions src/agent/pi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ import path from "node:path";
import { wrapCacheReport, wrapRuleReport } from "../acp-panel.js";
import { awaitNativeProxyOrigin } from "./native-bootstrap.js";
import { isModelApiUrl, nativeInterceptInstalled } from "./native-intercept.js";
import { wirePiSubagents } from "./pi-subagents.js";
import { detectProxyBase, destinationRoutedThroughProxy, fetchManifest, forwardTool, fetchStatus, fetchProxyVersion, postIdentityRegister, reportRuntimeInfoOnChange, armedIdleNotice, noSessionWarning, nonHttpProvidersFromEnv, type ManifestTool } from "./shared.js";

type Ctx = {
sessionManager?: { getSessionId?: () => string; getHeader?: () => unknown; getBranch?: () => unknown } | undefined;
model?: { contextWindow?: number; baseUrl?: string; provider?: string; id?: string; api?: string; [key: string]: unknown } | undefined;
// #2186: acp_delegate surface notifies stand-downs through the host toast
// when present (same channel CommandCtx already declares).
ui?: { notify?: (message: string, type?: string) => void } | undefined;
// #1961: pi 0.99+ exposes the live model catalog on the extension ctx;
// optional because older hosts lack it. The real ModelRegistry surface is
// find(provider, modelId) — there is no getModel (verified against pi
Expand Down Expand Up @@ -44,10 +48,18 @@ type CommandCtx = {
ui?: { notify?: (message: string, type?: string) => void } | undefined;
};

export type { ExtensionAPI, CommandCtx, ToolDefinition };

type ExtensionAPI = {
on: (event: string, handler: (event: never, ctx: Ctx) => unknown) => void;
registerTool: (tool: ToolDefinition) => void;
registerCommand?: (name: string, options: { description?: string; handler: (args: string, ctx: CommandCtx) => void | Promise<void> }) => void;
// #2186: acp_delegate (inlined from billion-context-pi-subagents) injects
// completion notifications through the host's persistent transcript
// channel; optional because older hosts and non-pi hosts lack it.
sendUserMessage?: (message: string, options?: { deliverAs?: string }) => void;
// #2186: delegate fleet-inspector shortcut — TUI nicety, never load-bearing.
registerShortcut?: (key: string, options: { description?: string; handler: (ctx: CommandCtx) => void | Promise<void> }) => void;
// #535: launcher passes provider URL rewrites via env; the extension
// overrides each provider's baseUrl at load (file-free routing — no
// models.json overlay). Optional because older hosts may lack it.
Expand Down Expand Up @@ -898,6 +910,10 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM
signal: AbortSignal.timeout(5000),
}).catch(() => {});
});
// #2186: acp_delegate surface for the pi lane, inlined from
// billion-context-pi-subagents. omp never reaches the wiring (the
// gate repeats inside) and a previously claimed surface stands down.
wirePiSubagents(pi, agent);
};
}

Expand Down
22 changes: 16 additions & 6 deletions tests/issue2072-native-caller-stamping.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,19 +143,25 @@ async function boot(): Promise<Harness> {

type TextBlock = { type: "text"; text: string };
type FakeTool = { name: string; parameters: unknown; execute: (id: string, params: Record<string, unknown>, signal: undefined, onUpdate: undefined, ctx: Record<string, unknown>) => Promise<{ content: TextBlock[]; isError?: boolean }> };
type PiHandler = (event: unknown, ctx: unknown) => unknown;
type FakePi = {
events: Map<string, (event: unknown, ctx: unknown) => unknown>;
// Real pi stores an ARRAY of handlers per event name and awaits each
// (pi-coding-agent@0.83.0 runner.js emit(): `ext.handlers.get(type)` →
// `for (const handler of handlers)`), so a second registration for the
// same event (e.g. the embedded subagents wiring) must APPEND, not
// replace. A Map-of-one would silently drop the factory's own handler.
events: Map<string, PiHandler[]>;
tools: FakeTool[];
commands: Map<string, unknown>;
providers: Map<string, string>;
on: (event: string, handler: unknown) => void;
on: (event: string, handler: PiHandler) => void;
registerTool: (tool: FakeTool) => void;
registerCommand: (name: string, options: unknown) => void;
registerProvider: (name: string, config: { baseUrl: string }) => void;
};

function makeFakePi(): FakePi {
const events = new Map<string, (event: unknown, ctx: unknown) => unknown>();
const events = new Map<string, PiHandler[]>();
const tools: FakeTool[] = [];
const commands = new Map<string, unknown>();
const providers = new Map<string, string>();
Expand All @@ -164,7 +170,11 @@ function makeFakePi(): FakePi {
tools,
commands,
providers,
on: (event, handler) => events.set(event, handler as (event: unknown, ctx: unknown) => unknown),
on: (event, handler) => {
const list = events.get(event);
if (list) list.push(handler);
else events.set(event, [handler]);
},
registerTool: (tool) => {
const i = tools.findIndex((t) => t.name === tool.name);
if (i >= 0) tools[i] = tool;
Expand All @@ -186,7 +196,7 @@ async function makeHost(h: Harness, sid: string): Promise<{ host: FakePi; ctx: R
cwd: "/tmp",
};
biliPlugin(host as never);
await host.events.get("session_start")!({}, ctx);
for (const handler of host.events.get("session_start") ?? []) await handler({}, ctx);
const deadline = Date.now() + 15000;
while (!host.tools.some((t) => t.name === "acp_cache")) {
if (Date.now() > deadline) throw new Error(`timed out waiting for the acp_cache tool on ${sid}`);
Expand All @@ -197,7 +207,7 @@ async function makeHost(h: Harness, sid: string): Promise<{ host: FakePi; ctx: R

async function stampedChatHeaders(host: FakePi, ctx: Record<string, unknown>): Promise<Record<string, string>> {
const headers: Record<string, string> = {};
await host.events.get("before_provider_headers")!({ headers }, ctx);
for (const handler of host.events.get("before_provider_headers") ?? []) await handler({ headers }, ctx);
headers["x-bili-plugin-model"] = "gpt-test";
return headers;
}
Expand Down
Loading
Loading