diff --git a/CLIENTS.md b/CLIENTS.md index 7411a09274..908016433e 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -587,15 +587,29 @@ HTTP transports; WS row documented from #2073, no live cell): Caveats worth knowing: -- **Restrictive `tools:` allowlists filter ACP tools.** An agent definition - whose frontmatter `tools:` list omits the ACP tool names (e.g. the builtin - `scout` lists only `read`/`bash`/…) will not expose them in the child, even - though the session is named and compressed. Pre-fix foreground children - happened to have the tools via proxy wire injection regardless of the - allowlist — so such agents see fewer tools after the upgrade. Restore them - by omitting the `tools:` field or adding - `compress,decompress,search_context,acp_status,acp_cache`. The filtering is - pi-subagents' pre-existing behavior, not a regression of this fix. +- **Roles with restrictive `tools:` allowlists get the ACP channel back + automatically (#2268).** An agent definition whose frontmatter `tools:` list + omits the ACP tool names — all seven builtin roles ship like this (e.g. + `delegate` lists `read,grep,find,ls,bash,edit,write,contact_supervisor`) — + no longer loses interactive compression after the #2185 named-plugin fix. + bili detects such children per request (pi-subagents stamps every child + session's system prompt with an `` marker; the gate + also requires the request's tools array to expose none of the names bili + would inject) and serves them through the **proxy-style compression + channel**: wire-injected ACP tools + nudge, server-side execution, + `acp_summary` carrier — while keeping the named plugin-session identity + from #2185. No configuration change required; the role's original allowlist + stays intact on the wire, and a mid-session whitelist change self-heals on + the next request. Scoped to nicobailon/pi-subagents children only (the + marker is theirs); every other plugin host is unaffected. If upstream ever + drops the marker, these roles degrade to pre-#2268 behavior (named session, + no local ACP tools). + - A role exposing **any** ACP/bili-injectable name stays in pure plugin + mode (duplicate tool declarations are rejected by providers), so + **partial grants are unsupported** — grant none, or grant all + (`compress,decompress,search_context,acp_status[,acp_cache]`). + - Want locally registered (plugin-carrier) tools for a specific role? Keep + the manual grant: omit the `tools:` field or add the ACP names to it. - **One-request registration race in background children** (ACP tools present from the second request on) is pre-existing in all modes. - **Behavior change disclosure:** foreground children move from anonymous diff --git a/CLIENTS.zh-CN.md b/CLIENTS.zh-CN.md index 06f9058bc7..c106531b12 100644 --- a/CLIENTS.zh-CN.md +++ b/CLIENTS.zh-CN.md @@ -182,7 +182,9 @@ pi-subagents(pi.dev 上的包)为前台/后台子代理运行派生**子会话** 值得知道的注意事项: -- **限制性 `tools:` 白名单会滤掉 ACP 工具。** frontmatter `tools:` 列表未包含 ACP 工具名的 agent 定义(如内建 `scout` 只列了 `read`/`bash`/…),child 里不会出现这些工具——尽管会话是具名的、压缩也成立。修复前的前台 child 恰好靠代理 wire 注入绕过了白名单拿到工具——所以这类 agent 升级后可用的工具变少了。恢复方式:省略 `tools:` 字段,或补上 `compress,decompress,search_context,acp_status,acp_cache`。该过滤是 pi-subagents 的既有行为,不是本修复引入的回归。 +- **限制性 `tools:` 白名单的角色会自动拿回 ACP 通道(#2268)。** frontmatter `tools:` 列表未包含任何 ACP 工具名的角色——全部 7 个内置角色都是如此(如 `delegate` 只列 `read,grep,find,ls,bash,edit,write,contact_supervisor`)——在 #2185 具名 plugin 化之后**不再**丢失交互式压缩。bili 按请求检测这类 child(pi-subagents 会在每个子会话的 system prompt 打上 `` 标记;门控还要求请求的 tools 数组未暴露任何 bili 可注入的工具名),并为其走 **proxy-style 压缩通道**:wire 注入 ACP 工具 + nudge、服务端执行、`acp_summary` carrier——同时保留 #2185 的具名 plugin 会话身份。无需任何配置改动;角色的原白名单在 wire 上原样保留,白名单中途变更会在下一个请求自愈。范围仅限 nicobailon/pi-subagents 的 child(标记是它的),其他 plugin host 不受影响。若上游日后移除该标记,这些角色会退回 #2268 之前的行为(具名会话、无本地 ACP 工具)。 + - 暴露**任一** ACP/bili 可注入名的角色保持纯 plugin 模式(重复的工具声明会被上游拒绝),因此**部分授予不受支持**——要么一个都不给,要么全给(`compress,decompress,search_context,acp_status[,acp_cache]`)。 + - 想让某个特定角色用本地注册(plugin-carrier)的工具?保留手动授权:省略 `tools:` 字段或在其中补上 ACP 工具名即可。 - **后台 child 存在一个请求的注册竞争**(ACP 工具从第二个请求起出现),所有模式下均为既有现象。 - **行为变更披露:** 前台 child 从匿名 proxy 模式(`pfa-*`)升级为具名 plugin 模式(child 会话 id + 父会话血统)。信息严格更多,但任何以 `pfa-*` 身份做键的工具将看到不同的 id。 diff --git a/src/server.ts b/src/server.ts index 11c1cc0bb4..8795e07dbc 100644 --- a/src/server.ts +++ b/src/server.ts @@ -159,6 +159,7 @@ import { DSH_COMPACTION_SHAPE_MSGS, dshCompactionRefusal, isDshCompactionCall } import { clampOutgoingOutput, countSystemAndToolsTokens, emergencyNudge, estimateInputTokens, estimateWireOverhead, projectThinkingMass } from "./server/budget.js"; import { awaitDrain, bufferToStream, dumpStreamToFile, pipeThrough, readStreamToBuffer } from "./server/stream-io.js"; import { artifactSeedHit, detectAcpArtifacts } from "./server/chain-artifacts.js"; +import { piSubagentChannelFallback } from "./server/pi-subagent-channel.js"; import { droppedOpenaiParts } from "./wire-drop-warn.js"; // #1086/#1218: the per-session chain-verdict memory moved to plugin.ts @@ -2801,7 +2802,22 @@ async function handle( // requests, and restoring on that would clear the degrade one round // after arming it (the session never actually degraded). if (pluginAgent !== undefined) pluginLaneRestore(session, pluginAgentHeader(req.headers) !== undefined, log); - const pluginMode = pluginAgent !== undefined && !pluginLaneDegraded(session); + // #2268: pi-subagents children whose role allowlist grants none of the ACP + // context tools are served through the proxy-style channel instead of pure + // plugin mode (mechanism + scope: src/server/pi-subagent-channel.ts). + // Session identity stays plugin-bound either way — only the compression + // channel flips, per request (stateless: whitelist changes self-heal). + // Like the #2155 degrade above it only ever demotes plugin→proxy, so the + // two signals compose conjunctively below. + const subagentFallback = pluginAgent === "pi" ? piSubagentChannelFallback(bodyBuffer, parsed) : { present: false as const }; + if (subagentFallback.present) { + if (session.metadata.subagentFallbackNotified !== true) { + session.metadata.subagentFallbackNotified = true; + markDirty(session); + log("info", `[${sessionId}] [pi-subagents] child "${subagentFallback.agent ?? "unknown"}" role allowlist lacks ACP context tools — serving proxy-style compression channel (#2268)`); + } + } + const pluginMode = pluginAgent !== undefined && !pluginLaneDegraded(session) && !subagentFallback.present; // [#1097/#1271] Stamp the resolved CCR policy. acp_retrieve needs a tool // channel that can round-trip the full original, so CCR arms only where // that channel exists and is resolvable: proxy mode always (the proxy diff --git a/src/server/pi-subagent-channel.ts b/src/server/pi-subagent-channel.ts new file mode 100644 index 0000000000..e04caff2f2 --- /dev/null +++ b/src/server/pi-subagent-channel.ts @@ -0,0 +1,95 @@ +// #2268: pi-subagents builtin roles ship strict frontmatter `tools:` allowlists +// that list none of the ACP context tool names. Since #2209's required-extension +// self-registration those children load bili and get named plugin sessions — but +// pi's child tool planning never adds extension-registered names to the effective +// allowlist, so the model cannot call compress/decompress/search_context/acp_status +// locally while the proxy (plugin mode) withholds wire injection. Pre-#2209, +// foreground children ran as anonymous proxy-mode sessions where wire-injected +// ACP tools worked; the upgrade silently downgraded interactive compression for +// those roles. +// +// Fix (owner-scoped to nicobailon/pi-subagents children only): a capability-aware +// channel fallback. Every in-process pi-subagents child request carries a stable +// marker at the head of its system prompt — `` (see +// buildInProcessChildLaunch in pi-subagents' child-launch.ts). When a +// plugin-stamped pi request carries that marker AND its tools array exposes none +// of the tool names bili would inject, the request is served through the +// proxy-style channel (wire-injected tools + nudge, server-side execution, +// acp_summary carrier): exactly what pre-#2209 foreground children got, now on +// top of named-session identity. The decision is stateless per request — a +// mid-session whitelist change self-heals on the next request, and if upstream +// ever drops the tag we degrade gracefully to today's behavior. A role exposing +// ANY bili-injectable name stays pure plugin mode (duplicate tool declarations +// are rejected by providers; partial grants remain unsupported by design). + +const PI_SUBAGENT_CHILD_MARKER = "\x3cactive_agent name="; + +/** Tool names bili may add to the request tools array when serving the + * proxy-style channel: the core ACP four plus the feature extras at their + * default names (absorb.toolName / ccr.toolName are config-renamable — a + * renamed extra colliding with a role-whitelisted name is an accepted residual + * edge, see PR #2268 discussion). */ +const BILI_INJECTABLE_TOOL_NAMES = new Set([ + "compress", + "decompress", + "search_context", + "acp_status", + "acp_rule", + "acp_retrieve", + "absorb", + "image_full", +]); + +export type PiSubagentChildSignal = { present: false } | { present: true; agent?: string }; + +/** Detect the pi-subagents child marker in the raw request body. The marker + * lives inside a JSON string value; `<`, letters, spaces and `=` are never + * JSON-escaped, so a raw byte search is exact for all four wire shapes. The + * role name is extracted best-effort from the bytes right after the marker + * (for logging only) — the surrounding quotes arrive backslash-escaped in the + * raw body. */ +export function detectPiSubagentChildSignal(bodyBuffer: Buffer): PiSubagentChildSignal { + const idx = bodyBuffer.indexOf(PI_SUBAGENT_CHILD_MARKER); + if (idx < 0) return { present: false }; + let agent: string | undefined; + const tail = bodyBuffer.subarray(idx, Math.min(bodyBuffer.length, idx + PI_SUBAGENT_CHILD_MARKER.length + 96)).toString("utf8").replace(/\\/g, ""); + const m = tail.match(/name="([^"]*)"/); + if (m && m[1]) agent = m[1]; + return { present: true, ...(agent ? { agent } : {}) }; +} + +function isInjectableName(v: unknown): boolean { + return typeof v === "string" && BILI_INJECTABLE_TOOL_NAMES.has(v); +} + +/** Does the client-declared tools array expose any bili-injectable tool name? + * One generic walk covers all four wire shapes: top-level `name` (anthropic / + * responses), `function.name` (openai), `functionDeclarations[].name` (google). + * Malformed entries are skipped, never thrown on — bodies are client-supplied. */ +export function exposesBiliInjectableTool(tools: unknown): boolean { + if (!Array.isArray(tools)) return false; + for (const entry of tools) { + if (typeof entry !== "object" || entry === null) continue; + const rec = entry as Record; + if (isInjectableName(rec.name)) return true; + const fn = rec.function; + if (typeof fn === "object" && fn !== null && isInjectableName((fn as Record).name)) return true; + const decls = rec.functionDeclarations; + if (Array.isArray(decls)) { + for (const d of decls) { + if (typeof d === "object" && d !== null && isInjectableName((d as Record).name)) return true; + } + } + } + return false; +} + +/** Full gate: pi-subagents child marker present AND the role allowlist exposes + * no bili-injectable tool name. Caller additionally requires pluginAgent==="pi". */ +export function piSubagentChannelFallback(bodyBuffer: Buffer, parsed: unknown): PiSubagentChildSignal { + const signal = detectPiSubagentChildSignal(bodyBuffer); + if (!signal.present) return signal; + const tools = typeof parsed === "object" && parsed !== null ? (parsed as { tools?: unknown }).tools : undefined; + if (exposesBiliInjectableTool(tools)) return { present: false }; + return signal; +} diff --git a/tests/e2e/e2e-native-pi.test.ts b/tests/e2e/e2e-native-pi.test.ts index 6602497ab1..257066eabd 100644 --- a/tests/e2e/e2e-native-pi.test.ts +++ b/tests/e2e/e2e-native-pi.test.ts @@ -15,6 +15,13 @@ // The first-request stamp race (#1243) is pinned by every stamp assertion: // a one-shot `pi -p` fires before_provider_headers exactly once, inside the // proxy bootstrap window. +// +// #2268 adds the real pi-subagents lane: an UNMODIFIED builtin role (delegate) +// runs as an in-process child whose allowlist grants no ACP names — the proxy +// must serve it through the capability-aware proxy-style channel while keeping +// named-session identity; the parent's pure plugin mode stays untouched. +// pi-subagents installs hermetically at the pinned version (skips when the +// registry is unreachable). import { spawn, spawnSync } from "node:child_process"; import fs from "node:fs"; @@ -43,6 +50,7 @@ const ACP_TOOLS = [ "acp_status", "acp_cache", ] as const; +const PI_SUBAGENTS_VERSION = "0.76.1"; function piAvailable(): boolean { try { @@ -55,6 +63,46 @@ function distBuilt(): boolean { return fs.existsSync(PI_NATIVE_ENTRY); } +// pi-subagents is installed hermetically into a suite-local dir (isolated from +// the repo — npm install in a dir WITHOUT its own package.json walks up to the +// repo root and pollutes package.json). Returns the package dir, or null when +// the registry is unreachable (the #2268 test then skips; the rest of the +// suite never depends on it). Cached across tests in one run. +let pisPkgCache: string | null | undefined; +async function ensurePiSubagents(): Promise { + if (pisPkgCache !== undefined) return pisPkgCache; + const dir = path.join(WORK_ROOT, "pis-install"); + const pkg = path.join(dir, "node_modules", "pi-subagents"); + if (!fs.existsSync(path.join(pkg, "package.json"))) { + try { + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, "package.json"), + JSON.stringify({ name: "pis-install", private: true }, null, 2), + ); + const r = spawnSync( + "npm", + [ + "install", + `pi-subagents@${PI_SUBAGENTS_VERSION}`, + "--no-audit", + "--no-fund", + ], + { cwd: dir, timeout: 120_000, stdio: ["ignore", "ignore", "pipe"] }, + ); + if (r.status !== 0 || !fs.existsSync(path.join(pkg, "package.json"))) { + pisPkgCache = null; + return null; + } + } catch { + pisPkgCache = null; + return null; + } + } + pisPkgCache = pkg; + return pkg; +} + const run = process.env.ACP_TEST_E2E_NATIVE === "1"; const skipReason = !run ? "set ACP_TEST_E2E_NATIVE=1 (real pi native package + local fake upstream; deterministic, zero tokens)" @@ -622,6 +670,296 @@ if (checkOnly) { }, ); + test( + "pi-subagents unmodified delegate child: proxy-style ACP channel fallback (#2268)", + { skip: suiteSkipReason }, + async (t) => { + const pisPkg = await ensurePiSubagents(); + if (!pisPkg) { + t.skip( + `pi-subagents@${PI_SUBAGENTS_VERSION} unavailable (npm registry unreachable)`, + ); + return; + } + const ctx = await startCtx(); + t.after(() => teardown(ctx)); + const settingsPath = path.join(ctx.piAgentDir, "settings.json"); + const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")) as { + packages: string[]; + }; + settings.packages.push(pisPkg); + fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2)); + + // The parent's scripted subagent call spawns the UNMODIFIED builtin + // delegate role in-process; its task text scripts the CHILD'S queue + // (separate conversation key) so the child makes one real ACP round trip. + const r = await piRun( + ctx, + '请调用subagent {"agent":"delegate","task":"请调用acp_status"}', + ); + assert.equal( + r.code, + 0, + `pi -p failed (code=${r.code}); stderr:\n${r.stderr}`, + ); + assert.match( + r.stdout, + /收到#done/, + `parent must finish the scripted loop; stdout:\n${r.stdout}`, + ); + + const oracle = readOracle(ctx.reqLog); + const parentConv = oracle.find((o) => + o.lastUser.includes("请调用subagent"), + )?.conv; + assert.ok(parentConv, "parent request must be present in the oracle"); + const childRows = oracle.filter( + (o) => o.plugin === "pi" && o.conv !== parentConv, + ); + // First child turn + the loop iteration that carries the ephemeral + // acp_status result back into the child's request. + assert.ok( + childRows.length >= 2, + `expected >=2 plugin-stamped child requests, got ${childRows.length} (oracle convs: ${JSON.stringify([...new Set(oracle.map((o) => o.conv))])}`, + ); + // Fallback channel active: every child request carries BOTH the role's + // original whitelist and the wire-injected ACP core four. + const CORE_ACP = ["compress", "decompress", "search_context", "acp_status"]; + const DELEGATE_WHITELIST = [ + "read", + "grep", + "find", + "ls", + "bash", + "edit", + "write", + "contact_supervisor", + ]; + for (const o of childRows) { + for (const n of [...CORE_ACP, ...DELEGATE_WHITELIST]) { + assert.ok( + o.tools.includes(n), + `child request tools must include ${n}; got ${JSON.stringify(o.tools)}`, + ); + } + } + const statusRow = childRows.find((o) => + o.toolResults.some((tr) => tr.name === "acp_status"), + ); + assert.ok( + statusRow, + "acp_status must have executed server-side with its result fed back to the child", + ); + assert.match( + statusRow.toolResults.find((tr) => tr.name === "acp_status")!.content, + /ACTIVE SURFACE[\s\S]*CONTEXT BREAKDOWN/, + "acp_status result must be the status report", + ); + // The once-per-session channel-fallback log pins the detection itself + // (marker + allowlist verdict), including the extracted role name. + assert.match( + biliLog(ctx), + /\[pi-subagents\] child "delegate" role allowlist lacks ACP context tools/, + "proxy must log the pi-subagents channel fallback for the delegate child", + ); + // The parent stays pure plugin mode: full ACP surface registered locally. + const parentLate = oracle.filter( + (o) => + o.conv === parentConv && + ACP_TOOLS.every((n) => o.tools.includes(n)), + ); + assert.ok( + parentLate.length >= 1, + "parent session must keep its full plugin-mode ACP tool surface", + ); + // Named identity persists for BOTH sessions, still plugin-bound. + await stopProxiesGracefully(ctx); + const sessions = sessionFiles(ctx); + assert.ok( + sessions.length >= 2, + `expected parent + child persisted sessions, got ${sessions.length}`, + ); + assert.ok( + sessions.every((s) => s.parsed.payload?.metadata?.pluginAgent === "pi"), + `all persisted sessions must bind pluginAgent=pi, got ${JSON.stringify(sessions.map((s) => s.parsed.payload?.metadata?.pluginAgent))}`, + ); + }, + ); + + test( + "pi-subagents unmodified delegate child (fork): real compress fold through the fallback channel (#2268)", + { skip: suiteSkipReason }, + async (t) => { + const pisPkg = await ensurePiSubagents(); + if (!pisPkg) { + t.skip( + `pi-subagents@${PI_SUBAGENTS_VERSION} unavailable (npm registry unreachable)`, + ); + return; + } + const ctx = await startCtx(); + t.after(() => teardown(ctx)); + const settingsPath = path.join(ctx.piAgentDir, "settings.json"); + const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")) as { + packages: string[]; + }; + settings.packages.push(pisPkg); + fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2)); + + // Run one loads bulky tagged filler into the PARENT session (persisted, + // with a leaf) — the raw material a forked child inherits. Inside the + // child it sits far enough behind the task prompt to leave the kernel's + // protected zone (last 5 messages / last 5000 tokens / most recent user + // message), so the scripted compress has a legal target. + const load = await piRun( + ctx, + `${filler(120)}\n${Array.from({ length: 4 }, () => "请调用probe_tool").join(";")}`, + ); + assert.equal( + load.code, + 0, + `load run failed (code=${load.code}); stderr:\n${load.stderr}`, + ); + + // Run two: the parent's scripted subagent call spawns the UNMODIFIED + // builtin delegate role in-process with an explicit fork; the child's + // task text scripts the CHILD'S queue (separate conversation key) into a + // real compress round trip plus a post-fold status call. + const fold = await piRun( + ctx, + '请调用subagent {"agent":"delegate","task":"请调用compress;请调用acp_status","context":"fork"}', + { resume: true }, + ); + assert.equal( + fold.code, + 0, + `fold run failed (code=${fold.code}); stderr:\n${fold.stderr}`, + ); + assert.match( + fold.stdout, + /收到#done/, + `parent must finish the scripted loop; stdout:\n${fold.stdout}`, + ); + + const oracle = readOracle(ctx.reqLog); + // The parent is the conversation whose model emitted the subagent tool + // call (the delegate whitelist cannot carry it); the forked child gets + // its own conversation id. + const parentConv = oracle.find((o) => o.toolName === "subagent")?.conv; + assert.ok(parentConv, "parent subagent-call request must be in the oracle"); + const childRows = oracle.filter( + (o) => o.plugin === "pi" && o.conv !== parentConv, + ); + // Forked-history turn + compress-result turn + acp_status-result turn. + assert.ok( + childRows.length >= 3, + `expected >=3 plugin-stamped child requests, got ${childRows.length} (oracle convs: ${JSON.stringify([...new Set(oracle.map((o) => o.conv))])}`, + ); + // Fallback channel active on EVERY child request: the role's original + // whitelist survives AND the wire-injected ACP core four ride along. + const CORE_ACP = [ + "compress", + "decompress", + "search_context", + "acp_status", + ]; + const DELEGATE_WHITELIST = [ + "read", + "grep", + "find", + "ls", + "bash", + "edit", + "write", + "contact_supervisor", + ]; + for (const o of childRows) { + for (const n of [...CORE_ACP, ...DELEGATE_WHITELIST]) { + assert.ok( + o.tools.includes(n), + `child request tools must include ${n}; got ${JSON.stringify(o.tools)}`, + ); + } + } + // REAL compression inside the unmodified delegate child: the scripted + // compress folded the inherited filler server-side and the receipt came + // back into the child's conversation. + const compressRow = childRows.find((o) => + o.toolResults.some((tr) => tr.name === "compress"), + ); + assert.ok( + compressRow, + "compress must have executed server-side with its result fed back to the child", + ); + const compressResult = + compressRow!.toolResults.find((tr) => tr.name === "compress")!.content; + assert.doesNotMatch( + compressResult, + /FAILED|Validation failed/, + `compress must succeed, got: ${compressResult.slice(0, 200)}`, + ); + assert.match( + compressResult, + /\[Compressed m\d+[–-]m\d+ → \d+ block\(s\), ~\d+ tokens saved\.\]/, + `compress result must report the fold, got: ${compressResult.slice(0, 200)}`, + ); + const statusRow = childRows.find((o) => + o.toolResults.some((tr) => tr.name === "acp_status"), + ); + assert.ok( + statusRow, + "post-fold acp_status must have executed with its result fed back", + ); + assert.match( + statusRow.toolResults.find((tr) => tr.name === "acp_status")!.content, + /ACTIVE SURFACE[\s\S]*CONTEXT BREAKDOWN/, + "acp_status result must be the status report", + ); + // The once-per-session channel-fallback log pins the detection itself + // (marker + allowlist verdict), including the extracted role name. + assert.match( + biliLog(ctx), + /\[pi-subagents\] child "delegate" role allowlist lacks ACP context tools/, + "proxy must log the pi-subagents channel fallback for the delegate child", + ); + // The parent stays pure plugin mode: full ACP surface registered locally. + const parentLate = oracle.filter( + (o) => + o.conv === parentConv && + ACP_TOOLS.every((n) => o.tools.includes(n)), + ); + assert.ok( + parentLate.length >= 1, + "parent session must keep its full plugin-mode ACP tool surface", + ); + // Named identity persists for BOTH sessions, still plugin-bound; the + // compressed block lands in the CHILD's session (the parent never folds + // in this scenario). + await stopProxiesGracefully(ctx); + const sessions = sessionFiles(ctx); + assert.ok( + sessions.length >= 2, + `expected parent + child persisted sessions, got ${sessions.length}`, + ); + assert.ok( + sessions.every((s) => s.parsed.payload?.metadata?.pluginAgent === "pi"), + `all persisted sessions must bind pluginAgent=pi, got ${JSON.stringify(sessions.map((s) => s.parsed.payload?.metadata?.pluginAgent))}`, + ); + const withBlocks = sessions.filter((s) => { + const blocks = s.parsed.payload?.state?.blocks; + return ( + blocks !== undefined && + blocks !== null && + Object.keys(blocks as Record).length >= 1 + ); + }); + assert.ok( + withBlocks.length >= 1, + `the child's persisted session must carry compressed blocks (got ${sessions.length} sessions)`, + ); + }, + ); + test( "/acp command: exits clean and the status endpoint it consumes is live", { skip: suiteSkipReason }, diff --git a/tests/pi-subagent-channel.test.ts b/tests/pi-subagent-channel.test.ts new file mode 100644 index 0000000000..13963a0198 --- /dev/null +++ b/tests/pi-subagent-channel.test.ts @@ -0,0 +1,248 @@ +// #2268: pi-subagents builtin-role channel fallback. Unit coverage for the gate +// (src/server/pi-subagent-channel.ts) plus server-level proof that a tagged, +// ACP-less child request gets proxy-style wire injection while identity stays +// plugin-bound — and that every scope boundary (no tag / any granted bili name / +// non-pi agent) keeps pure plugin mode. + +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; + +process.env.NODE_ENV = "test"; +process.env.BILI_PERSIST = "0"; + +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { type ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { + detectPiSubagentChildSignal, + exposesBiliInjectableTool, + piSubagentChannelFallback, +} from "../src/server/pi-subagent-channel.ts"; + +const DELEGATE_TOOLS = ["read", "grep", "find", "ls", "bash", "edit", "write", "contact_supervisor"]; +const ORACLE_TOOLS = ["read", "grep", "find", "ls", "bash"]; + +function anthropicBody(system: string, tools: string[]): Buffer { + return Buffer.from(JSON.stringify({ + model: "claude-test", + system, + messages: [{ role: "user", content: "hi" }], + tools: tools.map((name) => ({ name, description: `role tool ${name}`, input_schema: { type: "object" } })), + })); +} + +function tagged(role: string): string { + return `\n\nYou are the ${role} agent.`; +} + +// — marker detection — + +test("detectPiSubagentChildSignal: absent on a plain pi session body", () => { + assert.deepEqual(detectPiSubagentChildSignal(anthropicBody("You are a coding agent.", DELEGATE_TOOLS)), { present: false }); +}); + +test("detectPiSubagentChildSignal: finds the marker in JSON-escaped form and extracts the role", () => { + const sig = detectPiSubagentChildSignal(anthropicBody(tagged("delegate"), DELEGATE_TOOLS)); + assert.equal(sig.present, true); + if (sig.present) assert.equal(sig.agent, "delegate"); +}); + +test("detectPiSubagentChildSignal: complex role names and array-form system blocks", () => { + const arrBody = Buffer.from(JSON.stringify({ + model: "claude-test", + system: [{ type: "text", text: tagged("evidence-auditor") }], + messages: [{ role: "user", content: "hi" }], + })); + const sig = detectPiSubagentChildSignal(arrBody); + assert.equal(sig.present, true); + if (sig.present) assert.equal(sig.agent, "evidence-auditor"); +}); + +test("detectPiSubagentChildSignal: marker truncated at buffer end still detects, name degrades", () => { + const buf = Buffer.from(JSON.stringify({ system: " { + const buf = Buffer.from(JSON.stringify({ + model: "claude-test", + system: "plain system", + messages: [ + { role: "user", content: "hi" }, + { role: "assistant", content: [{ type: "text", text: tagged("oracle") }] }, + { role: "user", content: "go on" }, + ], + })); + const sig = detectPiSubagentChildSignal(buf); + assert.equal(sig.present, true); +}); + +// — exposure walker — + +test("exposesBiliInjectableTool: every injectable name in every wire shape", () => { + const names = ["compress", "decompress", "search_context", "acp_status", "acp_rule", "acp_retrieve", "absorb", "image_full"]; + for (const n of names) { + assert.equal(exposesBiliInjectableTool([{ name: n }]), true, `top-level ${n}`); + assert.equal(exposesBiliInjectableTool([{ type: "function", function: { name: n } }]), true, `openai ${n}`); + assert.equal(exposesBiliInjectableTool([{ functionDeclarations: [{ name: n }] }]), true, `google ${n}`); + assert.equal(exposesBiliInjectableTool([{ type: "function", name: n, description: "" }]), true, `responses ${n}`); + } +}); + +test("exposesBiliInjectableTool: role whitelists expose none; near-miss names do not match", () => { + assert.equal(exposesBiliInjectableTool(DELEGATE_TOOLS.map((name) => ({ name }))), false); + assert.equal(exposesBiliInjectableTool(ORACLE_TOOLS.map((name) => ({ type: "function", function: { name } }))), false); + for (const near of ["compress_x", "x_compress", "COMPRESS", "acp_statuses", "image-full"]) { + assert.equal(exposesBiliInjectableTool([{ name: near }]), false, near); + } +}); + +test("exposesBiliInjectableTool: malformed entries are skipped, never thrown", () => { + assert.equal(exposesBiliInjectableTool([null, 42, "str", { name: 5 }, { function: null }, { functionDeclarations: "nope" }, {}]), false); + assert.equal(exposesBiliInjectableTool(undefined), false); + assert.equal(exposesBiliInjectableTool(null), false); + assert.equal(exposesBiliInjectableTool([]), false); + // union across positions: a hidden function.name counts even when top-level differs + assert.equal(exposesBiliInjectableTool([{ name: "read", function: { name: "decompress" } }]), true); +}); + +// — composition gate — + +test("piSubagentChannelFallback: delegate/oracle children fall back; granted roles do not", () => { + assert.ok(piSubagentChannelFallback(anthropicBody(tagged("delegate"), DELEGATE_TOOLS), null).present); + assert.ok(piSubagentChannelFallback(anthropicBody(tagged("oracle"), ORACLE_TOOLS), null).present); + const granted = anthropicBody(tagged("delegate"), [...DELEGATE_TOOLS, "compress"]); + assert.deepEqual(piSubagentChannelFallback(granted, JSON.parse(granted.toString("utf8"))), { present: false }); + assert.deepEqual(piSubagentChannelFallback(anthropicBody("plain system", DELEGATE_TOOLS), null), { present: false }); +}); + +test("piSubagentChannelFallback: unparseable body is lenient (marker decides)", () => { + const buf = anthropicBody(tagged("scout"), ORACLE_TOOLS); + assert.ok(piSubagentChannelFallback(buf, null).present); +}); + +// — server-level: the actual channel decision through the real pipeline — + +type Rig = { proxyPort: number; upstreamPort: number; forwards: string[]; proxy: http.Server; upstream: http.Server }; + +function okAnthropic(): string { + return JSON.stringify({ + id: "msg_1", type: "message", role: "assistant", model: "claude-test", + content: [{ type: "text", text: "ok" }], stop_reason: "end_turn", + usage: { input_tokens: 10, output_tokens: 3 }, + }); +} + +async function startRig(): Promise { + const forwards: string[] = []; + const upstream = http.createServer((req, res) => { + let b = ""; + req.on("data", (c) => (b += c)); + req.on("end", () => { + forwards.push(b); + res.writeHead(200, { "content-type": "application/json" }); + res.end(okAnthropic()); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: {} }, + modelContextLimit: 200_000, + kernelConfig: defaultConfig(200_000), + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + return { proxyPort: (proxy.address() as { port: number }).port, upstreamPort, forwards, proxy, upstream }; +} + +async function postAnthropic(rig: Rig, convId: string, body: Record, agent: string): Promise { + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/messages`; + const res = await fetch(url, { + method: "POST", + headers: { + "content-type": "application/json", + "x-bili-plugin": agent, + "x-bili-plugin-conversation": convId, + }, + body: JSON.stringify(body), + }); + await res.text(); + return res.status; +} + +function forwardedToolNames(forwards: string[], index: number): string[] { + const parsed = JSON.parse(forwards[index]) as { tools?: Array> }; + const out: string[] = []; + for (const t of parsed.tools ?? []) { + if (typeof t.name === "string") out.push(t.name); + } + return out; +} + +const CORE_ACP = ["compress", "decompress", "search_context", "acp_status"]; + +test("#2268 server-level: tagged ACP-less delegate child gets proxy-style injection; scope boundaries keep plugin mode", async () => { + const rig = await startRig(); + try { + const base = { + model: "claude-test", + max_tokens: 64_000, + messages: [{ role: "user", content: "hi" }], + }; + const toolsOf = (names: string[]) => names.map((name) => ({ name, description: `role tool ${name}`, input_schema: { type: "object" } })); + + // A: unmodified builtin delegate role (the issue repro) — fallback ON. + assert.equal(await postAnthropic(rig, "sar-2268-a", { ...base, system: tagged("delegate"), tools: toolsOf(DELEGATE_TOOLS) }, "pi"), 200); + const a = forwardedToolNames(rig.forwards, 0); + for (const n of CORE_ACP) assert.ok(a.includes(n), `fallback must inject ${n}; got ${a.join(",")}`); + for (const n of DELEGATE_TOOLS) assert.ok(a.includes(n), `role tools must survive: ${n}`); + + // B: a role that grants ANY bili-injectable name stays pure plugin mode. + assert.equal(await postAnthropic(rig, "sar-2268-b", { ...base, system: tagged("delegate"), tools: toolsOf([...DELEGATE_TOOLS, "compress"]) }, "pi"), 200); + const b = forwardedToolNames(rig.forwards, 1); + for (const n of CORE_ACP) assert.equal(b.filter((x) => x === n).length, n === "compress" ? 1 : 0, `${n} must not be injected twice/added`); + + // C: pi-stamped request WITHOUT the child marker — no fallback. + assert.equal(await postAnthropic(rig, "sar-2268-c", { ...base, system: "You are a coding agent.", tools: toolsOf(DELEGATE_TOOLS) }, "pi"), 200); + const c = forwardedToolNames(rig.forwards, 2); + for (const n of CORE_ACP) assert.ok(!c.includes(n), `untagged request must stay plugin mode (${n})`); + + // D: the marker on a NON-pi plugin agent — scope is pi only. + assert.equal(await postAnthropic(rig, "sar-2268-d", { ...base, system: tagged("delegate"), tools: toolsOf(DELEGATE_TOOLS) }, "omp"), 200); + const d = forwardedToolNames(rig.forwards, 3); + for (const n of CORE_ACP) assert.ok(!d.includes(n), `non-pi agent must stay plugin mode (${n})`); + } finally { + rig.proxy.close(); + await once(rig.proxy, "close"); + rig.upstream.close(); + await once(rig.upstream, "close"); + } +});