Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(pi): PI 子代理(只读画像),与 Claude / Codex 共用同一张子代理卡 (#1458)
Chris Zhang64c81a5b9fb8
diff --git a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsxindex a037c826c5..14167f4985 100644--- a/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx@@ -29,7 +29,7 @@ import { useSidebarPanelReachable } from '@/features/cc-agent/embeddedSessionNavimport { cn } from '@/lib/utils';import { formatModelShortLabel } from '@/lib/modelShortLabel';import { CODEX_SUBAGENT_EFFORTS } from '../../../shared/subagentModelSettings';-import { subagentSpawnReceiptName } from '@cindy/maker-shared/agent-task';+import { PI_SUBAGENT_TOOL_NAME, subagentSpawnReceiptName } from '@cindy/maker-shared/agent-task';// 徽标可显示的思考强度档:协议全部合法档(效果词表 effortLevels 四语齐)。const EFFORT_BADGE_LEVELS = new Set<string>(['minimal', ...CODEX_SUBAGENT_EFFORTS]);@@ -217,14 +217,23 @@ export function AgentTaskCard({ toolCall, update, result, subagentModel, session: t('chat.agentTask.subagentStarted', { name: spawnReceiptName })): detailText(result, update?.summary);const duration = formatDuration(update?.usage?.durationMs);- const provider = update?.provider ?? (toolCall?.toolName?.startsWith('collab:') ? 'codex' : 'claude-code');+ // provider 推断与 maker-shared 的 buildAgentTaskCardModel 同口径(裸 `subagent` 是 pi+ // 扩展注册的工具名);历史回放没有 live update 时也不会把 pi 卡标成 Claude。+ const provider = update?.provider+ ?? (toolCall?.toolName?.startsWith('collab:')+ ? 'codex'+ : toolCall?.toolName === PI_SUBAGENT_TOOL_NAME+ ? 'pi'+ : 'claude-code');const providerLabel = isWorkflow? t('chat.agentTask.provider.workflow'): isBash? t('chat.agentTask.provider.shell'): provider === 'codex'? t('chat.agentTask.provider.codex')- : t('chat.agentTask.provider.claude');+ : provider === 'pi'+ ? t('chat.agentTask.provider.pi')+ : t('chat.agentTask.provider.claude');// 停止按钮:running + 本会话可定位 + claude-code(codex 无 stopTask 通道)。// 点击后交给 main 的 stopAgentTask;成功与否都由 task_notification 事件流收口diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 32735cd461..5ce12ede54 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -35,6 +35,9 @@ import {isAgentPlanToolName,isDeliveryProseText,} from '@cindy/maker-shared/message-render';+// 子代理卡判据只能有一份:此前桌面自带一份只认 Agent/Task/collab:* 的副本,新增 harness+// (PI 的 subagent)加进共享判据也到不了 AgentTaskCard,会静默落进普通工具组(codex review)。+import { isAgentTaskToolName } from '@cindy/maker-shared/agent-task';import type {AgentTaskUpdate,@@ -829,11 +832,6 @@ export function collectSessionImageSrcs(return out;}-// export 仅供单测(`buildRenderItemsKeyStability.test.ts`)使用,运行时无外部消费者。-function isAgentTaskToolName(toolName: string): boolean {- return toolName === 'Agent' || toolName === 'Task' || toolName.startsWith('collab:');-}-// Workflow 工具(Claude Code SDK 多 agent 编排)在父会话事件流里 = 单个 local_workflow// 任务(内部子 agent 不发独立 task 事件,只有 workflow 级聚合进度)。与 Agent/Task 一样// 走 agent_task 渲染项;AgentTaskCard 内部按 taskType/toolName 识别为 workflow,展示diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 9d58337c89..3a5559ada1 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5476,6 +5476,7 @@"provider": {"claude": "Claude Code","codex": "Codex",+ "pi": "Pi","workflow": "Workflow","shell": "Background command"},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex abfdc00808..689b77c897 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5474,6 +5474,7 @@"provider": {"claude": "Claude Code","codex": "Codex",+ "pi": "Pi","workflow": "Workflow","shell": "バックグラウンドコマンド"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 0fe7cce035..1bc1d9f718 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5474,6 +5474,7 @@"provider": {"claude": "Claude Code","codex": "Codex",+ "pi": "Pi","workflow": "Workflow","shell": "백그라운드 명령"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 65802912c1..da598007d3 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5474,6 +5474,7 @@"provider": {"claude": "Claude Code","codex": "Codex",+ "pi": "Pi","workflow": "Workflow","shell": "后台命令"},diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentParentWatchdog.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentParentWatchdog.test.tsnew file mode 100644index 0000000000..09fe0659f7--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentParentWatchdog.test.ts@@ -0,0 +1,146 @@+import { spawn, type ChildProcess } from 'node:child_process';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import {+ CINDY_SUBAGENT_PARENT_PID_ENV,+ CINDY_SUBAGENT_PARENT_WATCHDOG_INTERVAL_MS,+ CINDY_SUBAGENT_PARENT_WATCHDOG_SOURCE,+} from '../cindy-subagent-source.js';++/**+ * 父死子亡的**执行级**回归测试。+ *+ * 子代理进程是 Cindy 的孙进程:`PiRpcProcess.close()` 的 SIGTERM/SIGKILL 只打到 pi 父进程,+ * 孙进程会被 init 收养后继续请求模型烧额度(review)。守这条不能只做字符串断言 —— 那类断言+ * 在"看门狗写了但根本不工作"时照样通过。这里把注入的看门狗源码**原样**丢进真进程里跑,+ * 用一个真的假父进程验证两个方向:+ * - 父进程活着时不能自杀(否则子代理会在正常工作中途消失);+ * - 父进程被 SIGKILL(最狠的死法,任何父侧钩子都跑不到)后必须自己退出。+ */++const spawned: ChildProcess[] = [];+const tempDirs: string[] = [];++function track<T extends ChildProcess>(child: T): T {+ spawned.push(child);+ return child;+}++afterEach(async () => {+ for (const child of spawned.splice(0)) {+ try {+ child.kill('SIGKILL');+ } catch {+ /* already gone */+ }+ }+ for (const dir of tempDirs.splice(0)) {+ await rm(dir, { recursive: true, force: true });+ }+});++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++/** 已退出返回退出信息,仍在跑返回 null。 */+function exitInfo(child: ChildProcess): { code: number | null } | null {+ return child.exitCode === null && child.signalCode === null ? null : { code: child.exitCode };+}++function waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {+ if (exitInfo(child)) return Promise.resolve(true);+ return new Promise((resolve) => {+ const timer = setTimeout(() => resolve(false), timeoutMs);+ child.once('exit', () => {+ clearTimeout(timer);+ resolve(true);+ });+ });+}++function waitForStdout(child: ChildProcess, needle: string, timeoutMs: number): Promise<boolean> {+ return new Promise((resolve) => {+ let seen = '';+ const timer = setTimeout(() => resolve(false), timeoutMs);+ child.stdout?.setEncoding('utf8');+ child.stdout?.on('data', (chunk: string) => {+ seen += chunk;+ if (seen.includes(needle)) {+ clearTimeout(timer);+ resolve(true);+ }+ });+ });+}++/**+ * 写一个只跑看门狗的脚本:装上看门狗,再用一个 ref 住事件循环的长定时器模拟"子代理正在+ * 干活"。这样进程唯一的退出途径就是看门狗本身 —— 它没生效的话进程会一直挂着,测试会失败。+ */+async function writeWatchdogHarness(): Promise<string> {+ const dir = await mkdtemp(path.join(tmpdir(), 'cindy-subagent-watchdog-'));+ tempDirs.push(dir);+ const file = path.join(dir, 'watchdog.mjs');+ await writeFile(+ file,+ `${CINDY_SUBAGENT_PARENT_WATCHDOG_SOURCE}+installParentWatchdog();+const busy = setTimeout(function () {}, 120000);+process.stdout.write('ready\\n');+`,+ 'utf8',+ );+ return file;+}++/** 一个什么都不干、只是活着的假父进程。 */+function spawnFakeParent(): ChildProcess {+ return track(+ spawn(process.execPath, ['-e', 'setTimeout(function () {}, 120000)'], { stdio: 'ignore' }),+ );+}++describe('cindy-subagent parent watchdog (executed)', () => {+ it('父进程被强杀后子代理自己退出,不留孤儿烧额度', async () => {+ const file = await writeWatchdogHarness();+ const parent = spawnFakeParent();+ expect(parent.pid).toBeGreaterThan(0);++ const child = track(+ spawn(process.execPath, [file], {+ env: { ...process.env, [CINDY_SUBAGENT_PARENT_PID_ENV]: String(parent.pid) },+ stdio: ['ignore', 'pipe', 'pipe'],+ }),+ );+ expect(await waitForStdout(child, 'ready', 10_000)).toBe(true);++ // 方向一:父进程活着期间不能自杀。等足一个轮询周期以上,确认看门狗没有误杀。+ await sleep(CINDY_SUBAGENT_PARENT_WATCHDOG_INTERVAL_MS * 1.5);+ expect(exitInfo(child)).toBeNull();++ // 方向二:SIGKILL 父进程 —— 父侧任何 exit / 信号处理器都跑不到,只剩看门狗能救。+ parent.kill('SIGKILL');+ await waitForExit(parent, 5_000);++ expect(await waitForExit(child, 15_000)).toBe(true);+ expect(child.exitCode).toBe(0);+ }, 40_000);++ it('没拿到父 pid 时不装看门狗(不影响独立运行的 pi)', async () => {+ const file = await writeWatchdogHarness();+ const env = { ...process.env };+ delete env[CINDY_SUBAGENT_PARENT_PID_ENV];++ const child = track(spawn(process.execPath, [file], { env, stdio: ['ignore', 'pipe', 'pipe'] }));+ expect(await waitForStdout(child, 'ready', 10_000)).toBe(true);++ // 缺 pid 时看门狗直接 return:进程只受那个 120s 长定时器约束,不该被提前干掉。+ await sleep(CINDY_SUBAGENT_PARENT_WATCHDOG_INTERVAL_MS * 1.5);+ expect(exitInfo(child)).toBeNull();+ }, 30_000);+});diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.tsnew file mode 100644index 0000000000..8b16835b55--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts@@ -0,0 +1,292 @@+import { describe, expect, it } from 'vitest';++import { PI_SUBAGENT_TOOL_NAME } from '@cindy/maker-shared/agent-task';++import {+ CINDY_SUBAGENT_ENV,+ CINDY_SUBAGENT_EXTENSION_FILENAME,+ CINDY_SUBAGENT_EXTENSION_SOURCE,+ CINDY_SUBAGENT_PARENT_PID_ENV,+ CINDY_SUBAGENT_TOOL_NAME,+} from '../cindy-subagent-source.js';+import { PI_SUBAGENT_PROGRESS_MARKER } from '../subagent-progress.js';++/**+ * 注入源码是字符串常量,typecheck 与 vitest 都进不去,只能靠结构性断言守。这里守的是+ * 「改一处忘另一处就静默失效」的那几条,不是复读实现细节。+ */+describe('cindy-subagent extension source', () => {+ it('registers the tool name the card predicate recognises', () => {+ // 工具名与 maker-shared 的判据脱同步 = 子代理卡完全不渲染(且不报错)。+ expect(CINDY_SUBAGENT_TOOL_NAME).toBe(PI_SUBAGENT_TOOL_NAME);+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("const TOOL_NAME = '" + PI_SUBAGENT_TOOL_NAME + "'");+ });++ it('uses the same progress marker the host parser checks', () => {+ // 标记不一致 = 进度帧被 parse 当成别的工具的流式结果丢掉。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("const MARKER = '" + PI_SUBAGENT_PROGRESS_MARKER + "'");+ });++ it('reads the exact env names the host injects', () => {+ for (const name of Object.values(CINDY_SUBAGENT_ENV)) {+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("'" + name + "'");+ }+ });++ it('contains no template literals (String.raw would interpolate them at build time)', () => {+ // 模板里出现 ${...} 会被外层 String.raw 当插值吃掉,注入的源码将缺字段且不易发现。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain('`');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain('${');+ });++ it('keeps the read-only tool allowlist for every agent profile', () => {+ // 白名单一旦放进 bash/edit/write:ask 档下子进程无确认 UI → bridge fail-closed 全拒,+ // 功能表现为「子代理什么都干不了」;放进去还等于绕过审批面扩权。+ const allowlists = [...CINDY_SUBAGENT_EXTENSION_SOURCE.matchAll(/tools: '([^']+)'/g)].map((m) => m[1]);+ expect(allowlists.length).toBeGreaterThanOrEqual(3);+ for (const list of allowlists) {+ expect(list.split(',').sort()).toEqual(['find', 'grep', 'ls', 'read']);+ }+ });++ it('keeps the guards that stop a subagent from becoming a fork bomb or a wedged turn', () => {+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('const MAX_DEPTH = 1');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('if (readDepth() >= MAX_DEPTH) return;');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('const MAX_TASKS = 8');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('const MAX_CONCURRENCY = 4');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toMatch(/TASK_TIMEOUT_MS\s*=/);+ // 子代理不写会话文件,不污染 Cindy 的会话 JSONL。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("'--no-session'");+ // 必须**不**传 --no-extensions:否则子进程不加载 cindy-bridge,权限门对子代理失效。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain('--no-extensions');+ });++ it('reads model and provider from the runtime snapshot file, not from spawn-time env', () => {+ // env 在 spawn 时定型:会话中途 setModel 后子代理会继续用旧模型;provider 不一起传还会+ // 让网关与 BYOM 的同名模型落到默认 endpoint(pi-harness §3 要求 BYOM 直连原生 provider)。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('function readRuntimeSnapshot()');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("const runtime = readRuntimeSnapshot();");+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("args.push('--provider', runtime.provider)");+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("args.push('--model', runtime.model)");+ // 不得再从 env 直接取模型(那就是被 review 指出的 stale 源)。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain('CINDY_PI_SUBAGENT_MODEL');+ });++ it('reports failed when any parallel task failed, not only when all did', () => {+ // 部分失败被报成 completed 会让界面把整批任务显示为成功(greptile P1)。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(+ "report(aborted ? 'stopped' : failed > 0 ? 'failed' : 'completed'",+ );+ });++ it('does not register the tool when the host did not provide a pi binary path', () => {+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(+ "if (typeof binary !== 'string' || binary.trim().length === 0) return;",+ );+ });++ it('fails closed when the routing snapshot is unavailable', () => {+ // host 写快照失败时会不传 runtime 文件 env 并删除该文件。扩展必须两处都失败关闭:+ // 注册期不暴露工具、使用期拒绝派发 —— 退回 pi 默认解析会把 BYOM / 本地 provider 的+ // 请求发到错误 endpoint,比「本次没有子代理」糟糕得多(review)。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(+ "if (typeof runtimeFile !== 'string' || runtimeFile.trim().length === 0) return;",+ );+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('if (!runtime.provider) {');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('subagent is unavailable');+ });++ it('refuses to dispatch while the routing snapshot is pending, before anything spawns', () => {+ // host 在 set_model 的等待窗口里写的是带 `pending: true` 的新路由。放行这段窗口 = 子进程用+ // 一个尚未确认的 provider 起来,而 RPC 若被拒,host 能回滚文件却撤不回已经在跑的子进程+ // (review P1)。真实拒绝由集成用例(真 pi 进程 + 原生端点零请求)验证;这里钉的是+ // **顺序** —— 判断必须在任何 spawn 之前,否则"有这段代码"照样成立而进程已经起来了。+ const src = CINDY_SUBAGENT_EXTENSION_SOURCE;+ expect(src).toContain('pending: parsed.pending === true');+ expect(src).toContain('if (runtime.pending) {');+ expect(src).toContain('is not confirmed yet');+ const guard = src.indexOf('if (runtime.pending) {');+ const execute = src.indexOf('async execute(toolCallId');+ const spawn = src.indexOf('child = spawn(binary, args');+ expect(guard).toBeGreaterThan(execute);+ // runTask 里的 spawn 在源码里位于 execute 之前(函数声明顺序),所以不能只比字符位置 ——+ // 关键是这道闸在 execute 的**早返回段**里,即在 tasks 循环启动之前。+ expect(spawn).toBeLessThan(execute);+ const dispatch = src.indexOf('runTask(', guard);+ expect(dispatch).toBeGreaterThan(guard);+ });++ it('reports a terminal failed update before either pre-dispatch guard throws', () => {+ // 卡片模型在**没有任何** agent_task_update 时按"有工具结果 = completed"兜底,所以派发前直接+ // throw 会让这次被拒绝的委派在界面上立刻变绿(review)。两道闸都必须先发一帧终态 failed。+ // 真实效果由集成用例断言(事件流里出现 failed、不出现 completed);这里钉的是**顺序**:+ // report 的定义要排在两道闸之前,否则闸里根本调不到它(TDZ,而且改回去测试还得能红)。+ const src = CINDY_SUBAGENT_EXTENSION_SOURCE;+ const reportDefined = src.indexOf('const report = function (status: string');+ const snapshotGuard = src.indexOf('if (!runtime.provider) {');+ const pendingGuard = src.indexOf('if (runtime.pending) {');+ expect(reportDefined).toBeGreaterThan(-1);+ expect(snapshotGuard).toBeGreaterThan(reportDefined);+ expect(pendingGuard).toBeGreaterThan(reportDefined);+ // 每道闸内部:先 report('failed', …) 再 throw。+ for (const guard of [snapshotGuard, pendingGuard]) {+ const body = src.slice(guard, src.indexOf('}', src.indexOf('throw new Error(', guard)));+ const reported = body.indexOf("report('failed'");+ const thrown = body.indexOf('throw new Error(');+ expect(reported).toBeGreaterThan(-1);+ expect(reported).toBeLessThan(thrown);+ }+ // 而运行中那帧必须还在两道闸之后 —— 被拒时不该先闪一帧 running。+ // 带分号才是**语句**;不带的那个匹配会落在上面解释顺序的注释里(我先踩了一次)。+ expect(src.indexOf("report('running');")).toBeGreaterThan(pendingGuard);+ });++ it('defers settling to process close so grace-period usage is still counted', () => {+ // kill() 到 SIGKILL 之间约 2 秒宽限里子进程仍会吐 message_end,那是真实产生的 token/cost。+ // 原来 abort/timeout 立刻 finish + 在 JSON.parse 之前整条短路,这段用量直接丢掉(review)。+ // 单纯"解析但不上报"也救不回来:promise 已 resolve,调用方紧接着读走快照,之后改 totals+ // 没人再看。所以收口必须推迟到进程真的 'close'。+ const src = CINDY_SUBAGENT_EXTENSION_SOURCE;+ // abort 与 timeout 都只置原因 + 杀 + 兜底,不再直接 finish。+ expect(src).toContain("terminationReason = 'aborted';");+ expect(src).toContain("terminationReason = 'timeout';");+ expect(src).toContain('armSettleFallback(');+ // 真正的收口在 close 分支里,按 terminationReason 决定文案。+ const closeAt = src.indexOf("child.on('close'");+ expect(src.indexOf('if (terminationReason !== null) {', closeAt)).toBeGreaterThan(closeAt);+ // 'close' 万一不来,兜底定时器仍要收口,不能把父 turn 永久挂住。+ expect(src).toMatch(/settleFallbackTimer = setTimeout\(/);+ // 守卫仍在(只挡上报),但它现在只对"兜底已强行收口"生效。+ const feedGuard = src.indexOf('const feed = createLineReader');+ expect(src.indexOf('if (settled) return;', feedGuard)).toBeGreaterThan(feedGuard);+ });++ it('ships as its own extension file rather than being folded into cindy-bridge', () => {+ expect(CINDY_SUBAGENT_EXTENSION_FILENAME).toBe('cindy-subagent.ts');+ });++ it('strips the MCP bridge from the child env so subagents do not open MCP transports', () => {+ // 子进程继承 PI_CODING_AGENT_DIR → 会加载 cindy-bridge(权限门要靠这个)。bridge 一见到+ // CINDY_PI_MCP_BRIDGE 就逐个 connect 所有 MCP server 并持有有状态 transport,而子代理的+ // --tools 白名单里根本没有 MCP 工具 —— 纯浪费:每个子代理一整套连接、并发 4 单批最多 8,+ // 且子代理不显式 close。实测:一个 depth=1 的 pi 进程对 fake MCP server 发了 3 次请求,+ // 剥掉该 env 后为 0,而 bridge 的 bash 覆盖与权限门注册在 MCP 段**之前**,不受影响。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("const MCP_BRIDGE_ENV = 'CINDY_PI_MCP_BRIDGE'");+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('delete childEnv[MCP_BRIDGE_ENV];');+ // 权限门与网关路由必须**保留**:这两个被剥掉才是真事故(子代理越权 / 打错 endpoint)。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain('delete childEnv[RUNTIME_FILE_ENV]');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain("delete childEnv['CINDY_PI_PERMISSION_FILE']");+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain("delete childEnv['PI_CODING_AGENT_DIR']");+ });++ it('enforces a call-level output budget, not just a per-task one', () => {+ // 只限单项没用:8 个任务各 16k 拼起来 ~128k 字符注进父请求,一次委派就吃掉大半父上下文+ // (review)。成功与全失败两条返回路径都必须过总闸 —— text 在 throw 之前就已经收窄。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('const MAX_TOTAL_OUTPUT_CHARS = 32000;');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('function fitSectionsToBudget(sections)');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('fitSectionsToBudget(sections).join');+ // 全失败路径 throw 的是同一个已收窄的 text,不是未裁剪的原文。+ const budgeted = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf('const text = fitSectionsToBudget(sections).join');+ const thrown = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf('throw new Error(text);');+ expect(budgeted).toBeGreaterThan(-1);+ expect(thrown).toBeGreaterThan(budgeted);+ });++ it('reports delegated usage components (with cost) for the parent turn accounting', () => {+ // 只报一个 totalTokens 的话父侧无从拆分 input/output/cache/cost,turn 记账与+ // register.ts 的持久化都拿不到委派花费(review)。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('function emptyUsage()');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('totals.cost += cost');+ for (const field of ['input', 'output', 'cacheRead', 'cacheWrite', 'cost']) {+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(field + ': totals.usage.' + field + ',');+ }+ });++ it('does not SIGKILL a pid it no longer owns', () => {+ // SIGTERM 后的 2 秒宽限里子进程通常已经退了。原来那发 SIGKILL 既没存定时器(进程退出后+ // 仍多挂 2 秒)也不复查存活 —— 一旦 pid 被系统回收复用,这一发就打到无关进程上(review)。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('let killTimer = null;');+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('killTimer = setTimeout(');+ // 强杀前必须先确认子进程还没退。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(+ "if (child.exitCode !== null || child.signalCode !== null) return;",+ );+ // 存活复查必须在 SIGKILL **之前**。+ const guard = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf('if (child.exitCode !== null');+ const sigkill = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf("child.kill('SIGKILL')", guard);+ expect(guard).toBeGreaterThan(-1);+ expect(sigkill).toBeGreaterThan(guard);+ // close / error 两条退出路径都要清定时器。+ // 锚点必须是**真** error handler(带 err 形参);中止分支那个吞错 stub 是无形参的,+ // 用它当锚点会让断言落在错误的位置(我加中止分支时就先踩了一次)。+ for (const handler of ["child.on('close'", "child.on('error', function (err)"]) {+ const at = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf(handler);+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE.slice(at, at + 320)).toContain('clearTimeout(killTimer)');+ }+ });+++ it('never spawns a child once the batch is aborted', () => {+ // 批次取消时 worker 车道里可能还排着任务。原来它们照样先 spawn、再走 aborted 早返回,而那个+ // return 在注册 stdout/error/close **之前**:子进程永留 liveChildren,且 spawn 失败会变成+ // 无人监听的 'error' 事件 —— Node 里直接抛出,能把父 pi 进程带走(review)。+ const source = CINDY_SUBAGENT_EXTENSION_SOURCE;+ const runTaskAt = source.indexOf('function runTask(');+ const preCheck = source.indexOf('if (signal && signal.aborted === true) {', runTaskAt);+ const spawnAt = source.indexOf('child = spawn(binary, args', runTaskAt);+ expect(preCheck).toBeGreaterThan(runTaskAt);+ // 检查必须在 spawn **之前**。+ expect(preCheck).toBeLessThan(spawnAt);+ // 残余竞态(检查后、spawn 完成前才 abort)那条早返回要自己摘 liveChildren + 吞 error。+ const innerAbort = source.indexOf('if (signal.aborted) {', spawnAt);+ const innerBody = source.slice(innerAbort, innerAbort + 520);+ expect(innerBody).toContain('liveChildren.delete(child)');+ expect(innerBody).toContain("child.on('error'");+ });++ it('declares the watchdog constants exactly once in the composed module', () => {+ // 主体与看门狗段是拼起来的:同名 const 声明两次 → 拼接后的模块直接 SyntaxError,+ // 整个扩展加载失败(连 cindy-bridge 之外的既有能力都不受影响,纯粹是子代理全哑)。+ const declarations = [...CINDY_SUBAGENT_EXTENSION_SOURCE.matchAll(/const PARENT_PID_ENV\b/g)];+ expect(declarations).toHaveLength(1);+ const intervals = [...CINDY_SUBAGENT_EXTENSION_SOURCE.matchAll(/const PARENT_WATCHDOG_INTERVAL_MS\b/g)];+ expect(intervals).toHaveLength(1);+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("const PARENT_PID_ENV = '" + CINDY_SUBAGENT_PARENT_PID_ENV + "'");+ });++ it('installs the parent watchdog before the depth early-return', () => {+ // 子代理走的正是深度早返回那条分支。装在 return 之后 = 看门狗永远不生效,+ // 而字符串里"有这段代码"照样成立 —— 所以顺序必须钉住。+ const install = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf('if (readDepth() > 0) installParentWatchdog();');+ const earlyReturn = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf('if (readDepth() >= MAX_DEPTH) return;');+ expect(install).toBeGreaterThan(-1);+ expect(earlyReturn).toBeGreaterThan(install);+ });++ it('tracks live children and reaps them when the parent exits normally', () => {+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('liveChildren.add(child)');+ // 摘除必须挂在进程真正结束的 'close' / 'error' 上,**不能**挂在 finish() 里:超时与中止+ // 都是先 finish 再进 SIGKILL 宽限期,进程那时还活着,这段窗口内父进程退出仍要杀它。+ const finishStart = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf('const finish = function');+ const finishEnd = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf('const kill = function', finishStart);+ expect(finishStart).toBeGreaterThan(-1);+ expect(finishEnd).toBeGreaterThan(finishStart);+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE.slice(finishStart, finishEnd)).not.toContain('liveChildren.delete');+ // 锚点必须是**真** error handler(带 err 形参);中止分支那个吞错 stub 是无形参的,+ // 用它当锚点会让断言落在错误的位置(我加中止分支时就先踩了一次)。+ for (const handler of ["child.on('close'", "child.on('error', function (err)"]) {+ const at = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf(handler);+ expect(at).toBeGreaterThan(-1);+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE.slice(at, at + 240)).toContain('liveChildren.delete(child)');+ }+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("process.on('exit', reapLiveChildren)");+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("childEnv[PARENT_PID_ENV] = String(process.pid)");+ });++ it('registers no signal handlers (that would suppress pi\'s default terminate)', () => {+ // Node/Bun 里加一个 SIGTERM 监听就抑制了该信号的默认终止行为:pi 自身若没有别的处理器,+ // 收到 Cindy 的 SIGTERM 后不会退出,每次关会话都要等满 3s 宽限再被 SIGKILL。+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain("process.on('SIGTERM'");+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain("process.on('SIGINT'");+ });+});diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.tsindex 42f1bd9822..c13bb8062d 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts@@ -1477,4 +1477,322 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa}},);+ it(+ 'subagent tool spawns a real child pi, streams live card usage, and returns only its conclusion',+ { timeout: 120_000 },+ async () => {+ // 端到端:父会话调 subagent → Cindy 自有扩展 spawn 真 pi 子进程 → 子进程走同一+ // fake gateway → 结论回父模型;进度经工具原生 onUpdate 翻成 agent_task_update。+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-subagent-'));+ try {+ scriptedResponses.length = 0;+ scriptedResponses.push(+ anthropicToolUseBody('subagent', { agent: 'scout', task: 'find the auth entry point' }),+ // 子进程这一轮:子代理的结论。+ anthropicStreamBody('auth starts at src/auth/index.ts:42'),+ anthropicStreamBody('parent turn finished'),+ );++ const agent = new PiAgent(buildDeps());+ const resolverTools: string[] = [];+ let handle: AgentSessionHandle | null = null;+ const events: AgentEvent[] = [];+ try {+ handle = await agent.startSession({+ sessionId: 'pi-subagent-e2e',+ workingDir,+ model: 'pi-test-model',+ permissionMode: 'ask',+ });+ handle.setInteractionResolver?.(async (req) => {+ resolverTools.push((req as { toolName?: string }).toolName ?? '?');+ return {+ kind: 'permission',+ requestId: (req as { requestId: string }).requestId,+ behavior: 'allow',+ } as never;+ });+ const done = (async () => {+ for await (const ev of handle!.events()) {+ events.push(ev);+ if (ev.type === 'done') break;+ }+ })();+ await handle.send({ type: 'user', content: 'go' });+ await done;+ } finally {+ await handle?.close();+ }++ // 派子代理本身要过审批门(它不是只读内置工具)—— 这是有意的安全属性。+ expect(resolverTools).toContain('subagent');++ // 卡片走的是与 Claude / Codex 同一条 agent_task_update 通道。+ const cardUpdates = events+ .filter((ev) => ev.type === 'agent_task_update')+ .map((ev) => (ev as { data: Record<string, unknown> }).data);+ expect(cardUpdates.length).toBeGreaterThan(0);+ expect(cardUpdates.every((u) => u.provider === 'pi')).toBe(true);+ expect(cardUpdates.at(0)?.status).toBe('running');+ expect(cardUpdates.at(-1)?.status).toBe('completed');+ expect(cardUpdates.at(-1)?.title).toBe('scout');+ const finalUsage = cardUpdates.at(-1)?.usage as Record<string, number> | undefined;+ // 真实用量来自子进程的 message_end.usage(fake gateway 上报 42 input tokens)。+ expect(finalUsage?.totalTokens).toBeGreaterThan(0);+ expect(typeof finalUsage?.durationMs).toBe('number');++ // 子代理的结论确实回到了父模型(tool_result 出现在后续请求体里)。+ expect(seenRequests.some((r) => r.body.includes('auth starts at src/auth/index.ts:42'))).toBe(true);+ } finally {+ rmSync(workingDir, { recursive: true, force: true });+ scriptedResponses.length = 0;+ }+ },+ );++ it(+ 'subagent write boundary is enforced, not cosmetic: child cannot shell out even under Full Access',+ { timeout: 120_000 },+ async () => {+ // 安全回归:父会话给 Full Access(bypassPermissions)时,bridge 会在子进程里重新注册+ // bash —— 但 `--tools read,grep,find,ls` 是 pi 的**注册面**白名单(文档:allowlist+ // built-in, extension, and custom tools),对扩展注册的工具同样生效。这里同时验证+ // 「没被告知」与「调了也不执行」两层,防止把只读画像做成表面白名单。+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-subagent-boundary-'));+ const marker = path.join(workingDir, 'pwned.txt');+ try {+ scriptedResponses.length = 0;+ scriptedResponses.push(+ anthropicToolUseBody('subagent', { agent: 'scout', task: 'probe the write boundary' }),+ // 子代理这一轮:硬调 bash 往工作区写文件(白名单外的工具)。+ anthropicToolUseBody('bash', { command: `echo pwned > ${JSON.stringify(marker)}` }),+ anthropicStreamBody('child could not run bash'),+ anthropicStreamBody('parent turn finished'),+ );++ const agent = new PiAgent(buildDeps());+ let handle: AgentSessionHandle | null = null;+ try {+ handle = await agent.startSession({+ sessionId: 'pi-subagent-boundary',+ workingDir,+ model: 'pi-test-model',+ // 最宽档:子代理的写边界不能靠父会话的权限档兜。+ permissionMode: 'bypassPermissions',+ });+ const done = (async () => {+ for await (const ev of handle!.events()) {+ if (ev.type === 'done') break;+ }+ })();+ await handle.send({ type: 'user', content: 'go' });+ await done;+ } finally {+ await handle?.close();+ }++ // 第一层:子进程被告知的工具面里没有 bash,也没有桥接的 MCP 工具。+ const childRequest = seenRequests.find((r) => r.body.includes('scout subagent'));+ expect(childRequest).toBeDefined();+ const advertised = new Set(+ [...(childRequest?.body ?? '').matchAll(/"name":"([a-zA-Z0-9_]+)"/g)].map((m) => m[1]),+ );+ expect([...advertised].sort()).toEqual(['find', 'grep', 'ls', 'read']);+ expect(advertised.has('bash')).toBe(false);++ // 第二层(真正的边界):即便模型硬调 bash,工作区也不得被改动。+ expect(existsSync(marker)).toBe(false);+ } finally {+ rmSync(workingDir, { recursive: true, force: true });+ scriptedResponses.length = 0;+ }+ },+ );+ it(+ 'BYOM: a subagent dispatched right after startSession still routes to the native endpoint',+ { timeout: 120_000 },+ async () => {+ // review 回归:子代理的 provider/model 来自运行期快照文件。若该快照不是在会话对外暴露+ // **之前**写好,BYOM / 本地 provider 会话一开始就派子代理时文件还不存在 → 扩展不传+ // --provider/--model → 子进程退回 pi 默认解析,直接打到网关而不是用户选的原生端点。+ const nativeBodies: string[] = [];+ // 原生端点自带脚本队列:第 1 个请求(父)派子代理,第 2 个(子)出结论,其余兜底。+ const nativeScript = [+ anthropicToolUseBody('subagent', { agent: 'scout', task: 'probe byom routing' }),+ anthropicStreamBody('native child conclusion'),+ ];+ const nativeServer = createServer((req, res) => {+ let body = '';+ req.on('data', (chunk) => { body += String(chunk); });+ req.on('end', () => {+ nativeBodies.push(body);+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });+ res.end(nativeScript.shift() ?? anthropicStreamBody('native done'));+ });+ });+ await new Promise<void>((r) => nativeServer.listen(0, '127.0.0.1', r));+ const nativeAddr = nativeServer.address();+ const nativeUrl = typeof nativeAddr === 'object' && nativeAddr ? `http://127.0.0.1:${nativeAddr.port}` : '';++ const deps = buildDeps();+ deps.auth.getState = async (options) => (options?.providerId === 'localbyom'+ ? { authenticated: true, identity: 'Local BYOM', authSource: 'api-key' as const }+ : { authenticated: false });+ deps.auth.getAuthEnv = async () => ({ CINDY_PI_API_KEY: 'gateway-unavailable-placeholder' });+ deps.resolvePiNativeProviders = async () => ({+ providers: [+ {+ id: 'localbyom',+ name: 'Local BYOM',+ baseUrl: nativeUrl,+ api: 'anthropic-messages',+ apiKeyEnvVar: 'CINDY_PI_KEY_LOCALBYOM',+ models: [{ id: 'byom-model', name: 'BYOM Model' }],+ },+ ],+ env: { CINDY_PI_KEY_LOCALBYOM: 'byom-secret-key' },+ });++ const agent = new PiAgent(deps);+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-byom-subagent-'));+ let handle: AgentSessionHandle | null = null;+ try {+ const gatewayBefore = seenRequests.length;+ handle = await agent.startSession({+ sessionId: 'byom-subagent-session',+ workingDir,+ model: 'byom-model',+ // 派子代理本身要过审批门(ask 档无 resolver 即拒);本例只验路由,给最宽档。+ permissionMode: 'bypassPermissions',+ });+ const done = (async () => {+ for await (const ev of handle!.events()) {+ if (ev.type === 'done') break;+ }+ })();+ await handle.send({ type: 'user', content: 'delegate now' });+ await done;++ // eslint-disable-next-line no-console+ // 父 + 子两轮都打在原生端点上。+ expect(nativeBodies.length).toBeGreaterThanOrEqual(2);+ // 子进程确实是原生端点接的(子代理画像 prompt 只出现在子进程的请求里)。+ expect(nativeBodies.some((b) => b.includes('scout subagent'))).toBe(true);+ // 网关一个请求都没有 —— 子代理没有退回默认 provider。+ expect(seenRequests.length).toBe(gatewayBefore);+ } finally {+ await handle?.close();+ await new Promise<void>((r) => nativeServer.close(() => r()));+ rmSync(workingDir, { recursive: true, force: true });+ }+ },+ );++ it(+ 'refuses to dispatch while a model switch is unconfirmed (no child spawns in the pending window)',+ { timeout: 120_000 },+ async () => {+ // review P1:host 原来在 set_model 回包**之前**就把新路由写进快照,于是等待窗口里模型+ // 发起的派发会按一个尚未确认的 provider 起子进程;RPC 随后返回失败时,回滚文件撤不回+ // 已经在跑的子进程。修法是这段窗口里的快照带 `pending: true`,扩展见到就拒绝派发。+ //+ // 这条用例验的是那个拒绝**真的挡住了进程**:结构性断言只能证明源码里有这段判断,证明+ // 不了子进程没起来。判据用"子代理画像 prompt 只出现在子进程自己的请求里"——一个字节都+ // 没出现 = 一个子进程都没起来。+ const { readdirSync, readFileSync } = await import('node:fs');+ const nativeBodies: string[] = [];+ // 第 1 个请求(父)派子代理;若真起了子进程,它的请求会是第 2 个。+ const nativeScript = [+ anthropicToolUseBody('subagent', { agent: 'scout', task: 'must not run during a pending switch' }),+ anthropicStreamBody('parent handled it without delegating'),+ ];+ const nativeServer = createServer((req, res) => {+ let body = '';+ req.on('data', (chunk) => { body += String(chunk); });+ req.on('end', () => {+ nativeBodies.push(body);+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });+ res.end(nativeScript.shift() ?? anthropicStreamBody('native done'));+ });+ });+ await new Promise<void>((r) => nativeServer.listen(0, '127.0.0.1', r));+ const nativeAddr = nativeServer.address();+ const nativeUrl = typeof nativeAddr === 'object' && nativeAddr ? `http://127.0.0.1:${nativeAddr.port}` : '';++ const deps = buildDeps();+ deps.auth.getState = async (options) => (options?.providerId === 'localbyom'+ ? { authenticated: true, identity: 'Local BYOM', authSource: 'api-key' as const }+ : { authenticated: false });+ deps.auth.getAuthEnv = async () => ({ CINDY_PI_API_KEY: 'gateway-unavailable-placeholder' });+ deps.resolvePiNativeProviders = async () => ({+ providers: [+ {+ id: 'localbyom',+ name: 'Local BYOM',+ baseUrl: nativeUrl,+ api: 'anthropic-messages',+ apiKeyEnvVar: 'CINDY_PI_KEY_LOCALBYOM',+ models: [{ id: 'byom-model', name: 'BYOM Model' }],+ },+ ],+ env: { CINDY_PI_KEY_LOCALBYOM: 'byom-secret-key' },+ });++ const agent = new PiAgent(deps);+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-pending-switch-'));+ let handle: AgentSessionHandle | null = null;+ try {+ handle = await agent.startSession({+ sessionId: 'pending-switch-session',+ workingDir,+ model: 'byom-model',+ // 派子代理本身要过审批门(ask 档无 resolver 即拒);本例只验 pending 闸,给最宽档,+ // 免得"没起子进程"其实是被权限门挡的。+ permissionMode: 'bypassPermissions',+ });++ // 把快照改成 host 在等待窗口里写的那个形状(model/provider 不变,只多 pending)。+ // 这样"没起子进程"唯一可能的原因就是 pending 闸:路由本身仍然完全可用。+ // 文件名带每运行时 nonce(跨实例隔离),所以按「前缀 + sessionId」找。**不要**只用+ // startsWith('subagent-'):agentHome 是整组共享的,别的用例留下的快照会被先找到+ // (实测拿到了另一个会话的 localresponses,单跑绿、全量红)。+ const runtimeDir = path.join(agentHome, 'runtime');+ const snapshotName = readdirSync(runtimeDir)+ .find((f) => f.startsWith('subagent-pending-switch-session-'));+ expect(snapshotName).toBeTruthy();+ const snapshotPath = path.join(runtimeDir, snapshotName as string);+ const confirmed = JSON.parse(readFileSync(snapshotPath, 'utf8')) as Record<string, unknown>;+ expect(confirmed.provider).toBe('localbyom');+ writeFileSync(snapshotPath, JSON.stringify({ ...confirmed, pending: true }) + '\n');++ const events: AgentEvent[] = [];+ const done = (async () => {+ for await (const ev of handle!.events()) {+ events.push(ev);+ if (ev.type === 'done') break;+ }+ })();+ await handle.send({ type: 'user', content: 'delegate now' });+ await done;++ // 父进程确实调了工具(否则这条用例什么都没验证)。+ expect(nativeBodies.length).toBeGreaterThanOrEqual(1);+ // 一个子进程都没起来:画像 prompt 只出现在子进程自己的请求里。+ expect(nativeBodies.some((b) => b.includes('scout subagent'))).toBe(false);+ // 而且拒绝理由回传给了父模型(不是静默无事发生 —— 模型要知道该自己干)。+ expect(nativeBodies.some((b) => b.includes('not confirmed yet'))).toBe(true);+ // 卡片必须收到一帧终态 failed。少这一帧,两端的卡片模型都会按"有工具结果 = completed"+ // 兜底,于是这次被拒绝的委派在界面上立刻变绿(review)。+ const cardStatuses = events+ .filter((e) => e.type === 'agent_task_update')+ .map((e) => (e.data as { status?: string }).status);+ expect(cardStatuses).toContain('failed');+ expect(cardStatuses).not.toContain('completed');+ } finally {+ await handle?.close();+ await new Promise<void>((r) => nativeServer.close(() => r()));+ rmSync(workingDir, { recursive: true, force: true });+ }+ },+ );});diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex 0e09aa3b80..4f859f72fc 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -11,7 +11,7 @@* `set_model` id(都是用户选中的目录 id)。*/-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -23,6 +23,12 @@ const captured = vi.hoisted(() => ({requests: [] as Array<Record<string, unknown>>,sent: [] as Array<Record<string, unknown>>,proxyRegistration: null as { sessionId: string; token: string } | null,+ failSetModel: false,+ rejectSetModel: false,+ onAfterSetModel: null as null | (() => void),+ // 卡住 set_model 的回包,让测试能在"RPC 在飞"的那一刻观察盘上的路由快照。+ holdSetModel: null as null | Promise<void>,+ closed: false,}));vi.mock('../rpc-client.js', () => ({@@ -41,6 +47,16 @@ vi.mock('../rpc-client.js', () => ({cmd: Record<string, unknown> & { type: string },): Promise<{ success: boolean; data?: unknown }> {captured.requests.push(cmd);+ if (cmd.type === 'set_model' && captured.holdSetModel) {+ await captured.holdSetModel;+ }+ if (cmd.type === 'set_model' && captured.rejectSetModel) {+ throw new Error('pi rpc timeout after 30000ms: set_model');+ }+ if (cmd.type === 'set_model' && captured.failSetModel) {+ captured.onAfterSetModel?.();+ return { success: false };+ }if (cmd.type === 'get_state') {return { success: true, data: { sessionFile: '/mock/session.jsonl', model: { contextWindow: 200000 } } };}@@ -51,6 +67,7 @@ vi.mock('../rpc-client.js', () => ({}async close(): Promise<void> {this.isClosed = true;+ captured.closed = true;}},}));@@ -79,6 +96,11 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {captured.requests = [];captured.sent = [];captured.proxyRegistration = null;+ captured.failSetModel = false;+ captured.rejectSetModel = false;+ captured.onAfterSetModel = null;+ captured.holdSetModel = null;+ captured.closed = false;agentHome = mkdtempSync(path.join(tmpdir(), 'pi-dispatch-home-'));cwd = mkdtempSync(path.join(tmpdir(), 'pi-dispatch-cwd-'));savedNoProxy = process.env.NO_PROXY;@@ -185,6 +207,10 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {'CINDY_PI_API_KEY','CINDY_PI_SESSION_ID','CINDY_PI_SESSION_TOKEN',+ // 子代理路由快照是**控制面**:一次获批的 bash 拿到路径就能改写 provider/model,+ // 让后续每次委派打到攻击者选定的 endpoint。与 permission file 同类,必须从+ // bash/模型工具的 spawn 边界剥离(review)。+ 'CINDY_PI_SUBAGENT_RUNTIME_FILE',]),);const noProxy = (captured.env.NO_PROXY ?? '').split(',');@@ -194,6 +220,229 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {expect(captured.env.no_proxy).toBeUndefined();});++ it('refuses the model switch when the subagent routing snapshot cannot be persisted', async () => {+ // 顺序不能反:快照必须先落盘、再切 pi 侧模型。+ //+ // 上一版是先 set_model 成功、再写快照,写失败就置 subagentRoutingEnabled = false —— 而那个+ // 撤销是**无效的**:该标志只在构造 spawnEnv 时读一次(spawn 之前),进程起来后改它既收不回+ // 已注入的 env、也不能让扩展停止读那个文件。于是"写失败 + 删除也失败"(只读挂载/磁盘满)时,+ // 父会话已切到新 provider,子代理仍按上一个有效快照跑 —— 委派发往旧 endpoint(review)。+ const handle = await start();+ const runtimeDir = path.join(agentHome, 'runtime');+ const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));+ expect(snapshot).toBeTruthy();+ const snapshotPath = path.join(runtimeDir, snapshot as string);+ const before = readFileSync(snapshotPath, 'utf8');++ // 让写入必然失败:把快照文件换成同名目录(writeFile → EISDIR)。+ rmSync(snapshotPath, { force: true });+ mkdirSync(snapshotPath);+ captured.requests = [];++ await expect(handle.setModel('m')).rejects.toThrow(/子代理路由快照/);+ // 关键:pi 侧的 set_model **根本没发出去** —— 父子路由不会出现"父已切、子没切"的中间态。+ expect(captured.requests.map((r) => r.type)).not.toContain('set_model');++ // 收尾:恢复成文件,别把目录留给 close()。+ rmSync(snapshotPath, { recursive: true, force: true });+ writeFileSync(snapshotPath, before);+ await handle.close();+ });+++ it('terminates the session when the routing snapshot cannot be rolled back', async () => {+ // 新快照落盘成功、set_model 失败、回滚又失败(第一次写之后文件系统才转只读)时,盘上的+ // 快照指向**被拒绝的** provider/model,而父会话仍在旧路由 —— 下一次委派就打到用户并未启用+ // 的端点。此时 subagentRoutingEnabled 是空操作(只在 spawn 前读),删文件也已失败,唯一+ // 可证明有效的手段是让这个 pi 进程不再有下一次派发:终止会话(review 连点两轮)。+ const handle = await start();+ const runtimeDir = path.join(agentHome, 'runtime');+ const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));+ const snapshotPath = path.join(runtimeDir, snapshot as string);++ // 让 set_model 失败;第一次快照写入照常成功。+ captured.failSetModel = true;+ captured.requests = [];+ // 让**回滚**写入失败:回滚发生在 set_model 之后,这里用只读目录制造 EACCES/EISDIR。+ captured.onAfterSetModel = () => {+ rmSync(snapshotPath, { force: true });+ mkdirSync(snapshotPath);+ };++ await expect(handle.setModel('m')).rejects.toThrow(/已终止本会话/);+ // 会话必须真的被关掉,而不是只置一个拦不住任何东西的标志。+ expect(captured.closed).toBe(true);++ rmSync(snapshotPath, { recursive: true, force: true });+ });+++ it('terminates the session when set_model neither confirms nor rejects cleanly (reject/timeout)', async () => {+ // reject / 超时与 `success:false` 有本质区别:后者我们**知道**没生效、可以回滚;前者我们+ // **不知道** pi 侧切没切。两条路都不安全 —— 回滚可能与真实状态相反,放行也可能相反,任一+ // 方向都是父子路由分叉(下一次委派打到用户并未启用的端点)。所以 fail-closed:终止会话。+ const handle = await start();+ const runtimeDir = path.join(agentHome, 'runtime');+ const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));+ const snapshotPath = path.join(runtimeDir, snapshot as string);+ const before = JSON.parse(readFileSync(snapshotPath, 'utf8')) as { model?: string; provider?: string };+ // 启动快照必须是用户实际选的 provider(BYOM / 本地模型的直连约束)。+ expect(before.provider).toBeTruthy();++ captured.rejectSetModel = true;+ await expect(handle.setModel('m')).rejects.toThrow(/未收到确认/);+ // 会话必须真的被关掉:进程还活着就意味着"下一次委派"仍可能发生。+ expect(captured.closed).toBe(true);+ // 快照**刻意**停在 pending:它既不是已确认的新路由、也不是旧路由,扩展一律拒绝派发。+ // 这条路径上"顺手回滚成旧值"是错的 —— 我们并不知道 pi 侧到底切没切。+ const stuck = JSON.parse(readFileSync(snapshotPath, 'utf8')) as { pending?: boolean; model?: string };+ expect(stuck.pending).toBe(true);+ expect(stuck.model).toBe('m');+ });++ it('isolates the routing snapshot per runtime instance (dev + packaged sharing one userData)', async () => {+ // review P1:dev 与打包版共用同一个 userData、`--passive` 任意多开,都是明确支持的工作流+ // (单实例锁按 flavor 分域,passive 完全跳过锁)。原来快照只按 sessionId 命名 → 两个**活着的**+ // 实例打开同一 session 时共用一个文件:任一实例切模型就覆盖掉另一个的路由,那个实例的父会话+ // 还在自己的路由上,它的下一个子代理却按对面的 provider 起来,提示词发往这个实例里并没选的+ // 端点。修法沿用 configHome 的隔离:文件名带每运行时 nonce。+ const runtimeDir = path.join(agentHome, 'runtime');+ const snapshotsOf = () => readdirSync(runtimeDir).filter((f) => f.startsWith('subagent-s1-'));+ // 权限档同一个暴露面,而且更严重:另一个实例切到 Full Access 会让本实例的 bridge 现读到+ // bypassPermissions,本实例的破坏性工具不再确认(跨实例权限提升)。同一把 nonce 一起收口。+ const permsOf = () => readdirSync(runtimeDir).filter((f) => f.startsWith('perm-s1-'));++ const first = await start();+ const firstFiles = snapshotsOf();+ expect(firstFiles).toHaveLength(1);+ expect(permsOf()).toHaveLength(1);+ // 第二个实例:同一个 sessionId、同一个 agentHome —— 就是 dev + 打包版共库双开的形状。+ const second = await start();+ const bothFiles = snapshotsOf();+ expect(bothFiles).toHaveLength(2);+ // 权限档也必须是两份独立文件,否则一个实例切档会改掉另一个实例 bridge 现读的那份。+ expect(new Set(permsOf()).size).toBe(2);+ const firstPath = path.join(runtimeDir, firstFiles[0]);+ const secondPath = path.join(runtimeDir, bothFiles.find((f) => f !== firstFiles[0]) as string);+ expect(firstPath).not.toBe(secondPath);++ const secondBefore = readFileSync(secondPath, 'utf8');+ await first.setModel('m-only-in-first');++ // 切换只落在自己那份快照上;另一个活着的实例一个字节都没被动过。+ expect((JSON.parse(readFileSync(firstPath, 'utf8')) as { model?: string }).model)+ .toBe('m-only-in-first');+ expect(readFileSync(secondPath, 'utf8')).toBe(secondBefore);++ // 会话结束要回收:带 nonce 之后文件不再按 sessionId 复用,不回收就随每次 startSession 堆积。+ await first.close();+ await second.close();+ await vi.waitFor(() => {+ expect(snapshotsOf()).toHaveLength(0);+ expect(permsOf()).toHaveLength(0);+ });+ });++ it('marks the routing snapshot pending while set_model is in flight and clears it on confirm', async () => {+ // review P1:原来在 RPC 回包**之前**就把新路由写成"已确认"形状,于是等待窗口里模型发起的+ // 派发会现读快照、按未确认的 provider 起子进程;RPC 随后失败时回滚文件撤不回已起的子进程。+ // 修法:窗口内快照带 `pending: true`,扩展见到就拒绝派发(拒绝的真实性由集成用例验证)。+ const handle = await start();+ const runtimeDir = path.join(agentHome, 'runtime');+ const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));+ const snapshotPath = path.join(runtimeDir, snapshot as string);+ const before = JSON.parse(readFileSync(snapshotPath, 'utf8')) as Record<string, unknown>;+ // 起点必须是已确认形状 —— 否则下面的 pending 断言证明不了任何东西。+ expect(before.pending).toBeUndefined();++ let release = () => {};+ captured.holdSetModel = new Promise<void>((r) => { release = r; });+ captured.requests = [];+ const switching = handle.setModel('m-next');++ // 等到 RPC 真的在飞。+ await vi.waitFor(() => {+ expect(captured.requests.map((r) => r.type)).toContain('set_model');+ });+ // 窗口内:内容已经是新路由(可写、可回滚),但带 pending → 扩展拒绝派发。+ const during = JSON.parse(readFileSync(snapshotPath, 'utf8')) as Record<string, unknown>;+ expect(during.pending).toBe(true);+ expect(during.model).toBe('m-next');++ release();+ await switching;+ // 确认后标记必须清掉,否则这个会话的子代理会被永久挡住。+ const after = JSON.parse(readFileSync(snapshotPath, 'utf8')) as Record<string, unknown>;+ expect(after.pending).toBeUndefined();+ expect(after.model).toBe('m-next');+ expect(after.provider).toBe(before.provider);++ await handle.close();+ });++ it('serializes concurrent model switches so no unconfirmed combination is ever published', async () => {+ // 并发/连点切换(本地 + 远程控制端同时切)若交错:A 写 pending、B 写 pending、A 落定 B 的+ // 内容 —— 盘上就会出现没人确认过的 model/provider 组合,而 `previousSnapshot` 也不再是真正+ // 可回滚的那一份。串行闸保证第二次切换在第一次落定之后才开始。+ const handle = await start();+ const runtimeDir = path.join(agentHome, 'runtime');+ const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));+ const snapshotPath = path.join(runtimeDir, snapshot as string);++ let release = () => {};+ captured.holdSetModel = new Promise<void>((r) => { release = r; });+ captured.requests = [];+ const first = handle.setModel('m-first');+ const second = handle.setModel('m-second');++ await vi.waitFor(() => {+ expect(captured.requests.map((r) => r.type)).toContain('set_model');+ });+ // 第一次还在飞 → 第二次必须一个字节都还没写:盘上是 m-first + pending,不是 m-second。+ const during = JSON.parse(readFileSync(snapshotPath, 'utf8')) as Record<string, unknown>;+ expect(during.model).toBe('m-first');+ expect(during.pending).toBe(true);+ // 而且第二条 set_model 还没发出去(否则 pi 侧会收到乱序的两次切换)。+ expect(captured.requests.filter((r) => r.type === 'set_model')).toHaveLength(1);++ captured.holdSetModel = null;+ release();+ await Promise.all([first, second]);++ // 两次切换按调用序抵达 pi,终态是最后一次、且已确认。+ const setModelCalls = captured.requests.filter((r) => r.type === 'set_model');+ expect(setModelCalls.map((r) => r.modelId)).toEqual(['m-first', 'm-second']);+ const after = JSON.parse(readFileSync(snapshotPath, 'utf8')) as Record<string, unknown>;+ expect(after.model).toBe('m-second');+ expect(after.pending).toBeUndefined();++ await handle.close();+ });++ it('rolls back to the user-selected provider when set_model cleanly reports failure', async () => {+ // 与上一条对照:success:false 是**确定**没生效 → 回滚,快照必须回到用户原本选定的+ // provider/model,下一次委派才会继续直连那个 Pi 原生 provider(BYOM 约束)。+ const handle = await start();+ const runtimeDir = path.join(agentHome, 'runtime');+ const snapshot = readdirSync(runtimeDir).find((f) => f.startsWith('subagent-'));+ const snapshotPath = path.join(runtimeDir, snapshot as string);+ const before = JSON.parse(readFileSync(snapshotPath, 'utf8')) as { model?: string; provider?: string };++ captured.failSetModel = true;+ await expect(handle.setModel('m')).rejects.toThrow(/set_model failed/);+ // 会话不该因为一次干净的失败被终止(那是 reject/超时才有的代价)。+ expect(captured.closed).toBe(false);+ // 快照已回滚到切换前的值 —— 父进程路由与下一次委派一致。+ const after = JSON.parse(readFileSync(snapshotPath, 'utf8')) as+ { model?: string; provider?: string; pending?: boolean };+ expect(after).toEqual(before);+ // 回滚必须**同时**清掉 pending,否则子代理会被永久挡在门外(一次干净的失败不该有这个代价)。+ expect(after.pending).toBeUndefined();++ await handle.close();+ });+it('overrides the Pi bash tool and strips host credentials at its spawn boundary', async () => {await start();const { readFileSync } = await import('node:fs');diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.tsindex 22901483ce..fb5d849dbf 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts@@ -1,4 +1,4 @@-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -43,6 +43,17 @@ const noopLogger: Logger = {describe('Pi provider-aware model routing', () => {let agentHome = '';++ /**+ * runtime 文件名带每运行时 nonce(dev + 打包版 / passive 共用 userData 时的跨实例隔离),+ * 所以按「前缀 + sessionId」找,不能再拼死名字。前缀含 sessionId → 不会串到别的用例。+ */+ const runtimeFileOf = (prefix: string, sessionId: string): string => {+ const dir = path.join(agentHome, 'runtime');+ const name = readdirSync(dir).find((f) => f.startsWith(prefix + '-' + sessionId + '-'));+ if (!name) throw new Error('runtime file not found: ' + prefix + '-' + sessionId + '-*');+ return path.join(dir, name);+ };let cwd = '';beforeEach(() => {@@ -688,7 +699,7 @@ describe('Pi provider-aware model routing', () => {// 不得在其后 stale 覆盖(否则 bridge 现读到 bypassPermissions,而 host/UI 已是 Ask)。const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));const handle = await agent.startSession({ sessionId: 'perm-race', workingDir: cwd, model: 'local-model' });- const permFile = path.join(agentHome, 'runtime', 'perm-perm-race.json');+ const permFile = runtimeFileOf('perm', 'perm-race');const a = handle.setPermissionMode!('bypassPermissions');const b = handle.setPermissionMode!('ask');await Promise.all([a, b]);@@ -706,7 +717,7 @@ describe('Pi provider-aware model routing', () => {model: 'local-model',permissionMode: 'ask',});- const permFile = path.join(agentHome, 'runtime', 'perm-perm-recover.json');+ const permFile = runtimeFileOf('perm', 'perm-recover');// 下一次写(尝试放宽到 Full)失败一次;旧文件仍是安全的 ask,此后恢复真实写。const spy = vi.spyOn(fsp.promises, 'writeFile').mockRejectedValueOnce(new Error('transient EIO'));await handle.setPermissionMode!('bypassPermissions').catch(() => {});@@ -726,7 +737,7 @@ describe('Pi provider-aware model routing', () => {model: 'local-model',permissionMode: 'ask',});- const permFile = path.join(agentHome, 'runtime', 'perm-perm-failed-intent.json');+ const permFile = runtimeFileOf('perm', 'perm-failed-intent');const spy = vi.spyOn(fsp.promises, 'writeFile').mockRejectedValueOnce(new Error('transient EIO'));await expect(handle.setPermissionMode!('bypassPermissions')).rejects.toThrow('transient EIO');spy.mockRestore();diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.tsindex 7eceb598fd..8bb2d458e9 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts@@ -374,4 +374,134 @@ describe('pi translator', () => {expect(events).toEqual([]);expect(warn).not.toHaveBeenCalled();});++ describe('delegated (subagent) usage accounting', () => {+ const progressEvent = (taskId: string, usage: Record<string, number>, extra: Record<string, unknown> = {}) =>+ ev({+ type: 'tool_execution_update',+ toolCallId: taskId,+ partialResult: {+ details: { __cindySubagent: 1, taskId, status: 'running', usage, ...extra },+ },+ });++ it('folds subagent usage into the turn totals and done.data.usage', () => {+ // 子代理是独立 pi 进程,它的请求不经过父进程的 usage 流。不显式并进来,done.data.usage+ // 与 register.ts 持久化的 session token/cost 会漏掉全部委派花费(review)。+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);++ translatePiEvent(+ progressEvent('sa-1', { input: 100, output: 20, cacheRead: 5, cacheWrite: 2, cost: 0.01 }),+ queue,+ ctx,+ );+ expect(ctx.turnInput).toBe(100);+ expect(ctx.turnOutput).toBe(20);+ expect(ctx.turnCacheRead).toBe(5);+ expect(ctx.turnCacheWrite).toBe(2);+ expect(ctx.turnTokens).toBe(120);+ expect(ctx.costUsd).toBeCloseTo(0.01, 10);+ // 卡片帧照旧发出(用量记账是附加行为,不替代卡片)。+ expect(events.some((e) => e.type === 'agent_task_update')).toBe(true);++ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);+ const done = events.find((e) => e.type === 'done');+ expect((done?.data as { usage?: unknown }).usage).toEqual({+ inputTokens: 100,+ outputTokens: 20,+ cacheReadTokens: 5,+ cacheCreationTokens: 2,+ });+ });++ it('only counts the increment — progress frames report cumulative totals', () => {+ // 进度帧报累计值(丢一帧不该让那段用量永久消失),所以父侧必须按 taskId 作差。+ // 直接累加会让同一批 token 被反复计入,一次多帧的委派就能把 turn 用量翻好几倍。+ const ctx = createPiTranslateContext(noopLogger);+ const { queue } = makeQueue();+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);++ translatePiEvent(progressEvent('sa-1', { input: 100, output: 10, cost: 0.01 }), queue, ctx);+ translatePiEvent(progressEvent('sa-1', { input: 250, output: 40, cost: 0.03 }), queue, ctx);+ translatePiEvent(progressEvent('sa-1', { input: 250, output: 40, cost: 0.03 }), queue, ctx);++ expect(ctx.turnInput).toBe(250);+ expect(ctx.turnOutput).toBe(40);+ expect(ctx.turnTokens).toBe(290);+ expect(ctx.costUsd).toBeCloseTo(0.03, 10);+ });++ it('accumulates parallel delegations independently and never goes negative', () => {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue } = makeQueue();+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);++ translatePiEvent(progressEvent('sa-1', { input: 100, output: 10, cost: 0.01 }), queue, ctx);+ translatePiEvent(progressEvent('sa-2', { input: 200, output: 30, cost: 0.02 }), queue, ctx);+ // 回退的累计值(理论上不该出现)不得产生负增量。+ translatePiEvent(progressEvent('sa-2', { input: 5, output: 1, cost: 0 }), queue, ctx);++ expect(ctx.turnInput).toBe(300);+ expect(ctx.turnOutput).toBe(40);+ expect(ctx.costUsd).toBeCloseTo(0.03, 10);+ });++ it('does not pollute contextTokens with the subagent context', () => {+ // contextTokens = "最后一次 API 调用占了多少上下文"。子代理有自己独立的上下文窗口,+ // 混进来会让父会话的上下文占用条虚高。+ const ctx = createPiTranslateContext(noopLogger);+ const { queue } = makeQueue();+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ translatePiEvent(+ ev({+ type: 'message_end',+ message: { role: 'assistant', content: [], usage: { input: 1_000, cacheRead: 500, cacheWrite: 0, output: 5 } },+ }),+ queue,+ ctx,+ );+ const parentContext = ctx.contextTokens;+ expect(parentContext).toBe(1_500);++ translatePiEvent(progressEvent('sa-1', { input: 90_000, output: 9_000 }), queue, ctx);+ expect(ctx.contextTokens).toBe(parentContext);+ });++ it('resets the delegated cumulative bookkeeping at the turn boundary', () => {+ // 新 turn 的累计值不该跟上一 turn 作差(否则新 turn 的委派用量被吃掉);+ // 也避免长会话里 taskId 条目无界堆积。+ const ctx = createPiTranslateContext(noopLogger);+ const { queue } = makeQueue();+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ translatePiEvent(progressEvent('sa-1', { input: 100, output: 10 }), queue, ctx);+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);++ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ expect(ctx.delegatedUsage.size).toBe(0);+ translatePiEvent(progressEvent('sa-1', { input: 100, output: 10 }), queue, ctx);+ expect(ctx.turnInput).toBe(100);+ expect(ctx.turnOutput).toBe(10);+ });++ it('ignores progress frames without usage (card-only updates)', () => {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);+ translatePiEvent(+ ev({+ type: 'tool_execution_update',+ toolCallId: 'sa-1',+ partialResult: { details: { __cindySubagent: 1, taskId: 'sa-1', status: 'running', toolUses: 3 } },+ }),+ queue,+ ctx,+ );+ expect(ctx.turnInput).toBe(0);+ expect(ctx.turnTokens).toBe(0);+ expect(events.some((e) => e.type === 'agent_task_update')).toBe(true);+ expect(usageSnapshotOf(ctx).tokenUsage).toBe(0);+ });+ });});diff --git a/packages/maker-core/src/agents/pi/__tests__/subagentProgress.test.ts b/packages/maker-core/src/agents/pi/__tests__/subagentProgress.test.tsnew file mode 100644index 0000000000..42911ea7db--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/subagentProgress.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it } from 'vitest';++import { parsePiSubagentProgress } from '../subagent-progress.js';++/** 模拟 pi 工具 onUpdate 的中间结果:标记与数据都在 details 下。 */+function payload(extra: Record<string, unknown> = {}): unknown {+ return { details: { __cindySubagent: 1, taskId: 'sa-1', status: 'running', ...extra } };+}++describe('parsePiSubagentProgress', () => {+ it('maps a progress notify onto the shared agent task card fields', () => {+ expect(+ parsePiSubagentProgress(+ payload({+ agentName: 'scout',+ task: 'survey the auth flow',+ model: 'claude-haiku-4-5',+ totalTokens: 12_345,+ toolUses: 7,+ durationMs: 4_200,+ }),+ ),+ ).toEqual({+ update: {+ provider: 'pi',+ taskId: 'sa-1',+ parentToolUseId: 'sa-1',+ status: 'running',+ title: 'scout',+ description: 'survey the auth flow',+ model: 'claude-haiku-4-5',+ usage: { totalTokens: 12_345, toolUses: 7, durationMs: 4_200 },+ },+ });+ });++ it('carries terminal states and the final summary', () => {+ for (const status of ['completed', 'failed', 'stopped'] as const) {+ const update = parsePiSubagentProgress(payload({ status, summary: 'found 3 call sites' }));+ expect(update?.update.status).toBe(status);+ expect(update?.update.summary).toBe('found 3 call sites');+ }+ });++ it('ignores partial results that are not marked cindy subagent progress', () => {+ // 别的工具流式上报(bash 的 partialResult 等)不得被误认成子代理进度。+ expect(parsePiSubagentProgress({ content: [{ type: 'text', text: 'Working...' }] })).toBeNull();+ expect(parsePiSubagentProgress({ details: { taskId: 'sa-1', status: 'running' } })).toBeNull();+ // 标记必须是数字 1,字符串 '1' 不算(防松散判等放进无关载荷)。+ expect(parsePiSubagentProgress({ details: { __cindySubagent: '1', taskId: 'sa-1' } })).toBeNull();+ expect(parsePiSubagentProgress(undefined)).toBeNull();+ expect(parsePiSubagentProgress('running')).toBeNull();+ expect(parsePiSubagentProgress({ details: [{ __cindySubagent: 1 }] })).toBeNull();+ });++ it('requires a taskId — an unlinkable update cannot address a card', () => {+ expect(parsePiSubagentProgress({ details: { __cindySubagent: 1, status: 'running' } })).toBeNull();+ expect(parsePiSubagentProgress(payload({ taskId: ' ' }))).toBeNull();+ });++ it('never invents a terminal state for an unknown status', () => {+ // 不猜:状态不认识时按 running,把跑着的子代理显示成已完成比没状态更糟。+ expect(parsePiSubagentProgress(payload({ status: 'bogus' }))?.update.status).toBe('running');+ expect(parsePiSubagentProgress(payload({ status: undefined }))?.update.status).toBe('running');+ });++ it('drops malformed usage numbers instead of surfacing them', () => {+ const update = parsePiSubagentProgress(+ payload({ totalTokens: -5, toolUses: Number.NaN, durationMs: 'soon' }),+ );+ expect(update?.update.usage).toBeUndefined();+ });++ it('keeps partial usage when only some counters are known', () => {+ expect(parsePiSubagentProgress(payload({ toolUses: 2 }))?.update.usage).toEqual({ toolUses: 2 });+ });++ it('never rewrites taskId — a truncated id would stop matching the same card', () => {+ // taskId 是卡片/tool_use 的关联键。此前按 200 字符截断并追加省略号,超长 id 会被改写成+ // 新值,后续 update 命中不到同一张卡(卡片停更或另开一张)。+ const longId = 'sa-' + 'x'.repeat(500);+ const update = parsePiSubagentProgress(payload({ taskId: longId }));+ expect(update?.update.taskId).toBe(longId);+ expect(update?.update.parentToolUseId).toBe(longId);+ expect(update?.update.taskId).not.toContain('…');+ // 仅 trim,不改内容。+ expect(parsePiSubagentProgress(payload({ taskId: ' sa-9 ' }))?.update.taskId).toBe('sa-9');+ });++ it('surfaces the delegated usage components so the parent turn can account for them', () => {+ // 子代理是独立 pi 进程,请求不走父进程的 usage 流。分量必须逐项带出来(含 cost),+ // 父侧才能并进 turn 记账 → register.ts 持久化的 session token/cost 才含委派花费(review)。+ const progress = parsePiSubagentProgress(+ payload({ usage: { input: 100, output: 20, cacheRead: 5, cacheWrite: 2, cost: 0.0125 } }),+ );+ expect(progress?.delegatedUsage).toEqual({ input: 100, output: 20, cacheRead: 5, cacheWrite: 2, cost: 0.0125 });+ });++ it('drops an all-zero or malformed delegated usage payload', () => {+ // 全零帧不该在父侧建立记账条目;坏值按 0 处理而不是把 NaN 灌进 turn 计数。+ expect(parsePiSubagentProgress(payload({ usage: { input: 0, output: 0 } }))?.delegatedUsage).toBeUndefined();+ expect(parsePiSubagentProgress(payload({ usage: 'nope' }))?.delegatedUsage).toBeUndefined();+ expect(parsePiSubagentProgress(payload())?.delegatedUsage).toBeUndefined();+ expect(+ parsePiSubagentProgress(payload({ usage: { input: Number.NaN, output: -3, cost: 1 } }))?.delegatedUsage,+ ).toEqual({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 1 });+ });++ it('truncates long text so a chatty subagent cannot flood the event stream', () => {+ const update = parsePiSubagentProgress(payload({ task: 'x'.repeat(5_000) }));+ expect(update?.update.description?.length).toBe(2_000);+ expect(update?.update.description?.endsWith('…')).toBe(true);+ });+});diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-source.tsnew file mode 100644index 0000000000..8d76cff179--- /dev/null+++ b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts@@ -0,0 +1,758 @@+/**+ * cindy-subagent —— 写进 pi `PI_CODING_AGENT_DIR/extensions/` 的扩展源码(字符串常量)。+ *+ * 为什么是 Cindy 自己的实现,而不是装社区包:+ * - pi 上游刻意不内置子代理,社区(`pi-subagents` 等)一律以「扩展 + 子 pi 进程」补齐。+ * 但整包引入等于把第三方代码塞进 `pi-harness.md` §4.2 划定的自包含注入边界,并跟着上游+ * 版本跑。这里参考社区与上游示例的设计,只重做我们需要的部分,代码归 Cindy 所有。+ * - 沿用 §3 设计原则:直接用 pi 自身能力(`--mode json` 子进程、`--tools` 白名单、+ * `--append-system-prompt`),不再套一层外部框架、不做二次转义。+ *+ * 这段代码跑在 **pi 子进程**(bun runtime)里,不能 import cindy 任何模块;只依赖 pi 的+ * ExtensionAPI 与 node 内建。约束(与 cindy-bridge 同):模板里**不得出现模板字符串**,+ * 否则 `${...}` 会被外层 String.raw 插值 —— 一律用字符串拼接。+ *+ * 安全形态(重要,别当冗余删掉):+ * - 子进程**继承 `PI_CODING_AGENT_DIR`**,因此同样加载 cindy-bridge → 权限门(`tool_call`+ * 拦截 + 凭证路径硬拦)对子代理照样生效。不传 `--no-extensions` 正是为了保住这条。+ * - 第一期只给**只读**工具白名单(read/grep/find/ls)。这不只是保守:ask 档下非只读工具+ * 要走 `ctx.ui.confirm`,而 headless 子进程没有 UI 承接、bridge 的 catch 分支按 deny+ * 收口(fail-closed)。只读工具在门里直接放行,因此只读子代理开箱可用;写权限子代理需+ * 要先把子进程的确认请求转发到 Cindy 审批 UI,属独立一期。+ * - `CINDY_PI_SUBAGENT_DEPTH` 防递归:达到上限后本扩展不注册工具,子代理无法再派子代理。+ * - `--no-session`:子代理不写会话文件,不污染 Cindy 的会话 JSONL。+ * - **父死子亡**:子进程是 Cindy 的孙进程,`PiRpcProcess.close()` 的 SIGTERM/SIGKILL 只+ * 打到 pi 父进程,孙进程会被 init 收养后继续请求模型烧额度(review)。两条机制兜:+ * 子进程侧的父存活看门狗(见 `CINDY_SUBAGENT_PARENT_WATCHDOG_SOURCE`)+ 父进程侧的+ * `process.on('exit')` 同步清扫。刻意**不注册信号处理器**,原因见看门狗那段注释。+ *+ * 进度回传走 pi 工具原生的 `onUpdate` 流(→ `tool_execution_update`),由+ * `subagent-progress.ts` 翻成统一 `agent_task_update` → 与 Claude / Codex 共用+ * `AgentTaskCard`。不另开侧信道。+ *+ * 更新方式:PiAgent 每次 startSession 覆写该文件。+ */++/** 工具名 —— 与 `@cindy/maker-shared` 的 `PI_SUBAGENT_TOOL_NAME` 必须一致(卡片判据靠它)。 */+export const CINDY_SUBAGENT_TOOL_NAME = 'subagent';++export const CINDY_SUBAGENT_EXTENSION_FILENAME = 'cindy-subagent.ts';++/** Cindy 注入给子进程的 env 名:pi 二进制路径、递归深度、子代理模型。 */+export const CINDY_SUBAGENT_ENV = {+ binary: 'CINDY_PI_SUBAGENT_BINARY',+ depth: 'CINDY_PI_SUBAGENT_DEPTH',+ /**+ * 子代理运行期快照文件({model?, provider?})。刻意不用 env 传 model:env 在 spawn 时+ * 定型,会话中途 setModel 后子代理会继续用旧模型;provider 不一起传还会让同名模型落到+ * 错误 endpoint。扩展每次派子代理现读本文件(与权限档同机制)。+ */+ runtimeFile: 'CINDY_PI_SUBAGENT_RUNTIME_FILE',+} as const;++/**+ * 父进程 pid —— 由**父扩展**在 spawn 子代理时注入(不是 host 注入,所以不在+ * `CINDY_SUBAGENT_ENV` 里)。子进程里的看门狗靠它判断父进程是否还活着。+ */+export const CINDY_SUBAGENT_PARENT_PID_ENV = 'CINDY_PI_SUBAGENT_PARENT_PID';++/** 看门狗轮询间隔:也是父进程死亡后子代理最长残留时间。 */+export const CINDY_SUBAGENT_PARENT_WATCHDOG_INTERVAL_MS = 2000;++/**+ * 父存活看门狗 —— 追加在扩展源码末尾(函数声明会提升,所以放最后不影响调用)。+ *+ * 为什么必须由**子进程自己**盯着父进程,而不是父进程负责回收:+ * - Cindy 的 `PiRpcProcess.close()` 是 SIGTERM → 3s → SIGKILL,两者都只打到 pi 父进程;+ * 孙进程(子代理)不在同一进程组被信号覆盖,会被 init 收养后继续请求模型、烧额度。+ * - 父进程侧能挂的钩子覆盖不全:`process.on('exit')` 在 SIGTERM 默认终止路径上**不触发**,+ * SIGKILL 下更不可能有任何代码执行。所以父侧清扫只能当快路径,兜不住主要死法。+ * - 刻意**不在扩展里注册 `SIGTERM`/`SIGINT` 处理器**:Node/Bun 里一旦添加信号监听,该信号+ * 的默认终止行为就被抑制 —— 如果 pi 自身没有别的处理器,pi 收到 SIGTERM 后不会退出,+ * 每次关会话都得等满 Cindy 的 3s 宽限再被 SIGKILL,把"优雅关闭"变成"必然强杀"。+ *+ * 存活判据用 `process.kill(pid, 0)` —— 只做存在性检查,不真的发信号:+ * - `EPERM`(进程在、无权发信号)按**活着**处理;其余任何异常都按**已死**处理。方向是刻意+ * 选的:误判成死 = 子代理中途被杀(用户看到一次失败的子代理),误判成活 = 孤儿进程无上限+ * 地烧额度 —— 父进程一死,那个 10min 兜底超时的定时器也跟着消失了,没有第二道闸。+ * - pid 复用会让判活偏保守(误认为父进程还在),此时只能等子代理自己跑完;这是已知残留风险,+ * 换来的是绝不误杀正在干活的子代理。+ *+ * 平台覆盖:macOS 上已用真 pi 进程实测(父进程 SIGKILL 后子进程 ~1s 自行退出)。Windows 走+ * libuv 的 `OpenProcess` 存在性检查,语义相同但未实测 —— CI 的 Windows 分片会跑本机制的执行级+ * 测试,若那里表现不同,以测试结果为准。+ */+export const CINDY_SUBAGENT_PARENT_WATCHDOG_SOURCE = String.raw`+const PARENT_PID_ENV = 'CINDY_PI_SUBAGENT_PARENT_PID';+const PARENT_WATCHDOG_INTERVAL_MS = 2000;++function installParentWatchdog() {+ const raw = process.env[PARENT_PID_ENV];+ const parentPid = typeof raw === 'string' ? Number.parseInt(raw, 10) : Number.NaN;+ if (!Number.isFinite(parentPid) || parentPid <= 0) return;+ const timer = setInterval(function () {+ let alive = true;+ try {+ process.kill(parentPid, 0);+ } catch (err) {+ // EPERM = 进程在、只是没权限发信号 → 活着。其余(ESRCH 及任何意外错型)按死处理。+ alive = !!err && err.code === 'EPERM';+ }+ if (!alive) {+ clearInterval(timer);+ process.exit(0);+ }+ }, PARENT_WATCHDOG_INTERVAL_MS);+ // unref:看门狗自己不留住事件循环,子代理干完活该退就退。+ if (timer && typeof timer.unref === 'function') timer.unref();+}+`;++const CINDY_SUBAGENT_EXTENSION_BODY = String.raw`/**+ * cindy-subagent (generated by Cindy — do not edit; overwritten on session start)+ */+import { spawn } from 'node:child_process';+import { readFileSync } from 'node:fs';++const TOOL_NAME = 'subagent';+const MARKER = '__cindySubagent';+const BINARY_ENV = 'CINDY_PI_SUBAGENT_BINARY';+const DEPTH_ENV = 'CINDY_PI_SUBAGENT_DEPTH';+const RUNTIME_FILE_ENV = 'CINDY_PI_SUBAGENT_RUNTIME_FILE';+// cindy-bridge 用它决定要不要连 MCP server;子代理不需要,spawn 时剥掉(见 runTask)。+const MCP_BRIDGE_ENV = 'CINDY_PI_MCP_BRIDGE';+// PARENT_PID_ENV 与 PARENT_WATCHDOG_INTERVAL_MS 由末尾追加的看门狗段声明(那段要能独立+// 跑起来受测)。**别在这里重复声明** —— 同名 const 会让拼接后的模块直接 SyntaxError,+// 整个扩展加载失败。有测试守这条。++// 子代理不得再派子代理:深度到顶就不注册工具(与 codex agents.max_depth 同语义)。+const MAX_DEPTH = 1;+const MAX_TASKS = 8;+const MAX_CONCURRENCY = 4;+// 回给父模型的单任务输出上限:子代理的价值是"只回结论",别把全文灌回主线程。+const MAX_OUTPUT_CHARS = 16000;+// **调用级**总预算。只限单项没用:8 个任务各 16k 拼起来仍是 ~128k 字符注进父请求,+// 一次委派就能把父上下文吃掉大半(review)。成功与全失败两条返回路径都要过这道闸。+const MAX_TOTAL_OUTPUT_CHARS = 32000;+// 兜底超时:卡死的子代理不能把父 turn 永久挂住。+const TASK_TIMEOUT_MS = 10 * 60 * 1000;++// 只读画像。tools 同时是 --tools 白名单:非只读工具在 ask 档会被 bridge fail-closed+// 拒掉(headless 子进程没有确认 UI),所以第一期只给只读能力。+const PROFILES = {+ scout: {+ tools: 'read,grep,find,ls',+ prompt: 'You are a scout subagent. Investigate the codebase and answer the question you were given. '+ + 'Read only what you need. Report conclusions with file:line anchors — never paste long file contents. '+ + 'Be concise: the parent agent only needs your findings, not your process.',+ },+ reviewer: {+ tools: 'read,grep,find,ls',+ prompt: 'You are a code review subagent. Review what you were asked to review and report concrete, '+ + 'actionable defects with file:line anchors, most severe first. State the failure scenario for each. '+ + 'Do not restate what the code does. If you find nothing real, say so plainly.',+ },+ planner: {+ tools: 'read,grep,find,ls',+ prompt: 'You are a planning subagent. Read the relevant code, then produce a concrete implementation plan: '+ + 'which files change, in what order, and what could break. Cite file:line for every claim about current '+ + 'behavior. Do not write code.',+ },+};++function profileNames() {+ return Object.keys(PROFILES).join(' | ');+}++/**+ * 现读子代理运行期快照(model + provider)。每次派子代理都读 —— 会话中途 setModel 后+ * 立即生效。+ *+ * 读不到返回空对象,调用方**必须据此失败关闭**:退回 pi 默认解析会把 BYOM / 本地+ * provider 的请求发到错误 endpoint,那比"本次没有子代理"糟糕得多(review)。+ */+function readRuntimeSnapshot() {+ const file = process.env[RUNTIME_FILE_ENV];+ if (typeof file !== 'string' || file.length === 0) return {};+ try {+ const parsed = JSON.parse(readFileSync(file, 'utf8'));+ if (!parsed || typeof parsed !== 'object') return {};+ const model = typeof parsed.model === 'string' && parsed.model.trim().length > 0+ ? parsed.model.trim()+ : undefined;+ const provider = typeof parsed.provider === 'string' && parsed.provider.trim().length > 0+ ? parsed.provider.trim()+ : undefined;+ // pending = host 已写入这份路由但 pi 侧还没确认(set_model RPC 在飞)。这段窗口里派发是+ // 不安全的:用它就是用未确认的 provider,RPC 若被拒,子进程已经起来了、撤不回。+ return { model: model, provider: provider, pending: parsed.pending === true };+ } catch (err) {+ console.error('[cindy-subagent] runtime snapshot unreadable: ' + String(err));+ return {};+ }+}++function readDepth() {+ const raw = process.env[DEPTH_ENV];+ const parsed = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;+}++/**+ * 在途子代理进程。父进程正常退出(stdin EOF / 显式 process.exit)时同步强杀,免得+ * 孙进程被 init 收养后继续烧额度。SIGTERM / SIGKILL 覆盖不到这里 —— 那两条由子进程+ * 侧的 installParentWatchdog() 兜。+ */+const liveChildren = new Set();++function reapLiveChildren() {+ for (const child of liveChildren) {+ try {+ // exit 处理器里只能做同步动作:SIGKILL 一次到位,不给宽限期(没有下一轮事件循环)。+ child.kill('SIGKILL');+ } catch (err) {+ /* already gone */+ }+ }+ liveChildren.clear();+}++function clampText(text, max) {+ if (typeof text !== 'string') return '';+ const trimmed = text.trim();+ if (trimmed.length <= max) return trimmed;+ return trimmed.slice(0, max - 1) + '…';+}++/**+ * 调用级输出预算。单项 16k 之上还需要一道总闸:8 个任务拼起来 ~128k 字符会把父上下文+ * 吃掉大半(review)。+ *+ * 先均分,再把短任务省下的额度让给超额任务 —— 常见形态是一个任务话多、其余很短,直接+ * 均分会把长任务砍得没必要地狠。截断只切尾部,'## <agent> (failed)' 头部与失败诊断的+ * 开头一定保留,不会因为超预算就丢掉"哪个任务失败了"这个信息。+ */+function fitSectionsToBudget(sections) {+ let total = 0;+ for (const section of sections) total += section.length;+ if (total <= MAX_TOTAL_OUTPUT_CHARS || sections.length === 0) return sections;++ let share = Math.floor(MAX_TOTAL_OUTPUT_CHARS / sections.length);+ let surplus = 0;+ let overCount = 0;+ for (const section of sections) {+ if (section.length <= share) surplus += share - section.length;+ else overCount += 1;+ }+ if (overCount > 0) share += Math.floor(surplus / overCount);++ return sections.map(function (section) {+ return section.length <= share ? section : clampText(section, share);+ });+}++/** 归一化入参成任务数组;抛出的错误直接回给模型(它能据此改调用)。 */+function normalizeTasks(params) {+ const input = params && typeof params === 'object' ? params : {};+ const raw = Array.isArray(input.tasks) && input.tasks.length > 0+ ? input.tasks+ : [{ agent: input.agent, task: input.task }];+ if (raw.length > MAX_TASKS) {+ throw new Error('subagent: at most ' + MAX_TASKS + ' tasks per call (got ' + raw.length + ')');+ }+ return raw.map(function (entry, index) {+ const item = entry && typeof entry === 'object' ? entry : {};+ const agent = typeof item.agent === 'string' ? item.agent.trim() : '';+ const task = typeof item.task === 'string' ? item.task.trim() : '';+ if (!Object.prototype.hasOwnProperty.call(PROFILES, agent)) {+ throw new Error('subagent: unknown agent "' + agent + '" (available: ' + profileNames() + ')');+ }+ if (!task) {+ throw new Error('subagent: task ' + (index + 1) + ' is missing a task description');+ }+ return { agent: agent, task: task };+ });+}++/** 逐行喂 JSONL:pi 的 --mode json 每行一个事件,chunk 边界可能切断一行。 */+function createLineReader(onLine) {+ let buffer = '';+ return function (chunk) {+ buffer += chunk;+ for (;;) {+ const newline = buffer.indexOf('\n');+ if (newline < 0) break;+ const line = buffer.slice(0, newline).trim();+ buffer = buffer.slice(newline + 1);+ if (line.length > 0) onLine(line);+ }+ };+}++function assistantTextOf(message) {+ if (!message || typeof message !== 'object') return '';+ const content = Array.isArray(message.content) ? message.content : [];+ const parts = [];+ for (const block of content) {+ if (block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {+ parts.push(block.text);+ }+ }+ return parts.join('');+}++function emptyUsage() {+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };+}++/**+ * 累加子代理的一条 message_end.usage。+ *+ * 分量必须**逐项**留着,不能只汇总成一个 tokens:父进程要把这些委派用量并进本 turn 的+ * 记账(input/output/cacheRead/cacheWrite 各自成列,外加 cost.total),register.ts 持久化+ * 的 session 用量才包含委派请求。只给一个总数的话父侧无从拆分(review)。+ */+function addUsage(totals, usage) {+ if (!usage || typeof usage !== 'object') return;+ const keys = ['input', 'output', 'cacheRead', 'cacheWrite'];+ for (const key of keys) {+ const value = usage[key];+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {+ totals[key] += value;+ totals.tokens += value;+ }+ }+ const cost = usage.cost && typeof usage.cost.total === 'number' && Number.isFinite(usage.cost.total)+ ? usage.cost.total+ : 0;+ if (cost > 0) totals.cost += cost;+}++function mergeUsage(target, source) {+ if (!source) return;+ const keys = ['input', 'output', 'cacheRead', 'cacheWrite', 'cost'];+ for (const key of keys) {+ const value = source[key];+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) target[key] += value;+ }+}++/** 跑一个子代理,返回 { text, isError, toolUses, tokens }。 */+function runTask(binary, task, runtime, signal, onProgress) {+ return new Promise(function (resolve) {+ // 已中止就**根本不 spawn**。批次被取消时 worker 车道里可能还排着好几个任务,原来它们照样+ // 先 spawn 出子进程、再走到下面那个 aborted 早返回 —— 而那个 return 发生在注册+ // stdout / error / close 之前:子进程永远留在 liveChildren 里(父进程退出时才被清),+ // 而一次 spawn 失败会变成**无人监听的 'error' 事件**,在 Node 里直接抛出、能把父 pi+ // 进程带走。反复中断的批次因此既攒僵尸 handle 又有整进程崩掉的风险(review)。+ if (signal && signal.aborted === true) {+ resolve({ text: 'subagent aborted by user.', isError: true, toolUses: 0, tokens: 0, usage: emptyUsage() });+ return;+ }+ const profile = PROFILES[task.agent];+ const args = [+ '--mode', 'json',+ '--no-session',+ '--tools', profile.tools,+ '--append-system-prompt', profile.prompt,+ ];+ // provider 与 model 成对传:pi-harness §3 要求 BYOM / 本地模型直连对应原生 provider,+ // 只给 model 会让网关与 BYOM 同名模型落到默认 provider。+ if (runtime.provider) args.push('--provider', runtime.provider);+ if (runtime.model) args.push('--model', runtime.model);+ args.push(task.task);++ const childEnv = Object.assign({}, process.env);+ // 深度 +1:子代理进程里本扩展不再注册工具。+ childEnv[DEPTH_ENV] = String(readDepth() + 1);+ // 父 pid:子进程里的看门狗据此在父进程消失后自杀(SIGTERM/SIGKILL 打不到孙进程)。+ childEnv[PARENT_PID_ENV] = String(process.pid);+ // MCP 桥必须剥掉。子进程继承 PI_CODING_AGENT_DIR 会加载 cindy-bridge(权限门要靠这个,+ // 见文件头),而 bridge 一见到 CINDY_PI_MCP_BRIDGE 就会**逐个 connect 所有 MCP server**+ // 并持有有状态 transport。子代理的 --tools 白名单里根本没有 MCP 工具,所以这些连接纯属+ // 浪费:每个子代理一整套连接、每次派发一轮连接风暴(并发 4、单次最多 8),而且子代理不会+ // 显式 close,只能等进程退出(review)。剥这一个变量即可 —— 权限门与网关路由不受影响。+ delete childEnv[MCP_BRIDGE_ENV];++ let child;+ try {+ child = spawn(binary, args, { cwd: process.cwd(), env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });+ } catch (err) {+ resolve({ text: 'subagent failed to start: ' + String(err), isError: true, toolUses: 0, tokens: 0, usage: emptyUsage() });+ return;+ }+ liveChildren.add(child);++ const totals = emptyUsage();+ totals.tokens = 0;+ let toolUses = 0;+ let finalText = '';+ let stderr = '';+ let settled = false;+ let timer = null;+ // 强杀定时器:存下来才能在子进程真的退出后清掉(见 kill())。+ let killTimer = null;+ /**+ * 中止 / 超时的原因。置上它之后**不立刻 finish**,而是等 'close' 再收口 —— 这样 SIGTERM+ * 到 SIGKILL 之间那 2 秒宽限里子进程仍会吐出的 message_end 用量能被正常归集。+ *+ * 原来是"置守卫 + 立刻 finish":守卫连 JSON 解析一起跳过,已经真实产生的 token/cost 就+ * 丢了(review)。而单纯"解析但不上报"也救不回来 —— promise 已经 resolve,调用方紧接着就+ * 读走了那份快照,之后再改 totals 没人再看。所以正解是**推迟收口到进程真的关闭**。+ */+ let terminationReason = null;+ /** 收口兜底:'close' 万一不来(进程卡死在 SIGKILL 之外),不能把父 turn 永久挂住。 */+ let settleFallbackTimer = null;+ const armSettleFallback = function (result) {+ if (settleFallbackTimer) return;+ settleFallbackTimer = setTimeout(function () {+ settleFallbackTimer = null;+ finish(result);+ }, 5000);+ if (settleFallbackTimer && typeof settleFallbackTimer.unref === 'function') settleFallbackTimer.unref();+ };+ // 先声明:finish 在闭包里引用它,let 的 TDZ 不容许"定义在后、可能先被读"。+ let removeAbort = null;++ const finish = function (result) {+ if (settled) return;+ settled = true;+ if (timer) clearTimeout(timer);+ if (typeof removeAbort === 'function') removeAbort();+ resolve(result);+ };++ const kill = function () {+ try {+ child.kill('SIGTERM');+ } catch (err) {+ /* already gone */+ }+ // 宽限后强杀,避免僵尸子进程把 turn 挂住。定时器**存下来**并在 close/error 时清掉:+ // 留着它不仅让进程在退出后仍多挂 2 秒,更重要的是强杀前必须重新确认子进程还没退 ——+ // 否则一旦 pid 被系统回收复用,这一发 SIGKILL 就打到了别人身上(review)。+ // 双重保险:先查 exitCode/signalCode,再走 child.kill(Node 对已退出的 handle 是 no-op)。+ if (killTimer) return;+ killTimer = setTimeout(function () {+ killTimer = null;+ if (child.exitCode !== null || child.signalCode !== null) return;+ try {+ child.kill('SIGKILL');+ } catch (err) {+ /* already gone */+ }+ }, 2000);+ if (killTimer && typeof killTimer.unref === 'function') killTimer.unref();+ };++ const onAbort = function () {+ // 不立刻 finish:先杀,等 'close' 收口,期间继续归集用量(见 terminationReason 注释)。+ terminationReason = 'aborted';+ kill();+ armSettleFallback({ text: 'subagent aborted by user.', isError: true, toolUses: toolUses, tokens: totals.tokens, usage: totals });+ };+ if (signal && typeof signal.addEventListener === 'function') {+ if (signal.aborted) {+ // 残余竞态:上面的 spawn 前检查过后、spawn 完成前信号才置位。此时进程已经存在,而这条+ // 早返回仍在注册 stdout / error / close 之前 —— 必须自己把两件事做掉:从 liveChildren+ // 摘除(否则僵尸 handle 留到父进程退出),以及挂一个吞掉 'error' 的监听(ChildProcess+ // 的 'error' 无人监听会在 Node 里直接抛出,能把父 pi 进程带走)。+ liveChildren.delete(child);+ child.on('error', function () { /* 已中止,spawn 失败无需上报 */ });+ kill();+ finish({ text: 'subagent aborted by user.', isError: true, toolUses: 0, tokens: 0, usage: emptyUsage() });+ return;+ }+ signal.addEventListener('abort', onAbort, { once: true });+ removeAbort = function () {+ try {+ signal.removeEventListener('abort', onAbort);+ } catch (err) {+ /* ignore */+ }+ };+ }++ timer = setTimeout(function () {+ terminationReason = 'timeout';+ kill();+ armSettleFallback({+ text: 'subagent timed out after ' + Math.round(TASK_TIMEOUT_MS / 1000) + 's.',+ isError: true,+ toolUses: toolUses,+ tokens: totals.tokens,+ usage: totals,+ });+ }, TASK_TIMEOUT_MS);+ if (timer && typeof timer.unref === 'function') timer.unref();++ const feed = createLineReader(function (line) {+ // 终态已收口后丢弃迟到输出。注意**只跳过上报、不跳过解析**:kill() 到 SIGKILL 之间+ // 有约 2 秒宽限,子进程仍会吐 message_end,那里面是真实产生的 token/cost。原来在+ // JSON.parse 之前就整条短路,把这段用量丢了(review)。+ // 现在 abort / timeout 都推迟到 'close' 才 finish,所以这段窗口里 settled 仍为 false、+ // 用量照常归集;settled 为 true 只剩"兜底定时器已强行收口"这一种情况,此时上报会把+ // 已发出的 stopped/failed 改回 running,必须挡住。+ if (settled) return;+ let event;+ try {+ event = JSON.parse(line);+ } catch (err) {+ return;+ }+ if (!event || typeof event !== 'object') return;+ if (event.type === 'tool_execution_start') {+ toolUses += 1;+ onProgress({ toolUses: toolUses, tokens: totals.tokens, usage: totals });+ return;+ }+ if (event.type === 'message_end') {+ const message = event.message;+ if (message && message.role === 'assistant') {+ addUsage(totals, message.usage);+ const text = assistantTextOf(message);+ // 覆盖为最新一条有文本的 assistant 回复 = 子代理的结论。+ if (text.trim().length > 0) finalText = text;+ onProgress({ toolUses: toolUses, tokens: totals.tokens, usage: totals });+ }+ }+ });++ child.stdout.setEncoding('utf8');+ child.stdout.on('data', feed);+ child.stderr.setEncoding('utf8');+ child.stderr.on('data', function (chunk) {+ if (stderr.length < 4000) stderr += chunk;+ });+ child.on('error', function (err) {+ liveChildren.delete(child);+ if (killTimer) { clearTimeout(killTimer); killTimer = null; }+ finish({ text: 'subagent process error: ' + String(err), isError: true, toolUses: toolUses, tokens: totals.tokens, usage: totals });+ });+ child.on('close', function (code) {+ // 到 'close' 才摘除,不在 finish() 里摘:超时/中止已 finish 但进程还在 SIGKILL 宽限+ // 期里,这段窗口内父进程退出仍必须把它杀掉。+ liveChildren.delete(child);+ // 进程已退出:强杀定时器必须清掉,别对一个可能被复用的 pid 再发 SIGKILL(review)。+ if (killTimer) { clearTimeout(killTimer); killTimer = null; }+ if (terminationReason !== null) {+ // 中止/超时的收口点:等到进程真的关闭,此刻 totals 已含宽限期内到达的全部用量。+ if (settleFallbackTimer) { clearTimeout(settleFallbackTimer); settleFallbackTimer = null; }+ finish({+ text: terminationReason === 'timeout'+ ? 'subagent timed out after ' + Math.round(TASK_TIMEOUT_MS / 1000) + 's.'+ : 'subagent aborted by user.',+ isError: true,+ toolUses: toolUses,+ tokens: totals.tokens,+ usage: totals,+ });+ return;+ }+ const ok = code === 0;+ const body = finalText.trim().length > 0+ ? clampText(finalText, MAX_OUTPUT_CHARS)+ : (ok ? '(subagent produced no output)' : clampText(stderr, 2000) || ('subagent exited with code ' + String(code)));+ finish({ text: body, isError: !ok, toolUses: toolUses, tokens: totals.tokens, usage: totals });+ });+ });+}++export default async function cindySubagent(pi: any) {+ // depth > 0 = 本进程自己就是子代理:装上父存活看门狗,父进程(pi 会话)一消失就自杀。+ // 必须在下面的深度早返回**之前**装 —— 子代理正是走那条早返回分支的。+ if (readDepth() > 0) installParentWatchdog();+ if (readDepth() >= MAX_DEPTH) return;+ const binary = process.env[BINARY_ENV];+ // 拿不到 pi 二进制路径就不注册:宁可没有这个工具,也不让模型调用一个必然失败的工具。+ if (typeof binary !== 'string' || binary.trim().length === 0) return;+ // host 未能持久化路由快照时会**不传**该 env → 本次会话完全不暴露子代理工具(fail-closed)。+ const runtimeFile = process.env[RUNTIME_FILE_ENV];+ if (typeof runtimeFile !== 'string' || runtimeFile.trim().length === 0) return;++ // 父侧快路径:pi 正常退出(stdin EOF / 显式 exit)时同步清掉在途子代理。信号死法覆盖不到+ // 这里(SIGTERM 的默认终止不跑 'exit' 处理器),那部分由子进程侧看门狗兜。+ process.on('exit', reapLiveChildren);++ pi.registerTool({+ name: TOOL_NAME,+ label: 'Subagent',+ description: 'Delegate a focused, read-only investigation to a subagent running in its own context window. '+ + 'Use it for exploration whose intermediate output does not need to stay in this conversation: reading '+ + 'rule or design docs, surveying large or unfamiliar files, broad code searches, or getting an '+ + 'independent review. The subagent reports conclusions only. Available agents: ' + profileNames() + '. '+ + 'Pass {agent, task} for one, or {tasks:[{agent, task}, ...]} to run up to ' + MAX_TASKS + ' in parallel. '+ + 'Subagents are read-only (no bash, no file edits) and cannot spawn further subagents — do implementation '+ + 'and verification yourself.',+ parameters: {+ type: 'object',+ properties: {+ agent: { type: 'string', description: 'Agent profile: ' + profileNames() },+ task: {+ type: 'string',+ description: 'What to investigate. State exactly what to read and which question to answer.',+ },+ tasks: {+ type: 'array',+ description: 'Run several subagents in parallel (max ' + MAX_TASKS + ').',+ items: {+ type: 'object',+ properties: {+ agent: { type: 'string', description: 'Agent profile: ' + profileNames() },+ task: { type: 'string' },+ },+ required: ['agent', 'task'],+ },+ },+ },+ additionalProperties: false,+ },+ async execute(toolCallId: string, params: unknown, signal: AbortSignal, onUpdate: any) {+ const tasks = normalizeTasks(params);+ const runtime = readRuntimeSnapshot();+ const startedAt = Date.now();+ const label = tasks.map(function (t) { return t.agent; }).join(', ');+ const taskId = String(toolCallId || 'subagent');+ const totals = { toolUses: 0, tokens: 0, usage: emptyUsage() };+ const perTask = tasks.map(function () { return { toolUses: 0, tokens: 0, usage: emptyUsage() }; });++ const report = function (status: string, summary?: string) {+ if (typeof onUpdate !== 'function') return;+ const details: Record<string, unknown> = {+ taskId: taskId,+ status: status,+ agentName: label,+ task: tasks.length === 1 ? tasks[0].task : tasks.length + ' parallel tasks',+ toolUses: totals.toolUses,+ totalTokens: totals.tokens,+ durationMs: Date.now() - startedAt,+ // 委派用量的**累计**分量。父进程按 taskId 记住上次值、只把增量并进本 turn 的记账+ // (register.ts 持久化的 session token/cost 因此包含子代理请求)。报累计而不是增量:+ // 进度帧是 best-effort 的,丢一帧不该让那部分用量永久消失(review)。+ usage: {+ input: totals.usage.input,+ output: totals.usage.output,+ cacheRead: totals.usage.cacheRead,+ cacheWrite: totals.usage.cacheWrite,+ cost: totals.usage.cost,+ },+ };+ details[MARKER] = 1;+ if (summary) details.summary = summary;+ if (runtime.model) details.model = runtime.model;+ try {+ onUpdate({ content: [{ type: 'text', text: status === 'running' ? 'Running subagent…' : status }], details: details });+ } catch (err) {+ /* progress is best-effort */+ }+ };++ const recompute = function () {+ let toolUses = 0;+ let tokens = 0;+ const usage = emptyUsage();+ for (const entry of perTask) {+ toolUses += entry.toolUses;+ tokens += entry.tokens;+ mergeUsage(usage, entry.usage);+ }+ totals.toolUses = toolUses;+ totals.tokens = tokens;+ totals.usage = usage;+ };++ // 两道**派发前**的失败关闭闸。注意它们排在 report 定义**之后**、report('running')+ // **之前**:卡片状态机在没有任何 agent_task_update 时会按"有工具结果 = completed"兜底,+ // 所以在这里直接 throw 会让卡片瞬间变绿 —— 明明这次委派被拒了(review)。必须先发一帧+ // 终态 failed,再抛错。+ //+ // 使用点失败关闭:快照读不到(host 写失败后删除 / 目录只读 / 磁盘满)时拒绝派发,+ // 而不是不带 --provider/--model 让子进程走 pi 默认解析 —— 后者会把 BYOM / 本地+ // provider 的请求发到错误 endpoint。provider 恒由 host 写入,缺它即视为不可用。+ if (!runtime.provider) {+ report('failed', 'model routing snapshot unavailable');+ throw new Error(+ 'subagent is unavailable: Cindy could not read this session\'s model routing snapshot, '+ + 'so a subagent would run against the wrong provider. Tell the user; do the work yourself.',+ );+ }+ // 模型切换的等待窗口(host 已写新路由、pi 侧尚未确认)里一律不派发。放行就意味着子进程+ // 用一个**未经确认**的 provider 起来:切换若被拒,host 能回滚文件,却撤不回已经在跑的子+ // 进程 —— 那才是真正撤不回的父子路由分叉(review)。宁可这一次委派失败。+ if (runtime.pending) {+ report('failed', 'model switch in progress; routing not confirmed');+ throw new Error(+ 'subagent is unavailable right now: this session is switching model/provider and the new route '+ + 'is not confirmed yet. Do this step yourself, or retry the delegation after the switch settles.',+ );+ }++ report('running');++ const results: any[] = new Array(tasks.length);+ let next = 0;+ const worker = async function () {+ for (;;) {+ const index = next;+ next += 1;+ if (index >= tasks.length) return;+ results[index] = await runTask(binary, tasks[index], runtime, signal, function (progress: any) {+ perTask[index] = { toolUses: progress.toolUses, tokens: progress.tokens, usage: progress.usage };+ recompute();+ report('running');+ });+ perTask[index] = {+ toolUses: results[index].toolUses,+ tokens: results[index].tokens,+ usage: results[index].usage,+ };+ recompute();+ report('running');+ }+ };+ const lanes = Math.min(MAX_CONCURRENCY, tasks.length);+ const running = [];+ for (let i = 0; i < lanes; i += 1) running.push(worker());+ await Promise.all(running);++ const failed = results.filter(function (r) { return r && r.isError; }).length;+ const aborted = signal && signal.aborted === true;+ const sections = results.map(function (result, index) {+ const head = '## ' + tasks[index].agent + (result && result.isError ? ' (failed)' : '');+ return head + '\n' + (result ? result.text : '(no result)');+ });+ const text = fitSectionsToBudget(sections).join('\n\n');+ // 任一子任务失败即整卡 failed:部分成功不足以把批次报成完成(greptile P1)。+ report(aborted ? 'stopped' : failed > 0 ? 'failed' : 'completed',+ failed > 0 ? failed + ' of ' + results.length + ' subagents failed' : undefined);++ if (failed === results.length && results.length > 0) {+ throw new Error(text);+ }+ return {+ content: [{ type: 'text', text: text }],+ details: {+ tasks: tasks.map(function (t, index) {+ return {+ agent: t.agent,+ task: t.task,+ isError: results[index] ? results[index].isError === true : true,+ toolUses: perTask[index].toolUses,+ tokens: perTask[index].tokens,+ };+ }),+ },+ };+ },+ });+}+`;++/**+ * 最终注入的扩展源码 = 主体 + 看门狗段。+ *+ * 看门狗单独成段、拼在最后,是为了让它能在测试里被**原样执行**(真起进程验证"父死子亡"),+ * 而不是只做字符串结构断言。函数声明会提升,所以放在末尾不影响主体调用。+ */+export const CINDY_SUBAGENT_EXTENSION_SOURCE =+ CINDY_SUBAGENT_EXTENSION_BODY + CINDY_SUBAGENT_PARENT_WATCHDOG_SOURCE;diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 2b979ab356..b66126bec8 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -40,6 +40,11 @@ import {CINDY_BRIDGE_EXTENSION_FILENAME,CINDY_BRIDGE_EXTENSION_SOURCE,} from './cindy-bridge-source.js';+import {+ CINDY_SUBAGENT_ENV,+ CINDY_SUBAGENT_EXTENSION_FILENAME,+ CINDY_SUBAGENT_EXTENSION_SOURCE,+} from './cindy-subagent-source.js';import { normalizePiToolForAutoReview } from './auto-review-policy.js';import {createAutoReviewUnavailableNotice,@@ -693,6 +698,13 @@ export class PiAgent extends BaseAgent {path.join(extensionsDir, CINDY_BRIDGE_EXTENSION_FILENAME),CINDY_BRIDGE_EXTENSION_SOURCE,);+ // cindy-subagent extension:与 bridge 并列的独立扩展(职责分离 —— bridge 管权限门与+ // MCP 桥,这个只管子代理)。子进程继承 PI_CODING_AGENT_DIR,因此同样加载 bridge,+ // 权限门对子代理照样生效;递归由扩展内的 depth env 自己截断。+ await fs.writeFile(+ path.join(extensionsDir, CINDY_SUBAGENT_EXTENSION_FILENAME),+ CINDY_SUBAGENT_EXTENSION_SOURCE,+ );// 权限档文件:extension 每次 tool_call 现读(热切换);读不到按 ask fail-closed。const runtimeDir = path.join(agentHome, 'runtime');@@ -704,10 +716,41 @@ export class PiAgent extends BaseAgent {if (sid !== undefined && (sid === '.' || sid === '..' || /[\\/\0]/.test(sid))) {throw new Error(`pi: unsafe sessionId for runtime path: ${JSON.stringify(sid)}`);}+ // 每运行时 nonce —— 与 configHome(`agentHome/run-tmp/<hex>`)同一套隔离思路。+ //+ // dev + 打包版共用同一个 userData、以及 `--passive` 任意多开,都是**明确支持**的工作流+ // (单实例锁按 flavor 分域,passive 完全跳过锁;见 `bootstrap-electron.ts` 的单实例锁注释)。+ // 那种拓扑下 runtimeDir 里只按 sessionId 命名的文件会被另一个**活着的**实例覆盖:+ // - 路由快照被覆盖 → 本实例的父会话还在自己的路由上,它的下一个子代理却按另一个进程的+ // provider 起来 —— 提示词发往用户在**这个**实例里并没选的端点(review);+ // - 权限档被覆盖 → 另一个实例切到 Full Access,本实例的 bridge 下一次 tool_call 现读到+ // bypassPermissions,本实例的破坏性工具不再确认。这是跨实例权限提升,比路由更严重,+ // 属于「本 PR 代码路径会走到的权限类缺陷」,一并收口而不是外推。+ // 代价是文件按 startSession 而非 sessionId 唯一 → 必须显式回收,见 cleanupRuntimeFiles。+ const runtimeInstanceId = randomBytes(8).toString('hex');const permissionFile = path.join(runtimeDir,- `perm-${sid ?? `anon-${process.pid}-${Date.now()}`}.json`,+ `perm-${sid ?? `anon-${process.pid}-${Date.now()}`}-${runtimeInstanceId}.json`,);+ // 子代理运行期快照(model + provider)。与权限档同机制:文件而非 env —— env 在 spawn+ // 时定型,会话中途 setModel 后子代理会继续用启动时的旧模型(greptile P1),而 BYOM /+ // 本地 provider 不一起传还会让同名模型落到错误 endpoint(codex P2,pi-harness §3 要求+ // BYOM 直连原生 provider)。扩展每次派子代理现读本文件。+ const subagentRuntimeFile = path.join(+ runtimeDir,+ `subagent-${sid ?? `anon-${process.pid}-${Date.now()}`}-${runtimeInstanceId}.json`,+ );+ let runtimeFilesCleaned = false;+ /**+ * 回收本运行时的两个 runtime 文件(幂等)。带 nonce 之后它们不再按 sessionId 复用,+ * 不回收就会随每次 startSession 无界堆积在 runtimeDir 里。+ */+ const cleanupRuntimeFiles = (): void => {+ if (runtimeFilesCleaned) return;+ runtimeFilesCleaned = true;+ void fs.rm(permissionFile, { force: true }).catch(() => {});+ void fs.rm(subagentRuntimeFile, { force: true }).catch(() => {});+ };// auto 保留(Cindy 侧 dispatcher 用);bridge 只特判 bypassPermissions,auto 在// 桥内行为同 ask(非只读全部冒泡)。其余档(default/acceptEdits/plan)归 ask 最严。const normalizePermissionMode = (mode: string | undefined): 'ask' | 'auto' | 'bypassPermissions' =>@@ -785,6 +828,66 @@ export class PiAgent extends BaseAgent {};await writePermissionFile(requestedPermissionSnapshot);+ // 子代理运行期快照的写入:代际串行,最新意图胜出(理由同权限档 —— 并发/连续 setModel+ // 时无串行的 writeFile 可能让较早的模型写在较新的之后落盘,子代理就会读到过期模型)。+ //+ // **返回 Promise 且调用方必须 await**:不能 fire-and-forget。startSession 要在会话对外+ // 暴露(模型能调 subagent)**之前**落盘初始 provider/model,否则 BYOM / 本地 provider 或+ // 非默认模型的会话一开始就调子代理时,文件还不存在 → 扩展不传 --provider/--model → 子进程+ // 走 pi 默认解析,直接跑错 endpoint(review)。setModel 同理:切完模型立刻派子代理必须+ // 已经能看到新值。+ //+ // **写失败一律 fail-closed,不许 catch 成功**(review):runtime 目录只读 / 磁盘满时,+ // 若把失败吞成成功,子代理会带着空快照或旧快照继续跑 —— BYOM / 本地 provider 的请求+ // 就发到错误 endpoint 去了。返回 false 表示"本次未能持久化",调用方据此**禁用本次会话+ // 的子代理路由**;失败时还会 best-effort 删掉该文件,让扩展在使用点也失败关闭+ // (它把"读不到快照"当作不可用,而不是退回 pi 默认解析)。+ let subagentRuntimeWriteChain: Promise<void> = Promise.resolve();+ let subagentRuntimeWriteGen = 0;+ /**+ * 首次快照持久化失败 → 本次会话根本不注入 runtime 文件 env,扩展因此不注册 subagent 工具。+ *+ * **只在 spawn 之前有意义**:它的唯一消费点是下面构造 spawnEnv 的那一处。进程一旦起来,改它+ * 既收不回已注入的 env、也拦不住扩展继续读快照文件 —— 所以**禁止**在 setModel 等运行期路径上+ * 用它当"撤销开关"(上一版就是这么用的,那是个空操作,review 连点两轮)。运行期要收回子代理+ * 能力只有一条可证明有效的路:终止会话。+ */+ let subagentRoutingEnabled = true;+ const writeSubagentRuntimeFile = async (+ next: { model?: string; provider?: string; pending?: boolean },+ ): Promise<boolean> => {+ const gen = ++subagentRuntimeWriteGen;+ const snapshot = {+ ...(next.model ? { model: next.model } : {}),+ ...(next.provider ? { provider: next.provider } : {}),+ // `pending: true` = 这条路由**尚未**被 pi 确认。扩展见到它就拒绝派发(fail-closed),+ // 于是模型切换的等待窗口里一个子进程都起不来 —— 详见 setModel 的注释。+ ...(next.pending ? { pending: true } : {}),+ };+ const run = subagentRuntimeWriteChain.then(async (): Promise<boolean> => {+ // 已被更晚的意图取代:旧内容不得在新内容之后落盘(视作成功,最新那次负责收口)。+ if (gen !== subagentRuntimeWriteGen) return true;+ await fs.writeFile(subagentRuntimeFile, JSON.stringify(snapshot) + '\n');+ return true;+ });+ // 链永不停在 rejected 上(同权限档):否则一次写失败后续写永远追加不进去。+ subagentRuntimeWriteChain = run.then(() => {}, () => {});+ try {+ return await run;+ } catch (error) {+ this.deps.logger.error('pi subagent runtime snapshot write failed; disabling subagent routing', {+ message: error instanceof Error ? error.message : String(error),+ });+ // 留着旧内容比没有更危险(会把请求发到过期 provider),删掉让使用点也失败关闭。+ await fs.rm(subagentRuntimeFile, { force: true }).catch(() => {});+ return false;+ }+ };+ // 会话暴露前先落初始快照(await:模型第一次调 subagent 时文件必须已经在)。+ if (!(await writeSubagentRuntimeFile({ model: opts.model, provider: initialProvider }))) {+ subagentRoutingEnabled = false;+ }+// MCP:host 把 in-process providers 暴露成 localhost streamable-HTTP,也可给出// 外部 HTTP server 描述(header 真值另走 mcpEnv,不进入描述符)。// 传 session 身份(sessionId/workingDir/vendorOptions)让 host 在 bridge 上注册@@ -971,6 +1074,12 @@ export class PiAgent extends BaseAgent {...Object.keys(nativeEnv),...Object.keys(mcpEnv),...(mcpBridge && mcpBridge.servers.length > 0 ? [PI_MCP_BRIDGE_ENV] : []),+ // 子代理路由快照:虽然不是凭证,但它是**控制面** —— 一次获批的 bash 拿到路径就能改写+ // provider/model,让后续每次委派都打到攻击者选定的 endpoint(提示词与代码随之外泄)。+ // 与 CINDY_PI_PERMISSION_FILE 同一类:靠改写受信文件给后续调用永久换向(review)。+ // 只从 bash/模型工具的 spawn 边界剥离;子代理自己的 spawn 不走 bridge 的 bash 钩子,+ // 扩展照旧现读快照,能力不受影响。+ CINDY_SUBAGENT_ENV.runtimeFile,]));const spawnEnv: NodeJS.ProcessEnv = {...process.env,@@ -985,6 +1094,13 @@ export class PiAgent extends BaseAgent {[PI_SECRET_ENV_NAMES_ENV]: JSON.stringify(piSecretEnvNames),PI_CODING_AGENT_DIR: configHome,CINDY_PI_PERMISSION_FILE: permissionFile,+ // 子代理:cindy-subagent 扩展据此 spawn 子 pi 进程。给二进制路径而不是让扩展猜+ // process.execPath —— host 本来就知道本次会话用的是哪个 pi。+ [CINDY_SUBAGENT_ENV.binary]: this.deps.binaryPath,+ // 只给文件路径:model/provider 由扩展每次现读,setModel 后立即生效。+ // 快照没能持久化时**不传**该 env —— 扩展据此完全不注册 subagent 工具(fail-closed,+ // 宁可本次会话没有子代理,也不让它带着空/旧快照把请求发到错误 endpoint)。+ ...(subagentRoutingEnabled ? { [CINDY_SUBAGENT_ENV.runtimeFile]: subagentRuntimeFile } : {}),// 嵌入式 runtime 不做启动期联网:关掉 pi 的版本检查与安装遥测// (pi.dev/api/latest-version、report-install)。LLM 请求走 provider 通道不受影响。PI_OFFLINE: '1',@@ -1044,8 +1160,9 @@ export class PiAgent extends BaseAgent {});}}- // 进程已死:隔离的 configHome(models.json + extension)不再被读,清理。+ // 进程已死:隔离的 configHome(models.json + extension)与 runtime 文件不再被读,清理。cleanupConfigHome();+ cleanupRuntimeFiles();queue.end();},});@@ -1056,6 +1173,7 @@ export class PiAgent extends BaseAgent {/* best-effort:注销失败不掩盖原始构造错误 */}cleanupConfigHome();+ cleanupRuntimeFiles();throw err;}@@ -1246,6 +1364,7 @@ export class PiAgent extends BaseAgent {}await proc.close().catch(() => {});cleanupConfigHome();+ cleanupRuntimeFiles();throw err;}@@ -1271,6 +1390,155 @@ export class PiAgent extends BaseAgent {throw new PiImageInputUnsupportedError();};+ /** setModel 的串行闸(见 handle.setModel)。 */+ let setModelChain: Promise<void> = Promise.resolve();+ /**+ * setModel 的临界区正文。经 `setModelChain` 串行化后调用 —— 不要直接调它,+ * 并发进入会让 pending / 落定两次写交错。+ */+ const switchModel = async (+ model: string,+ setOpts?: { providerId?: string | null; effort?: Effort },+ ): Promise<void> => {+ const requestedProviderId = setOpts && Object.hasOwn(setOpts, 'providerId')+ ? setOpts.providerId+ : undefined;+ // 显式选一个启动快照 nativeProviderById 里“无法服务该 model”的 BYOM provider 时 fail+ // closed:要么该 provider 是会话启动后才新增的(不在快照),要么它虽在、但用户编辑+ // 配置后从中删/改了这个 model。两种都会让 resolveProviderForModel 静默回落 cindy 网关;+ // 若该 model id 也在网关目录里则 set_model “成功”、后续 prompt 发往网关而非用户选的+ // 本地/自定义端点(codex review P1)。提示重启会话以刷新启动快照,而不是静默换目的地。+ if (explicitByomUnresolvable(requestedProviderId, model)) {+ throw new Error(+ `pi: BYOM provider '${requestedProviderId}' cannot serve model '${model}' in this session's ` ++ 'startup provider set (provider not present, or it no longer offers this model); restart the ' ++ 'session to use it (refusing to fall back to the Cindy gateway).',+ );+ }+ const provider = resolveProviderForModel(model, requestedProviderId);+ // effort 能力校验必须排在写路由快照**之前**:它会抛错中止本次切换,而快照一旦落盘就+ // 指向了新 provider —— 那正是父子路由分叉的形状(upstream #1451 与本 PR 的合并点)。+ const nextEffortSnapshot = resolveStartupEffortSnapshot(provider, model);+ if (setOpts?.effort) {+ assertStartupEffortAllowed(nextEffortSnapshot, setOpts.effort);+ }+ // 子代理路由快照必须**先落盘、再切 pi 侧模型**,顺序不能反(review)。+ //+ // 上一版是先 set_model 成功、再写快照,写失败就置 `subagentRoutingEnabled = false`。+ // 那个撤销是**无效的**:该标志只在构造 spawnEnv 时读一次(会话启动、进程 spawn 之前),+ // 进程起来之后改它既不能收回已注入的 env、也不能让扩展停止读那个文件。于是"写失败 ++ // 删除也失败"(只读挂载 / 磁盘满)时,父会话已经切到新 provider,而子代理还在按**上一个+ // 有效快照**跑 —— 委派请求发往旧 endpoint,提示词与代码随之外泄到用户并没选的目的地。+ //+ // 改为:写不成就**让整个模型切换失败**,一个字节都不改。父子路由要么一起前进、要么都+ // 不动,不存在"父已切、子没切"的中间态。代价是只读文件系统下切不了模型 —— 那是显式+ // 报错、用户看得见,远好过静默把委派发到错误端点。+ //+ // 但"先落盘"单独还不够。落的若是**新路由**,那么从这一刻到 RPC 回包之间存在一个等待+ // 窗口:pi 侧仍在旧模型上,而这段时间里模型发起的 subagent 派发会现读快照、按新 provider+ // 起子进程。RPC 随后返回 `success: false` 时,回滚快照撤不回已经起来的子进程 —— 它已经+ // 在用一个 pi 明确拒绝了的 endpoint 干活(review)。+ //+ // 所以这一步落的是**带 pending 标记的**新路由:内容已经就位(证明可写、内容可回滚),但+ // 扩展见到 `pending: true` 就拒绝派发。等待窗口里一个子进程都起不来,既不会用未确认的新+ // 路由、也不会用与父不一致的旧路由;确认后再清掉标记放行。+ const previousSnapshot = { model: mutableModel, provider: mutablePiProviderId };+ if (!(await writeSubagentRuntimeFile({ model, provider, pending: true }))) {+ throw new Error(+ 'pi: 无法持久化子代理路由快照,已取消本次模型切换(避免父会话切到新 provider 而子代理仍按旧路由派发)。'+ + '请检查运行目录是否可写后重试。',+ );+ }+ let resp;+ try {+ resp = await proc.request({ type: 'set_model', provider, modelId: model });+ } catch (err) {+ // RPC **reject / 超时 / 写 stdin 失败 / 进程已退出**:与 `success:false` 有本质区别 ——+ // 那种情况我们**知道**没生效,可以回滚;这里我们**不知道** pi 侧到底切没切。+ //+ // 因此两条路都不能走:回滚可能与真实状态正好相反(RPC 其实生效了,回滚后父会话在新+ // 模型、快照指向旧模型);放行则可能相反(RPC 没生效,快照却指向新模型)。任一方向都是+ // 父子路由分叉 —— 下一次委派打到用户并未启用的端点(错误计费 + 提示词外泄)。+ //+ // 也没选"重新读取并校准":`get_state` 在本文件消费的形状里只暴露 `contextWindow`,+ // 拿不到权威的 model / provider 身份;靠未经验证的字段去猜,比直接失败更糟。而且 RPC+ // 刚超时,紧接着再发一条 RPC 很可能同样挂住。+ //+ // 所以按 fail-closed 收口:终止会话,让这个 pi 进程不再有下一次派发。快照**刻意**保持+ // `pending: true` 不动:它既不是已确认的新路由、也不是旧路由,扩展会一律拒绝派发 ——+ // 这条路径上留着 pending 正是我们想要的终态,不要"顺手"回滚成旧值。+ deps.logger.error('pi: set_model RPC did not confirm; terminating session to avoid split subagent routing', {+ message: err instanceof Error ? err.message : String(err),+ });+ try {+ await proc.close();+ } catch (closeErr) {+ deps.logger.warn('pi: session termination after unconfirmed set_model also failed', {+ message: closeErr instanceof Error ? closeErr.message : String(closeErr),+ });+ }+ throw new Error(+ 'pi: 模型切换请求未收到确认(超时或链路错误),无法确定 pi 侧是否已生效;'+ + '已终止本会话以避免子代理按不确定的路由派发。请重开会话后再切换模型。',+ );+ }+ if (!resp.success) {+ // pi 侧没切成:快照必须回滚成上一份**已确认**的路由,否则子代理会一直被 pending 挡住。+ // 这次回滚是安全的 —— 等待窗口里 pending 标记挡住了全部派发,不存在"已经起来的子进程+ // 正在用被拒绝的 provider"这种撤不回的状态(review)。+ if (!(await writeSubagentRuntimeFile(previousSnapshot))) {+ // 回滚也失败(第一次写成功之后文件系统才转只读之类):此刻盘上的快照指向**被拒绝的**+ // provider/model,而父会话仍在旧路由 —— 子代理的下一次派发就会打到用户并未启用的+ // 端点(错误计费 + 提示词与仓库上下文外泄)。+ //+ // 这里**不能**再退回 `subagentRoutingEnabled = false`(上一版就是这么写的,而它是个+ // 空操作,我在上面的注释里已经承认过):该标志只在构造 spawnEnv 时读一次,进程早就+ // 起来了,改它既收不回已注入的 env,也拦不住扩展继续读那个文件。删除文件同样已经+ // 试过并失败 —— 使用点的 fail-closed 因此也指望不上。+ //+ // 写不了、删不掉,唯一还能保证的手段就是**让这个 pi 进程不再有下一次派发**:直接+ // 终止会话。代价明确(会话中断,用户要重开),但它是可证明有效的;继续跑下去的代价+ // 是把提示词发到错误端点,那个不可接受。+ deps.logger.error(+ 'pi: set_model failed and the subagent routing snapshot could not be rolled back; '+ + 'terminating the session because subagent delegation would otherwise route to the rejected provider',+ );+ try {+ await proc.close();+ } catch (err) {+ deps.logger.warn('pi: session termination after routing rollback failure also failed', {+ message: err instanceof Error ? err.message : String(err),+ });+ }+ throw new Error(+ 'pi: 模型切换失败且子代理路由快照无法回滚,已终止本会话以避免委派请求发往未启用的端点。'+ + '请检查运行目录是否可写后重开会话。',+ );+ }+ throw new Error(`pi set_model failed: ${resp.error ?? 'unknown'}`);+ }+ // pi 已确认 → 清掉 pending 标记放行派发。写失败时**不**抛错:模型切换本身确实成功了,+ // 谎报失败会让上层与 UI 状态和 pi 真实状态背离。代价是这个会话的子代理一直被 pending+ // 挡住(可见的降级、拒绝时有明确文案),而它是安全方向 —— 绝不会把委派发到错误 endpoint。+ if (!(await writeSubagentRuntimeFile({ model, provider }))) {+ deps.logger.error(+ 'pi: model switch confirmed but the subagent routing snapshot stayed pending; '+ + 'subagent delegation stays disabled for this session (fail-closed)',+ );+ }+ mutableModel = model;+ mutablePiProviderId = provider;+ activeEffortSnapshot = nextEffortSnapshot;+ if (setOpts && Object.hasOwn(setOpts, 'providerId')) mutableProviderId = setOpts.providerId;+ autoReviewDecisionCache.clear();+ // 换模型 / 换路由可能正好修掉了审阅器不可用的原因;换完又不可用值得再提醒一次。+ autoReviewUnavailableNotice.reset();+ const data = (resp.data ?? {}) as { contextWindow?: number };+ if (typeof data.contextWindow === 'number' && data.contextWindow > 0) {+ ctx.contextWindow = data.contextWindow;+ }+ };+const handle: AgentSessionHandle = {// getter 而非固定值:setModel / commitRewindFiles 会更新闭包里的 mutableModel /// sdkSessionId,Session.model / Session.sdkSessionId 直读这两个 handle 属性 ——@@ -1352,8 +1620,9 @@ export class PiAgent extends BaseAgent {});}await proc.close();- // 会话结束:清理隔离的 configHome(onExit 幂等,二者先到先清)。+ // 会话结束:清理隔离的 configHome 与 runtime 文件(onExit 幂等,二者先到先清)。cleanupConfigHome();+ cleanupRuntimeFiles();},events(): AsyncIterable<AgentEvent> {@@ -1369,39 +1638,14 @@ export class PiAgent extends BaseAgent {},async setModel(model: string, setOpts?: { providerId?: string | null; effort?: Effort }): Promise<void> {- const requestedProviderId = setOpts && Object.hasOwn(setOpts, 'providerId')- ? setOpts.providerId- : undefined;- // 显式选一个启动快照 nativeProviderById 里“无法服务该 model”的 BYOM provider 时 fail- // closed:要么该 provider 是会话启动后才新增的(不在快照),要么它虽在、但用户编辑- // 配置后从中删/改了这个 model。两种都会让 resolveProviderForModel 静默回落 cindy 网关;- // 若该 model id 也在网关目录里则 set_model “成功”、后续 prompt 发往网关而非用户选的- // 本地/自定义端点(codex review P1)。提示重启会话以刷新启动快照,而不是静默换目的地。- if (explicitByomUnresolvable(requestedProviderId, model)) {- throw new Error(- `pi: BYOM provider '${requestedProviderId}' cannot serve model '${model}' in this session's ` +- 'startup provider set (provider not present, or it no longer offers this model); restart the ' +- 'session to use it (refusing to fall back to the Cindy gateway).',- );- }- const provider = resolveProviderForModel(model, requestedProviderId);- const nextEffortSnapshot = resolveStartupEffortSnapshot(provider, model);- if (setOpts?.effort) {- assertStartupEffortAllowed(nextEffortSnapshot, setOpts.effort);- }- const resp = await proc.request({ type: 'set_model', provider, modelId: model });- if (!resp.success) throw new Error(`pi set_model failed: ${resp.error ?? 'unknown'}`);- mutableModel = model;- mutablePiProviderId = provider;- activeEffortSnapshot = nextEffortSnapshot;- if (setOpts && Object.hasOwn(setOpts, 'providerId')) mutableProviderId = setOpts.providerId;- autoReviewDecisionCache.clear();- // 换模型 / 换路由可能正好修掉了审阅器不可用的原因;换完又不可用值得再提醒一次。- autoReviewUnavailableNotice.reset();- const data = (resp.data ?? {}) as { contextWindow?: number };- if (typeof data.contextWindow === 'number' && data.contextWindow > 0) {- ctx.contextWindow = data.contextWindow;- }+ // 会话级串行闸:整段"写待切换快照 → set_model RPC → 落定/回滚"必须是一个临界区。+ // 并发或连点切换(本地 + 远程控制端同时切)若交错,A 写 pending、B 写 pending、A 落定 B 的+ // 内容,盘上就会出现没人确认过的组合。串行化之后每次切换都看到确定的前一状态,+ // `previousSnapshot` 才是真正可回滚的那一份(review)。+ const run = setModelChain.then(() => switchModel(model, setOpts));+ // 链永不停在 rejected 上:一次失败之后的切换仍要能排进来。+ setModelChain = run.then(() => {}, () => {});+ return run;},async setEffort(effort: Effort): Promise<void> {diff --git a/packages/maker-core/src/agents/pi/subagent-progress.ts b/packages/maker-core/src/agents/pi/subagent-progress.tsnew file mode 100644index 0000000000..6bf3e02f0f--- /dev/null+++ b/packages/maker-core/src/agents/pi/subagent-progress.ts@@ -0,0 +1,156 @@+/**+ * PI 子代理进度:把工具流式中间结果翻成统一的子代理卡更新。+ *+ * pi 原生没有子代理(上游 usage/security 文档明说刻意不做),社区实现一律是「扩展 + 子+ * pi 进程」。Cindy 不整包引入外部扩展 —— 那会把第三方代码塞进 `pi-harness.md` §4.2 划定+ * 的自包含注入边界,还要跟着上游版本跑。做法是参考社区设计,在 Cindy 自有扩展里重做。+ *+ * 通道选的是 pi 工具**原生的** `onUpdate` 流(→ `tool_execution_update` 事件),不另开+ * 侧信道:+ * - `tool_execution_start` / `_end` 已由 translator 推成 `tool_use` / `tool_result`,+ * 工具名 `subagent` 命中 `isAgentTaskToolName` → 卡片生命周期本就成立;+ * - 缺的只是运行期的 tokens / 工具调用数 / 耗时,正好由 `_update` 的 partialResult 带。+ * - `_update` 此前是空处理,挂进来是纯增量,不改任何既有行为。+ *+ * 卡片本体与 Claude / Codex 子代理共用 `AgentTaskCard`,这里只补齐 pi 侧数据,不引入新+ * 的 UI 概念。+ */++import type { AgentTaskUpdateEventData } from '../../types/events.js';++/** 子代理卡状态(`AgentTaskStatus` 的子集)。 */+export type PiSubagentStatus = 'running' | 'completed' | 'failed' | 'stopped';++const STATUSES = new Set<PiSubagentStatus>(['running', 'completed', 'failed', 'stopped']);++/** 单条上报的最大字符数:防子代理把长输出经进度帧灌进事件流。 */+const MAX_TEXT = 2_000;++/** 扩展与本模块共用的载荷标记 —— 扩展源码里逐字使用同一个键名。 */+export const PI_SUBAGENT_PROGRESS_MARKER = '__cindySubagent';++/**+ * 子代理的**累计**用量分量(与 pi 自己的 `message_end.usage` 同形)。+ *+ * 子代理是独立 pi 进程,它的请求不经过父进程的 usage 流 —— 不显式并进来,父 turn 的记账+ * 与 register.ts 持久化的 session token/cost 就会漏掉全部委派用量(review)。+ */+export interface PiSubagentUsage {+ input: number;+ output: number;+ cacheRead: number;+ cacheWrite: number;+ cost: number;+}++/**+ * parse 结果:卡片更新 + 可选的委派用量。+ *+ * 字段刻意叫 `delegatedUsage` 而不是 `usage`:`update.usage` 已经是**卡片**要显示的+ * {totalTokens, toolUses, durationMs},两个都叫 usage 极易读错(我自己在改测试时就先踩了+ * 一次)。这里是给父 turn 记账用的 token/cost 分量,语义完全不同。+ */+export interface PiSubagentProgress {+ update: AgentTaskUpdateEventData;+ /** 累计值,不是增量。调用方按 taskId 记住上次值再作差。 */+ delegatedUsage?: PiSubagentUsage;+}++function readUsage(value: unknown): PiSubagentUsage | undefined {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;+ const raw = value as Record<string, unknown>;+ const read = (key: string): number => {+ const n = raw[key];+ return typeof n === 'number' && Number.isFinite(n) && n > 0 ? n : 0;+ };+ const usage: PiSubagentUsage = {+ input: read('input'),+ output: read('output'),+ cacheRead: read('cacheRead'),+ cacheWrite: read('cacheWrite'),+ cost: read('cost'),+ };+ // 全零就当没有:避免为无意义的帧在父侧建立 taskId 记账条目。+ if (!usage.input && !usage.output && !usage.cacheRead && !usage.cacheWrite && !usage.cost) {+ return undefined;+ }+ return usage;+}++function readString(value: unknown, max = MAX_TEXT): string | undefined {+ if (typeof value !== 'string') return undefined;+ const trimmed = value.trim();+ if (!trimmed) return undefined;+ return trimmed.length > max ? `${trimmed.slice(0, max - 1)}…` : trimmed;+}++function readCount(value: unknown): number | undefined {+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return undefined;+ return Math.floor(value);+}++/**+ * 从 `tool_execution_update` 的 partialResult 里取子代理进度。+ *+ * 入参是工具中间结果本体(`{ content?, details? }`);标记与数据都在 `details` 下。+ * 返回 null = 与子代理无关(别的工具在流式、载荷不带标记、缺 taskId),调用方原样忽略。+ *+ * 刻意不猜:状态不在白名单内一律按 running,而不是编造终态 —— 把仍在跑的子代理显示成+ * 已完成比没有状态更糟。+ */+export function parsePiSubagentProgress(partialResult: unknown): PiSubagentProgress | null {+ const raw = readProgressDetails(partialResult);+ if (!raw) return null;++ // taskId 是卡片/tool_use 的关联键,**只 trim 不截断**:截断+省略号会改写 id,+ // 后续 update 再也命中不到同一张卡(表现为卡片不更新或另开一张)。+ const taskId = typeof raw.taskId === 'string' ? raw.taskId.trim() : '';+ if (!taskId) return null;++ const status: PiSubagentStatus = STATUSES.has(raw.status as PiSubagentStatus)+ ? (raw.status as PiSubagentStatus)+ : 'running';++ const totalTokens = readCount(raw.totalTokens);+ const toolUses = readCount(raw.toolUses);+ const durationMs = readCount(raw.durationMs);+ const usage = totalTokens !== undefined || toolUses !== undefined || durationMs !== undefined+ ? {+ ...(totalTokens !== undefined ? { totalTokens } : {}),+ ...(toolUses !== undefined ? { toolUses } : {}),+ ...(durationMs !== undefined ? { durationMs } : {}),+ }+ : undefined;++ const title = readString(raw.agentName, 96);+ const description = readString(raw.task);+ const summary = readString(raw.summary);+ const model = readString(raw.model, 200);++ const delegatedUsage = readUsage(raw.usage);++ return {+ update: {+ provider: 'pi',+ taskId,+ parentToolUseId: taskId,+ status,+ ...(title ? { title } : {}),+ ...(description ? { description } : {}),+ ...(summary ? { summary } : {}),+ ...(model ? { model } : {}),+ ...(usage ? { usage } : {}),+ },+ ...(delegatedUsage ? { delegatedUsage } : {}),+ };+}++function readProgressDetails(partialResult: unknown): Record<string, unknown> | null {+ if (!partialResult || typeof partialResult !== 'object' || Array.isArray(partialResult)) return null;+ const details = (partialResult as { details?: unknown }).details;+ if (!details || typeof details !== 'object' || Array.isArray(details)) return null;+ const raw = details as Record<string, unknown>;+ // 标记必须逐字命中:别的工具流式上报恰好带 details 时不得被误认成子代理进度。+ if (raw[PI_SUBAGENT_PROGRESS_MARKER] !== 1) return null;+ return raw;+}diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex 8af504a5e5..c1be326d88 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -19,6 +19,7 @@ import type { Logger } from '../../interfaces/logger.js';import type { AgentEvent, UsageSnapshot } from '../../types/index.js';import type { AsyncQueue } from '../shared/async-queue.js';import type { PiRpcEvent } from './rpc-client.js';+import { parsePiSubagentProgress, type PiSubagentUsage } from './subagent-progress.js';interface PiUsage {input?: number;@@ -70,6 +71,11 @@ export interface PiTranslateContext {* 不带上就会对 Pi 静默跳过这些钩子(codex review P1)。*/finalAssistantText: string;+ /**+ * 每个子代理调用(taskId)最近一次上报的**累计**委派用量。进度帧报累计值,这里存上次值+ * 用来算增量,避免同一批用量被反复加进 turn 记账。与其它 turn 计数器同点(agent_start)清空。+ */+ delegatedUsage: Map<string, PiSubagentUsage>;}export function createPiTranslateContext(logger: Logger): PiTranslateContext {@@ -87,6 +93,7 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {thinkingSeq: 0,thinkingBlocks: new Map(),finalAssistantText: '',+ delegatedUsage: new Map(),};}@@ -128,6 +135,38 @@ function applyUsage(ctx: PiTranslateContext, usage: PiUsage | undefined): void {if (typeof cost === 'number' && Number.isFinite(cost)) ctx.costUsd += cost;}+/**+ * 把子代理(委派)的用量并进本 turn 的记账。+ *+ * 进度帧报的是**累计**值(丢一帧不该让那段用量永久消失),所以这里按 taskId 记住上次值、+ * 只加增量。回退的累计值(理论上不该出现)按 0 处理,绝不产生负增量。+ *+ * 刻意**不动 `ctx.contextTokens`**:那是"最后一次 API 调用占了多少上下文",而子代理有它+ * 自己独立的上下文窗口 —— 混进来会让父会话的上下文占用条读数虚高。+ */+function applyDelegatedUsage(+ ctx: PiTranslateContext,+ taskId: string,+ cumulative: PiSubagentUsage | undefined,+): void {+ if (!cumulative || !taskId) return;+ const previous = ctx.delegatedUsage.get(taskId);+ const delta = {+ input: Math.max(0, cumulative.input - (previous?.input ?? 0)),+ output: Math.max(0, cumulative.output - (previous?.output ?? 0)),+ cacheRead: Math.max(0, cumulative.cacheRead - (previous?.cacheRead ?? 0)),+ cacheWrite: Math.max(0, cumulative.cacheWrite - (previous?.cacheWrite ?? 0)),+ cost: Math.max(0, cumulative.cost - (previous?.cost ?? 0)),+ };+ ctx.delegatedUsage.set(taskId, cumulative);+ ctx.turnTokens += delta.input + delta.output;+ ctx.turnInput += delta.input;+ ctx.turnOutput += delta.output;+ ctx.turnCacheRead += delta.cacheRead;+ ctx.turnCacheWrite += delta.cacheWrite;+ ctx.costUsd += delta.cost;+}+function assistantTextOf(message: PiAssistantMessage): string {const parts: string[] = [];for (const block of message.content ?? []) {@@ -190,6 +229,9 @@ export function translatePiEvent(ctx.turnCacheRead = 0;ctx.turnCacheWrite = 0;ctx.finalAssistantText = '';+ // 与其它 turn 计数器同点清:新 turn 的委派用量不该跟上一 turn 的累计值作差,+ // 也避免长会话里 taskId 条目无界堆积。+ ctx.delegatedUsage.clear();pushStatus(queue, ctx, 'Working…', true);return;}@@ -246,8 +288,20 @@ export function translatePiEvent(return;}- case 'tool_execution_update':+ case 'tool_execution_update': {+ // 子代理卡的实时状态:`subagent` 工具用 pi 原生的 onUpdate 流上报 tokens /+ // 工具调用数 / 耗时(卡片的 tool_use / tool_result 由 start / end 分支承载)。+ // 其它工具的流式中间结果照旧忽略 —— 载荷不带标记时 parse 返回 null。+ const progress = parsePiSubagentProgress(event.partialResult);+ if (progress) {+ // 委派用量并进本 turn 的记账。子代理是独立 pi 进程,它的请求不走父进程的 usage 流,+ // 不在这里显式并进来,done.data.usage 与 register.ts 持久化的 session token/cost+ // 就会漏掉全部子代理花费(review)。+ applyDelegatedUsage(ctx, progress.update.taskId, progress.delegatedUsage);+ queue.push({ type: 'agent_task_update', data: progress.update, source: 'pi' });+ }return;+ }case 'tool_execution_end': {const toolUseId = String(event.toolCallId ?? '');diff --git a/packages/maker-shared/src/__tests__/agentTask.test.ts b/packages/maker-shared/src/__tests__/agentTask.test.tsindex 599e909d04..253b0edf28 100644--- a/packages/maker-shared/src/__tests__/agentTask.test.ts+++ b/packages/maker-shared/src/__tests__/agentTask.test.ts@@ -5,6 +5,7 @@ import {findAgentTaskUpdate,isAgentTaskToolName,mergeAgentTaskUpdate,+ PI_SUBAGENT_TOOL_NAME,normalizeAgentTaskUpdate,normalizeWorkflowProgressEntries,type AgentTaskUpdate,@@ -22,6 +23,19 @@ describe('isAgentTaskToolName', () => {expect(isAgentTaskToolName('TodoWrite')).toBe(false);expect(isAgentTaskToolName('')).toBe(false);});++ it('matches the PI subagent tool so its card renders like Claude / Codex', () => {+ // 这条判据是三家 harness 唯一的卡片入口:漏了 PI 的工具名,子代理调用会**静默**落进普通+ // 工具组 —— 不报错、不缺数据,只是卡片不出现,极难从日志发现(review 要求补覆盖)。+ expect(isAgentTaskToolName(PI_SUBAGENT_TOOL_NAME)).toBe(true);+ // 用字面量再钉一次:常量与判据一起被改坏时,只断言常量的测试会一起变绿。+ expect(isAgentTaskToolName('subagent')).toBe(true);+ expect(PI_SUBAGENT_TOOL_NAME).toBe('subagent');+ // 大小写与近似名不得误命中(pi 工具名是精确匹配,不是前缀/模糊)。+ expect(isAgentTaskToolName('Subagent')).toBe(false);+ expect(isAgentTaskToolName('subagents')).toBe(false);+ expect(isAgentTaskToolName('sub-agent')).toBe(false);+ });});describe('normalizeAgentTaskUpdate', () => {diff --git a/packages/maker-shared/src/agentTask.ts b/packages/maker-shared/src/agentTask.tsindex 9cae6009c8..2da9e4ebd3 100644--- a/packages/maker-shared/src/agentTask.ts+++ b/packages/maker-shared/src/agentTask.ts@@ -152,11 +152,22 @@ export interface AgentTaskUpdate {updatedAt?: string;}-/** Tool names that spawn a sub-agent task: Claude `Task`/`Agent`, Codex collab agents. */+/**+ * Tool names that spawn a sub-agent task: Claude `Task`/`Agent`, Codex collab agents,+ * PI `subagent`(Cindy 自有扩展注册的工具名,与 pi 社区惯例一致)。+ *+ * MCP 工具一律带 `mcp__` 前缀,不会与裸 `subagent` 撞名。+ */export function isAgentTaskToolName(toolName: string): boolean {- return toolName === 'Agent' || toolName === 'Task' || toolName.startsWith('collab:');+ return toolName === 'Agent'+ || toolName === 'Task'+ || toolName === PI_SUBAGENT_TOOL_NAME+ || toolName.startsWith('collab:');}+/** PI 子代理工具名 —— maker-core 的 pi 扩展注册端与本文件的卡片判据共用,不各写字面量。 */+export const PI_SUBAGENT_TOOL_NAME = 'subagent';+/*** Validate + shape a raw `agent_task_update` event payload into an `AgentTaskUpdate`.* Returns null when neither a taskId nor a parentToolUseId is present (un-linkable).@@ -354,7 +365,12 @@ export function buildAgentTaskCardModel(input: {const { toolName, toolInput, update, result } = input;const status: AgentTaskStatus = update?.status ?? (result ? 'completed' : 'running');const provider: 'claude-code' | 'codex' | 'pi' =- update?.provider ?? (toolName?.startsWith('collab:') ? 'codex' : 'claude-code');+ update?.provider+ ?? (toolName?.startsWith('collab:')+ ? 'codex'+ : toolName === PI_SUBAGENT_TOOL_NAME+ ? 'pi'+ : 'claude-code');const title = compactText(update?.title?? readInputString(toolInput, ['description', 'task', 'name'])