Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): 完善子代理控制与结果回传
zqchrisea45fddb8e3c
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 4875a24442..29078c7246 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -68,6 +68,8 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi时从本机 session JSONL 校正(只打开启动时 `--session-dir` 真身内的普通文件,并有字节/时间预算,超限回退 RPC);远端仍走 `get_entries`。+> Cindy 自有子代理的委派、控制、结果收口与测试边界见 [Pi 子代理设计](../research/pi-subagent-delegation.md)。与 Orca 协作模式分别维护。+### 原生请求 Fast 偏好支持 Fast 的原生模型在 `before_provider_request` 中经现有 RPC 通道发出diff --git a/docs/research/pi-subagent-delegation.md b/docs/research/pi-subagent-delegation.mdnew file mode 100644index 0000000000..f7c9805c4b--- /dev/null+++ b/docs/research/pi-subagent-delegation.md@@ -0,0 +1,124 @@+# Pi 子代理:委派、控制与结果收口++核对版本:Cindy `5888d140db`;Pi 原生运行时 `1.0.2`。++## 范围++这里讨论父 Pi 模型调用 `subagent` 后启动的独立 Pi 子会话。实现入口是+`cindy-subagent-source.ts`、`cindy-subagent-runner-source.ts`、+`pi-subagent-runs.ts` 和 `PiAgent`。Orca 的跨 Agent 协作、伙伴委派及其 UI+不构成本工具能力的证据。++沿用 Cindy 的持久 runner、原生 RPC、独立 session、审批转发和现有子代理卡。+模型控制与界面控制共用同一份持久状态和 resume 实现。++## 对标与取舍++对照社区 [pi-subagents 工具契约](https://github.com/nicobailon/pi-subagents/blob/main/docs/tool-reference.md)、+[扩展生命周期](https://github.com/nicobailon/pi-subagents/blob/main/src/extension/index.ts) 和+[后台通知](https://github.com/nicobailon/pi-subagents/blob/main/src/runs/background/notify.ts)。+社区包的 main 会继续变化;本文采用的原则是可定位子代理、明确区分插话与续跑、+后台结果可靠进入父模型、投递后才确认消费。++| 环节 | 原有缺口 | 本次实现 |+| --- | --- | --- |+| 能力发现 | 角色名在工具说明里,模型难以系统查询 | `capabilities` 返回角色、工具、可选型号与并发限制 |+| 启动 | runId 仅在 details,模型收到笼统启动回执 | 文本回执带 runId/taskId |+| 控制 | 模型只能针对整个 run;写入邮箱就宣称成功 | `childId` 定向,等待 runner receipt,拒绝与不确定分别报告 |+| 等待 | 只能反复 get | `wait` 最长 60 秒,超时不终止子代理 |+| 插话 | 中间说明文字被误认作最终结果 | 用 `resultReady` 标记真实无工具终答,新 generation 清零 |+| 续跑 | UI 能继续,模型不能 | `resume` 共用 host 续跑函数,新 runId、原 sessionId |+| 回传 | 后台结果只更新卡片,不进入父模型 | 在 Pi 原生结束前边界收集结果并继续父模型 |+| fork | 原始分支前 32K 字符丢掉最新纠正 | 原生投影视图,优先最新用户要求、摘要与最近证据 |+| 诊断 | 中间输出可能遮住最终错误 | 同时返回输出与失败原因 |++本次保留四种内置角色、一层子代理、每次最多 8 个子任务、每个 run 最多 4 个并发。+未新增多层嵌套、工作流脚本、任意扩展/MCP 继承、自定义角色文件或 SSH 子代理。+这些能力应分别设计:角色/工具配置需可视化;继承资源须与 Pi 原生装配一致;+远端执行须在任务所在设备管理状态、审批、会话与 runner,不能读取控制端的同名目录。+不以调整宿主审批或修改 Pi 二进制实现这些能力。++## 模型工具契约++- `run`:原有前台/后台执行。`async:true` 允许父模型同时做其它工作;+ 默认在父轮结束前收集结果。`notify:false` 显式脱离收口,之后用 `wait/get`。+- `list/get`:列出当前 runtime owner 的 run、childId、状态与有预算的结果。+ 完整读取一个终态 run 后,取消该 run 尚未投递的自动通知;单个 child 的读取不吞掉兄弟结果。+- `wait`:可选 childId;0–60 秒(默认 30)。取消只取消等待;不暗中停止 child。+- `steer`:修改活跃 generation 的方向;中间说明 + toolCall 仍可接受。+- `follow_up`:给仍存活的 run 排队下一轮要求。终态 run 明确指向 `resume`。+- `resume`:terminal run 才可继续,支持 childId;共用 UI 的恢复路径、审批快照、+ 路由、会话目录校验和启动 fence。返回新 runId,保留原 child session。+- `stop`:支持 childId;已终态幂等返回。停止整个 run 仍沿用 runner 的停止优先级。++控制回执表示 **runner 接受并写入子 Pi RPC/待启动队列**,不承诺模型已经理解要求。+回执拒绝时返回错误;发出后取消、5 秒内没有回执时报告「投递不确定」和 requestId,+不自动重发,避免重复执行。旧 runner 的回执协议保持兼容。++## 生命周期与结果通知++```mermaid+sequenceDiagram+ participant P as 父 Pi 模型+ participant E as Cindy subagent 扩展+ participant R as 持久 runner+ participant N as Pi 原生会话+ P->>E: run async:true+ E->>R: 启动子会话+ E-->>P: runId+ P->>P: 继续处理其它工作+ N->>E: agent_before_settle+ E->>E: 检查宿主停止/关闭状态+ R-->>E: 终态结果+ E-->>N: custom_message + continue+ N->>P: 携带子结果继续+ P-->>N: 汇总+ N-->>N: agent_settled+```++采用 Pi 1.0.2 的+[`agent_before_settle`](https://github.com/earendil-works/pi/blob/v1.0.2/packages/coding-agent/src/core/agent-session.ts)+与原生 boundary drafts,不在已结束的任务之外伪造用户输入或启动另一套调度器。+因此父轮的权限来源、用量生命周期与最终 done 边界继续由 Pi/PiAgent 管理。++- 待投递意图记在原生 custom entry;结果通过 custom message 持久化。+ 从当前分支恢复时,已投递/已消费的 run 不再通知。+- 父轮已经 abort/error 时不追加自动继续;结束前等待中定期查询 host gate,+ 用户停止、关闭或账号边界会撤销本轮通知。原生 Pi 再检查一次等待期间的 abort。+- 新输入优先于收集等待。`agent_settled` 清除未投递意图,防止下一次不相关输入复活旧通知。+- 导航关闭不会终止明确后台运行的 child;重新打开后的显式交流可按原生分支恢复待收集记录。+ 不会因为 child 在无人查看时完成就自行唤醒已空闲的父任务。+- 结果按当前输出预算截断;多个同时完成的 run 共用一次 32K 字符预算。+ runner 退出诊断立即回传;收集期限以 run timeout 加宽限为界。+ 超时缺少终态时明确报告状态未知,不谎称子代理已停止。++## fork 与数据边界++使用 `buildSessionProjection().messages`,兼容可用的原生 context projection 接口;+不从未经压缩/编辑处理的 `getBranch()` 重建模型内容。无法取得投影视图时提示使用 fresh。++最多 32K 字符:优先最新用户消息(长消息同时保留头尾)、最近压缩摘要,+再从最近往前补充消息及工具结果。保留时间顺序;不复制 system/thinking,+图片用省略标记表示。原始 assignment 单独保留,不能因快照预算截掉末尾指示。++所有查询/控制继续绑定 runtime owner 和具体 run;childId 必须属于该 run。+不扩大子代理工具、凭证、隐式扩展与审批权限。++## 验证证据++行为测试直接编译执行生成扩展;runner 测试启动真实 Node runner 与可控 RPC 子进程。+覆盖最新纠正/压缩投影、真实控制回执、单 child、等待超时、所有权隔离、续跑、+结果去重、取消不唤醒、runner 崩溃和失败诊断。PiAgent 生命周期测试验证模型续跑与+UI 共用路径、停止 gate,以及关闭等待在途 resume 后才转交资源租约。++2026-10-08 本机另外运行经仓库 SHA256 校验的官方 Pi 1.0.2 父子进程,使用本地+OpenAI SSE 测试服务、虚拟凭证和隔离 HOME,验证:++1. 子代理发出说明文字并执行 bash 时,纠正请求得到 accepted 回执,随后进入真实子模型请求。+2. 后台结果进入父模型请求,父轮最终只出现一次 `agent_settled`。+3. resume 保持原 sessionId,子请求同时包含旧结果与新指示。+4. 停止父轮后,child 可独立完成,但没有新增父模型请求。+5. 长历史后的最新纠正进入 fork 子请求。++这证明原生 RPC、会话与扩展链路行为;不是外部模型质量评测,也不是打包 Desktop GUI、+Windows 或 SSH 的实机验收。发布前仍以 CI 与实际分发版本验收为准。diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.tsnew file mode 100644index 0000000000..715a135288--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentDelegation.test.ts@@ -0,0 +1,208 @@+import { randomUUID } from 'node:crypto';+import { createRequire } from 'node:module';+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import ts from 'typescript';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { CINDY_SUBAGENT_EXTENSION_SOURCE } from '../cindy-subagent-source.js';++// Execute the exact staged extension, including its filesystem mailbox and+// lifecycle handlers. Export helpers only in this test's in-memory module.+const compiled = ts.transpileModule(CINDY_SUBAGENT_EXTENSION_SOURCE + '\nexport { parentContextSnapshot, createResultDelivery };', {+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },+}).outputText;+const extension: any = {};+new Function('require', 'exports', compiled)(createRequire(import.meta.url), extension);+const roots: string[] = [];+afterEach(async () => {+ vi.unstubAllEnvs();+ await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })));+});+async function fixture() {+ const root = await mkdtemp(path.join(os.tmpdir(), 'pi-delegation-'));+ roots.push(root);+ vi.stubEnv('CINDY_PI_SUBAGENT_RUN_ROOT', root);+ vi.stubEnv('CINDY_PI_SUBAGENT_OWNER_ID', 'owner');+ vi.stubEnv('CINDY_PI_SUBAGENT_BINARY', '/fixture/pi');+ vi.stubEnv('CINDY_PI_SUBAGENT_RUNTIME_FILE', path.join(root, 'runtime.json'));+ await writeFile(path.join(root, 'runtime.json'), JSON.stringify({ modelRoutes: { 'available-model': [] } }));+ const runId = randomUUID();+ const dir = path.join(root, runId);+ await mkdir(dir);+ const status = { version: 1, runId, taskId: 'tool-call', runtimeOwnerId: 'owner', state: 'running',+ tasks: [1, 2].map(n => ({ childId: 'child-' + n, agent: 'worker', status: 'running', output: 'interim text' })) };+ const publish = () => writeFile(path.join(dir, 'status.json'), JSON.stringify(status));+ await publish();+ const hooks: Record<string, (...args: any[]) => any> = {};+ let tool: any;+ const pi = { on: (event: string, handler: any) => { hooks[event] = handler; }, appendEntry: vi.fn(),+ registerTool: (value: any) => { tool = value; } };+ await extension.default(pi);+ const ctx = { ui: { input: vi.fn(async (_title: string, _payload: string) => JSON.stringify({ ok: true })) },+ sessionManager: { getBranch: () => [] }, hasPendingMessages: () => false };+ const execute = (params: any, signal = new AbortController().signal) => tool.execute('control-id', params, signal, undefined, ctx);+ return { root, runId, dir, status, publish, hooks, pi, ctx, execute };+}+const boundary = { outcome: 'completed', context: { pendingMessages: [] } };++describe('Pi delegation behavior', () => {+ it('forks the native projected context, prioritizing the latest correction and compaction summary', () => {+ const snapshot = extension.parentContextSnapshot({ sessionManager: {+ getBranch: () => { throw new Error('Raw branch resurrects discarded content'); },+ buildSessionProjection: () => ({ messages: [+ { role: 'system', content: 'SYSTEM_NOT_COPIED' },+ { role: 'user', content: 'OLD_CONTEXT ' + 'x'.repeat(40000) },+ { role: 'compactionSummary', summary: 'DECISIONS_RETAINED' },+ { role: 'assistant', content: [{ type: 'thinking', thinking: 'PRIVATE_THINKING' }] },+ { role: 'toolResult', toolName: 'read', content: [{ type: 'text', text: 'LATEST_FILE_EVIDENCE' }] },+ { role: 'user', content: 'LATEST_REQUEST ' + 'a'.repeat(20000) + ' FINAL_CORRECTION' },+ ] }),+ } });+ expect(snapshot).toContain('LATEST_REQUEST');+ expect(snapshot).toContain('FINAL_CORRECTION');+ expect(snapshot).toContain('DECISIONS_RETAINED');+ expect(snapshot).toContain('LATEST_FILE_EVIDENCE');+ expect(snapshot).not.toContain('SYSTEM_NOT_COPIED');+ expect(snapshot).not.toContain('PRIVATE_THINKING');+ expect(snapshot.length).toBeLessThanOrEqual(32000);+ });++ it('refuses to silently fork an unprojectable raw session', () => {+ expect(() => extension.parentContextSnapshot({ sessionManager: { getBranch: () => [] } })).toThrow('context:fresh');+ });++ it('wait times out without stopping children and rejects a foreign child id', async () => {+ const f = await fixture();+ const result = await f.execute({ action: 'wait', taskId: f.runId, childId: 'child-1', waitSeconds: 0 });+ expect(result.content[0].text).toContain('child-1');+ expect(result.content[0].text).not.toContain('child-2');+ expect(await readdir(f.dir)).toEqual(['status.json']);+ await expect(f.execute({ action: 'stop', taskId: f.runId, childId: 'foreign' })).rejects.toThrow('does not belong');+ await expect(f.execute({ action: 'stop', taskId: f.runId, childId: ' ' })).rejects.toThrow('non-empty');+ });++ it('does not expose another runtime owner through list or controls', async () => {+ const f = await fixture();+ f.status.runtimeOwnerId = 'other-instance';+ await f.publish();+ expect((await f.execute({ action: 'list' })).content[0].text).toContain('No durable');+ await expect(f.execute({ action: 'stop', taskId: f.runId })).rejects.toThrow('not found');+ });++ it.each([true, false])('reports the actual runner receipt (accepted=%s), preserving child targeting', async accepted => {+ const f = await fixture();+ const operation = f.execute({ action: 'steer', taskId: f.runId, childId: 'child-1', message: 'LATEST_CORRECTION' });+ // Attach rejection handling before publishing the receipt.+ const outcome = operation.then((value: any) => ({ value }), (error: Error) => ({ error }));+ const files = await readdir(path.join(f.dir, 'controls'));+ const request = JSON.parse(await readFile(path.join(f.dir, 'controls', files[0]!), 'utf8'));+ expect(request).toMatchObject({ acknowledge: true, childId: 'child-1', message: 'LATEST_CORRECTION' });+ await mkdir(path.join(f.dir, 'control-receipts'));+ await writeFile(path.join(f.dir, 'control-receipts', request.requestId + '.json'), JSON.stringify({ requestId: request.requestId, accepted, reason: 'target-terminal' }));+ const result = await outcome;+ if (accepted) expect(result.value.content[0].text).toContain('accepted by the runner');+ else expect(result.error.message).toContain('rejected: target-terminal');+ });++ it('cancellation after mailbox delivery reports uncertainty without replaying the command', async () => {+ const f = await fixture();+ const controller = new AbortController();+ const operation = f.execute({ action: 'follow_up', taskId: f.runId, message: 'check again' }, controller.signal);+ const outcome = expect(operation).rejects.toThrow('delivery is uncertain');+ controller.abort();+ await outcome;+ expect(await readdir(path.join(f.dir, 'controls'))).toHaveLength(1);+ });++ it('resumes one retained child through the host and returns its new generation id', async () => {+ const f = await fixture();+ f.status.state = 'completed';+ f.status.tasks.forEach(task => { task.status = 'completed'; });+ await f.publish();+ const newId = randomUUID();+ f.ctx.ui.input.mockResolvedValue(JSON.stringify({ ok: true, runId: newId }));+ const result = await f.execute({ action: 'resume', taskId: f.runId, childId: 'child-2', message: 'recheck' });+ const payload = JSON.parse(f.ctx.ui.input.mock.calls[0]![1] as string);+ expect(payload).toMatchObject({ action: 'resume', runId: f.runId, childId: 'child-2', message: 'recheck' });+ expect(result.content[0].text).toContain(newId);+ expect(f.pi.appendEntry).toHaveBeenCalledWith('cindy-subagent-delivery', expect.objectContaining({ runId: newId, state: 'pending' }));+ });++ it('commits one bounded result before settlement and deduplicates after reload', async () => {+ const f = await fixture();+ const delivery = extension.createResultDelivery(f.pi);+ delivery.track(f.runId, Date.now() + 10000, true);+ f.status.state = 'completed';+ f.status.tasks.forEach(task => { task.status = 'completed'; task.output = 'x'.repeat(40000); });+ await f.publish();+ const result = await f.hooks.agent_before_settle!(boundary, f.ctx);+ expect(result.continue).toBe(true);+ expect(result.entries[0].details.runIds).toEqual([f.runId]);+ expect(result.entries[0].content.length).toBeLessThanOrEqual(32000);+ expect(await f.hooks.agent_before_settle!(boundary, f.ctx)).toBeUndefined();+ const entries = [ { type: 'custom', customType: 'cindy-subagent-delivery', data: f.pi.appendEntry.mock.calls[0]![1] }, ...result.entries ];+ f.hooks.session_start!({}, { sessionManager: { getBranch: () => entries } });+ expect(await f.hooks.agent_before_settle!(boundary, f.ctx)).toBeUndefined();+ });++ it('stopping the parent revokes the continuation without stopping its detached children', async () => {+ const f = await fixture();+ extension.createResultDelivery(f.pi).track(f.runId, Date.now() + 10000, true);+ f.ctx.ui.input.mockResolvedValue(JSON.stringify({ ok: false }));+ expect(await f.hooks.agent_before_settle!(boundary, f.ctx)).toBeUndefined();+ expect(f.pi.appendEntry).toHaveBeenLastCalledWith('cindy-subagent-delivery', { runId: f.runId, state: 'consumed' });+ expect(await readdir(f.dir)).toEqual(['status.json']);+ });++ it('explicit get consumes a terminal result and notify:false never holds settlement', async () => {+ const f = await fixture();+ // Replay a pending native entry into the production tool's own tracker.+ f.hooks.session_start!({}, { sessionManager: { getBranch: () => [{ type: 'custom', customType: 'cindy-subagent-delivery', data: { runId: f.runId, state: 'pending', deadlineAt: Date.now() + 10000 } }] } });+ f.status.state = 'completed';+ f.status.tasks.forEach(task => { task.status = 'completed'; });+ await f.publish();+ await f.execute({ action: 'get', taskId: f.runId });+ expect(await f.hooks.agent_before_settle!(boundary, f.ctx)).toBeUndefined();+ extension.createResultDelivery(f.pi).track(f.runId, Date.now() + 10000, false);+ expect(await f.hooks.agent_before_settle!(boundary, f.ctx)).toBeUndefined();+ expect(f.ctx.ui.input).not.toHaveBeenCalled();+ });++ it('clears notification intent when an aborted turn settles without a collection hook', async () => {+ const f = await fixture();+ extension.createResultDelivery(f.pi).track(f.runId, Date.now() + 10000, true);+ f.hooks.agent_settled!();+ expect(await f.hooks.agent_before_settle!(boundary, f.ctx)).toBeUndefined();+ expect(f.ctx.ui.input).not.toHaveBeenCalled();+ });++ it('returns runner exit diagnostics without waiting for the whole task timeout', async () => {+ const f = await fixture();+ extension.createResultDelivery(f.pi).track(f.runId, Date.now() + 10000, true);+ f.ctx.ui.input.mockImplementation(async (_title, payload) => JSON.stringify(JSON.parse(payload).action === 'status'+ ? { ok: false, exited: true, error: 'Runner crashed' } : { ok: true }));+ const result = await f.hooks.agent_before_settle!(boundary, f.ctx);+ expect(result.entries[0].content).toContain('Runner crashed');+ });++ it('retains the failure reason alongside intermediate output', async () => {+ const f = await fixture();+ Object.assign(f.status.tasks[0]!, { status: 'failed', error: 'Provider disconnected' });+ const result = await f.publish().then(() => f.execute({ action: 'get', taskId: f.runId }));+ expect(result.content[0].text).toContain('interim text');+ expect(result.content[0].text).toContain('Provider disconnected');+ });++ it('waits for asynchronous completion, but yields to pending user input and never continues an error', async () => {+ const f = await fixture();+ extension.createResultDelivery(f.pi).track(f.runId, Date.now() + 10000, true);+ expect(await f.hooks.agent_before_settle!({ ...boundary, outcome: 'error' }, f.ctx)).toBeUndefined();+ expect(await f.hooks.agent_before_settle!({ ...boundary, context: { pendingMessages: [{}] } }, f.ctx)).toBeUndefined();+ const operation = f.hooks.agent_before_settle!(boundary, f.ctx);+ f.status.state = 'completed';+ f.status.tasks.forEach(task => { task.status = 'completed'; task.output = 'CHILD_RESULT'; });+ await f.publish();+ expect((await operation).entries[0].content).toContain('CHILD_RESULT');+ });+});diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.tsindex d5dc7a3a10..22bcf36f9f 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts@@ -192,8 +192,8 @@ describe('Cindy PI Subagent foreground durable path', () => {);process.env[CINDY_SUBAGENT_ENV.binary] = wrapper;await chmod(wrapper, 0o700);- const extension = require(f.extensionFile).default as (pi: { registerTool: (tool: unknown) => void }) => Promise<void>;- await extension({ registerTool: (tool) => Object.assign(registered, tool) });+ const extension = require(f.extensionFile).default as (pi: { registerTool: (tool: unknown) => void; appendEntry: () => void }) => Promise<void>;+ await extension({ registerTool: (tool) => Object.assign(registered, tool), appendEntry: vi.fn() });expect(registered.execute).toBeTypeOf('function');const input = hostInput(f);const result = await registered.execute!(@@ -248,8 +248,8 @@ describe('Cindy PI Subagent foreground durable path', () => {});const registered: { execute?: (...args: unknown[]) => Promise<unknown> } = {};try {- const extension = require(f.extensionFile).default as (pi: { registerTool: (tool: unknown) => void }) => Promise<void>;- await extension({ registerTool: (tool) => Object.assign(registered, tool) });+ const extension = require(f.extensionFile).default as (pi: { registerTool: (tool: unknown) => void; appendEntry: () => void }) => Promise<void>;+ await extension({ registerTool: (tool) => Object.assign(registered, tool), appendEntry: vi.fn() });const input = hostInput(f);const execution = registered.execute!('tool-runner-exit',@@ -315,8 +315,8 @@ setTimeout(() => process.exit(0), 20000).unref();const registered: { execute?: (...args: unknown[]) => Promise<unknown> } = {};const controller = new AbortController();try {- const extension = require(f.extensionFile).default as (pi: { registerTool: (tool: unknown) => void }) => Promise<void>;- await extension({ registerTool: (tool) => Object.assign(registered, tool) });+ const extension = require(f.extensionFile).default as (pi: { registerTool: (tool: unknown) => void; appendEntry: () => void }) => Promise<void>;+ await extension({ registerTool: (tool) => Object.assign(registered, tool), appendEntry: vi.fn() });const input = hostInput(f);const startedAt = Date.now();const execution = registered.execute!(@@ -430,8 +430,8 @@ setTimeout(() => process.exit(2), 5000).unref();const registered: { execute?: (...args: unknown[]) => Promise<unknown> } = {};const controller = new AbortController();try {- const extension = require(f.extensionFile).default as (pi: { registerTool: (tool: unknown) => void }) => Promise<void>;- await extension({ registerTool: (tool) => Object.assign(registered, tool) });+ const extension = require(f.extensionFile).default as (pi: { registerTool: (tool: unknown) => void; appendEntry: () => void }) => Promise<void>;+ await extension({ registerTool: (tool) => Object.assign(registered, tool), appendEntry: vi.fn() });const input = hostInput(f);const execution = registered.execute!('tool-abort-before-status',diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.tsindex fdfbac10da..81430a3e22 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts@@ -229,6 +229,7 @@ async function makeFixture(options: {modelError?: boolean;retryThenSucceed?: boolean;outputThenHang?: boolean;+ commentaryThenHang?: boolean;hangOnMessage?: string;holdExitAfterInputEnd?: boolean;runtimeOwnerId?: string;@@ -326,7 +327,9 @@ setTimeout(() => process.exit(0), 60000).unref();const fixtureOutput = JSON.stringify(options.outputText ?? 'fixture result');const approvalMethod = options.approvalMethod ?? 'confirm';const approvalIds = options.approvalIds ?? (options.approval ? ['approval-1'] : []);- const fixtureLifecycle = options.outputThenHang+ const fixtureLifecycle = options.commentaryThenHang+ ? `process.stdout.write(JSON.stringify({ type: 'message_end', message: { role: 'assistant', stopReason: 'toolUse', content: [{ type: 'text', text: 'Inspecting the files now' }, { type: 'toolCall', id: 'inspect', name: 'read', arguments: { path: 'a.txt' } }] } }) + '\\n');`+ : options.outputThenHang? `process.stdout.write(JSON.stringify({ type: 'message_end', message: { role: 'assistant', content: [{ type: 'text', text: ${fixtureOutput} }], usage: { input: 3, output: 2, cost: { total: 0.01 } } } }) + '\\n');`: options.hang? ''@@ -1492,6 +1495,27 @@ describe('Cindy durable PI Subagent runner', () => {await waitForClose(fixture.child, fixture.stderr);});+ it('accepts a correction after commentary while the child is still executing tools', async () => {+ const fixture = await makeFixture({ commentaryThenHang: true });+ const running = await waitFor(async () => {+ const [run] = await listPiSubagentRuns(fixture.root);+ return run?.tasks[0]?.output === 'Inspecting the files now' ? run : null;+ });+ try {+ expect(running.tasks[0]?.resultReady).toBe(false);+ await expect(controlPiSubagentRuns(fixture.root, running.runId, 'steer', {+ childId: running.tasks[0]?.childId, message: 'Inspect billing only',+ })).resolves.toBe(1);+ await waitFor(async () => {+ const commands = await readCommandsIfPresent(fixture.commandsFile);+ return commands?.some(command => command.type === 'steer' && command.message === 'Inspect billing only') ? true : null;+ });+ } finally {+ await controlPiSubagentRuns(fixture.root, running.runId, 'stop');+ await waitForClose(fixture.child, fixture.stderr);+ }+ });+it('keeps completed output immutable and requires follow-up instead of late steer', async () => {const fixture = await makeFixture({ outputThenHang: true });// The precondition under test is the *durable status* carrying the child'sdiff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.tsindex db7cb1bc79..e4055701eb 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts@@ -2314,6 +2314,60 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {await handle.close();});+ it('routes model resume through the same retained-session helper and returns its generation id', async () => {+ const handle = await new PiAgent(buildDeps()).startSession(opts());+ const resumedId = '123e4567-e89b-42d3-a456-426614174098';+ const resumeSpy = vi.spyOn(piSubagentRuns, 'resumePiSubagentRun').mockResolvedValue(resumedId);+ try {+ knobs.onEvent?.({ type: 'extension_ui_request', id: 'resume-from-model', method: 'input',+ title: 'cindy:pi-subagent-runner', placeholder: JSON.stringify({+ action: 'resume', runId: '123e4567-e89b-42d3-a456-426614174097', childId: 'one-child', message: 'check again',+ }) });+ await vi.waitFor(() => expect(knobs.sent).toContainEqual(expect.objectContaining({+ id: 'resume-from-model', value: JSON.stringify({ ok: true, runId: resumedId }),+ })));+ expect(resumeSpy).toHaveBeenCalledWith(expect.any(String), '123e4567-e89b-42d3-a456-426614174097',+ 'check again', expect.objectContaining({ runtimeOwnerId: expect.any(String), launchRunner: expect.any(Function) }), 'one-child');+ } finally { await handle.close(); }+ });++ it('revokes the pre-settlement delivery gate when the user stops the parent', async () => {+ const handle = await new PiAgent(buildDeps()).startSession(opts());+ const query = (id: string) => knobs.onEvent?.({ type: 'extension_ui_request', id, method: 'input',+ title: 'cindy:pi-subagent-runner', placeholder: JSON.stringify({ action: 'delivery', runId: '123e4567-e89b-42d3-a456-426614174097' }) });+ try {+ knobs.onEvent?.({ type: 'agent_start' });+ query('before-stop');+ await vi.waitFor(() => expect(knobs.sent).toContainEqual(expect.objectContaining({ id: 'before-stop', value: JSON.stringify({ ok: true, confirmed: true }) })));+ await handle.abort();+ query('after-stop');+ await vi.waitFor(() => expect(knobs.sent).toContainEqual(expect.objectContaining({ id: 'after-stop', value: JSON.stringify({ ok: false, unconfirmed: true }) })));+ } finally { await handle.close(); }+ });++ it('retains every resume lease when a newer concurrent resume fails first', async () => {+ const handle = await new PiAgent(buildDeps()).startSession(opts());+ let release!: (runId: string) => void;+ const pending = new Promise<string>(resolve => { release = resolve; });+ const spy = vi.spyOn(piSubagentRuns, 'resumePiSubagentRun')+ .mockImplementationOnce(async () => pending)+ .mockRejectedValueOnce(new Error('second resume rejected'));+ const first = handle.resumeBackgroundTask!('first', 'continue');+ await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(1));+ await expect(handle.resumeBackgroundTask!('second', 'continue')).rejects.toThrow('second resume rejected');+ let closed = false;+ const closing = handle.close().then(() => { closed = true; });+ try {+ await new Promise(resolve => setTimeout(resolve, 20));+ expect(closed).toBe(false);+ expect(proxyDisposed).toBe(0);+ } finally {+ release('123e4567-e89b-42d3-a456-426614174098');+ await first;+ await closing;+ }+ });+it('waits for an in-flight Subagent resume before transferring the proxy lease', async () => {const agent = new PiAgent(buildDeps());const handle = await agent.startSession(opts());diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.tsindex bb332afcbd..89121bd52a 100644--- a/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts@@ -276,6 +276,7 @@ function main() {usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 },usageSegments: [],output: '',+ resultReady: false,outputTruncated: false,error: undefined,// Approval requests this child is still waiting on, oldest first. The@@ -368,12 +369,12 @@ function main() {toolUses: task.toolUses,usage: task.usage,usageSegments: task.usageSegments,- // message_end is already a complete generation result even if Pi- // keeps the RPC process alive for follow-up. Publish it immediately- // so the host can hide late Steer before writing a doomed control.+ // Intermediate commentary is useful progress, not a final result.+ // Publish its readiness separately so controls never infer it from text.output: task.output || (task.status === 'running' || task.status === 'queued' ? undefined : ''),+ resultReady: task.resultReady,outputTruncated: task.outputTruncated || undefined,error: task.error,// Only the oldest unanswered request is published so the status@@ -595,10 +596,9 @@ function main() {let accepted = false;for (const task of selected) {if (state.stopRequested || task.stopRequested) continue;- // A message_end is the immutable result of that completed generation.- // Sending steer after it exists makes Pi emit a short acknowledgement- // that can replace the real result. Continue via follow_up instead.- if (control.action === 'steer' && typeof task.output === 'string' && task.output.trim()) {+ // Only a final assistant response closes the steering window. A text+ // preamble followed by tools is still an active, steerable generation.+ if (control.action === 'steer' && task.resultReady) {continue;}const command = {@@ -908,6 +908,11 @@ function main() {scheduleStatus();return;}+ if (event.type === 'agent_start') {+ task.resultReady = false;+ scheduleStatus();+ return;+ }if (event.type === 'tool_execution_start') {task.toolUses += 1;scheduleStatus();@@ -915,6 +920,10 @@ function main() {}if (event.type === 'message_end' && event.message && event.message.role === 'assistant') {const text = textOf(event.message);+ task.resultReady = event.message.stopReason !== 'toolUse'+ && !(Array.isArray(event.message.content) && event.message.content.some(function (block) {+ return block && block.type === 'toolCall';+ }));if (event.message.stopReason === 'error') {terminalError = typeof event.message.errorMessage === 'string' && event.message.errorMessage.trim()? event.message.errorMessage.trim().slice(0, 4000)@@ -1179,6 +1188,7 @@ function main() {agent: task.agent,status: task.status,output: task.output,+ resultReady: task.resultReady,outputTruncated: task.outputTruncated || undefined,error: task.error,usage: task.usage,diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-source.tsindex 8af0069696..6c2d768d3f 100644--- a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts@@ -5,7 +5,7 @@* - pi 上游刻意不内置子代理,社区(`pi-subagents` 等)一律以「扩展 + 子 pi 进程」补齐。* 但整包引入等于把第三方代码塞进 `pi-harness.md` §4.2 划定的自包含注入边界,并跟着上游* 版本跑。这里参考社区与上游示例的设计,只重做我们需要的部分,代码归 Cindy 所有。- * - 沿用 §3 设计原则:直接用 pi 自身能力(`--mode json` 子进程、`--tools` 白名单、+ * - 沿用 §3 设计原则:直接用 pi 自身能力(`--mode rpc` 子进程、`--tools` 白名单、* `--append-system-prompt`),不再套一层外部框架、不做二次转义。** 这段代码跑在 **pi 子进程**(bun runtime)里,不能 import cindy 任何模块;只依赖 pi 的@@ -13,7 +13,7 @@* 否则 `${...}` 会被外层 String.raw 插值 —— 一律用字符串拼接。** 安全形态(重要,别当冗余删掉):- * - 子进程**继承 `PI_CODING_AGENT_DIR`**,但显式 `--no-extensions` 关闭隐式发现,再只用+ * - 子进程使用独立 `PI_CODING_AGENT_DIR`,显式 `--no-extensions` 关闭隐式发现,再只用* `--extension <runDir>/cindy-bridge.ts` 回装从内部扩展目录复制的权限门。这样 project extension* 永远不会执行,bridge 的 tool_call 拦截 + 凭证路径硬拦仍对子代理生效。* - 只读角色固定 read/grep/find/ls;worker/custom-write 才拿 edit/write/bash。Ask/Auto@@ -21,7 +21,7 @@* Cindy 现有审批 UI,再把 allow/deny 精确回送给对应 child RPC。父任务未加载时不猜测,* 请求保持挂起并在恢复后处理;超时仍由 runner fail-closed 收口。* - `CINDY_PI_SUBAGENT_DEPTH` 防递归:达到上限后本扩展不注册工具,子代理无法再派子代理。- * - `--no-session`:子代理不写会话文件,不污染 Cindy 的会话 JSONL。+ * - 每个子代理持久化独立会话,恢复时沿用原 session id,不写入父任务的会话 JSONL。* - foreground child 仍遵守**父死子亡**,由父存活看门狗 + exit 同步清扫兜底。显式* async 则交给 Cindy detached runner:父 session 导航/卸载只停止 observer,不终止* child;停止、超时和删除均由持有真实 ChildProcess handle 的 runner 执行。@@ -284,26 +284,70 @@ function enforceIsolation(input) {}}+// Use Pi's model-visible projection: raw branch entries can resurrect content+// removed by compaction or context edits. Keep the newest request even when a+// large tool result follows it; omit image bytes and hidden reasoning.function parentContextSnapshot(ctx) {- try {- const branch = ctx && ctx.sessionManager && typeof ctx.sessionManager.getBranch === 'function'- ? ctx.sessionManager.getBranch()- : [];- const sections = [];- for (const entry of branch) {- if (!entry || entry.type !== 'message' || !entry.message) continue;- const role = entry.message.role;- if (role !== 'user' && role !== 'assistant') continue;- const content = Array.isArray(entry.message.content) ? entry.message.content : [];- const text = content.map(function (block) {- return block && block.type === 'text' && typeof block.text === 'string' ? block.text : '';- }).join('').trim();- if (text) sections.push(String(role).toUpperCase() + ':\n' + text);- }- return clampText(sections.join('\n\n'), MAX_PARENT_CONTEXT_CHARS);- } catch (err) {- return '';+ const manager = ctx && ctx.sessionManager;+ if (!manager) return '';+ let messages;+ if (typeof manager.buildSessionProjection === 'function') {+ messages = manager.buildSessionProjection().messages;+ } else if (typeof manager.buildSessionContext === 'function') {+ messages = manager.buildSessionContext().messages;+ } else {+ // Older Pi exposes compaction-aware entries rather than a projection.+ const entries = typeof manager.buildContextEntries === 'function'+ ? manager.buildContextEntries()+ : null;+ if (!entries) throw new Error('subagent: Pi cannot project the parent context; use context:fresh.');+ messages = entries.flatMap(function (entry) {+ if (entry.type === 'message') return [entry.message];+ if (entry.type === 'compaction' || entry.type === 'branch_summary') {+ return [{ role: 'summary', content: entry.summary }];+ }+ if (entry.type === 'custom_message') return [{ role: 'custom', content: entry.content }];+ return [];+ });}+ if (!Array.isArray(messages)) return '';+ const sections = messages.flatMap(function (message, index) {+ if (!message || message.role === 'system') return [];+ const content = message.content;+ const text = typeof content === 'string' ? content : Array.isArray(content)+ ? content.map(function (block) {+ if (block && block.type === 'text') return block.text || '';+ if (block && block.type === 'image') return '[Image omitted from text snapshot]';+ if (block && block.type === 'toolCall') return '[Tool call: ' + block.name + ']';+ return '';+ }).join('') : typeof message.summary === 'string' ? message.summary : '';+ if (!text.trim()) return [];+ return [{ index: index, role: message.role, text: String(message.role).toUpperCase()+ + (message.toolName ? ' (' + message.toolName + ')' : '') + ':\n' + text.trim() }];+ });+ const latestUser = sections.filter(function (section) { return section.role === 'user'; }).pop();+ const summary = sections.filter(function (section) { return /summary/i.test(section.role); }).pop();+ const selected = new Map();+ let budget = MAX_PARENT_CONTEXT_CHARS;+ function keep(section, limit) {+ if (!section || selected.has(section.index) || budget < 3) return;+ const size = Math.min(limit, budget - 2);+ // Long user messages often put corrections after attachments/logs. Retain+ // both ends and make omission explicit, rather than silently losing the tail.+ const text = section.text.length > size && section.role === 'user' && size > 80+ ? section.text.slice(0, Math.floor((size - 30) / 2)) + '\n[… middle omitted …]\n'+ + section.text.slice(-Math.floor((size - 30) / 2))+ : clampText(section.text, size);+ selected.set(section.index, text);+ budget -= text.length + 2;+ }+ keep(latestUser, 16000);+ keep(summary, 8000);+ for (let index = sections.length - 1; index >= 0 && budget > 2; index -= 1) {+ keep(sections[index], sections[index].role === 'toolResult' ? 4000 : 8000);+ }+ return [...selected.entries()].sort(function (a, b) { return a[0] - b[0]; })+ .map(function (entry) { return entry[1]; }).join('\n\n');}function resolveTaskModelRoutes(tasks, runtime) {@@ -520,56 +564,119 @@ function writeControlRequest(runDir, control) {requestedAt: requestedAt,...control,});+ return requestId;+}++function isTerminalStatus(state) {+ return state === 'completed' || state === 'failed' || state === 'stopped';+}++function selectedTasks(status, childId) {+ const tasks = childId ? status.tasks.filter(function (task) { return task.childId === childId; }) : status.tasks;+ if (!tasks.length) throw new Error('subagent: childId does not belong to this run');+ return tasks;}-function writeDurableControl(status, action, message) {+function describeRun(status, childId) {+ const sections = selectedTasks(status, childId).map(function (task) {+ return '## ' + (task.title || task.agent) + ' [' + task.status + '] childId=' + task.childId+ + (task.error ? '\nError: ' + task.error : '')+ + '\n' + (task.output || '(no output)');+ });+ return 'runId=' + status.runId + ' [' + status.state + ']\n' + fitSectionsToBudget(sections).join('\n\n');+}++async function writeDurableControl(status, action, message, childId, signal) {const root = process.env[RUN_ROOT_ENV];- if (!root || !status || typeof status.runId !== 'string') return false;- writeControlRequest(join(root, status.runId), {- action: action,+ if (!root) throw new Error('subagent: durable storage is unavailable');+ if (signal && signal.aborted) throw new Error('subagent: control cancelled before delivery');+ const runDir = join(root, status.runId);+ const requestId = writeControlRequest(runDir, {+ action: action, acknowledge: true,+ ...(childId ? { childId: childId } : {}),...(message ? { message: message } : {}),});- return true;+ const receiptFile = join(runDir, 'control-receipts', requestId + '.json');+ const deadline = Date.now() + 5000;+ while (Date.now() < deadline) {+ let receipt;+ try { receipt = JSON.parse(readFileSync(receiptFile, 'utf8')); } catch (err) { /* not acknowledged yet */ }+ if (receipt && receipt.requestId === requestId) {+ if (receipt.accepted !== true) throw new Error('subagent: ' + action + ' rejected: ' + (receipt.reason || 'not accepted'));+ return action + ' accepted by the runner for ' + (childId || status.runId) + '.';+ }+ if (signal && signal.aborted) break;+ await new Promise(function (resolve) { setTimeout(resolve, 50); });+ }+ // The write may already have been consumed. Never tell the model to replay it.+ throw new Error('subagent: control receipt unavailable; delivery is uncertain. Inspect the run before retrying. requestId=' + requestId);}-function managementResult(params) {+async function managementResult(params, ctx, signal, delivery) {const action = params.action;- if (!['list', 'get', 'stop', 'steer', 'follow_up'].includes(action)) {+ if (action === 'capabilities') {+ return JSON.stringify({ roles: Object.keys(PROFILES).map(function (agent) {+ return { agent: agent, tools: toolsFor(agent).split(',') };+ }), models: Object.keys(readRuntimeSnapshot().modelRoutes || {}),+ maxTasks: MAX_TASKS, concurrency: MAX_CONCURRENCY, context: ['fresh', 'fork'],+ actions: ['run', 'list', 'get', 'wait', 'stop', 'steer', 'follow_up', 'resume'] });+ }+ if (!['list', 'get', 'wait', 'stop', 'steer', 'follow_up', 'resume'].includes(action)) {throw new Error('subagent: unknown management action');}const statuses = durableStatuses();if (action === 'list') {if (statuses.length === 0) return 'No durable PI Subagent runs.';return statuses.map(function (status) {- return status.runId + ' · ' + status.state + ' · ' + (status.title || status.description || status.taskId);+ return status.runId + ' · ' + status.state + ' · ' + (status.title || status.description || status.taskId)+ + '\n' + status.tasks.map(function (task) { return ' ' + task.childId + ' · ' + task.agent + ' · ' + task.status; }).join('\n');}).join('\n');}const taskId = typeof params.taskId === 'string' ? params.taskId.trim() : '';- if (!taskId) throw new Error('subagent: action ' + action + ' requires taskId or runId');- const status = statuses.find(function (entry) {- return entry.taskId === taskId || entry.runId === taskId;- });+ if (!taskId) throw new Error('subagent: action ' + action + ' requires taskId (runId or tool call id)');+ const status = statuses.find(function (entry) { return entry.taskId === taskId || entry.runId === taskId; });if (!status) throw new Error('subagent: durable task not found');- if (action === 'get') {- const text = status.tasks.map(function (task) {- return '## ' + (task.title || task.agent) + ' [' + task.status + ']\n'- + (task.output || task.error || '(no output)');- }).join('\n\n');- return clampText(text, MAX_TOTAL_OUTPUT_CHARS);+ if (params.childId !== undefined && (typeof params.childId !== 'string' || !params.childId.trim())) {+ throw new Error('subagent: childId must be a non-empty exact child id');}- if (status.state === 'completed' || status.state === 'failed' || status.state === 'stopped') {- throw new Error('subagent: durable task is already terminal');+ const childId = typeof params.childId === 'string' ? params.childId.trim() : '';+ selectedTasks(status, childId);+ if (action === 'get') {+ if (!childId && isTerminalStatus(status.state)) delivery.consume(status.runId);+ return describeRun(status, childId);}- if (action === 'stop') {- writeDurableControl(status, 'stop', '');- return 'Stop requested.';+ if (action === 'wait') {+ const seconds = params.waitSeconds === undefined ? 30 : params.waitSeconds;+ if (!Number.isInteger(seconds) || seconds < 0 || seconds > 60) throw new Error('subagent: waitSeconds must be from 0 to 60');+ const deadline = Date.now() + seconds * 1000;+ let current = status;+ while (!selectedTasks(current, childId).every(function (task) { return isTerminalStatus(task.status); })) {+ if (signal && signal.aborted) throw new Error('subagent: wait cancelled; children remain independently controllable');+ if (Date.now() >= deadline) break;+ await new Promise(function (resolve) { setTimeout(resolve, 100); });+ current = durableStatuses().find(function (entry) { return entry.runId === status.runId; });+ if (!current) throw new Error('subagent: run is no longer available');+ }+ if (!childId && isTerminalStatus(current.state)) delivery.consume(current.runId);+ return describeRun(current, childId);}const message = typeof params.message === 'string' ? params.message.trim() : '';- if (!message || message.length > MAX_TASK_CHARS) {- throw new Error('subagent: steer/follow_up requires a message up to ' + MAX_TASK_CHARS + ' characters');+ if (action !== 'stop' && (!message || message.length > MAX_TASK_CHARS)) {+ throw new Error('subagent: ' + action + ' requires a message up to ' + MAX_TASK_CHARS + ' characters');+ }+ if (action === 'resume') {+ if (!isTerminalStatus(status.state)) throw new Error('subagent: run is still active; use steer or follow_up');+ if (signal && signal.aborted) throw new Error('subagent: resume cancelled');+ const resumed = await requestRunnerControl(ctx, 'resume', status.runId, { message: message, childId: childId || undefined });+ if (typeof resumed.runId !== 'string' || !/^[0-9a-f-]{36}$/i.test(resumed.runId)) throw new Error('subagent: invalid resume receipt');+ delivery.track(resumed.runId, undefined, params.notify !== false);+ return 'Subagent resumed. runId=' + resumed.runId + '. Use wait/get to collect the result.';+ }+ if (isTerminalStatus(status.state)) {+ if (action === 'stop') return 'Subagent is already terminal. ' + describeRun(status, childId);+ throw new Error('subagent: durable task is already terminal; use action:resume to continue its retained session');}- writeDurableControl(status, action, message);- return action === 'steer' ? 'Steer requested.' : 'Follow-up queued.';+ return writeDurableControl(status, action, message, childId, signal);}function writeApprovalControl(runDir, childId, approvalId, response) {@@ -769,13 +876,13 @@ function launchFenceBlocksSpawn(runRoot, runtimeOwnerId) {return fenceNamesLiveHost(join(fenceDir, LEGACY_LAUNCH_FENCE_FILENAME), hostPid, hostStartTimeSec);}-async function requestRunnerControl(ctx, action, runId) {+async function requestRunnerControl(ctx, action, runId, options = {}) {if (!ctx || !ctx.ui || typeof ctx.ui.input !== 'function') {throw new Error('subagent: Cindy runner control is unavailable.');}const raw = await ctx.ui.input(RUNNER_CONTROL_TITLE,- JSON.stringify({ action: action, runId: runId }),+ JSON.stringify({ ...options, action: action, runId: runId }),);let response;try { response = JSON.parse(typeof raw === 'string' ? raw : '{}'); } catch (err) { response = null; }@@ -1172,6 +1279,109 @@ function mergeUsage(target, source) {}}+// Pi's pre-settlement boundary keeps the parent's turn (and permission scope)+// open while async children finish. No idle wake, synthetic user prompt, or+// host-side scheduler is involved. Bookkeeping survives extension reload.+function createResultDelivery(pi) {+ const pending = new Map();+ const marker = 'cindy-subagent-delivery';+ const consumed = function (runId) {+ if (!pending.delete(runId)) return;+ pi.appendEntry(marker, { runId: runId, state: 'consumed' });+ };+ const track = function (runId, deadlineAt, notify) {+ if (!notify) return;+ if (!Number.isFinite(deadlineAt)) {+ let timeoutMs = DEFAULT_TIMEOUT_SECONDS * 1000;+ try {+ const config = JSON.parse(readFileSync(join(process.env[RUN_ROOT_ENV], runId, 'config.json'), 'utf8'));+ if (Number.isFinite(config.timeoutMs) && config.timeoutMs > 0 && config.timeoutMs <= MAX_TIMEOUT_SECONDS * 1000) timeoutMs = config.timeoutMs;+ } catch (error) { /* resume still has a bounded collection deadline */ }+ deadlineAt = Date.now() + timeoutMs + 15000;+ }+ pending.set(runId, deadlineAt);+ pi.appendEntry(marker, { runId: runId, state: 'pending', deadlineAt: deadlineAt });+ };+ // Older hosts can still load the tool, but cannot promise automatic delivery.+ if (typeof pi.on === 'function') {+ pi.on('session_start', function (event, ctx) {+ pending.clear();+ const entries = ctx.sessionManager.getBranch();+ for (const entry of entries) {+ if (entry.type === 'custom' && entry.customType === marker && entry.data) {+ const data = entry.data;+ if (typeof data.runId !== 'string') continue;+ if (data.state === 'pending' && Number.isFinite(data.deadlineAt)) pending.set(data.runId, data.deadlineAt);+ else pending.delete(data.runId);+ }+ if (entry.type === 'custom_message' && entry.customType === marker && Array.isArray(entry.details?.runIds)) {+ for (const runId of entry.details.runIds) pending.delete(runId);+ }+ }+ });+ pi.on('agent_settled', function () {+ // Aborted/error turns can skip before-settle entirely. Do not revive+ // their notification intents on the next unrelated user request.+ for (const runId of Array.from(pending.keys())) consumed(runId);+ });+ pi.on('agent_before_settle', async function (event, ctx) {+ if (!pending.size || event.outcome !== 'completed') return;+ // User/extension input already queued takes priority over waiting.+ if (event.context?.pendingMessages?.length) return;+ let nextHostPoll = 0;+ while (pending.size) {+ try {+ await requestRunnerControl(ctx, 'delivery', pending.keys().next().value);+ } catch (error) {+ // Stop, close and account teardown revoke this turn's continuation.+ // Durable children stay available through explicit list/get/resume.+ for (const runId of Array.from(pending.keys())) consumed(runId);+ return;+ }+ if (typeof ctx.hasPendingMessages === 'function' && ctx.hasPendingMessages()) return;+ const statuses = durableStatuses();+ const ready = [];+ const runIds = [];+ const pollHost = Date.now() >= nextHostPoll;+ if (pollHost) nextHostPoll = Date.now() + 1000;+ for (const [runId, deadlineAt] of pending) {+ const status = statuses.find(function (entry) { return entry.runId === runId; });+ if (status && isTerminalStatus(status.state)) {+ ready.push(describeRun(status));+ runIds.push(runId);+ } else if (pollHost) {+ try { await requestRunnerControl(ctx, 'status', runId); } catch (error) {+ if (error && error.runnerExited) {+ ready.push('runId=' + runId + ': ' + error.message);+ runIds.push(runId);+ continue;+ }+ }+ }+ if (!runIds.includes(runId) && Date.now() >= deadlineAt) {+ ready.push('runId=' + runId + ': no terminal result was available before the delivery deadline. Use list/get to inspect; this does not confirm the child stopped.');+ runIds.push(runId);+ }+ }+ if (runIds.length) {+ try { await requestRunnerControl(ctx, 'delivery', runIds[0]); } catch (error) {+ for (const runId of Array.from(pending.keys())) consumed(runId);+ return;+ }+ // The native boundary commits the result and continuation together.+ // Abort during the hook suppresses continuation in Pi itself.+ for (const runId of runIds) pending.delete(runId);+ return { entries: [{ type: 'custom_message', customType: marker,+ content: fitSectionsToBudget(ready).join('\n\n'), display: false,+ details: { runIds: runIds } }], continue: true };+ }+ await new Promise(function (resolve) { setTimeout(resolve, 250); });+ }+ });+ }+ return { track: track, consume: consumed };+}+export default async function cindySubagent(pi: any) {// depth > 0 = 本进程自己就是子代理:装上父存活看门狗,父进程(pi 会话)一消失就自杀。// 必须在下面的深度早返回**之前**装 —— 子代理正是走那条早返回分支的。@@ -1184,6 +1394,8 @@ export default async function cindySubagent(pi: any) {const runtimeFile = process.env[RUNTIME_FILE_ENV];if (typeof runtimeFile !== 'string' || runtimeFile.trim().length === 0) return;+ const delivery = createResultDelivery(pi);+pi.registerTool({name: TOOL_NAME,label: 'Subagent',@@ -1191,18 +1403,21 @@ export default async function cindySubagent(pi: any) {+ 'Available roles: ' + profileNames() + '. Read-only roles cannot edit. worker uses the parent '+ 'permission mode; Ask/Auto requests are forwarded to Cindy approval. Pass model/thinking to override the '+ 'parent model for a child. Pass async:true for a detached background run that survives parent navigation. '+ + 'Results are collected before this parent turn settles; notify:false leaves collection explicit. '+ 'Pass {agent, task} for one, or {tasks:[{agent, task}, ...]} to fan out in parallel. '- + 'Use action:list/get/stop/steer/follow_up for durable runs. Children cannot spawn further subagents.',+ + 'Use action:capabilities/list/get/wait/stop/steer/follow_up/resume for durable runs. Select childId to control one child. Children cannot spawn further subagents.',parameters: {type: 'object',properties: {action: {type: 'string',- enum: ['run', 'list', 'get', 'stop', 'steer', 'follow_up'],+ enum: ['run', 'capabilities', 'list', 'get', 'wait', 'stop', 'steer', 'follow_up', 'resume'],description: 'Default run; other actions inspect or control durable runs.',},- taskId: { type: 'string', description: 'Durable run id (or opaque task id) for get/stop/steer/follow_up.' },- message: { type: 'string', description: 'Direction for steer (delivered after current tool calls) or follow_up.' },+ taskId: { type: 'string', description: 'Durable run id (or opaque task id) for get/wait/stop/steer/follow_up/resume.' },+ childId: { type: 'string', description: 'Optional exact child id from list/get; omitted targets the whole run.' },+ waitSeconds: { type: 'integer', minimum: 0, maximum: 60, description: 'Bounded wait for a result; default 30 seconds. Timeout does not stop the child.' },+ message: { type: 'string', description: 'Direction for steer, follow_up (active run), or resume (terminal run).' },agent: { type: 'string', description: 'Agent profile: ' + profileNames() },task: {type: 'string',@@ -1212,6 +1427,7 @@ export default async function cindySubagent(pi: any) {model: { type: 'string', description: 'Optional exact child model id.' },thinking: { type: 'string', description: 'Optional thinking level: ' + THINKING_LEVELS },async: { type: 'boolean', description: 'Run in Cindy durable background mode.' },+ notify: { type: 'boolean', description: 'Default true: collect async/resume results before the parent finishes. false: use wait/get explicitly.' },timeoutSeconds: {type: 'integer',minimum: MIN_TIMEOUT_SECONDS,@@ -1250,7 +1466,7 @@ export default async function cindySubagent(pi: any) {const input = params && typeof params === 'object' ? params as Record<string, unknown> : {};const action = typeof input.action === 'string' ? input.action : 'run';if (action !== 'run') {- const text = managementResult(input);+ const text = await managementResult(input, ctx, signal, delivery);return { content: [{ type: 'text', text: text }], details: { action: action } };}enforceIsolation(input);@@ -1262,10 +1478,7 @@ export default async function cindySubagent(pi: any) {? invocation.tasks.map(function (task) {return Object.assign({}, task, {originalTask: task.task,- task: clampText(- 'Parent task snapshot (immutable):\n\n' + snapshot + '\n\nAssignment:\n' + task.task,- MAX_TASK_CHARS + MAX_PARENT_CONTEXT_CHARS,- ),+ task: 'Parent task snapshot (immutable):\n\n' + snapshot + '\n\nAssignment:\n' + task.task,});}): invocation.tasks;@@ -1379,8 +1592,9 @@ export default async function cindySubagent(pi: any) {ctx,);if (wantAsync) {+ delivery.track(launched.runId, launched.deadlineAt, input.notify !== false);return {- content: [{ type: 'text', text: LAUNCH_RECEIPT }],+ content: [{ type: 'text', text: LAUNCH_RECEIPT + ' runId=' + launched.runId + '; taskId=' + taskId + '. Use wait/get for results.' }],details: { launched: true, taskId: taskId, runId: launched.runId },};}@@ -1405,7 +1619,7 @@ export default async function cindySubagent(pi: any) {});const results: any[] = durableStatus.tasks.map(function (task) {return {- text: task.output || task.error || '(no result)',+ text: (task.error ? 'Error: ' + task.error + '\n' : '') + (task.output || '(no result)'),isError: task.status !== 'completed',toolUses: Number(task.toolUses || 0),tokens: Number(task.usage && (diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 80d3530cd4..f695007e32 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -5286,6 +5286,45 @@ export class PiAgent extends BaseAgent {return proxyLeaseInitialInspection;};let durableSpawnEnv: NodeJS.ProcessEnv = {};+ // Both model controls and the UI use the same durable resume path. Track it+ // before yielding so close/account-boundary teardown can await its lease.+ const resumeSubagent = async (taskId: string, message: string, childId?: string): Promise<string> => {+ if (closed || accountBoundaryTeardown) throw new Error('PI session is closed');+ if (!localSubagentSupported) throw new Error('PI Subagent is available only in local PI sessions.');+ const operation = (async () => {+ await permissionWriteChain;+ if (closed) throw new Error('PI session is closed');+ const [modelsJson, bridgeSource, runnerSource] = await Promise.all([+ fs.readFile(path.join(configHome, 'models.json')),+ fs.readFile(bridgeExtensionPath),+ fs.readFile(subagentRunnerPath),+ ]);+ const runId = await resumePiSubagentRun(subagentRunRoot, taskId, message, {+ launchRunner: (request) => this.launchSubagentRunner(request),+ env: durableSpawnEnv,+ runtimeOwnerId: subagentRuntimeOwnerId,+ permissionSnapshot: {+ ...requestedPermissionSnapshot,+ mode: permissionMode,+ readOnlyRoots: [...requestedPermissionSnapshot.readOnlyRoots],+ writableRoots: [...requestedPermissionSnapshot.writableRoots],+ ...reviewPathSnapshot,+ },+ runnerFallbackFile: subagentRunnerPath,+ runtimeSnapshot: { modelsJson, bridgeSource, runnerSource },+ }, childId);+ if (!runId) throw new Error('No terminal PI Subagent run is available to resume.');+ await requestPiSubagentRefresh();+ return runId;+ })();+ // close() waits for every resume that entered while this handle was+ // live before inspecting durable runs and transferring the proxy-token+ // lease. Otherwise a concurrent close can observe no new directory,+ // revoke the token, and then let this resume launch a doomed child.+ piSubagentResumeTail = Promise.allSettled([piSubagentResumeTail, operation]).then(() => undefined);+ return operation;+ };+let piSpawnStartedAt: number | undefined;let piSpawnLogged = false;try {@@ -5530,7 +5569,12 @@ export class PiAgent extends BaseAgent {deviceHosted: Boolean(hosted),allowPiPackageManagement,piPackageManagementToken,+ resumeSubagent,controlSubagentRunner: async (action, runId) => {+ if (action === 'delivery') {+ return localSubagentSupported && !closed && !accountBoundaryTeardown+ && !proc.isClosed && !isCurrentTurnHostAbortRequested(ctx);+ }if (!localSubagentSupported || !PI_SUBAGENT_RUN_ID_RE.test(runId)) {throw new Error('PI Subagent runner request is unavailable');}@@ -6267,8 +6311,6 @@ export class PiAgent extends BaseAgent {throw new AgentStartupStoppedError(err);}- const launchSubagentRunner = (request: PiSubagentRunnerLaunchRequest): Promise<void> =>- this.launchSubagentRunner(request);const deps = this.deps;const agentKind = this.kind;let firstModelRequestLogged = false;@@ -7386,37 +7428,7 @@ export class PiAgent extends BaseAgent {async resumeBackgroundTask(taskId: string, message: string, childId?: string): Promise<void> {if (closed) throw new Error('PI session is closed');if (!localSubagentSupported) throw new Error('PI Subagent is available only in local PI sessions.');- const operation = (async () => {- await permissionWriteChain;- if (closed) throw new Error('PI session is closed');- const [modelsJson, bridgeSource, runnerSource] = await Promise.all([- fs.readFile(path.join(configHome, 'models.json')),- fs.readFile(bridgeExtensionPath),- fs.readFile(subagentRunnerPath),- ]);- const runId = await resumePiSubagentRun(subagentRunRoot, taskId, message, {- launchRunner: launchSubagentRunner,- env: durableSpawnEnv,- runtimeOwnerId: subagentRuntimeOwnerId,- permissionSnapshot: {- ...requestedPermissionSnapshot,- mode: permissionMode,- readOnlyRoots: [...requestedPermissionSnapshot.readOnlyRoots],- writableRoots: [...requestedPermissionSnapshot.writableRoots],- ...reviewPathSnapshot,- },- runnerFallbackFile: subagentRunnerPath,- runtimeSnapshot: { modelsJson, bridgeSource, runnerSource },- }, childId);- if (!runId) throw new Error('No terminal PI Subagent run is available to resume.');- await requestPiSubagentRefresh();- })();- // close() waits for every resume that entered while this handle was- // live before inspecting durable runs and transferring the proxy-token- // lease. Otherwise a concurrent close can observe no new directory,- // revoke the token, and then let this resume launch a doomed child.- piSubagentResumeTail = operation.then(() => undefined, () => undefined);- await operation;+ await resumeSubagent(taskId, message, childId);},listBackgroundTasks() {@@ -8264,9 +8276,10 @@ export class PiAgent extends BaseAgent {allowPiPackageManagement: boolean;piPackageManagementToken?: string;controlSubagentRunner: (- action: 'launch' | 'terminate' | 'status',+ action: 'launch' | 'terminate' | 'status' | 'delivery',runId: string,) => Promise<boolean>;+ resumeSubagent?: (taskId: string, message: string, childId?: string) => Promise<string>;emitExtensionNotification: (message: string, event?: PiRpcEvent) => AgentEvent;/*** 把一张挂起的权限卡登记进会话级表,返回注销函数。档位切换 / 关闭会话时由@@ -8339,16 +8352,29 @@ export class PiAgent extends BaseAgent {try {const payload = JSON.parse(typeof event.placeholder === 'string' ? event.placeholder : '{}',- ) as { action?: unknown; runId?: unknown };+ ) as { action?: unknown; runId?: unknown; message?: unknown; childId?: unknown };if ((payload.action !== 'launch'&& payload.action !== 'terminate'- && payload.action !== 'status')+ && payload.action !== 'status'+ && payload.action !== 'delivery'+ && payload.action !== 'resume')|| typeof payload.runId !== 'string'|| !PI_SUBAGENT_RUN_ID_RE.test(payload.runId)) {throw new Error('Invalid PI Subagent runner request');}+ if (payload.action === 'resume') {+ if (!context.resumeSubagent || context.isPermissionContextClosed()+ || typeof payload.message !== 'string' || !payload.message.trim()+ || payload.message.length > 32000+ || (payload.childId !== undefined && typeof payload.childId !== 'string')) {+ throw new Error('Invalid PI Subagent resume request');+ }+ const runId = await context.resumeSubagent(payload.runId, payload.message, payload.childId as string | undefined);+ proc.send({ type: 'extension_ui_response', id, value: JSON.stringify({ ok: true, runId }) });+ return;+ }const accepted = await context.controlSubagentRunner(payload.action, payload.runId);proc.send({type: 'extension_ui_response',diff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.tsindex d19fb92896..758e5265e2 100644--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts@@ -162,6 +162,8 @@ export interface PiSubagentTaskStatus {};output?: string;outputTruncated?: boolean;+ /** Final assistant response, distinct from intermediate output before tools. */+ resultReady?: boolean;error?: string;pendingApproval?: {id: string;@@ -2214,7 +2216,7 @@ export async function controlPiSubagentRuns(if (action === 'approval') {return task.pendingApproval?.id === options.approvalId;}- if (action === 'steer' && task.output?.trim()) return false;+ if (action === 'steer' && task.resultReady === true) return false;return task.status === 'queued' || task.status === 'running';},);