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
32 changes: 23 additions & 9 deletions CLIENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<active_agent name="…">` 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
Expand Down
4 changes: 3 additions & 1 deletion CLIENTS.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 打上 `<active_agent name="…">` 标记;门控还要求请求的 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。

Expand Down
18 changes: 17 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
95 changes: 95 additions & 0 deletions src/server/pi-subagent-channel.ts
Original file line number Diff line number Diff line change
@@ -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 — `<active_agent name="...">` (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<string, unknown>;
if (isInjectableName(rec.name)) return true;
const fn = rec.function;
if (typeof fn === "object" && fn !== null && isInjectableName((fn as Record<string, unknown>).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<string, unknown>).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;
}
Loading
Loading