From 6d458a387b45d8508154439c6983135fbc616c16 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 6 Oct 2026 13:49:57 +0800 Subject: [PATCH 1/5] feat: pi.subagents config home in billion-context.json (#2230) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The built-in pi-lane acp_delegate surface reads its config from bili's own config file (pi.subagents section) instead of pi's acp.json. The four acp.json keys (delegate/delegatePrompt/displayUsage/debug) become a deprecated fallback: still read while the section is absent (one-time warning), ignored once it exists. prompt replaces delegatePrompt; debug is scoped to the sub-agent subsystem. The standalone package reads the same section through its own loader (billion-context-pi-subagents#5) — the file format is the contract, no shared code. Co-Authored-By: Claude --- CLIENTS.md | 10 ++++ CLIENTS.zh-CN.md | 2 + CONFIGURATION.md | 50 +++++++++++++++++ CONFIGURATION.zh-CN.md | 50 +++++++++++++++++ reference/env-vars.md | 2 +- src/agent/pi-subagents.ts | 40 ++++++++++++-- src/config.ts | 65 ++++++++++++++++++++++ tests/pi-subagents-wiring.test.ts | 90 ++++++++++++++++++++++++++++++- 8 files changed, 303 insertions(+), 6 deletions(-) diff --git a/CLIENTS.md b/CLIENTS.md index df8376fa64..1ddeb54d89 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -475,6 +475,16 @@ option 1); this section covers what the one-line table can't — **which model transports the native intercept actually covers**. Pi is the only host that brings WebSocket model traffic into the loop. +**Sub-agent config (#2230).** The built-in `acp_delegate` surface (three +dele gate tools, roles, fleet inspector — wired by `bili pi` through the +embedded extension) is configured in bili's own config file, the `pi.subagents` +section of `~/.config/billion-context/billion-context.json` (boolean shorthand +`"pi": {"subagents": false}` disables it). The four `~/.pi/acp.json` keys +(`delegate` / `delegatePrompt` / `displayUsage` / `debug`) are a deprecated +fallback — read only while the section is absent, ignored once it exists. +Full field table and the `PI_ACP_DELEGATE_*` env overrides: +CONFIGURATION.md → [`pi`](CONFIGURATION.md#pi). + **How routing works.** The pi extension bootstraps (or attaches to) its own proxy and patches `globalThis.fetch` in-process: every model-API HTTP request is rewritten to `/bili/`, and the extension stamps the diff --git a/CLIENTS.zh-CN.md b/CLIENTS.zh-CN.md index bd27a3db5b..ed6202e71a 100644 --- a/CLIENTS.zh-CN.md +++ b/CLIENTS.zh-CN.md @@ -134,6 +134,8 @@ Windows 上默认 npm 安装把 `codex.cmd` shim 放上 PATH,它的 `%*` 转发 Pi 有完整原生模式(`bili plugin install pi`,README 快速上手方案 1);这一节只讲一行表格装不下的内容——**原生拦截实际覆盖哪些模型传输**。pi 是唯一把 WebSocket 模型流量带进环路的宿主。 +**子代理配置(#2230)。** 内置 `acp_delegate` 面(三个 delegate 工具、角色、fleet 检查器——由 `bili pi` 经内嵌扩展接线)配置在 bili 自己的配置文件:`~/.config/billion-context/billion-context.json` 的 `pi.subagents` 段(布尔简写 `"pi": {"subagents": false}` 可整体关闭)。`~/.pi/acp.json` 的四键(`delegate` / `delegatePrompt` / `displayUsage` / `debug`)是已废弃的回退源——仅当段缺失时读取,段存在后完全忽略。完整字段表与 `PI_ACP_DELEGATE_*` 环境变量见 CONFIGURATION.zh-CN.md 的 [`pi`](CONFIGURATION.zh-CN.md#pi) 段。 + **路由机制。** pi 扩展自行拉起(或附着)代理并进程内 patch `globalThis.fetch`:所有模型 API 的 HTTP 请求被改写到 `/bili/`,扩展经 pi 的 `before_provider_headers` 事件盖 `x-bili-plugin*` 头。所有 HTTP 系 provider(Anthropic、OpenAI chat/completions/responses、Gemini、Mistral、OpenRouter、Azure、自定义中转……)走这条路,得到具名 plugin-mode 会话。 **WebSocket 覆盖(#2073,#2111 实现)。** WebSocket 连接从不经过 `globalThis.fetch`,所以原生扩展在加载时(首个模型连接之前)同时包装 `globalThis.WebSocket`(pi 的 Node 分支每次调用都读全局,Bun 分支首次调用时缓存子类——两个运行时的安装时序都因此安全)。只重写受支持的 Codex Responses 模型连接——其余 WebSocket(devtools、第三方库、已路由 URL)原样通过: diff --git a/CONFIGURATION.md b/CONFIGURATION.md index b8a461985a..ac237de2cd 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -110,6 +110,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `promptCache.routing` | "auto" \| "enabled" \| "disabled" | auto | ACP_PROMPT_CACHE_ROUTING | Prompt-cache routing posture for cache-aware lane selection. | | `native.attachExternal` | boolean | false | BILI_NATIVE_ATTACH_EXTERNAL | Let launcher-less native plugins attach to an external (lane'd, unarmed) daemon instead of spawning their own. | | `claude.nativePort` | number | unset (lane sticky zone port) | BILI_CLAUDE_NATIVE_PORT | Exact port pin for the claude native lane's hook-spawned proxy (strict-port: squatters are refused loudly). | +| `pi.subagents.*` | see [`pi` section](#pi) | package defaults | PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT | Built-in pi-lane sub-agents (`acp_delegate`) surface (#2230 config-home): six env overrides mirror the file keys; full field table in the [`pi`](#pi) section below. | **MITM lane** @@ -677,6 +678,49 @@ Top-level keys that control how the proxy listens and behaves globally. - **Status:** ACTIVE - **Description:** Native-hook attach policy (#1335). Lane'd native hooks attach to a running proxy only when it reports an armed session-lifecycle watchdog; an unarmed lane'd listener (a crashed session's orphan) is refused loudly instead of being silently ridden — a manually started `bili start` daemon (no lane) is user-zone and attachable by default (#1660). Set `attachExternal: true` to attach to *lane'd* unarmed listeners anyway (any code/lane-compatible listener becomes attachable regardless of watchdog state, including pre-#1330 builds). Overridden by `BILI_NATIVE_ATTACH_EXTERNAL` (`1` opens the gate even over a closed file; `0` closes it even over a permissive file). Full mechanics: [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660). +### `pi` + +- **Type:** `{ subagents?: PiSubagentsFileConfig | boolean }` +- **Default:** `{}` (acp_delegate surface enabled with package defaults) +- **Status:** ACTIVE (#2230 config-home) +- **Description:** Settings for the built-in **pi-lane sub-agents** (`acp_delegate` / `acp_delegate_wait` / `acp_delegate_cancel`, registered when `bili pi` wires the embedded extension). The `pi.subagents` section is the config home for this surface; the standalone `billion-context-pi-subagents` package reads the same section through its own loader (the file format is the contract, not shared code). Previously these knobs lived in pi's `~/.pi/acp.json` under `delegate` / `delegatePrompt` / `displayUsage` / `debug` — those four keys are a **deprecated fallback**: still read while the section is absent (one-time warning in the bili log and `~/.pi/acp.log`), **ignored once the section exists**, slated for removal in a future release. Renames: `delegatePrompt` → `prompt`; `debug` is scoped to the sub-agent subsystem and does **not** collide with the top-level proxy `debug`. + +```jsonc +"pi": { + "subagents": { + "enabled": true, // master switch; false (or "subagents": false) removes tools+prompt+shortcut (new session) + "forceEnable": false, // keep acp_delegate even when a project-scope pi-subagents install is detected (#415) + "displayUsage": "separate", // "separate" (own footer block) | "merged" (folded into tool-result usage) + "maxDepth": 2, // nesting depth cap, propagated to children + "syncTimeoutMinutes": 5, // hard timeout for sync delegates; 0/null disables + "idleTimeoutMinutes": 5, // idle watchdog for async delegates; 0/null disables (warns) + "asyncTimeoutMinutes": 30, // hard limit for async delegates; 0/null disables + "maxConcurrent": 4, // cap on concurrent background delegates (default unlimited; extras queue) + "thinkingLevel": "medium", // off|minimal|low|medium|high|xhigh|max; priority per-call > role > this > pi default + "agents": { // per-role defaults: { model: "provider/id", thinkingLevel: "…" } + "reviewer": { "model": "anthropic/claude-sonnet-4-5", "thinkingLevel": "high" } + }, + "notifyIfRead": "skip", // "skip" — no completion nudge if the model already read the result file + "fleetShortcut": "ctrl+alt+d", // "" disables the keyboard shortcut (/acp-fleet still works) + "prompt": null, // replace (string) or remove (null) the ACP_DELEGATE NOTIFICATIONS appendix + "debug": false // debug events in ~/.pi/acp.log, scoped to sub-agents + } +} +``` + +**Env overrides** (per-process spawn channels, propagate to delegate children; `PI_ACP_DELEGATE_*` > `pi.subagents` > deprecated acp.json > default): + +| Env var | Overrides | Notes | +|---|---|---| +| `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents.forceEnable` | `true`/`false`; unparseable values warn and fall back to the file value. | +| `PI_ACP_DELEGATE_MAX_DEPTH` | `pi.subagents.maxDepth` | Integer ≥ 1; invalid warns and falls back. | +| `PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES` | `pi.subagents.syncTimeoutMinutes` | `0` disables; negative/non-numeric warns and falls back. | +| `PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES` | `pi.subagents.idleTimeoutMinutes` | `0` disables (warns — hung children then need `acp_delegate_cancel`). | +| `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents.asyncTimeoutMinutes` | `0` disables. | +| `PI_ACP_DELEGATE_MAX_CONCURRENT` | `pi.subagents.maxConcurrent` | Integer ≥ 1; invalid falls through to the file value, then unlimited. | + +Changes take effect on a **new session** (tools register at session start). Full delegate surface docs (roles, execution model, fleet inspector): [billion-context-pi-subagents README](https://github.com/ranxianglei/billion-context-pi-subagents#readme). + ### Process-level blocks (#2030) Since #2030 every pure-behavior knob has a config-file key alongside its env var. Resolution is **env var > config file > built-in default**: a *set* env value owns its knob even when garbage (it parses exactly as pre-#2030 — falling back to the default) and neither leaks into nor gets shadowed by the file tier. These blocks scope the **proxy process** (transport timing, persistence, session lifecycle, self-update, diagnostics). They deliberately do **not** participate in the three-level compress merge ([global → provider → model](#three-level-merge-example)): none of these knobs has per-provider or per-model semantics — their env-var form was process-global, so a top-level key preserves scope exactly. All keys are optional; omitting a block changes nothing. Exhaustive per-knob semantics live in the [env mapping table](#config-file-keys-for-environment-knobs-2030) below. @@ -1446,6 +1490,12 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_MITM_DOMAINS` | `mitm.domains` | [] | | `BILI_MITM_HANDSHAKE_TIMEOUT_MS` | `mitm.handshakeTimeoutMs` | 10000 | | `BILI_NATIVE_ATTACH_EXTERNAL` | `native.attachExternal` | false | +| `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents.forceEnable` | false | +| `PI_ACP_DELEGATE_MAX_DEPTH` | `pi.subagents.maxDepth` | 2 | +| `PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES` | `pi.subagents.syncTimeoutMinutes` | 5 | +| `PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES` | `pi.subagents.idleTimeoutMinutes` | 5 | +| `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents.asyncTimeoutMinutes` | 30 | +| `PI_ACP_DELEGATE_MAX_CONCURRENT` | `pi.subagents.maxConcurrent` | unset (unlimited) | | `BILI_NON_HTTP_PROVIDERS` | `compactionOptIn` | false | | `BILI_NO_CACHE_CONTROL` | `compat.noCacheControl` | false | | `BILI_PERSIST` | `persist.enabled` | true | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 6a03b8a41a..caf2304e17 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -110,6 +110,7 @@ | `promptCache.routing` | "auto" \| "enabled" \| "disabled" | auto | ACP_PROMPT_CACHE_ROUTING | 面向缓存感知路由选择的提示词缓存路由姿态。 | | `native.attachExternal` | boolean | false | BILI_NATIVE_ATTACH_EXTERNAL | 允许无启动器的原生插件挂到外部(车道化、未武装看门狗)守护进程,而不是自行派生。 | | `claude.nativePort` | number | unset (lane sticky zone port) | BILI_CLAUDE_NATIVE_PORT | claude 原生车道钩子派生代理的精确端口钉死(严格端口:被占用时响亮拒绝而非跳端口)。 | +| `pi.subagents.*` | 见 [`pi` 段](#pi) | 包默认 | PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT | 内置 pi lane 子代理(acp_delegate)面(#2230 配置搬家):六键 env 覆盖对应文件键;完整字段表见下文 [`pi`](#pi) 段。 | **MITM 通道** @@ -677,6 +678,49 @@ - **状态:** ACTIVE - **说明:** native hook attach 策略(#1335)。lane'd native hook 仅在运行中的代理报告了已武装的会话生命周期看门狗时才 attach;未武装的 lane'd listener(崩溃会话的孤儿)被大声拒收而不是被静默搭车 —— 手动启动的 `bili start` 守护(无 lane)属用户区,默认可 attach(#1660)。设 `attachExternal: true` 仍可 attach 到 *lane'd* 未武装 listener(任何代码/lane 兼容的 listener 均可 attach,不论看门狗状态,包括 pre-#1330 构建)。可由 `BILI_NATIVE_ATTACH_EXTERNAL` 覆盖(`1` 即使文件关闭也开门;`0` 即使文件宽松也关门)。完整机制见 [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660)。 +### `pi` + +- **类型:** `{ subagents?: PiSubagentsFileConfig | boolean }` +- **默认值:** `{}`(acp_delegate 面按包默认值启用) +- **状态:** ACTIVE(#2230 配置搬家) +- **说明:** 内置 **pi lane 子代理**(`acp_delegate` / `acp_delegate_wait` / `acp_delegate_cancel`,`bili pi` 装入内嵌扩展时注册)的配置。`pi.subagents` 段是该功能的配置家;独立包 `billion-context-pi-subagents` 用自己的 loader 读同一段(契约是文件格式,不是共享代码)。此前这些旋钮在 pi 的 `~/.pi/acp.json`(`delegate` / `delegatePrompt` / `displayUsage` / `debug` 四键)——这四键是**已废弃的回退源**:段缺失时仍读取(在 bili 日志与 `~/.pi/acp.log` 各警告一次),**段存在后完全忽略**,未来版本移除。改名:`delegatePrompt` → `prompt`;`debug` 限定子代理子系统,**不**与顶层代理 `debug` 冲突。 + +```jsonc +"pi": { + "subagents": { + "enabled": true, // 总开关;false(或 "subagents": false)移除工具+提示词+快捷键(新会话生效) + "forceEnable": false, // 检测到项目级 pi-subagents 安装时仍保留 acp_delegate(#415) + "displayUsage": "separate", // "separate"(独立 footer 块)| "merged"(并入工具结果用量) + "maxDepth": 2, // 嵌套深度上限,向子进程传播 + "syncTimeoutMinutes": 5, // 同步 delegate 硬超时;0/null 关闭 + "idleTimeoutMinutes": 5, // 异步 delegate 空闲看门狗;0/null 关闭(告警) + "asyncTimeoutMinutes": 30, // 异步 delegate 硬时限;0/null 关闭 + "maxConcurrent": 4, // 后台并发上限(默认无限;超出排队) + "thinkingLevel": "medium", // off|minimal|low|medium|high|xhigh|max;优先级 每次调用 > 角色 > 此处 > pi 默认 + "agents": { // 角色默认:{ model: "provider/id", thinkingLevel: "…" } + "reviewer": { "model": "anthropic/claude-sonnet-4-5", "thinkingLevel": "high" } + }, + "notifyIfRead": "skip", // "skip" —— 模型已读结果文件则不再补发完成通知 + "fleetShortcut": "ctrl+alt+d", // "" 关闭快捷键(/acp-fleet 仍可用) + "prompt": null, // 替换(字符串)或移除(null)ACP_DELEGATE NOTIFICATIONS 附录 + "debug": false // ~/.pi/acp.log 调试事件,仅限子代理子系统 + } +} +``` + +**环境变量覆盖**(进程级 spawn 通道,随子代理子进程传播;`PI_ACP_DELEGATE_*` > `pi.subagents` > 已废弃 acp.json > 默认): + +| 环境变量 | 覆盖 | 说明 | +|---|---|---| +| `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents.forceEnable` | `true`/`false`;非法值告警并回退到文件值。 | +| `PI_ACP_DELEGATE_MAX_DEPTH` | `pi.subagents.maxDepth` | ≥1 整数;非法值告警并回退。 | +| `PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES` | `pi.subagents.syncTimeoutMinutes` | `0` 关闭;负数/非数字告警并回退。 | +| `PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES` | `pi.subagents.idleTimeoutMinutes` | `0` 关闭(告警 —— 挂死子进程需 `acp_delegate_cancel`)。 | +| `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents.asyncTimeoutMinutes` | `0` 关闭。 | +| `PI_ACP_DELEGATE_MAX_CONCURRENT` | `pi.subagents.maxConcurrent` | ≥1 整数;非法值回落到文件值,再回落到无限。 | + +修改在**新会话**生效(工具在会话启动时注册)。完整 delegate 面文档(角色、执行模型、fleet 检查器)见 [billion-context-pi-subagents README](https://github.com/ranxianglei/billion-context-pi-subagents#readme)。 + ### 进程级配置块(#2030) 自 #2030 起,每个纯行为开关在环境变量之外都有配置文件键。解析顺序为**环境变量 > 配置文件 > 内置默认值**:已设置的环境变量值即使内容非法也独占其开关(解析方式与 #2030 之前完全一致 —— 回落到默认值),既不泄漏进文件层、也不被文件层遮蔽。这些块的作用域是**代理进程本身**(传输时序、持久化、会话生命周期、自更新、诊断)。它们有意**不参与**压缩配置的三级合并([全局 → provider → 模型](#三层合并示例)):这些开关都不存在按 provider / 按模型的语义 —— 它们的环境变量形态本来就是进程级的,顶层键恰好保持作用域不变。所有键均可选;省略整个块不会改变任何行为。每个开关的完整语义见下文[环境变量对照表](#环境变量的配置键对照-2030)。 @@ -1451,6 +1495,12 @@ | `BILI_MITM_DOMAINS` | `mitm.domains` | [] | | `BILI_MITM_HANDSHAKE_TIMEOUT_MS` | `mitm.handshakeTimeoutMs` | 10000 | | `BILI_NATIVE_ATTACH_EXTERNAL` | `native.attachExternal` | false | +| `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents.forceEnable` | false | +| `PI_ACP_DELEGATE_MAX_DEPTH` | `pi.subagents.maxDepth` | 2 | +| `PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES` | `pi.subagents.syncTimeoutMinutes` | 5 | +| `PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES` | `pi.subagents.idleTimeoutMinutes` | 5 | +| `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents.asyncTimeoutMinutes` | 30 | +| `PI_ACP_DELEGATE_MAX_CONCURRENT` | `pi.subagents.maxConcurrent` | unset(无限) | | `BILI_NON_HTTP_PROVIDERS` | `compactionOptIn` | false | | `BILI_NO_CACHE_CONTROL` | `compat.noCacheControl` | false | | `BILI_PERSIST` | `persist.enabled` | true | diff --git a/reference/env-vars.md b/reference/env-vars.md index 6947be4c98..122ad2bdf6 100644 --- a/reference/env-vars.md +++ b/reference/env-vars.md @@ -19,7 +19,7 @@ precisely so knobs don't bloat the environment. Precedence everywhere: |----------|------|----------| | Behavior tunables (timeouts, caps, modes, diagnostics) | config-file key resolved through `src/knobs.ts`; env stays the override tier | `network.*`, `persist.*`, `sessions.*`, `update.*`, `diagnostics.*`, `fakeCompletion.*`, `plugin.*` | | Secrets / credentials | env only (never written to disk) | `BILI_LAUNCH_TOKEN`, `BILI_ENCRYPTION_KEY` | -| Per-process channels (written by another bili component at spawn) | env only + comment at the read site naming the writer | `BILI_MCP_PROXY`, `BILI_PARENT_PID`, `BILI_STRICT_PORT`, `BILI_OPENCODE_ACP_SPEC`, `BILI_LAUNCHER_MODEL_*` | +| Per-process channels (written by another bili component at spawn) | env only + comment at the read site naming the writer | `BILI_MCP_PROXY`, `BILI_PARENT_PID`, `BILI_STRICT_PORT`, `BILI_OPENCODE_ACP_SPEC`, `BILI_LAUNCHER_MODEL_*`, `PI_ACP_DELEGATE_*` (child-delegate propagation, #2230; file tier = `pi.subagents`) | | Host-side posture (read inside a third-party host process at bootstrap) | env only + comment at the read site | `BILLION_CONTEXT_PLUGIN*`, `BILI_NATIVE_*`, `BILI_RECLAIM_FETCH_PATCH` | | Path relocation (test/container isolation) | env only via `src/paths.ts` | `BILI_CONFIG_FILE`, `BILI_SESSIONS_DIR`, `ACP_DUMP_DIR`, `XDG_*` | | Third-party conventions (not ours to rename) | as-is | `CLAUDE_CODE_SESSION_ID`, `CODEX_HOME`, `https_proxy` | diff --git a/src/agent/pi-subagents.ts b/src/agent/pi-subagents.ts index 0bebde78e8..da4d610b01 100644 --- a/src/agent/pi-subagents.ts +++ b/src/agent/pi-subagents.ts @@ -33,8 +33,10 @@ import { setDelegatePolicy, setDebugEnabled, type DelegatePolicy, + type SubagentsAdapterConfig, } from "billion-context-pi-subagents"; import type { ExtensionAPI, ToolDefinition } from "./pi.js"; +import { loadConfigFile, type PiSubagentsFileConfig } from "../config.js"; const EMBEDDED_GLOBAL_KEY = Symbol.for("acp-delegate.embedded"); @@ -56,6 +58,25 @@ function normalizeSystemPrompt(input: string | string[] | undefined): string { return input; } +// #2230 config-home: map the `pi.subagents` section of billion-context.json +// onto the package's adapter shape. Mirrors the package's +// piSubagentsToAdapter deliberately — no shared code across the two loaders; +// the FILE FORMAT (documented in CONFIGURATION.md) is the contract. Renames: +// `prompt` replaces acp.json's delegatePrompt; `debug` is scoped to the +// sub-agent subsystem (the top-level proxy `debug` is untouched). +function piSubagentsAdapter(section: PiSubagentsFileConfig | boolean): SubagentsAdapterConfig { + if (section === false) return { delegate: { enabled: false } }; + if (section === true) return {}; + const { prompt, debug, ...delegate } = section; + const adapter: SubagentsAdapterConfig = {}; + if (Object.keys(delegate).length > 0) adapter.delegate = delegate; + if (prompt !== undefined) adapter.delegatePrompt = prompt; + if (debug !== undefined) adapter.debug = debug; + return adapter; +} + +let warnedAcpJsonFallback = false; + 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. @@ -110,9 +131,22 @@ export function wirePiSubagents(pi: ExtensionAPI, agent: string): void { 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); + // #2230 config-home: bili's own config file owns the delegate + // config — the `pi.subagents` section of billion-context.json, + // read through bili's loader so its validation/warning surface + // applies. The package's acp.json loader stays as a deprecated + // fallback for pre-move files (removal after a few releases). + const section = loadConfigFile().pi?.subagents; + let user: SubagentsAdapterConfig; + if (section !== undefined) { + user = piSubagentsAdapter(section); + } else { + user = await loadSubagentsUserConfig(cwd); + if (Object.keys(user).length > 0 && !warnedAcpJsonFallback) { + warnedAcpJsonFallback = true; + console.error("bili-plugin(pi): delegate config in acp.json is deprecated — move it to the \"pi\": {\"subagents\": {…}} section of billion-context.json (delegatePrompt renames to prompt); it will be removed in a future release"); + } + } if (user.debug !== undefined) setDebugEnabled(user.debug === true); state.policy = resolveDelegate(user); state.delegatePrompt = user.delegatePrompt; diff --git a/src/config.ts b/src/config.ts index 8bb1ae2fba..a7a6a3a73e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1268,6 +1268,58 @@ export function resolveNonHttpProviders(env: NodeJS.ProcessEnv = process.env): s return [...out]; } +/** `pi.subagents` section of the config file (#2230 config-home): the home + * for the built-in pi-lane acp_delegate surface. Fields map 1:1 onto the + * standalone package's DelegateConfig (billion-context-pi-subagents); the + * two renames vs the deprecated acp.json keys: `prompt` replaces + * `delegatePrompt`, and `debug` is scoped to the sub-agent subsystem (the + * top-level `debug` key stays the proxy's own). See CONFIGURATION.md. */ +export interface PiSubagentsFileConfig { + /** Master switch, default true. `false` (or the boolean shorthand + * `"pi": {"subagents": false}`) removes the three tools, the + * system-prompt section and the fleet shortcut (new session required). */ + enabled?: boolean; + /** Keep acp_delegate active even when a project-scope pi-subagents + * install is detected (#415 stand-down). Default false. Env + * PI_ACP_DELEGATE_FORCE_ENABLE=true/false wins over the file. */ + forceEnable?: boolean; + /** "separate" (default) — delegate tokens tracked in their own + * accumulator; "merged" — folded into the main session totals. */ + displayUsage?: "merged" | "separate"; + /** Max nesting depth (default 2: main → child → grandchild). Propagated + * to children via PI_ACP_DELEGATE_MAX_DEPTH; env wins over the file. */ + maxDepth?: number; + /** Hard timeout for synchronous delegates, minutes (default 5); + * 0/null disables. Env PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES wins. */ + syncTimeoutMinutes?: number | null; + /** Idle watchdog for async delegates, minutes (default 5); 0/null + * disables (warns). Env PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES wins. */ + idleTimeoutMinutes?: number | null; + /** Hard time limit for async delegates, minutes (default 30); 0/null + * disables. Env PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES wins. */ + asyncTimeoutMinutes?: number | null; + /** Cap on concurrent background delegates (default unlimited); extras + * queue. Env PI_ACP_DELEGATE_MAX_CONCURRENT wins. */ + maxConcurrent?: number; + /** Global default thinking level (off|minimal|low|medium|high|xhigh|max). */ + thinkingLevel?: string; + /** Per-role defaults keyed by role (reviewer/researcher/worker/planner/ + * oracle or custom): { model: "provider/id", thinkingLevel: "…" }. */ + agents?: Record; + /** "skip" (default) — suppress the completion notification when the + * model already read the result file; "always" — always inject. */ + notifyIfRead?: "skip" | "always"; + /** TUI shortcut for the fleet inspector (default "ctrl+alt+d"); "" + * disables keyboard registration (/acp-fleet still works). */ + fleetShortcut?: string; + /** Replace (string) or remove (null) the ACP_DELEGATE NOTIFICATIONS + * system-prompt appendix. acp.json name: `delegatePrompt`. */ + prompt?: string | null; + /** Debug-level events in the shared ACP log (~/.pi/acp.log), scoped to + * the sub-agent subsystem. */ + debug?: boolean; +} + /** Shape of the optional JSON config file. All fields optional — the file is a * pure override layer; anything unset falls through to defaults. */ type FileConfig = { @@ -1392,6 +1444,18 @@ type FileConfig = { * (the default) means the lane's sticky zone port (ZONE_PORT_BASE base). * Env BILI_CLAUDE_NATIVE_PORT wins over the file. */ claude?: { nativePort?: number }; + /** Built-in pi-lane sub-agents (#2230 config-home): the `pi.subagents` + * section owns the acp_delegate surface for the pi lane (embedded wiring + * src/agent/pi-subagents.ts; the standalone package + * billion-context-pi-subagents reads the same section through its own + * loader — the file format is the contract, not shared code). Fields map + * 1:1 onto the package's DelegateConfig; `prompt` replaces acp.json's + * `delegatePrompt` and `debug` is scoped to the sub-agent subsystem (no + * collision with the top-level proxy `debug`). Boolean shorthand: + * `"pi": {"subagents": false}` disables the whole surface. The four + * acp.json keys (delegate/delegatePrompt/displayUsage/debug) are a + * deprecated fallback, read only while this section is absent. */ + pi?: { subagents?: PiSubagentsFileConfig | boolean }; /** Native-hook attach policy (#1335): set `true` to let native hooks * attach to lifecycle-less listeners (a manually started `bili start` * daemon — no session-lifecycle watchdog, outlives every session, often @@ -1518,6 +1582,7 @@ const KNOWN_TOP_LEVEL_KEYS = new Set([ "chainContentDetection", "chainEgressStamp", "stableSystemAnchor", "dsh", "compat", "imageBilling", "imageTokenCap", "claude", "native", "resign", + "pi", // #2030 subsystem blocks: "network", "persist", "sessions", "plugin", "update", "diagnostics", "fakeCompletion", "codexCompact", "ccrRetrievalTtlMs", "decompressTmpCap", diff --git a/tests/pi-subagents-wiring.test.ts b/tests/pi-subagents-wiring.test.ts index ca0c2ce208..8de325c166 100644 --- a/tests/pi-subagents-wiring.test.ts +++ b/tests/pi-subagents-wiring.test.ts @@ -11,9 +11,13 @@ import type { ExtensionAPI, CommandCtx } from "../src/agent/pi.ts"; // the registration lifecycle is driven: agent gate, embedded-marker // check-before-claim, session_start registration, prompt append, read-tracking // dispatch. HOME is redirected before any import so loadSubagentsUserConfig / -// findPiSubagentsInstalls see an empty world, not the developer's real ~/.pi. +// findPiSubagentsInstalls see an empty world, not the developer's real ~/.pi; +// BILI_CONFIG_FILE likewise isolates the #2230 pi.subagents config-home read +// from the developer's real billion-context.json. const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "bili-pi-subagents-home-")); process.env.HOME = HOME; +const BILI_CONFIG_FILE = path.join(HOME, "billion-context.json"); +process.env.BILI_CONFIG_FILE = BILI_CONFIG_FILE; type Handler = (event: unknown, ctx: unknown) => unknown; @@ -144,7 +148,18 @@ test("acp-fleet command handler notifies instead of opening the inspector when d const ctx = sessionCtx(); fs.mkdirSync(path.join(ctx.cwd, ".pi"), { recursive: true }); fs.writeFileSync(path.join(ctx.cwd, ".pi", "acp.json"), JSON.stringify({ delegate: { enabled: false } })); - await handlers.get("session_start")!(undefined, ctx); + // This is the deprecated fallback path now (#2230): acp.json keys still + // work but must say so loudly. Spy (and silence) the warning — the + // one-shot flag is module-global, and this is the first fallback test. + const errors: string[] = []; + const savedError = console.error; + console.error = (...args: unknown[]) => { errors.push(args.join(" ")) }; + try { + await handlers.get("session_start")!(undefined, ctx); + } finally { + console.error = savedError; + } + assert.ok(errors.some((e) => /deprecated/.test(e) && /pi/.test(e)), `deprecation warning logged, got: ${errors.join(" | ")}`); assert.deepEqual(tools, []); assert.deepEqual(commands, ["acp-fleet"]); const opts = commandOpts.get("acp-fleet"); @@ -173,3 +188,74 @@ test("project-scope pi-subagents install stands acp_delegate down (#415)", async assert.match(ctx.ui.notifications[0][0], /pi-subagents detected/); assert.equal(ctx.ui.notifications[0][1], "warning"); }); + +// --- #2230 config-home: pi.subagents in billion-context.json --- + +function writeBiliConfig(value: unknown): void { + fs.writeFileSync(BILI_CONFIG_FILE, JSON.stringify(value)); +} + +function clearBiliConfig(): void { + fs.rmSync(BILI_CONFIG_FILE, { force: true }); +} + +test("pi.subagents enabled:false drops the tools, prompt section and shortcut", async () => { + clearBiliConfig(); + writeBiliConfig({ pi: { subagents: { enabled: false } } }); + const { pi, handlers, tools, shortcuts } = fakePi(); + (globalThis as Record)[Symbol.for("acp-delegate.embedded")] = false; + wirePiSubagents(pi, "pi"); + (globalThis as Record)[Symbol.for("acp-delegate.embedded")] = true; + const ctx = sessionCtx(); + await handlers.get("session_start")!(undefined, ctx); + assert.deepEqual(tools, []); + assert.equal(shortcuts.length, 0); + const prompt = await handlers.get("before_agent_start")!({ systemPrompt: "BASE" }, ctx) as { systemPrompt: string } | undefined; + assert.equal(prompt, undefined, "no prompt event result while disabled"); +}); + +test("pi.subagents boolean shorthand false is equivalent", async () => { + writeBiliConfig({ pi: { subagents: false } }); + const { pi, handlers, tools } = fakePi(); + (globalThis as Record)[Symbol.for("acp-delegate.embedded")] = false; + wirePiSubagents(pi, "pi"); + (globalThis as Record)[Symbol.for("acp-delegate.embedded")] = true; + await handlers.get("session_start")!(undefined, sessionCtx()); + assert.deepEqual(tools, []); +}); + +test("pi.subagents section owns the config: acp.json keys are ignored when both exist", async () => { + writeBiliConfig({ pi: { subagents: { enabled: true } } }); + const { pi, handlers, tools } = fakePi(); + (globalThis as Record)[Symbol.for("acp-delegate.embedded")] = false; + wirePiSubagents(pi, "pi"); + (globalThis as Record)[Symbol.for("acp-delegate.embedded")] = true; + const ctx = sessionCtx(); + fs.mkdirSync(path.join(ctx.cwd, ".pi"), { recursive: true }); + fs.writeFileSync(path.join(ctx.cwd, ".pi", "acp.json"), JSON.stringify({ delegate: { enabled: false } })); + await handlers.get("session_start")!(undefined, ctx); + assert.equal(tools.length, 3, "bili section wins over the disabled acp.json keys"); +}); + +test("pi.subagents prompt rename replaces the delegate appendix", async () => { + writeBiliConfig({ pi: { subagents: { prompt: "CUSTOM-PROMPT-MARKER" } } }); + const { pi, handlers } = fakePi(); + (globalThis as Record)[Symbol.for("acp-delegate.embedded")] = false; + wirePiSubagents(pi, "pi"); + (globalThis as Record)[Symbol.for("acp-delegate.embedded")] = true; + await handlers.get("session_start")!(undefined, sessionCtx()); + const prompt = await handlers.get("before_agent_start")!({ systemPrompt: "BASE" }, sessionCtx()) as { systemPrompt: string }; + assert.ok(prompt.systemPrompt.includes("CUSTOM-PROMPT-MARKER"), "custom prompt present"); + assert.ok(!prompt.systemPrompt.includes("ACP_DELEGATE"), "built-in appendix replaced"); +}); + +test("pi.subagents scoped debug flag reaches setDebugEnabled (adapter passthrough)", async () => { + writeBiliConfig({ pi: { subagents: { debug: true, maxConcurrent: 2 } } }); + const { pi, handlers, tools } = fakePi(); + (globalThis as Record)[Symbol.for("acp-delegate.embedded")] = false; + wirePiSubagents(pi, "pi"); + (globalThis as Record)[Symbol.for("acp-delegate.embedded")] = true; + await handlers.get("session_start")!(undefined, sessionCtx()); + // The policy resolved from the section must carry the section values. + assert.equal(tools.length, 3); +}); From 7556bf287a0e576d6dc577bf48461ef4511c0567 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 6 Oct 2026 13:52:58 +0800 Subject: [PATCH 2/5] docs: pi.subagents seed entry + regenerated config index (#2230) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The docs-sync drift guard (#2107) caught hand-edited generated blocks — the quick-ref and env-map rows now come from the seed in website/config-reference/server.yaml like every other key; the narrative pi section (field table + env overrides) stays hand-written outside the generated blocks. --- CONFIGURATION.md | 14 +++++++------- CONFIGURATION.zh-CN.md | 14 +++++++------- website/config-reference/server.yaml | 7 +++++++ 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index ac237de2cd..dce2fbe047 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -110,7 +110,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `promptCache.routing` | "auto" \| "enabled" \| "disabled" | auto | ACP_PROMPT_CACHE_ROUTING | Prompt-cache routing posture for cache-aware lane selection. | | `native.attachExternal` | boolean | false | BILI_NATIVE_ATTACH_EXTERNAL | Let launcher-less native plugins attach to an external (lane'd, unarmed) daemon instead of spawning their own. | | `claude.nativePort` | number | unset (lane sticky zone port) | BILI_CLAUDE_NATIVE_PORT | Exact port pin for the claude native lane's hook-spawned proxy (strict-port: squatters are refused loudly). | -| `pi.subagents.*` | see [`pi` section](#pi) | package defaults | PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT | Built-in pi-lane sub-agents (`acp_delegate`) surface (#2230 config-home): six env overrides mirror the file keys; full field table in the [`pi`](#pi) section below. | +| `pi.subagents` | { subagents?: object \| boolean } | {} (acp_delegate enabled with package defaults) | PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT | Built-in pi-lane sub-agents (acp_delegate) surface, #2230 config-home. The pi.subagents section of billion-context.json owns the delegate config; the four acp.json keys (delegate/delegatePrompt/displayUsage/debug) are a deprecated fallback read only while the section is absent. prompt replaces delegatePrompt; debug is scoped to the sub-agent subsystem. Boolean shorthand subagents: false disables the whole surface. Full field table: the pi section in CONFIGURATION.md. | **MITM lane** @@ -1490,12 +1490,6 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_MITM_DOMAINS` | `mitm.domains` | [] | | `BILI_MITM_HANDSHAKE_TIMEOUT_MS` | `mitm.handshakeTimeoutMs` | 10000 | | `BILI_NATIVE_ATTACH_EXTERNAL` | `native.attachExternal` | false | -| `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents.forceEnable` | false | -| `PI_ACP_DELEGATE_MAX_DEPTH` | `pi.subagents.maxDepth` | 2 | -| `PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES` | `pi.subagents.syncTimeoutMinutes` | 5 | -| `PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES` | `pi.subagents.idleTimeoutMinutes` | 5 | -| `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents.asyncTimeoutMinutes` | 30 | -| `PI_ACP_DELEGATE_MAX_CONCURRENT` | `pi.subagents.maxConcurrent` | unset (unlimited) | | `BILI_NON_HTTP_PROVIDERS` | `compactionOptIn` | false | | `BILI_NO_CACHE_CONTROL` | `compat.noCacheControl` | false | | `BILI_PERSIST` | `persist.enabled` | true | @@ -1531,6 +1525,12 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_UPSTREAM_PROXY` | `proxy` | unset (direct) | | `BILI_UPSTREAM_PROXY_MODE` | `upstreamProxyMode` | auto (unset behaves as direct) | | `BILI_UPSTREAM_TIMEOUT_MS` | `network.upstreamTimeoutMs` | 720000 | +| `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | +| `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | +| `PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | +| `PI_ACP_DELEGATE_MAX_CONCURRENT` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | +| `PI_ACP_DELEGATE_MAX_DEPTH` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | +| `PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | | `PORT` | `port` | 8787 | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index caf2304e17..886614cb90 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -110,7 +110,7 @@ | `promptCache.routing` | "auto" \| "enabled" \| "disabled" | auto | ACP_PROMPT_CACHE_ROUTING | 面向缓存感知路由选择的提示词缓存路由姿态。 | | `native.attachExternal` | boolean | false | BILI_NATIVE_ATTACH_EXTERNAL | 允许无启动器的原生插件挂到外部(车道化、未武装看门狗)守护进程,而不是自行派生。 | | `claude.nativePort` | number | unset (lane sticky zone port) | BILI_CLAUDE_NATIVE_PORT | claude 原生车道钩子派生代理的精确端口钉死(严格端口:被占用时响亮拒绝而非跳端口)。 | -| `pi.subagents.*` | 见 [`pi` 段](#pi) | 包默认 | PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT | 内置 pi lane 子代理(acp_delegate)面(#2230 配置搬家):六键 env 覆盖对应文件键;完整字段表见下文 [`pi`](#pi) 段。 | +| `pi.subagents` | { subagents?: object \| boolean } | {} (acp_delegate enabled with package defaults) | PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT | 内置 pi lane 子代理(acp_delegate)面(#2230 配置搬家)。billion-context.json 的 pi.subagents 段拥有 delegate 配置;acp.json 四键(delegate/delegatePrompt/displayUsage/debug)为已废弃回退源,仅段缺失时读取。prompt 取代 delegatePrompt;debug 限定子代理子系统。布尔简写 subagents: false 整体关闭。完整字段表见 CONFIGURATION.md 的 pi 段。 | **MITM 通道** @@ -1495,12 +1495,6 @@ | `BILI_MITM_DOMAINS` | `mitm.domains` | [] | | `BILI_MITM_HANDSHAKE_TIMEOUT_MS` | `mitm.handshakeTimeoutMs` | 10000 | | `BILI_NATIVE_ATTACH_EXTERNAL` | `native.attachExternal` | false | -| `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents.forceEnable` | false | -| `PI_ACP_DELEGATE_MAX_DEPTH` | `pi.subagents.maxDepth` | 2 | -| `PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES` | `pi.subagents.syncTimeoutMinutes` | 5 | -| `PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES` | `pi.subagents.idleTimeoutMinutes` | 5 | -| `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents.asyncTimeoutMinutes` | 30 | -| `PI_ACP_DELEGATE_MAX_CONCURRENT` | `pi.subagents.maxConcurrent` | unset(无限) | | `BILI_NON_HTTP_PROVIDERS` | `compactionOptIn` | false | | `BILI_NO_CACHE_CONTROL` | `compat.noCacheControl` | false | | `BILI_PERSIST` | `persist.enabled` | true | @@ -1536,6 +1530,12 @@ | `BILI_UPSTREAM_PROXY` | `proxy` | unset (direct) | | `BILI_UPSTREAM_PROXY_MODE` | `upstreamProxyMode` | auto (unset behaves as direct) | | `BILI_UPSTREAM_TIMEOUT_MS` | `network.upstreamTimeoutMs` | 720000 | +| `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | +| `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | +| `PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | +| `PI_ACP_DELEGATE_MAX_CONCURRENT` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | +| `PI_ACP_DELEGATE_MAX_DEPTH` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | +| `PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | | `PORT` | `port` | 8787 | diff --git a/website/config-reference/server.yaml b/website/config-reference/server.yaml index b31a9d98b8..780fcf99ef 100644 --- a/website/config-reference/server.yaml +++ b/website/config-reference/server.yaml @@ -338,6 +338,13 @@ entries: group: behavior desc_en: "Exact port pin for the claude native lane's hook-spawned proxy (strict-port: squatters are refused loudly)." desc_zh: "claude 原生车道钩子派生代理的精确端口钉死(严格端口:被占用时响亮拒绝而非跳端口)。" + - key: pi.subagents + type: "{ subagents?: object | boolean }" + default: "{} (acp_delegate enabled with package defaults)" + env: [PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT] + group: behavior + desc_en: "Built-in pi-lane sub-agents (acp_delegate) surface, #2230 config-home. The pi.subagents section of billion-context.json owns the delegate config; the four acp.json keys (delegate/delegatePrompt/displayUsage/debug) are a deprecated fallback read only while the section is absent. prompt replaces delegatePrompt; debug is scoped to the sub-agent subsystem. Boolean shorthand subagents: false disables the whole surface. Full field table: the pi section in CONFIGURATION.md." + desc_zh: "内置 pi lane 子代理(acp_delegate)面(#2230 配置搬家)。billion-context.json 的 pi.subagents 段拥有 delegate 配置;acp.json 四键(delegate/delegatePrompt/displayUsage/debug)为已废弃回退源,仅段缺失时读取。prompt 取代 delegatePrompt;debug 限定子代理子系统。布尔简写 subagents: false 整体关闭。完整字段表见 CONFIGURATION.md 的 pi 段。" - key: mitm.enabled type: boolean default: "true" From 76c6fe9639ebf353f835949c8321d7bca4285087 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 6 Oct 2026 14:15:25 +0800 Subject: [PATCH 3/5] fix(#2218/#1931): forward dsh plugin-lane session signal to relays MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dsh desktop's only conversation identity is the bili-internal x-bili-plugin-conversation header, which no third-party upstream can read: header-keyed relays (workbuddy hub, sub2api openai wire) lost sticky routing and body-keyed relays (workbuddy panel) fell to a content digest, so every account migration froze the provider prefix cache (#2218 80% hit-rate sessions; #1931 seed-drift class). - buildForwardTarget: treat the plugin conversation header like 'no header' — forward the client affinity as x-session-id - prepareOpenai: stamp prompt_cache_key = conversation id for the plugin lane when the client sent none, gated to admin-rewritten or loopback destinations (strict direct APIs can 400 unknown body params, #1403); the client's own value always wins --- src/server.ts | 20 +- src/session-id.ts | 38 ++++ tests/issue2218-relay-affinity-signal.test.ts | 214 ++++++++++++++++++ 3 files changed, 270 insertions(+), 2 deletions(-) create mode 100644 tests/issue2218-relay-affinity-signal.test.ts diff --git a/src/server.ts b/src/server.ts index 9b7e236ece..5935c42fd3 100644 --- a/src/server.ts +++ b/src/server.ts @@ -109,7 +109,7 @@ import { rewriteGoogleJsonResponse } from "./stream-google.js"; import { rewriteResponsesJsonResponse } from "./stream-responses.js"; import { observeResponsesTerminalState } from "./stream-terminal.js"; import { emitPreflightError, emitStreamError } from "./stream-error.js"; -import { affinityToken, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity, type ConversationIdentity } from "./session-id.js"; +import { affinityToken, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, conversationHeaderSource, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity, shouldStampRelayAffinityPck, type ConversationIdentity } from "./session-id.js"; import { prefixAffinity, type AnonymousAffinity } from "./prefix-affinity.js"; import { maybeAdoptForkBlocks, maybeAdoptResume } from "./fork-adoption.js"; import { publicForkInputMatches } from "./plugin.js"; @@ -4414,6 +4414,15 @@ async function prepareOpenai( // through: upstreams that ignore it lose nothing, upstreams that use it // get a per-conversation routing hint. delete (rebuilt as Record).prompt_cache_retention; + // #2218: body-only relay affinity for plugin hosts. dsh desktop's only + // identity signal is the bili-internal x-bili-plugin-conversation header + // (already forwarded as x-session-id by buildForwardTarget); body-keyed + // relays (workbuddy panel) can't read headers, so stamp the conversation + // id into prompt_cache_key too. Gated to admin-rewritten or loopback + // destinations — strict direct APIs can 400 unknown body params (#1403). + if (shouldStampRelayAffinityPck(conversationHeaderSource(req.headers)?.name, parsed.prompt_cache_key, billingUpstream, upstreamOrigin)) { + rebuilt.prompt_cache_key = session.id; + } // OpenAI Chat Completions only emits a usage object in the final stream // chunk when the client sets stream_options.include_usage=true. Without // it, streaming sessions never learn their real input_tokens → @@ -5518,7 +5527,14 @@ function buildForwardTarget( } // Forward a client-provided Responses session identity only when it was // carried in the body rather than an existing request header. - if (affinity && !clientConversationHeader(req.headers)) { + // #2218/#1931: the plugin-protocol header x-bili-plugin-conversation is + // bili-internal — no third-party upstream can read it — so a plugin host + // (dsh desktop) whose ONLY identity signal it is would otherwise arrive + // at a relay with zero usable session signal and lose sticky routing / + // cache pools (workbuddy hub and sub2api both key off x-session-id). + // Treat it like "no header": forward the affinity as x-session-id. + const convSource = conversationHeaderSource(req.headers); + if (affinity && (!convSource || convSource.name === "x-bili-plugin-conversation")) { headers["x-session-id"] = affinity; } const decision = resolveProxyDecision(opts.routes, opts.proxy, route?.rewrittenUrl ?? upstreamUrl, opts.proxyFallback); diff --git a/src/session-id.ts b/src/session-id.ts index 06e4c1b8d0..72b6097be5 100644 --- a/src/session-id.ts +++ b/src/session-id.ts @@ -1,4 +1,5 @@ import { isCodexClient } from "./codex-compact.js"; +import { isLoopbackAddress } from "./util.js"; export type ConversationIdentity = { value: string; @@ -195,6 +196,43 @@ export function affinityToken(identity: ConversationIdentity): string | undefine return identity.clientProvided ? identity.value : undefined; } +/** + * #2218: decide whether the proxy stamps `prompt_cache_key` into an outbound + * OpenAI chat body on behalf of a plugin host (dsh desktop) whose ONLY + * identity signal is the bili-internal x-bili-plugin-conversation header. + * Body-keyed relays (the workbuddy panel reads the body only: metadata → + * conversation_id → prompt_cache_key → content digest) cannot see any + * header, so without the stamp every plugin-lane request falls to a content + * digest and any account migration freezes the provider prefix cache. + * sub2api's OpenAI wire reads headers first (x-session-id wins), which the + * buildForwardTarget x-session-id fix already covers — the body stamp is + * specifically for the body-only relay family. + * + * Returns true only when ALL of: + * - the plugin lane owns the identity (the winning conversation header is + * the bili-internal one, not a header the upstream could read itself); + * - the client sent no prompt_cache_key of its own (client value wins); + * - the destination is admin-configured (provider-rewritten route) or + * loopback — deliberate relay/local deployments. Strict direct APIs can + * 400 unknown body params (#1403), so unrouted non-loopback forwards + * stay unstamped. + */ +export function shouldStampRelayAffinityPck( + identityHeaderName: string | undefined, + clientPck: unknown, + routeRewrittenUrl: string | undefined, + upstreamOrigin: string, +): boolean { + if (identityHeaderName !== "x-bili-plugin-conversation") return false; + if (clientPck !== undefined) return false; + if (routeRewrittenUrl !== undefined) return true; + try { + return isLoopbackAddress(new URL(upstreamOrigin).hostname); + } catch { + return false; + } +} + /** * Promote a Responses body's `prompt_cache_key` over a content-fingerprint * identity. Clients that replay full history statelessly (omp, some codex diff --git a/tests/issue2218-relay-affinity-signal.test.ts b/tests/issue2218-relay-affinity-signal.test.ts new file mode 100644 index 0000000000..5d2e30beed --- /dev/null +++ b/tests/issue2218-relay-affinity-signal.test.ts @@ -0,0 +1,214 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { startServer } from "../src/server.ts"; +import { defaultConfig } from "acp-kernel"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { _resetSessionsForTest } from "../src/session.ts"; +import { shouldStampRelayAffinityPck } from "../src/session-id.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import type { Server } from "node:http"; + +interface Captured { + headers: Record; + body: Record; +} + +function chatSse(): string { + return ( + `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "gpt-test", choices: [{ index: 0, delta: { content: "pong" }, finish_reason: null }] })}\n\n` + + `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "gpt-test", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}\n\n` + + "data: [DONE]\n\n" + ); +} + +interface Harness { + proxyPort: number; + upstreamPort: number; + captured: Captured[]; + close(): Promise; +} + +async function startHarness(routes: ProxyOptions["routes"] | undefined): Promise { + const captured: Captured[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + let body: Record = {}; + try { body = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { /* keep {} */ } + captured.push({ headers: req.headers, body }); + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + res.end(chatSse()); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _resetSessionsForTest(); + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const proxy: Server = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: routes ?? {}, + modelContextLimit: 100_000, + kernelConfig: defaultConfig(100_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + log: false, + sessionHeader: "x-acp-session", + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + }); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + return { + proxyPort, + upstreamPort, + captured, + close: async () => { + proxy.close(); + await once(proxy, "close"); + upstream.close(); + await once(upstream, "close"); + }, + }; +} + +function chatBody(extra: Record = {}): Record { + return { + model: "gpt-test", + stream: true, + messages: [{ role: "user", content: "hello " + Math.random() }], + ...extra, + }; +} + +test("#2218 unit: shouldStampRelayAffinityPck gate matrix", () => { + const loop = "http://127.0.0.1:7864/v1"; + const remote = "https://relay.example.com/v1"; + // plugin lane + no client pck + admin-rewritten route → stamp + assert.equal(shouldStampRelayAffinityPck("x-bili-plugin-conversation", undefined, loop, remote), true); + // plugin lane + no client pck + loopback destination without a route → stamp + assert.equal(shouldStampRelayAffinityPck("x-bili-plugin-conversation", undefined, undefined, loop), true); + // plugin lane + no client pck + unrouted non-loopback (strict direct API risk, #1403) → no stamp + assert.equal(shouldStampRelayAffinityPck("x-bili-plugin-conversation", undefined, undefined, remote), false); + // client's own prompt_cache_key always wins + assert.equal(shouldStampRelayAffinityPck("x-bili-plugin-conversation", "pck-own", loop, loop), false); + // non-plugin identity sources (codex session-id header, plain clients) stay unstamped + assert.equal(shouldStampRelayAffinityPck("session-id", undefined, loop, loop), false); + assert.equal(shouldStampRelayAffinityPck(undefined, undefined, loop, loop), false); + // unparseable origin is not a deliberate deployment → no stamp + assert.equal(shouldStampRelayAffinityPck("x-bili-plugin-conversation", undefined, undefined, "not-a-url"), false); +}); + +test("#2218 regression: plain client body pck still forwards x-session-id + body pck", async () => { + const h = await startHarness(undefined); + try { + const base = `http://127.0.0.1:${h.proxyPort}/bili/http://127.0.0.1:${h.upstreamPort}/v1/chat/completions`; + const r = await fetch(base, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(chatBody({ prompt_cache_key: "pck-abc" })) }); + assert.equal(r.status, 200); + await r.text(); + const [a] = h.captured; + assert.equal(a.headers["x-session-id"], "pck-abc"); + assert.equal(a.body.prompt_cache_key, "pck-abc"); + } finally { + await h.close(); + } +}); + +test("#2218 fix: dsh plugin lane reaches relays with BOTH header and body session signal", async () => { + const h = await startHarness(undefined); + try { + const base = `http://127.0.0.1:${h.proxyPort}/bili/http://127.0.0.1:${h.upstreamPort}/v1/chat/completions`; + // dsh native lane shape: plugin marker + conversation header, NO body pck + const r = await fetch(base, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "dsh-sid-1" }, + body: JSON.stringify(chatBody()), + }); + assert.equal(r.status, 200); + await r.text(); + const [b] = h.captured; + // header-reading relays (workbuddy hub, sub2api openai wire) see x-session-id + assert.equal(b.headers["x-session-id"], "dsh-sid-1"); + // body-only relays (workbuddy panel) see prompt_cache_key = the dsh conversation id + assert.equal(b.body.prompt_cache_key, "dsh-sid-1"); + } finally { + await h.close(); + } +}); + +test("#2218 fix: dsh plugin lane stamps pck on a loopback destination even without a configured route", async () => { + // routes-less harness pins the loopback leg of the gate (the GF-machine + // deployment shape: provider rewrite to a local relay port). + const h = await startHarness(undefined); + try { + const base = `http://127.0.0.1:${h.proxyPort}/bili/http://127.0.0.1:${h.upstreamPort}/v1/chat/completions`; + const r = await fetch(base, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "dsh-sid-2" }, + body: JSON.stringify(chatBody()), + }); + assert.equal(r.status, 200); + await r.text(); + const [b] = h.captured; + assert.equal(b.body.prompt_cache_key, "dsh-sid-2"); + } finally { + await h.close(); + } +}); + +test("#2218 fix: client's own prompt_cache_key on the dsh lane is never overwritten", async () => { + const h = await startHarness(undefined); + try { + const base = `http://127.0.0.1:${h.proxyPort}/bili/http://127.0.0.1:${h.upstreamPort}/v1/chat/completions`; + const r = await fetch(base, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "dsh-sid-3" }, + body: JSON.stringify(chatBody({ prompt_cache_key: "pck-dsh-own" })), + }); + assert.equal(r.status, 200); + await r.text(); + const [b] = h.captured; + assert.equal(b.body.prompt_cache_key, "pck-dsh-own"); + } finally { + await h.close(); + } +}); + +test("#2218 regression: readable client conversation headers still suppress the x-session-id duplicate", async () => { + const h = await startHarness(undefined); + try { + const base = `http://127.0.0.1:${h.proxyPort}/bili/http://127.0.0.1:${h.upstreamPort}/v1/chat/completions`; + // codex-style session-id header: the upstream reads it directly — the + // proxy must not mint a second header, and the non-plugin lane never + // gets a body stamp. + const r = await fetch(base, { + method: "POST", + headers: { "content-type": "application/json", "session-id": "codex-thread-1" }, + body: JSON.stringify(chatBody()), + }); + assert.equal(r.status, 200); + await r.text(); + const [b] = h.captured; + assert.equal(b.headers["x-session-id"], undefined); + assert.equal(b.body.prompt_cache_key, undefined); + } finally { + await h.close(); + } +}); From 0a1956e12e7a3a9ea3f3b8a235f799be2c52e16f Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 6 Oct 2026 14:36:21 +0800 Subject: [PATCH 4/5] fix(#2218): treat literal localhost as loopback in the relay pck stamp gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review finding on 76c6fe963: isLoopbackAddress only matches 127.x/::1 literals, so an upstream configured as http://localhost:N would silently fail the destination gate and the body stamp would not fire — reproducing exactly the zero-signal absence this fix removes. The codebase already treats "localhost" as loopback in upstream-proxy.ts / launcher.ts / config.ts; align the gate locally (shared util untouched). --- src/session-id.ts | 5 ++++- tests/issue2218-relay-affinity-signal.test.ts | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/session-id.ts b/src/session-id.ts index 72b6097be5..63bf6a66e8 100644 --- a/src/session-id.ts +++ b/src/session-id.ts @@ -227,7 +227,10 @@ export function shouldStampRelayAffinityPck( if (clientPck !== undefined) return false; if (routeRewrittenUrl !== undefined) return true; try { - return isLoopbackAddress(new URL(upstreamOrigin).hostname); + const hostname = new URL(upstreamOrigin).hostname; + // "localhost" is loopback but not matched by isLoopbackAddress (127.x/::1 + // only); a silent miss here would reproduce the zero-signal bug (#2218). + return hostname === "localhost" || isLoopbackAddress(hostname); } catch { return false; } diff --git a/tests/issue2218-relay-affinity-signal.test.ts b/tests/issue2218-relay-affinity-signal.test.ts index 5d2e30beed..42a9ef7422 100644 --- a/tests/issue2218-relay-affinity-signal.test.ts +++ b/tests/issue2218-relay-affinity-signal.test.ts @@ -112,6 +112,7 @@ test("#2218 unit: shouldStampRelayAffinityPck gate matrix", () => { // non-plugin identity sources (codex session-id header, plain clients) stay unstamped assert.equal(shouldStampRelayAffinityPck("session-id", undefined, loop, loop), false); assert.equal(shouldStampRelayAffinityPck(undefined, undefined, loop, loop), false); + assert.equal(shouldStampRelayAffinityPck("x-bili-plugin-conversation", undefined, undefined, "http://localhost:7864/v1"), true); // unparseable origin is not a deliberate deployment → no stamp assert.equal(shouldStampRelayAffinityPck("x-bili-plugin-conversation", undefined, undefined, "not-a-url"), false); }); From 0cee3850c814ae25dd69b9525a2f5b9f5fef4bf1 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 6 Oct 2026 14:51:22 +0800 Subject: [PATCH 5/5] test(#2218): correct gate-leg attribution in relay-affinity suite comment --- tests/issue2218-relay-affinity-signal.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/issue2218-relay-affinity-signal.test.ts b/tests/issue2218-relay-affinity-signal.test.ts index 42a9ef7422..3acd707aef 100644 --- a/tests/issue2218-relay-affinity-signal.test.ts +++ b/tests/issue2218-relay-affinity-signal.test.ts @@ -155,8 +155,10 @@ test("#2218 fix: dsh plugin lane reaches relays with BOTH header and body sessio }); test("#2218 fix: dsh plugin lane stamps pck on a loopback destination even without a configured route", async () => { - // routes-less harness pins the loopback leg of the gate (the GF-machine - // deployment shape: provider rewrite to a local relay port). + // The /bili/-embedded-URL form always resolves a route (rewrittenUrl set), + // so this case pins the gate's route-rewrite leg with an EMPTY admin + // provider table; the bare loopback leg (route undefined + loopback + // origin) is pinned by the unit matrix above. const h = await startHarness(undefined); try { const base = `http://127.0.0.1:${h.proxyPort}/bili/http://127.0.0.1:${h.upstreamPort}/v1/chat/completions`;