Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): report executor exit before descendant pipes close (#4182)
Chris Zhang7e275443b082
diff --git a/docs/research/pi-long-tool-lifecycle-3916.md b/docs/research/pi-long-tool-lifecycle-3916.mdnew file mode 100644index 0000000000..ee37f2497f--- /dev/null+++ b/docs/research/pi-long-tool-lifecycle-3916.md@@ -0,0 +1,129 @@+# Pi 长工具生命周期:#3916 受控取证++## 结论与范围++已在代码级复现并修复一条确定的退出通知缺陷:**Pi 已退出,但工具后代继承+stdout/stderr,Node 的 child `close` 一直等管道 EOF,导致 Cindy 没收到执行者退出通知。**+这不等于已经证明原用户的 Windows exe 打包故障就是此根因;原报告没有对应的+PID/退出码与最后 RPC 帧时间线。++本单只修本地 stdio transport。统一执行者丢失与终态接续归并行的 P0 修复;正文+事件/持久化归 #3696。未修改它们的 coordinator、重放或正文恢复逻辑。++## 版本与既有修复++- [原报告 #3916](https://github.com/makecindy/cindy/issues/3916):客户端 0.1.72,+ 提交时快照为 Windows、Pi、Grok 4.6。原作者称长 exe 打包几乎每次停在「已工作」,+ 需要再发消息才接上;子进程是否仍跑未确认。讨论中的分析与 fico-hub 回复均要求受控取证。+- [0.1.72 发布](https://github.com/makecindy/cindy/releases/tag/v0.1.72):2026-09-03,+ 发布正文锚定 `2a039176935c71ee0e1a6377defccbea738b034b`;Pi pin 为 0.84.4。+- [#3761](https://github.com/makecindy/cindy/issues/3761) 是同类用户现象,但使用 Codex,+ 不把其候选根因当作 Pi 根因。+- [#944](https://github.com/makecindy/cindy/pull/944) 已提供 Session 零事件 watchdog。+ 当前代码仍有该保护;不能笼统声称长工具阶段所有保护都暂停。+- [#3742](https://github.com/makecindy/cindy/pull/3742) 增加 Pi 帧级诊断,已在 0.1.72+ 发布清单中;它不是丢帧恢复。[#2574](https://github.com/makecindy/cindy/pull/2574)+ 属 durable subagent,不证明主 Pi turn 已解决。+- 当前取证基线 `56c0e50028dcf0f5f83fb9a878e5cb32eee8806e` 与 0.1.72 的本地+ transport 都只用 child `error` / `close` 通知退出,没有 child `exit` 的兜底。+- 核对 [Pi 0.84.4 的 rpc-mode.ts](https://github.com/earendil-works/pi/blob/v0.84.4/packages/coding-agent/src/modes/rpc/rpc-mode.ts):普通 prompt 在 preflight 成功时确认接受,+ 不需要等长工具完成才返回。因此不能把 prompt 接受期限直接当成本单根因。++## 受控复现++`pi-long-tool-lifecycle.test.ts` 仅把 transport 的 executable 换成轻量 Node fixture;+使用生产 `PiAgent → PiRpcProcess → translator → AsyncQueue → Session`。+fixture 不调用模型、不运行真实打包,不读取个人凭证;生成物位于独立 `os.tmpdir()` 目录。++失败路径:fixture 确认 prompt、发 `agent_start` 和 `tool_execution_start`,随后+启动继承输出管道的轻量后代并 `exit(23)`。测试直接检查 Pi PID 已不存在、后代 PID 仍存活。++修复前,最初 4 个用例中 3 个对照通过,继承管道用例在 2 秒内始终没有 terminal error,+断言失败。修复后同一路径约 0.3 秒收到包含退出码 23 的 terminal error,Session 自动+关闭;后代仍存活,没有生成工具成功结果,也没有重新发送 prompt。++| 注入情形 | 当前生产链路的观察 | 本单处理 |+| --- | --- | --- |+| 正常工具静默 20 分钟(虚拟时钟),然后完成 | 保持 running;结果、正文、usage、done 到达且自动解锁 | 对照通过;不缩短工具期限 |+| Pi 已退出,后代仍持有管道 | 修复前没有退出终态;修复后明确失败且关闭旧 Session | 已修复 |+| 工具阶段 Pi 普通退出 | 既有 onClose 路径明确报错 | 既有保护通过 |+| 丢 `tool_execution_end`,其余终态到达 | Pi 最终回复仍可见、Session 解锁,但工具结果确实缺失 | 不编造结果、不重跑构建;尚未恢复丢失结果 |+| 丢 `message_end`,工具结果与 settled 到达 | 无正文/该条 usage,现有 `silentStop` 标记生效 | 交 #3696 / 既有续跑责任方,不在本单恢复 |+| 丢 `agent_settled` | 有正文但仍 running;45 分钟现有 watchdog 发明确超时 | 定界用例;本单未加终态轮询 |+| Pi 仍活着,RPC stdout EOF | 不是确认的进程退出;45 分钟现有 watchdog 兜底 | 定界用例;未实现即时 RPC 故障恢复 |+| 用户 Stop | cancelled done,只有一次 abort,没有新 prompt | 取消对照通过 |++另用 transport 单测覆盖退出后尾帧先到、关闭回调一次、关闭后的迟到帧被忽略,+以及 Stop/close 先于或后于 exit 两种竞态;已确认退出后不会再发送 SIGKILL。++## 修复契约++收到 child `exit` 后立即禁止继续写入,最多给输出尾帧 250ms 排空时间;正常 child+`close` 更早到达时沿用原路径。后代迟迟不关闭管道时,复用既有 `fireClose` 通知+上层并释放本端管道,显式 close 的等待也复用该通知。没有新增 supervisor 或共享接口。++250ms 只从**进程已退出**开始计算,不是正常工具、模型静默或整个 turn 的期限。+未添加自动续跑、原请求重放、进程树 kill 或独立 generation 状态机。++兼容:PiTransport 的字段和 `onClose(code, signal, reason)` 契约不变,P0 可独立、乱序+合入并复用;SSH transport 不经过本改动。手机/设备互联控制本地 Pi 时仍消费宿主原有+终态事件;无新增 IPC、wire 字段或 UI 入口,不涉及 relay 重连与多 peer 故障半径。++## 验证与限制++定向验证统一 `--maxWorkers=1 --minWorkers=1`,包括新增全链路 fixture、transport、+translator、两套 RPC client 与 Session watchdog 用例。ESLint 和 `git diff --check`+检查本单文件。最终这 6 个定向文件共 134 个用例通过;根级 `test:runner` 为 511 通过、+1 跳过。++`pnpm test:unit:related -- --workspace-concurrency=1` 第二轮完整通过:Desktop、+lizi-mcps、maker-core related 与 orca-workflow 的无模型单测均通过。定向行为测试保持+单 worker;根门禁的 Desktop 内部沿用仓库默认 8 worker,其余 workspace 串行。+首轮只在无本单改动的 `skillSlot.test.ts` 遇到一次临时软链接 ENOENT;该文件单独+单 worker 复查 27/27 通过,第二轮完整门禁也未再出现。未放宽断言或改插件基座,+该偶发失败的根因尚未确定。++额外 `tsc --noEmit` 发现 `maker.shutdown.test.ts:91` 的 `TS2322`:泛型 resolve 的+可选参数签名与 Promise resolver 不匹配。以 CompilerHost 从 Git HEAD 读取所有已改文件、+排除新增 fixture 后,原基线复现同一个错误;本单没有改该文件。包当前没有 `typecheck`+script,规定的 `run --if-present typecheck` 跳过,不把跳过称作类型检查通过。++缓存/模型指标:未修改 system 前缀、工具 schema、模型路由或 usage 计算。+正常 fixture 的 10 input / 3 output 在 done 中原样保留;热路径只增加一个 closed+布尔检查,无额外 IO/模型调用;新增 timer 每个退出进程最多一个,不进入 token 循环。+未运行真实模型缓存率或吞吐性能基准。++未覆盖:Windows 实机、真实 Pi 二进制 exe 打包、SSH、Renderer 重载/历史重开与 Light/Dark+目检。没有启动 dev、重启正式版、使用 Orca 编排或调用计费模型 API。++释放本端输出管道可能使继续输出的后代遇到 EPIPE;**通知 Pi 退出不等于证明构建后代已+安全停止或成功完成**。原用户根因的最小缺口仍是停住时 Pi/构建 PID 与退出码、最后+RPC 帧和 Session 终态的同轮时间线;本单不能据此宣称 #3916 整体已解决。++## PR 审查补充:关闭失败不能冒充退出++审查指出显式关闭期间 `kill()` 同步触发 `error` 会通过通用关闭通知提前完成 waiter。+受控测试确认:`error` 事件及抛异常两种路径原来都错误地 resolve;修复后保留资源登记,+继续 SIGTERM → SIGKILL,未收到退出证据则 reject,后续仍可重试并由真实 exit 收口。+通用通知中的 waiter 现在显式检查 exitInfo;终止中的 error 只记录错误,不伪造退出。+另覆盖退出发生在 3 秒升级或 8 秒确认期限前 1ms 的情况:排空期间不再发信号,也不误报超时。++另一条审查认为 exit-first/close-second 会立即 resolve 并丢失退出码。加强时序及+code/signal 断言后,在审查所指提交 d8bd012f1 上两种顺序均通过:Promise executor 中+`return` 只退出 executor,不会 resolve 外层 Promise;仍由 250ms 排空通知调用 finish。+因此保留现有排空行为,不将该报告称作已复现缺陷。新增断言持续保护真实退出信息。++## Windows CI fixture 修正++旧提交 d8bd012f1 的 Windows shard 2 在后代存活断言处失败(kill ESRCH,127ms),+不是等待终态超时。Node 22.23.2 的 [libuv Windows 实现](https://github.com/nodejs/node/blob/v22.23.2/deps/uv/src/win/process.c#L69)+将非 detached 子进程加入父进程持有的 kill-on-close Job,因此原 fixture 在 Windows+没有建立“父退出、后代继续持有管道”的前提。仅对测试后代设置 Windows detached,+继续继承输出句柄;保留 PID 存活、明确失败、2 秒终态期限及 afterEach 清理断言。+生产 Pi 的 spawn/进程树策略不变;Windows 修正效果以新提交的 CI 为准。++Windows 后续运行 b1c442b4e 已通过后代存活等行为断言,但 afterEach 删除临时目录时+遇到 EBUSY。清理现在区分“发出 kill”与“退出已确认”:等待该 fixture PID 的 ESRCH+再删除目录,文件系统残留锁采用有界异步重试,避免阻塞事件循环;不吞掉清理失败。+同轮 shard 1 的 Windows mutex 探测与飞书 Unicode 校验超时未改动相关源码,+前一提交的同 shard 曾通过,尚无基线复现证据;由新 CI 复查,不认定已确定为偶发。diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.tsnew file mode 100644index 0000000000..1576754724--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts@@ -0,0 +1,252 @@+import { mkdtempSync } from 'node:fs';+import { rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { PiTransport } from '../transport.js';+import type { AgentEvent } from '../../../types/events.js';+import type { AgentDeps } from '../../base-agent.js';+import type { Logger } from '../../../interfaces/logger.js';++const fixture = vi.hoisted(() => ({ transport: null as PiTransport | null }));++// Replace only the executable. PiAgent, RPC framing, translator, queue and+// Session are production code. No provider or real build is involved.+vi.mock('../transport.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../transport.js')>();+ return {+ ...actual,+ createPiStdioTransport: (opts: Parameters<typeof actual.createPiStdioTransport>[0]) => {+ const program = `+ const { spawn } = require('node:child_process');+ const readline = require('node:readline');+ const output = frame => process.stdout.write(JSON.stringify(frame) + '\\n');+ const result = { content: [{ type: 'text', text: 'fixture build complete' }] };+ let rpcLost = false;+ const finish = (omit) => {+ if (omit !== 'tool_execution_end') output({ type: 'tool_execution_end', toolCallId: 'build-1', toolName: 'bash', result });+ if (omit !== 'message_end') output({ type: 'message_end', message: { role: 'assistant', content: [{ type: 'text', text: 'Build finished.' }],+ stopReason: 'stop', usage: { input: 10, output: 3, cacheRead: 0, cacheWrite: 0, totalTokens: 13 } } });+ if (omit !== 'agent_settled') output({ type: 'agent_settled' });+ };+ readline.createInterface({ input: process.stdin }).on('line', line => {+ const cmd = JSON.parse(line);+ if (rpcLost) return process.exit(23);+ if (cmd.type === 'fixture_finish') return finish(cmd.omit);+ if (cmd.type === 'fixture_lose_rpc') {+ rpcLost = true;+ output({ type: 'fixture_rpc_losing' });+ return process.stdout.end();+ }+ if (cmd.type === 'fixture_exit_with_descendant') {+ const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000)'], {+ // libuv's Windows job kills non-detached children on parent exit.+ // This fixture specifically needs a surviving pipe owner; production+ // spawn options remain unchanged, and afterEach owns its cleanup.+ detached: process.platform === 'win32',+ stdio: ['ignore', process.stdout, process.stderr], env: process.env+ });+ child.once('spawn', () => {+ output({ type: 'fixture_descendant', pid: child.pid });+ // Drain the fixture metadata before exiting, leaving both pipes+ // open in the descendant exactly as a shell/build child can.+ process.stdout.write('', () => process.exit(23));+ });+ return;+ }+ if (cmd.type === 'fixture_exit') return process.exit(23);+ output({ type: 'response', id: cmd.id, command: cmd.type, success: true,+ data: cmd.type === 'get_state'+ ? { sessionFile: '/fixture/session.jsonl', model: { id: 'm', provider: 'cindy', contextWindow: 200000 } }+ : { commands: [], entries: [] } });+ if (cmd.type === 'prompt') {+ output({ type: 'agent_start' });+ output({ type: 'tool_execution_start', toolCallId: 'build-1', toolName: 'bash', args: { command: 'fixture-build', timeout: 1800 } });+ }+ if (cmd.type === 'abort') output({ type: 'agent_settled' });+ });+ `;+ const env: Record<string, string | undefined> = {};+ for (const key of ['PATH', 'Path', 'SystemRoot', 'SYSTEMROOT', 'TMPDIR', 'TEMP', 'TMP']) {+ if (process.env[key] !== undefined) env[key] = process.env[key];+ }+ fixture.transport = actual.createPiStdioTransport({+ ...opts, binaryPath: process.execPath, args: ['-e', program], env,+ });+ return fixture.transport;+ },+ };+});++import { PiAgent } from '../index.js';+import { Session } from '../../../session.js';++const logger: Logger = {+ trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger,+};++describe('Pi long tool lifecycle through real stdio RPC', () => {+ let root = '';+ let session: Session | undefined;+ let descendantPid: number | undefined;++ afterEach(async () => {+ vi.useRealTimers();+ // Only terminate the descendant created and reported by this fixture.+ if (descendantPid) {+ try { process.kill(descendantPid, 'SIGKILL'); } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;+ }+ // kill() requests termination; on Windows the descendant can still hold+ // its inherited cwd open until exit completes. Confirm before deleting it.+ await vi.waitFor(() => {+ try { process.kill(descendantPid!, 0); } catch (error) {+ expect(error).toMatchObject({ code: 'ESRCH' });+ return;+ }+ throw new Error('fixture descendant has not exited');+ }, { timeout: 2000, interval: 20 });+ }+ await session?.close();+ if (root) await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });+ session = undefined;+ descendantPid = undefined;+ fixture.transport = null;+ });++ async function start(fakeClock = false) {+ root = mkdtempSync(path.join(tmpdir(), 'pi-long-tool-'));+ const deps: AgentDeps = {+ auth: {+ getState: async () => ({ authenticated: true, identity: 'fixture', authSource: 'api-key' as const }),+ triggerLogin: async () => ({ authenticated: true }), logout: async () => {}, getAuthEnv: async () => ({}),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },+ binaryPath: path.join(root, 'pi'), logger,+ resolvePiAgentHome: () => root,+ resolvePiGatewayModelApi: () => 'openai-responses',+ capabilityAdditions: { availableModels: [+ { id: 'm', displayName: 'fixture', contextWindow: 200000, efforts: [], defaultEffort: null },+ ] },+ };+ const agent = new PiAgent(deps);+ const handle = await agent.startSession({ sessionId: 'long-tool', workingDir: root, model: 'm' });+ const transport = fixture.transport!;+ const nativeFrames: string[] = [];+ transport.onLine(line => {+ const frame = JSON.parse(line);+ nativeFrames.push(frame.type);+ if (frame.type === 'fixture_descendant') descendantPid = frame.pid;+ });+ const events: AgentEvent[] = [];+ if (fakeClock) vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });+ session = new Session({+ id: 'long-tool', agentKind: 'pi', workDir: root, handle,+ capabilities: agent.capabilities, logger,+ });+ session.onEvent(event => events.push(event));+ await session.send('Build the fixture');+ await vi.waitFor(() => expect(events.some(event => event.type === 'tool_use')).toBe(true));+ return { events, transport, handle, nativeFrames };+ }++ it('keeps a quiet live tool running and delivers its result, usage and terminal without another send', async () => {+ const { events, transport, handle } = await start(true);+ // Twenty minutes without model tokens or tool output is not evidence of+ // failure. Stay within the native bash tool's supported 30-minute budget.+ await vi.advanceTimersByTimeAsync(20 * 60_000);+ expect(handle.isTurnRunning?.()).toBe(true);+ expect(events.some(event => event.type === 'done' || event.type === 'error')).toBe(false);+ await transport.writeLine(JSON.stringify({ type: 'fixture_finish' }));+ await vi.waitFor(() => expect(events.some(event => event.type === 'done')).toBe(true));+ expect(events.find(event => event.type === 'tool_result_full')?.data).toMatchObject({ fullText: 'fixture build complete' });+ expect(events.find(event => event.type === 'done')?.data).toMatchObject({+ result: 'Build finished.', status: 'completed', usage: {+ inputTokens: 10, outputTokens: 3, turnDurationMs: expect.any(Number),+ },+ });+ const usage = (events.find(event => event.type === 'done')!.data as {+ usage: { turnDurationMs: number; durationMs?: number };+ }).usage;+ expect(usage.turnDurationMs).toBeGreaterThanOrEqual(20 * 60_000);+ // Tool wall time must not be charged as model generation time/TPS.+ expect(usage.durationMs).toBeUndefined();+ expect(session!.isTurnRunning()).toBe(false);+ });++ it('reports executor exit while a build descendant still holds the RPC pipes open', async () => {+ const { events, transport } = await start();+ await transport.writeLine(JSON.stringify({ type: 'fixture_exit_with_descendant' }));+ await vi.waitFor(() => expect(descendantPid).toBeTypeOf('number'));+ await vi.waitFor(() => expect(() => process.kill(transport.pid!, 0)).toThrow());+ await vi.waitFor(() => expect(events.some(event => event.type === 'error')).toBe(true), { timeout: 2000 });+ expect(events.find(event => event.type === 'error')?.data).toMatchObject({+ isTerminal: true, message: expect.stringContaining('code=23'),+ });+ // Failure of Pi does not prove the build stopped or succeeded.+ expect(() => process.kill(descendantPid!, 0)).not.toThrow();+ expect(events.some(event => event.type === 'tool_result_full')).toBe(false);+ await vi.waitFor(() => expect(session!.getStatus()).toBe('closed'));+ });++ it('reports ordinary RPC process exit during a tool', async () => {+ const { events, transport } = await start();+ await transport.writeLine(JSON.stringify({ type: 'fixture_exit' }));+ await vi.waitFor(() => expect(events.some(event => event.type === 'error')).toBe(true));+ });++ it('does not invent a lost tool result when Pi settles with its final answer', async () => {+ const { events, transport } = await start();+ await transport.writeLine(JSON.stringify({ type: 'fixture_finish', omit: 'tool_execution_end' }));+ await vi.waitFor(() => expect(events.some(event => event.type === 'done')).toBe(true));+ expect(events.some(event => event.type === 'tool_result_full')).toBe(false);+ expect(events.find(event => event.type === 'done')?.data).toMatchObject({ result: 'Build finished.' });+ expect(session!.isTurnRunning()).toBe(false);+ // The missing result is an upstream evidence gap; executor-exit handling+ // must not replay the build or fabricate its output to fill that gap.+ });++ it('distinguishes missing message_end from a missing agent_settled', async () => {+ const { events, transport } = await start();+ await transport.writeLine(JSON.stringify({ type: 'fixture_finish', omit: 'message_end' }));+ await vi.waitFor(() => expect(events.some(event => event.type === 'done')).toBe(true));+ expect(events.find(event => event.type === 'done')?.data).toMatchObject({+ result: '', silentStop: true, usage: { outputTokens: 0 },+ });+ expect(events.some(event => event.type === 'tool_result_full')).toBe(true);+ expect(session!.isTurnRunning()).toBe(false);+ });++ it('leaves a missing settled frame to the existing bounded Session watchdog', async () => {+ const { events, transport } = await start(true);+ await transport.writeLine(JSON.stringify({ type: 'fixture_finish', omit: 'agent_settled' }));+ await vi.waitFor(() => expect(events.some(event => event.type === 'text')).toBe(true));+ expect(session!.isTurnRunning()).toBe(true);+ expect(events.some(event => event.type === 'done')).toBe(false);+ await vi.advanceTimersByTimeAsync(45 * 60_000 + 1);+ expect(events.find(event => event.type === 'error')?.data).toMatchObject({ reason: 'turn_no_event_timeout' });+ });++ it('distinguishes RPC EOF with a live executor from confirmed process exit', async () => {+ const { events, transport, nativeFrames } = await start(true);+ await transport.writeLine(JSON.stringify({ type: 'fixture_lose_rpc' }));+ await vi.waitFor(() => expect(nativeFrames).toContain('fixture_rpc_losing'));+ expect(() => process.kill(transport.pid!, 0)).not.toThrow();+ expect(events.some(event => event.type === 'error')).toBe(false);+ // EOF alone currently has no native executor-exit proof. Characterize the+ // existing fallback honestly; the new exit drain must not kill a live tool.+ await vi.advanceTimersByTimeAsync(45 * 60_000 + 1);+ expect(events.find(event => event.type === 'error')?.data).toMatchObject({ reason: 'turn_no_event_timeout' });+ });++ it('honors Stop without issuing another prompt or reviving the tool', async () => {+ const { events, transport } = await start();+ const write = vi.spyOn(transport, 'writeLine');+ await session!.abort();+ await vi.waitFor(() => expect(events.some(event => event.type === 'done')).toBe(true));+ expect(events.find(event => event.type === 'done')?.data).toMatchObject({ status: 'cancelled' });+ expect(write.mock.calls.map(([line]) => JSON.parse(line).type)).toEqual(['abort']);+ expect(session!.isTurnRunning()).toBe(false);+ });+});diff --git a/packages/maker-core/src/agents/pi/__tests__/transport.test.ts b/packages/maker-core/src/agents/pi/__tests__/transport.test.tsindex f1561065a1..d3102c9540 100644--- a/packages/maker-core/src/agents/pi/__tests__/transport.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/transport.test.ts@@ -33,15 +33,18 @@ function makeChild(pid = 4321) {child.pid = pid;child.stdout = new EventEmitter();child.stderr = new EventEmitter();- child.stdin = { write: vi.fn() };+ Object.assign(child.stdout, { destroy: vi.fn() });+ Object.assign(child.stderr, { destroy: vi.fn() });+ child.stdin = { write: vi.fn(), destroy: vi.fn() } as typeof child.stdin;child.kill = vi.fn();return child;}-function makeTransport(): { transport: PiTransport; child: ReturnType<typeof makeChild> } {+function makeTransport(onProcessSpawned?: (pid: number) => (() => void)): { transport: PiTransport; child: ReturnType<typeof makeChild> } {const child = makeChild();mocks.spawn.mockReturnValue(child);const transport = createPiStdioTransport({+ onProcessSpawned,binaryPath: '/pi',args: ['--mode', 'rpc'],cwd: '/work',@@ -159,6 +162,53 @@ describe('createPiStdioTransport', () => {}});+ it.each(['event', 'throw'])('does not confirm termination when kill fails via %s', async (failure) => {+ vi.useFakeTimers();+ try {+ const dispose = vi.fn();+ const { transport, child } = makeTransport(() => dispose);+ const onClose = vi.fn();+ transport.onClose(onClose);+ child.kill.mockImplementation(() => {+ const error = new Error('kill EPERM');+ if (failure === 'throw') throw error;+ child.emit('error', error);+ return false;+ });+ const closing = transport.close();+ const rejected = expect(closing).rejects.toThrow(/did not confirm exit/);+ await vi.advanceTimersByTimeAsync(8000);+ await rejected;+ expect(child.kill.mock.calls).toEqual([['SIGTERM'], ['SIGKILL']]);+ expect(onClose).not.toHaveBeenCalled();+ expect(dispose).not.toHaveBeenCalled();+ child.kill.mockImplementation(() => true);+ const retry = transport.close();+ child.emit('exit', 23, null);+ await vi.advanceTimersByTimeAsync(250);+ await retry;+ expect(onClose).toHaveBeenCalledWith(expect.objectContaining({ code: 23, signal: null }));+ expect(dispose).toHaveBeenCalledTimes(1);+ } finally { vi.useRealTimers(); }+ });++ it.each([2999, 7999])('preserves confirmed exit while draining across the %i ms termination deadline', async (exitAt) => {+ vi.useFakeTimers();+ try {+ const { transport, child } = makeTransport();+ const onClose = vi.fn();+ transport.onClose(onClose);+ const closing = transport.close();+ await vi.advanceTimersByTimeAsync(exitAt);+ const signals = child.kill.mock.calls.map(([signal]) => signal);+ child.emit('exit', 23, null);+ await vi.advanceTimersByTimeAsync(250);+ await closing;+ expect(child.kill.mock.calls.map(([signal]) => signal)).toEqual(signals);+ expect(onClose).toHaveBeenCalledWith(expect.objectContaining({ code: 23, signal: null }));+ } finally { vi.useRealTimers(); }+ });+it('writeLine rejects when closed', async () => {const { transport, child } = makeTransport();child.emit('close', 0, null);@@ -201,6 +251,53 @@ describe('createPiStdioTransport', () => {expect(handler).toHaveBeenCalledWith('line1');expect(handler).toHaveBeenCalledWith('line2');});++ it('drains exit tail frames before notifying executor loss, even without pipe EOF', async () => {+ vi.useFakeTimers();+ try {+ const { transport, child } = makeTransport();+ const observed: string[] = [];+ transport.onLine(line => observed.push(line));+ transport.onClose(info => observed.push(`exit:${info.code}`));+ child.emit('exit', 23, null);+ await expect(transport.writeLine('{}')).rejects.toThrow(/closed/);+ child.stdout.emit('data', '{"type":"message_end"}\n{"type":"agent_settled"}\n');+ expect(observed).toEqual(['{"type":"message_end"}', '{"type":"agent_settled"}']);+ await vi.advanceTimersByTimeAsync(250);+ expect(observed.at(-1)).toBe('exit:23');+ child.stdout.emit('data', '{"type":"late-descendant-output"}\n');+ child.emit('close', 23, null);+ expect(observed).toHaveLength(3);+ expect(child.kill).not.toHaveBeenCalled();+ } finally { vi.useRealTimers(); }+ });++ it.each([false, true])('close racing executor exit reuses the same drain (close first: %s)', async (closeFirst) => {+ vi.useFakeTimers();+ try {+ const { transport, child } = makeTransport();+ const onClose = vi.fn();+ transport.onClose(onClose);+ let closing: Promise<void>;+ if (closeFirst) {+ closing = transport.close();+ child.emit('exit', null, 'SIGTERM');+ } else {+ child.emit('exit', 23, null);+ closing = transport.close();+ }+ await vi.advanceTimersByTimeAsync(249);+ expect(onClose).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ await closing;+ expect(onClose).toHaveBeenCalledTimes(1);+ expect(onClose).toHaveBeenCalledWith(expect.objectContaining(closeFirst+ ? { code: null, signal: 'SIGTERM' } : { code: 23, signal: null }));+ expect(child.kill.mock.calls).toEqual(closeFirst ? [['SIGTERM']] : []);+ await vi.advanceTimersByTimeAsync(8000);+ expect(child.kill).not.toHaveBeenCalledWith('SIGKILL');+ } finally { vi.useRealTimers(); }+ });});describe('attachJsonlReader', () => {diff --git a/packages/maker-core/src/agents/pi/transport.ts b/packages/maker-core/src/agents/pi/transport.tsindex 92e5b78884..128e691d4d 100644--- a/packages/maker-core/src/agents/pi/transport.ts+++ b/packages/maker-core/src/agents/pi/transport.ts@@ -118,6 +118,8 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo// run a fresh SIGTERM -> SIGKILL sequence.let closing = false;let closeAttempt: Promise<void> | null = null;+ let exitInfo: PiTransportCloseInfo | null = null;+ let exitDrainTimer: ReturnType<typeof setTimeout> | undefined;let disposeProcessRegistration: (() => void) | undefined;if (child.pid != null && child.pid > 0) {try {@@ -143,6 +145,8 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspoconst fireClose = (info: PiTransportCloseInfo): void => {if (closed) return;closed = true;+ if (exitDrainTimer) clearTimeout(exitDrainTimer);+ exitDrainTimer = undefined;disposeRegistration();for (const handler of closeHandlers) {try { handler(info); } catch { /* handler should not throw */ }@@ -168,6 +172,7 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo};attachJsonlReader(child.stdout, (line) => {+ if (closed) return;for (const handler of lineHandlers) handler(line);});attachJsonlReader(child.stderr, (line) => {@@ -182,11 +187,35 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspochild.on('error', (err) => {logger.error('pi process error', { message: err.message });+ // kill() may synchronously emit error (e.g. EPERM). An error while+ // terminating is not exit evidence: retain registration and the attempt's+ // escalation/confirmation timers until exit or close actually arrives.+ if (closing) return;fireClose({ code: null, signal: null, reason: `pi process error: ${err.message}` });});child.on('close', (code, signal) => {fireClose({ code, signal, reason: `pi process exited (code=${code}, signal=${signal})` });});+ child.on('exit', (code, signal) => {+ // A shell/build descendant can inherit the pipes after Pi itself exits.+ // Node's `close` then waits for that descendant, potentially indefinitely.+ // Exit is authoritative executor loss, but allow already-written RPC tail+ // frames to drain before notifying owners. This is NOT a tool timeout:+ // a quiet, live Pi process never enters this path.+ closing = true;+ const info = { code, signal, reason: `pi process exited (code=${code}, signal=${signal})` };+ exitInfo = info;+ if (closed) return;+ exitDrainTimer = setTimeout(() => {+ fireClose(info);+ // Release only our pipe endpoints after the confirmed executor exit.+ // No process-tree kill or automatic command replay is performed.+ child.stdout.destroy();+ child.stderr.destroy();+ child.stdin.destroy();+ }, 250);+ exitDrainTimer.unref?.();+ });const KILL_GRACE_MS = 3_000;// SIGKILL 后确认退出的窗口(轮 40-w4-t3 HIGH —— 对齐 session-registry)。@@ -203,15 +232,20 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspoconst finish = (): void => {if (done) return;done = true;- clearTimeout(killTimer);+ if (killTimer) clearTimeout(killTimer);if (confirmTimer) clearTimeout(confirmTimer);child.removeListener('close', onClose);+ closeHandlers.delete(onConfirmedExit);resolve();};const onClose = (): void => finish();- const killTimer = setTimeout(() => {- try { child.kill('SIGKILL'); } catch { /* already gone */ }+ const onConfirmedExit = (): void => { if (exitInfo) finish(); };+ const killTimer = exitInfo ? undefined : setTimeout(() => {+ if (exitInfo) return; // Confirmed exit is still draining its tail frames.+ try { child.kill('SIGKILL'); } catch { /* still require exit confirmation */ }+ if (done) return;confirmTimer = setTimeout(() => {+ if (exitInfo) return;survived = true;logger.error('pi process did not confirm exit after SIGKILL', {pid: child.pid,@@ -220,12 +254,16 @@ export function createPiStdioTransport(opts: PiStdioTransportOptions): PiTranspo}, KILL_CONFIRM_MS);confirmTimer.unref?.();}, KILL_GRACE_MS);- killTimer.unref?.();+ killTimer?.unref?.();+ // The same close notification also completes an explicit Stop/close+ // racing an exit whose inherited pipes have not reached EOF yet.+ closeHandlers.add(onConfirmedExit);child.once('close', onClose);+ if (exitInfo) return;try {child.kill('SIGTERM');} catch {- finish();+ // A thrown kill failure is not proof of exit either. Keep escalation.}});