Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): 正式包 Subagent 改走 utilityProcess 启动 (#3427)

Chris Zhangb2a28104a7cf
diff --git a/apps/desktop/eslint.config.mjs b/apps/desktop/eslint.config.mjs
index 953c5a8228..5fc095c592 100644
--- a/apps/desktop/eslint.config.mjs
+++ b/apps/desktop/eslint.config.mjs
@@ -11,9 +11,9 @@ export default tseslint.config(
},
{
files: ['src/main/**/*.{ts,tsx}'],
- // watcher-host、workdir-probe-host、Review PDF 与 Ghost Node broker 是受测的
- // utilityProcess 宿主,和 localDb 一样属于“进程边界基建”,只对精确入口
- // 豁免导入限制。
+ // watcher-host、workdir-probe-host、Review PDF、Ghost Node broker 与 Pi Subagent
+ // 后台宿主是受测的 utilityProcess 基建,和 localDb 一样属于“进程边界基建”,
+ // 只对精确入口豁免导入限制。
ignores: [
'src/main/localDb/**/*.{ts,tsx}',
'src/main/watcher-host/**/*.{ts,tsx}',
@@ -21,6 +21,7 @@ export default tseslint.config(
'src/main/mcp-integrations/forgeIconConversionHost.ts',
'src/main/reviewer/reviewPdfProcess.ts',
'src/main/cindy-brain/nodeRuntimeBroker.ts',
+ 'src/main/cindy-brain/piSubagentRunnerHost.ts',
'src/main/__spike__/**/*.{ts,tsx}',
],
rules: {
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index bc118c28e8..807e7a6245 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -1600,6 +1600,13 @@ const config: ForgeConfig = {
// 避免把挂死 I/O 留在 Electron main 的 libuv 线程池。
target: 'preload',
},
+ {
+ entry: 'src/main/cindy-brain/piSubagentRunnerProcess.ts',
+ config: 'vite.preload.config.ts',
+ // 正式包关闭 RunAsNode;Pi Subagent 后台管理程序通过固定的
+ // utility-process 入口执行,开发版和正式包保持同一进程边界。
+ target: 'preload',
+ },
{
entry: 'src/main/cindy-brain/nodeRuntimeWorkerProcess.ts',
config: 'vite.preload.config.ts',
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts
index 2c12afcd06..b07b40eb90 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts
@@ -21,6 +21,29 @@ describe('Node runtime packaging contract', () => {
expect(forge).toContain('[FuseV1Options.OnlyLoadAppFromAsar]: true');
});
+ it('Pi Subagent 与正式包的 RunAsNode=false 契约使用同一受支持入口', () => {
+ const forge = fs.readFileSync(path.join(desktopRoot, 'forge.config.ts'), 'utf8');
+ const piHost = fs.readFileSync(path.join(desktopRoot, 'src/main/maker-host/pi-host.ts'), 'utf8');
+ const runtime = fs.readFileSync(path.join(desktopRoot, 'src/main/cindy-brain/piSubagentRunnerHost.ts'), 'utf8');
+ const repoRoot = path.resolve(desktopRoot, '..', '..');
+ const subagentSource = fs.readFileSync(
+ path.join(repoRoot, 'packages/maker-core/src/agents/pi/cindy-subagent-source.ts'),
+ 'utf8',
+ );
+ const piAgent = fs.readFileSync(
+ path.join(repoRoot, 'packages/maker-core/src/agents/pi/index.ts'),
+ 'utf8',
+ );
+
+ expect(forge).toContain("entry: 'src/main/cindy-brain/piSubagentRunnerProcess.ts'");
+ expect(forge).toContain('[FuseV1Options.RunAsNode]: false');
+ expect(runtime).toContain('utilityProcess.fork');
+ expect(piHost).toContain('spawnPiSubagentRunner,');
+ expect(subagentSource).not.toContain('ELECTRON_RUN_AS_NODE');
+ expect(subagentSource).not.toContain('CINDY_PI_SUBAGENT_NODE');
+ expect(piAgent).not.toContain('[CINDY_SUBAGENT_ENV.nodeExecutable]');
+ });
+
it('scaffold worker is parentPort-only and does not reopen RunAsNode', () => {
const worker = fs.readFileSync(
path.join(desktopRoot, 'src/main/cindy-brain/forgeScaffoldWorkerProcess.ts'),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/piSubagentRunnerHost.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/piSubagentRunnerHost.test.ts
new file mode 100644
index 0000000000..6a7d48a466
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/piSubagentRunnerHost.test.ts
@@ -0,0 +1,140 @@
+import { EventEmitter } from 'node:events';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { spawnPiSubagentRunner } from '../piSubagentRunnerHost.js';
+
+class FakeUtilityProcess extends EventEmitter {
+ readonly pid = 2468;
+ readonly kill = vi.fn(() => true);
+}
+
+describe('piSubagentRunnerHost', () => {
+ it('uses the fixed utility-process entry and forwards only the staged runner paths', () => {
+ const child = new FakeUtilityProcess();
+ const fork = vi.fn(() => child);
+ const runId = '123e4567-e89b-42d3-a456-4266141740aa';
+ const runDir = path.join(path.sep, 'tmp', runId);
+ const request = {
+ runId,
+ runDir,
+ runnerFile: path.join(runDir, 'runner.cjs'),
+ configFile: path.join(runDir, 'config.json'),
+ cwd: '/tmp',
+ env: { TEST_VALUE: '1' },
+ };
+ const processHandle = spawnPiSubagentRunner(request, fork as never);
+
+ expect(fork).toHaveBeenCalledWith(
+ expect.stringMatching(/piSubagentRunnerProcess\.js$/),
+ [path.resolve(request.runnerFile), path.resolve(request.configFile)],
+ expect.objectContaining({
+ cwd: '/tmp',
+ env: { TEST_VALUE: '1' },
+ stdio: 'ignore',
+ serviceName: `cindy-pi-subagent:${runId}`,
+ }),
+ );
+
+ const spawned = vi.fn();
+ const exited = vi.fn();
+ const closed = vi.fn();
+ processHandle.once('spawn', spawned);
+ processHandle.once('exit', exited);
+ processHandle.once('close', closed);
+ child.emit('message', { type: 'ready' });
+ expect(spawned).toHaveBeenCalledTimes(1);
+
+ child.emit('exit', 0);
+ expect(exited).toHaveBeenCalledWith(0, null);
+ expect(closed).toHaveBeenCalledWith(0, null);
+ });
+
+ it('keeps original absolute paths when a parent directory is a symlink', () => {
+ const alias = `${path.sep}alias${path.sep}home`;
+ const real = `${path.sep}real${path.sep}home`;
+ const realpathSync = vi.spyOn(fs, 'realpathSync').mockImplementation((file) => {
+ return String(file).split(alias).join(real);
+ });
+ const fork = vi.fn(() => new FakeUtilityProcess());
+ const runId = '123e4567-e89b-42d3-a456-4266141740aa';
+ const runDir = path.join(alias, runId);
+ const request = {
+ runId,
+ runDir,
+ runnerFile: path.join(runDir, 'runner.cjs'),
+ configFile: path.join(runDir, 'config.json'),
+ cwd: '/tmp',
+ env: {},
+ };
+ spawnPiSubagentRunner(request, fork as never);
+ expect(fork).toHaveBeenCalledWith(
+ expect.stringMatching(/piSubagentRunnerProcess\.js$/),
+ [path.resolve(request.runnerFile), path.resolve(request.configFile)],
+ expect.objectContaining({ cwd: '/tmp' }),
+ );
+ realpathSync.mockRestore();
+ });
+
+ it('accepts normalized paths inside the run directory', () => {
+ const fork = vi.fn(() => new FakeUtilityProcess());
+ const runId = '123e4567-e89b-42d3-a456-4266141740aa';
+ const runDir = path.join(path.sep, 'tmp', runId);
+ spawnPiSubagentRunner({
+ runId,
+ runDir,
+ runnerFile: path.join(runDir, '.', 'runner.cjs'),
+ configFile: path.join(runDir, 'config.json'),
+ cwd: '/tmp',
+ env: {},
+ }, fork as never);
+ expect(fork).toHaveBeenCalledTimes(1);
+ });
+
+ it('adds Windows taskkill /F only for SIGKILL so SIGTERM can publish stopped', () => {
+ const source = fs.readFileSync(new URL('../piSubagentRunnerHost.ts', import.meta.url), 'utf8');
+ expect(source).toContain("if (signal === 'SIGKILL') args.push('/F')");
+ expect(source).not.toMatch(/taskkill', \['\/PID', String\(pid\), '\/T', '\/F'\]/);
+ });
+
+ it('signals SIGTERM to the utility-process pid so the runner can reap children', () => {
+ const child = new FakeUtilityProcess();
+ const fork = vi.fn(() => child);
+ const runId = '123e4567-e89b-42d3-a456-4266141740aa';
+ const runDir = path.join(path.sep, 'tmp', runId);
+ const processHandle = spawnPiSubagentRunner({
+ runId,
+ runDir,
+ runnerFile: path.join(runDir, 'runner.cjs'),
+ configFile: path.join(runDir, 'config.json'),
+ cwd: '/tmp',
+ env: {},
+ }, fork as never);
+ const realKill = process.kill.bind(process);
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(((pid: number, signal?: NodeJS.Signals | number) => {
+ if (pid !== child.pid) return realKill(pid, signal);
+ return true;
+ }) as typeof process.kill);
+ expect(processHandle.kill('SIGTERM')).toBe(true);
+ expect(killSpy).toHaveBeenCalledWith(child.pid, 'SIGTERM');
+ expect(child.kill).not.toHaveBeenCalled();
+ killSpy.mockRestore();
+ });
+
+ it('rejects runner or config paths outside the declared run directory', () => {
+ const fork = vi.fn();
+ const runId = '123e4567-e89b-42d3-a456-4266141740aa';
+ const runDir = path.join(path.sep, 'tmp', runId);
+ expect(() => spawnPiSubagentRunner({
+ runId,
+ runDir,
+ runnerFile: path.join(path.sep, 'tmp', 'runner.cjs'),
+ configFile: path.join(runDir, 'config.json'),
+ cwd: '/tmp',
+ env: {},
+ }, fork as never)).toThrow(/paths are invalid/);
+ expect(fork).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/piSubagentRunnerHost.ts b/apps/desktop/src/main/cindy-brain/piSubagentRunnerHost.ts
new file mode 100644
index 0000000000..915a7028cc
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/piSubagentRunnerHost.ts
@@ -0,0 +1,121 @@
+import { spawnSync } from 'node:child_process';
+import { EventEmitter } from 'node:events';
+import fs from 'node:fs';
+import path from 'node:path';
+import { utilityProcess } from 'electron';
+
+import type {
+ PiSubagentRunnerLaunchRequest,
+ PiSubagentRunnerProcess,
+} from '@cindy/maker-core';
+
+function resolveLaunchPath(file: string): string {
+ const resolved = path.resolve(file);
+ try {
+ return fs.realpathSync(resolved);
+ } catch {
+ return resolved;
+ }
+}
+
+function isContainedRunnerLayout(
+ runId: string,
+ runDir: string,
+ runnerFile: string,
+ configFile: string,
+): boolean {
+ return path.basename(runnerFile) === 'runner.cjs'
+ && path.basename(configFile) === 'config.json'
+ && path.dirname(runnerFile) === runDir
+ && path.dirname(configFile) === runDir
+ && path.basename(runDir) === runId;
+}
+
+/** Launch a durable PI Subagent runner through Electron's supported Node service. */
+export function spawnPiSubagentRunner(
+ request: PiSubagentRunnerLaunchRequest,
+ fork: typeof utilityProcess.fork = utilityProcess.fork,
+): PiSubagentRunnerProcess {
+ const requestedRunDir = path.resolve(request.runDir);
+ const requestedRunnerFile = path.resolve(request.runnerFile);
+ const requestedConfigFile = path.resolve(request.configFile);
+ const runDir = resolveLaunchPath(request.runDir);
+ const runnerFile = resolveLaunchPath(request.runnerFile);
+ const configFile = resolveLaunchPath(request.configFile);
+ if (
+ !isContainedRunnerLayout(request.runId, requestedRunDir, requestedRunnerFile, requestedConfigFile)
+ || !isContainedRunnerLayout(request.runId, runDir, runnerFile, configFile)
+ ) {
+ throw new Error('PI Subagent runner paths are invalid');
+ }
+
+ const hostEntry = path.join(__dirname, 'piSubagentRunnerProcess.js');
+ const child = fork(hostEntry, [requestedRunnerFile, requestedConfigFile], {
+ cwd: request.cwd,
+ env: request.env,
+ stdio: 'ignore',
+ serviceName: `cindy-pi-subagent:${request.runId}`,
+ ...(process.platform === 'darwin' ? { disclaim: true } : {}),
+ });
+ const events = new EventEmitter();
+ let ready = false;
+ let killed = false;
+
+ child.on('message', (message) => {
+ if (
+ !ready
+ && message
+ && typeof message === 'object'
+ && !Array.isArray(message)
+ && (message as Record<string, unknown>).type === 'ready'
+ ) {
+ ready = true;
+ events.emit('spawn');
+ }
+ });
+ child.on('exit', (code) => {
+ killed = true;
+ events.emit('exit', code, null);
+ events.emit('close', code, null);
+ });
+ child.on('error', (type, location) => {
+ events.emit('error', new Error(`PI Subagent utility process ${type} at ${location}`));
+ });
+
+ const adapter: PiSubagentRunnerProcess = {
+ get pid() {
+ return child.pid;
+ },
+ get killed() {
+ return killed;
+ },
+ once(event, listener) {
+ events.once(event, listener);
+ return adapter;
+ },
+ kill(signal): boolean {
+ killed = true;
+ const pid = child.pid;
+ if (pid !== undefined && process.platform === 'win32') {
+ const args = ['/PID', String(pid), '/T'];
+ if (signal === 'SIGKILL') args.push('/F');
+ const tree = spawnSync('taskkill', args, {
+ windowsHide: true,
+ stdio: 'ignore',
+ timeout: 5_000,
+ });
+ if (!tree.error && tree.status === 0) return true;
+ }
+ if (pid !== undefined) {
+ try {
+ process.kill(pid, signal ?? 'SIGTERM');
+ return true;
+ } catch {
+ // The process may already be gone or the platform may not support the signal.
+ }
+ }
+ return child.kill();
+ },
+ };
+ return adapter;
+}
diff --git a/apps/desktop/src/main/cindy-brain/piSubagentRunnerProcess.ts b/apps/desktop/src/main/cindy-brain/piSubagentRunnerProcess.ts
new file mode 100644
index 0000000000..1e41fe2007
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/piSubagentRunnerProcess.ts
@@ -0,0 +1,36 @@
+import { createRequire } from 'node:module';
+import path from 'node:path';
+
+interface ParentPortLike {
+ postMessage(message: unknown): void;
+}
+
+const parentPort = (process as unknown as { parentPort?: ParentPortLike }).parentPort;
+const runnerFile = process.argv[2];
+const configFile = process.argv[3];
+
+if (!parentPort) throw new Error('PI Subagent runner process is missing parentPort');
+if (
+ typeof runnerFile !== 'string'
+ || !path.isAbsolute(runnerFile)
+ || path.basename(runnerFile) !== 'runner.cjs'
+ || typeof configFile !== 'string'
+ || !path.isAbsolute(configFile)
+ || path.basename(configFile) !== 'config.json'
+ || path.dirname(runnerFile) !== path.dirname(configFile)
+) {
+ throw new Error('PI Subagent runner process arguments are invalid');
+}
+
+parentPort.postMessage({ type: 'ready' });
+try {
+ Object.defineProperty(process, 'parentPort', {
+ configurable: true,
+ value: undefined,
+ });
+} catch {
+ // The host accepts only the fixed ready frame; leaving an inaccessible port is harmless.
+}
+
+process.argv = [process.argv[0], runnerFile, configFile];
+createRequire(__filename)(runnerFile);
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 43d1b1515b..252b037076 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -56,6 +56,7 @@ import type {
import { getReadyBinaryPath } from '../agent-binaries/index.js';
import { t } from '../i18n.js';
+import { spawnPiSubagentRunner } from '../cindy-brain/piSubagentRunnerHost.js';
import { getPiExtraSpawnConfig } from '../mcp-integrations/piEnvironment.js';
import { listCustomProvidersWithSecureHeaders } from './custom-provider-header-secrets.js';
import {
@@ -1628,6 +1629,7 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {
logger: opts.logger,
turnChangeCapture: opts.turnChangeCapture,
registerLocalAgentProcess: opts.registerLocalAgentProcess,
+ spawnPiSubagentRunner,
derivePiProxySessionToken,
capabilityAdditions: opts.capabilityAdditions,
reviewAutoPermissionAction: opts.reviewAutoPermissionAction,
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index face382ddb..1d7eda1622 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -130,6 +130,22 @@ Claude Code 仍用独立百分比。env:`CINDY_PI_API_KEY`、
extension(`cindy-bridge` / `cindy-subagent`)源码字节必须进入 launch identity:
`CINDY_PI_EXTENSION_BUNDLE_HASH` 只由源码确定,禁止随机数或时间戳;字节不变可 reattach,
字节变化必须 restart。
+11. **正式包后台脚本启动边界**:Desktop 正式包保持 `RunAsNode=false`,因此 Main 的
+ `process.execPath` 是 Cindy 应用程序,**不是 Node 可执行文件**。Pi Subagent 的 durable
+ runner 必须经 host 注入的 `spawnPiSubagentRunner` 交给 Desktop
+ `utilityProcess.fork` 固定入口执行;扩展与 maker-core 不得再拼
+ `ELECTRON_RUN_AS_NODE=1` 或把 `process.execPath` 写入子代理 env。开发版 / Vitest 里
+ `process.execPath` 恰好可执行 JavaScript 不构成生产证据。打包契约测试必须同时断言
+ `RunAsNode=false`、固定 utility-process 入口在 forge 清单中、Pi host 使用该入口,避免
+ 两份各自正确的测试再次掩盖跨模块矛盾。身份校验必须读未截断命令行(POSIX `ps -ww`
+ / Linux `/proc/<pid>/cmdline`);成功读到的命令行不含本 run 的 `runnerScript` 即
+ 视为 gone,只有读失败才 unverifiable。紧急停止和就绪超时都先对 runner pid 发 SIGTERM
+ 再 SIGKILL,禁止 `kill(-pid)` 把 utility-process 当成独立进程组。未确认退出不得写
+ failed 终态(控制协议要带回 unconfirmed),否则 quit / 账号边界 sweep 会跳过仍可能活着的 runner。
+ 真正 spawn 前必须再读一次账号边界,并把在途 launch 纳入 teardown 收敛。Host 只用
+ realpath 校验包含关系,传给 runner 的 argv 必须与 `config.runDir` 同一套原始绝对路径。
+ dispose 未确认 runner 退出必须失败;Host 观察到的退出要能通过控制协议通知前台等待,不能只靠 status.json。
+ Windows 上 SIGTERM 不得带 taskkill /F;前台若已读到终态必须先返回,不得被 Host 退出通知盖成失败。
## 5. 已交付(2026-07 里程碑)
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 7e4be94f94..7191b3a7cc 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -475,6 +475,27 @@ export interface PiExtensionUiStrings {
mutationSuccess: Record<PiManagedPackageMutationRequest['action'], string>;
}
+export interface PiSubagentRunnerProcess {
+ readonly pid?: number;
+ readonly killed: boolean;
+ once(event: 'spawn', listener: () => void): this;
+ once(event: 'error', listener: (error: Error) => void): this;
+ once(
+ event: 'exit' | 'close',
+ listener: (code: number | null, signal: NodeJS.Signals | null) => void,
+ ): this;
+ kill(signal?: NodeJS.Signals): boolean;
+}
+
+export interface PiSubagentRunnerLaunchRequest {
+ runId: string;
+ runDir: string;
+ runnerFile: string;
+ configFile: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+}
+
export interface AgentDeps {
/** Optional low-I/O, provider-neutral turn change recorder supplied by the host. */
turnChangeCapture?: TurnChangeCaptureHooks;
@@ -550,6 +571,15 @@ export interface AgentDeps {
*/
getPiExtensionUiStrings?: () => PiExtensionUiStrings;
+ /**
+ * Pi-only: start a durable Subagent runner through a host-supported Node
+ * process boundary. Desktop injects Electron utilityProcess; maker-core never
+ * assumes that the application executable can run JavaScript.
+ */
+ spawnPiSubagentRunner?: (
+ request: PiSubagentRunnerLaunchRequest,
+ ) => PiSubagentRunnerProcess;
+
/**
* Pi-only: resolve the immutable Cindy project-approval input for one new
* runtime. The host owns identity canonicalization, approval audit/revocation,
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts
index ecfe6f98d2..7b27957d79 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts
@@ -1,3 +1,4 @@
+import { spawn, type ChildProcess } from 'node:child_process';
import { chmod, mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
@@ -8,12 +9,14 @@ import ts from 'typescript';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CINDY_SUBAGENT_RUNNER_SOURCE } from '../cindy-subagent-runner-source.js';
+import { recordPiSubagentRunnerFailure } from '../pi-subagent-runs.js';
import {
CINDY_SUBAGENT_ENV,
CINDY_SUBAGENT_EXTENSION_SOURCE,
} from '../cindy-subagent-source.js';
const roots: string[] = [];
+const children = new Set<ChildProcess>();
const require = createRequire(import.meta.url);
async function fixture() {
@@ -103,7 +106,46 @@ process.stdin.on('end', () => process.exit(0));
return { root, configHome, runRoot, permissionFile, runtimeFile, runnerFile, fakePi, extensionFile };
}
+function hostInput(f: Awaited<ReturnType<typeof fixture>>, permission = 'allow') {
+ const runners = new Map<string, ChildProcess>();
+ return vi.fn(async (title: string, placeholder: string) => {
+ if (title !== 'cindy:pi-subagent-runner') return permission;
+ const request = JSON.parse(placeholder) as { action: 'launch' | 'terminate' | 'status'; runId: string };
+ const runDir = path.join(f.runRoot, request.runId);
+ if (request.action === 'status') {
+ return JSON.stringify({ ok: true });
+ }
+ if (request.action === 'terminate') {
+ const child = runners.get(request.runId);
+ if (child) child.kill('SIGTERM');
+ return JSON.stringify({ ok: true });
+ }
+ const child = spawn(process.execPath, [path.join(runDir, 'runner.cjs'), path.join(runDir, 'config.json')], {
+ cwd: f.root,
+ env: process.env,
+ stdio: 'ignore',
+ });
+ runners.set(request.runId, child);
+ children.add(child);
+ child.once('close', (code, signal) => {
+ runners.delete(request.runId);
+ children.delete(child);
+ void recordPiSubagentRunnerFailure(
+ runDir,
+ `Durable runner exited${signal ? ` with signal ${signal}` : ''}`
+ + (typeof code === 'number' ? ` with code ${code}` : ''),
+ );
+ });
+ return new Promise<string>((resolve) => {
+ child.once('spawn', () => resolve(JSON.stringify({ ok: true })));
+ child.once('error', () => resolve(JSON.stringify({ ok: false })));
+ });
+ });
+}
+
afterEach(async () => {
+ for (const child of children) child.kill('SIGKILL');
+ children.clear();
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
@@ -119,7 +161,6 @@ describe('Cindy PI Subagent foreground durable path', () => {
[CINDY_SUBAGENT_ENV.runtimeFile]: f.runtimeFile,
[CINDY_SUBAGENT_ENV.runRoot]: f.runRoot,
[CINDY_SUBAGENT_ENV.runnerFile]: f.runnerFile,
- [CINDY_SUBAGENT_ENV.nodeExecutable]: process.execPath,
[CINDY_SUBAGENT_ENV.ownerId]: 'foreground-owner',
CINDY_PI_PERMISSION_FILE: f.permissionFile,
CINDY_PI_SESSION_ID: 'parent-session',
@@ -154,7 +195,7 @@ describe('Cindy PI Subagent foreground durable path', () => {
const extension = require(f.extensionFile).default as (pi: { registerTool: (tool: unknown) => void }) => Promise<void>;
await extension({ registerTool: (tool) => Object.assign(registered, tool) });
expect(registered.execute).toBeTypeOf('function');
- const input = vi.fn(async () => 'allow');
+ const input = hostInput(f);
const result = await registered.execute!(
'tool-foreground',
{ agent: 'worker', task: 'write the fixture', model: 'claude-fable-5' },
@@ -200,27 +241,27 @@ describe('Cindy PI Subagent foreground durable path', () => {
[CINDY_SUBAGENT_ENV.runtimeFile]: f.runtimeFile,
[CINDY_SUBAGENT_ENV.runRoot]: f.runRoot,
[CINDY_SUBAGENT_ENV.runnerFile]: f.runnerFile,
- [CINDY_SUBAGENT_ENV.nodeExecutable]: process.execPath,
[CINDY_SUBAGENT_ENV.ownerId]: 'foreground-owner',
CINDY_PI_PERMISSION_FILE: f.permissionFile,
CINDY_PI_SESSION_ID: 'parent-session',
PI_CODING_AGENT_DIR: f.configHome,
});
- const registered: { execute?: (...args: any[]) => Promise<unknown> } = {};
+ 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 input = hostInput(f);
const execution = registered.execute!(
'tool-runner-exit',
{ agent: 'scout', task: 'inspect the fixture' },
new AbortController().signal,
() => undefined,
- { sessionManager: { getBranch: () => [] } },
+ { ui: { input }, sessionManager: { getBranch: () => [] } },
);
await expect(Promise.race([
execution,
new Promise((_, reject) => setTimeout(() => reject(new Error('foreground wait hung')), 5_000)),
- ])).rejects.toThrow(/exited before publishing a terminal status.*exit 7/i);
+ ])).rejects.toThrow(/Durable runner exited.*code 7/i);
} finally {
for (const key of Object.keys(process.env)) if (!(key in previous)) delete process.env[key];
Object.assign(process.env, previous);
@@ -266,7 +307,6 @@ setTimeout(() => process.exit(0), 20000).unref();
[CINDY_SUBAGENT_ENV.runtimeFile]: f.runtimeFile,
[CINDY_SUBAGENT_ENV.runRoot]: f.runRoot,
[CINDY_SUBAGENT_ENV.runnerFile]: f.runnerFile,
- [CINDY_SUBAGENT_ENV.nodeExecutable]: process.execPath,
[CINDY_SUBAGENT_ENV.ownerId]: 'foreground-owner',
CINDY_PI_PERMISSION_FILE: f.permissionFile,
CINDY_PI_SESSION_ID: 'parent-session',
@@ -277,13 +317,14 @@ setTimeout(() => process.exit(0), 20000).unref();
try {
const extension = require(f.extensionFile).default as (pi: { registerTool: (tool: unknown) => void }) => Promise<void>;
await extension({ registerTool: (tool) => Object.assign(registered, tool) });
+ const input = hostInput(f);
const startedAt = Date.now();
const execution = registered.execute!(
'tool-abort-wedged-runner',
{ agent: 'scout', task: 'inspect the fixture' },
controller.signal,
() => undefined,
- { sessionManager: { getBranch: () => [] } },
+ { ui: { input }, sessionManager: { getBranch: () => [] } },
);
setTimeout(() => controller.abort(), 50);
// The bound is the 5s stop grace, not the run deadline (which is at
@@ -335,25 +376,32 @@ setTimeout(() => process.exit(0), 20000).unref();
const fs = require('node:fs');
const path = require('node:path');
const config = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
+let settled = false;
+const publishStopped = () => {
+ if (settled) return;
+ settled = true;
+ const now = Date.now();
+ const status = {
+ version: 1, runId: config.runId, taskId: config.taskId,
+ parentSessionId: config.parentSessionId, runnerInstanceId: 'abort-fixture',
+ state: 'stopped', startedAt: now, updatedAt: now, endedAt: now,
+ tasks: config.tasks.map((task) => ({
+ childId: task.childId, sessionId: task.sessionId, agent: task.agent,
+ status: 'stopped', error: 'stopped before first status', endedAt: now,
+ })),
+ };
+ fs.writeFileSync(path.join(config.runDir, 'status.json'), JSON.stringify(status) + '\\n');
+ process.exit(0);
+};
+process.on('SIGTERM', publishStopped);
const timer = setInterval(() => {
let files = [];
try { files = fs.readdirSync(path.join(config.runDir, 'controls')); } catch {}
for (const file of files) {
const control = JSON.parse(fs.readFileSync(path.join(config.runDir, 'controls', file), 'utf8'));
if (control.action !== 'stop') continue;
- const now = Date.now();
- const status = {
- version: 1, runId: config.runId, taskId: config.taskId,
- parentSessionId: config.parentSessionId, runnerInstanceId: 'abort-fixture',
- state: 'stopped', startedAt: now, updatedAt: now, endedAt: now,
- tasks: config.tasks.map((task) => ({
- childId: task.childId, sessionId: task.sessionId, agent: task.agent,
- status: 'stopped', error: 'stopped before first status', endedAt: now,
- })),
- };
- fs.writeFileSync(path.join(config.runDir, 'status.json'), JSON.stringify(status) + '\\n');
clearInterval(timer);
- process.exit(0);
+ publishStopped();
}
}, 20);
// Publish readiness only after the stop-control poller is installed. Writing
@@ -369,23 +417,23 @@ setTimeout(() => process.exit(2), 5000).unref();
[CINDY_SUBAGENT_ENV.runtimeFile]: f.runtimeFile,
[CINDY_SUBAGENT_ENV.runRoot]: f.runRoot,
[CINDY_SUBAGENT_ENV.runnerFile]: f.runnerFile,
- [CINDY_SUBAGENT_ENV.nodeExecutable]: process.execPath,
[CINDY_SUBAGENT_ENV.ownerId]: 'foreground-owner',
CINDY_PI_PERMISSION_FILE: f.permissionFile,
CINDY_PI_SESSION_ID: 'parent-session',
PI_CODING_AGENT_DIR: f.configHome,
});
- const registered: { execute?: (...args: any[]) => Promise<unknown> } = {};
+ 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 input = hostInput(f);
const execution = registered.execute!(
'tool-abort-before-status',
{ agent: 'scout', task: 'inspect the fixture' },
controller.signal,
() => undefined,
- { sessionManager: { getBranch: () => [] } },
+ { ui: { input }, sessionManager: { getBranch: () => [] } },
);
// Abort only after the runner is up. A 50ms timer races spawn and the
// parent reports "Durable runner exited" instead of the stop status.
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts
index a078903b44..fdd55bc247 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts
@@ -39,6 +39,26 @@ import {
const roots: string[] = [];
+async function launchRunnerWithNode(request: {
+ runnerFile: string;
+ configFile: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+}): Promise<void> {
+ const child = spawn(process.execPath, [request.runnerFile, request.configFile], {
+ cwd: request.cwd,
+ env: request.env,
+ detached: true,
+ windowsHide: true,
+ stdio: 'ignore',
+ });
+ child.unref();
+ await new Promise<void>((resolve, reject) => {
+ child.once('spawn', resolve);
+ child.once('error', reject);
+ });
+}
+
/**
* `runner.cjs` is byte-identical for every fixture and by far the biggest file
* each one writes. Writing it once for the suite keeps ~30 real file creations
@@ -630,7 +650,7 @@ describe('Cindy durable PI Subagent runner', () => {
function resumeLaunch(fixture: Awaited<ReturnType<typeof makeFixture>>) {
return {
- nodeExecutable: process.execPath,
+ launchRunner: launchRunnerWithNode,
runtimeOwnerId: 'resume-owner',
runnerFallbackFile: fixture.runnerFile,
env: {
@@ -897,7 +917,7 @@ describe('Cindy durable PI Subagent runner', () => {
first.runId,
'continue from the prior result',
{
- nodeExecutable: process.execPath,
+ launchRunner: launchRunnerWithNode,
runtimeOwnerId: 'resume-owner',
runnerFallbackFile: fixture.runnerFile,
env: {
@@ -946,7 +966,7 @@ describe('Cindy durable PI Subagent runner', () => {
resumedRunId!,
'continue for a second resumed generation',
{
- nodeExecutable: process.execPath,
+ launchRunner: launchRunnerWithNode,
runtimeOwnerId: 'resume-owner',
runnerFallbackFile: fixture.runnerFile,
env: {
@@ -993,7 +1013,7 @@ describe('Cindy durable PI Subagent runner', () => {
first.runId,
'continue from redirected catalog',
{
- nodeExecutable: process.execPath,
+ launchRunner: launchRunnerWithNode,
runtimeOwnerId: 'resume-owner',
runnerFallbackFile: fixture.runnerFile,
env: process.env,
@@ -1016,7 +1036,7 @@ describe('Cindy durable PI Subagent runner', () => {
first.runId,
'continue without leaving partial staging',
{
- nodeExecutable: process.execPath,
+ launchRunner: launchRunnerWithNode,
runtimeOwnerId: 'resume-owner',
runnerFallbackFile: fixture.runnerFile,
env: process.env,
@@ -1038,7 +1058,7 @@ describe('Cindy durable PI Subagent runner', () => {
});
await waitForClose(fixture.child, fixture.stderr);
const launch = {
- nodeExecutable: process.execPath,
+ launchRunner: launchRunnerWithNode,
runtimeOwnerId: 'resume-owner',
runnerFallbackFile: fixture.runnerFile,
env: {
diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts
index 026fce46e6..ecc50f59c8 100644
--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentSource.test.ts
@@ -11,6 +11,7 @@ import {
CINDY_SUBAGENT_EXTENSION_FILENAME,
CINDY_SUBAGENT_EXTENSION_SOURCE,
CINDY_SUBAGENT_PARENT_PID_ENV,
+ CINDY_SUBAGENT_RUNNER_CONTROL_TITLE,
CINDY_SUBAGENT_TOOL_NAME,
} from '../cindy-subagent-source.js';
import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';
@@ -146,20 +147,37 @@ describe('cindy-subagent extension source', () => {
expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('childConfigHome: childConfigHome');
});
- it('persists a terminal failure if the detached runner cannot spawn', () => {
- expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("runner.once('error'");
+ it('persists a terminal failure if the host rejects the runner launch', () => {
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("await requestRunnerControl(ctx, 'launch', runId)");
expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("state: 'failed'");
expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("writePrivateJson(join(runDir, 'status.json')");
expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("runnerInstanceId: 'launch-pending-' + runId");
});
- it('publishes the run directory before reading the fence, and spawns after', () => {
- // The Host cannot prevent this spawn by scanning: it happens here, inside
- // Pi, in an extension the Host never calls. A single fence read before the
- // spawn is not enough either — the Host could raise the fence and finish
- // scanning in the gap between the read and the write. What makes it
- // airtight is the *order*: the Host writes its fence and then scans, this
- // writes its run directory and then reads. Opposite orders, so at least one
+ it('does not persist failed when the host reports an unconfirmed runner exit', () => {
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('response.unconfirmed === true');
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('{ unconfirmed: true }');
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(
+ 'if (!(err && err.unconfirmed)) persistFailureIfNeeded(message)',
+ );
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(
+ 'if (!unconfirmed) persistFailureIfNeeded(message)',
+ );
+ });
+
+ it('never treats the packaged application executable as Node', () => {
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain('ELECTRON_RUN_AS_NODE');
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain('CINDY_PI_SUBAGENT_NODE');
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain('spawn(nodeExecutable');
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(
+ `const RUNNER_CONTROL_TITLE = '${CINDY_SUBAGENT_RUNNER_CONTROL_TITLE}';`,
+ );
+ });
+
+ it('publishes the run directory before reading the fence, and asks the host to launch after', () => {
+ // The extension publishes its intent before asking the Host to launch. The
+ // Host raises its fence before scanning, while the extension writes the run
+ // directory before reading that fence. Opposite orders ensure at least one
// side always sees the other. Both halves are pinned here because either
// one moving re-opens the hole.
const src = CINDY_SUBAGENT_EXTENSION_SOURCE;
@@ -171,11 +189,11 @@ describe('cindy-subagent extension source', () => {
);
// The pre-per-host name stays readable through the upgrade window.
expect(src).toContain("const LEGACY_LAUNCH_FENCE_FILENAME = '.launch-fence.json'");
- const launch = src.indexOf('function launchDurableRun(');
+ const launch = src.indexOf('async function launchDurableRun(');
const mkdir = src.indexOf('mkdirSync(runDir', launch);
const publish = src.indexOf("writePrivateJson(join(runDir, 'status.json')", launch);
const check = src.indexOf('if (launchFenceBlocksSpawn(runRoot, runtimeOwnerId)) {', launch);
- const spawned = src.indexOf('spawn(nodeExecutable', launch);
+ const spawned = src.indexOf("await requestRunnerControl(ctx, 'launch', runId)", launch);
expect(mkdir).toBeGreaterThan(launch);
expect(publish).toBeGreaterThan(mkdir);
expect(check).toBeGreaterThan(publish);
@@ -214,7 +232,7 @@ describe('cindy-subagent extension source', () => {
const src = CINDY_SUBAGENT_EXTENSION_SOURCE;
const body = src.slice(
src.indexOf("const LAUNCH_FENCE_PREFIX = '.launch-fence-'"),
- src.indexOf('function launchDurableRun('),
+ src.indexOf('async function launchDurableRun('),
);
const gateFor = (read: (file: string) => string): (root: string, owner: string) => boolean => (
new Function(
@@ -293,7 +311,7 @@ describe('cindy-subagent extension source', () => {
const guard = src.indexOf('if (runtime.pending) {');
const execute = src.indexOf('async execute(toolCallId');
expect(guard).toBeGreaterThan(execute);
- const dispatch = src.indexOf('const launched = launchDurableRun(', guard);
+ const dispatch = src.indexOf('const launched = await launchDurableRun(', guard);
expect(dispatch).toBeGreaterThan(guard);
});
@@ -446,15 +464,18 @@ describe('cindy-subagent extension source', () => {
}
});
- it('escalates to its own handle when taskkill reports failure', () => {
- // spawnSync 的失败只体现在返回值(status / error)上,不进 catch。不检查 = Windows 上
- // fallback 永远不可达:runner 里的 child.kill 死代码,扩展里则干等满 grace 才升级。
+ it('keeps Windows taskkill fallback inside the durable runner and delegates runner termination to the host', () => {
+ // Child PI processes still belong to the durable runner, so its Windows
+ // taskkill fallback remains. The extension no longer owns the runner
+ // process handle; it asks Desktop to terminate through the supported host
+ // process boundary instead.
expect(CINDY_SUBAGENT_RUNNER_SOURCE).toMatch(
/const killed = spawnSync\('taskkill'[\s\S]*?if \(killed\.error \|\| killed\.status !== 0\) child\.kill\(signal\);/,
);
- expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toMatch(
- /const killed = spawnSync\('taskkill'[\s\S]*?if \(killed\.error \|\| killed\.status !== 0\) runner\.kill\('SIGKILL'\);/,
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain(
+ "await requestRunnerControl(ctx, 'terminate', runId)",
);
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).not.toContain("runner.kill('SIGKILL')");
});
it('records parent start time and checks process identity in the runner watchdog', () => {
@@ -509,6 +530,59 @@ describe('cindy-subagent extension source', () => {
expect(source).toContain("kind: terminal ? 'terminal' : 'spawn'");
});
+ it('rechecks the account boundary before spawning a durable runner', () => {
+ const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '../index.ts'), 'utf8');
+ const control = source.indexOf('controlSubagentRunner: async (action, runId)');
+ const launch = source.indexOf('const launching = this.launchSubagentRunner({', control);
+ const recheck = source.lastIndexOf('if (accountBoundaryTeardown)', launch);
+ expect(control).toBeGreaterThan(-1);
+ expect(recheck).toBeGreaterThan(control);
+ expect(launch).toBeGreaterThan(recheck);
+ expect(source).toContain('inFlightSubagentLaunches');
+ expect(source).toContain('ok: false, unconfirmed: true');
+ const postSpawn = source.indexOf('if (accountBoundaryTeardown)', launch);
+ expect(postSpawn).toBeGreaterThan(launch);
+ expect(source.indexOf('PiSubagentRunnerExitUnconfirmedError', postSpawn))
+ .toBeGreaterThan(postSpawn);
+ expect(source).toContain('PI Subagent runner did not confirm exit');
+ expect(source).toContain("action: 'launch' | 'terminate' | 'status'");
+ const live = source.indexOf('this.subagentRunners.has(runId)', control);
+ const belong = source.indexOf('PI Subagent runner request does not belong to this task', control);
+ expect(live).toBeGreaterThan(control);
+ expect(belong).toBeGreaterThan(live);
+ expect(source.slice(control, belong)).toContain('if (action === \'terminate\' && live)');
+ const runnerControl = source.indexOf('event.title === CINDY_SUBAGENT_RUNNER_CONTROL_TITLE');
+ const boundary = source.indexOf('isAccountBoundaryTornDown()', runnerControl);
+ const boundaryUnconfirmed = source.indexOf("ok: false, unconfirmed: true", boundary);
+ expect(boundary).toBeGreaterThan(runnerControl);
+ expect(boundaryUnconfirmed).toBeGreaterThan(boundary);
+ expect(source.slice(boundary, boundaryUnconfirmed + 80)).not.toContain('cancelled: true');
+ });
+
+ it('lets the foreground waiter observe a host exit when status.json cannot be written', () => {
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain("await requestRunnerControl(ctx, 'status', launched.runId)");
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('err.runnerExited');
+ expect(CINDY_SUBAGENT_EXTENSION_SOURCE).toContain('response.exited === true');
+ const wait = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf('async function waitForDurableRun(');
+ const terminal = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf(
+ "status.state === 'completed' || status.state === 'failed' || status.state === 'stopped'",
+ wait,
+ );
+ const hostPoll = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf(
+ "await requestRunnerControl(ctx, 'status', launched.runId)",
+ wait,
+ );
+ expect(terminal).toBeGreaterThan(wait);
+ expect(hostPoll).toBeGreaterThan(terminal);
+ const exited = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf('err.runnerExited', hostPoll);
+ const reread = CINDY_SUBAGENT_EXTENSION_SOURCE.indexOf(
+ "join(launched.runDir, 'status.json')",
+ exited,
+ );
+ expect(exited).toBeGreaterThan(hostPoll);
+ expect(reread).toBeGreaterThan(exited);
+ });
+
it('does not store an English resume prefix as the run title', () => {
const source = readFileSync(
path.join(path.dirname(fileURLToPath(import.meta.url)), '../pi-subagent-runs.ts'),
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.ts
index c4a3339cbb..cb7ae72883 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
@@ -9,6 +9,7 @@
* (CI / 未装 pi 的环境不红)。
*/
+import { spawn } from 'node:child_process';
import { createServer, type Server } from 'node:http';
import {
chmodSync,
@@ -400,6 +401,17 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
],
},
resolvePiAgentHome: () => agentHome,
+ spawnPiSubagentRunner: (request) => {
+ const child = spawn(process.execPath, [request.runnerFile, request.configFile], {
+ cwd: request.cwd,
+ env: request.env,
+ detached: true,
+ windowsHide: true,
+ stdio: 'ignore',
+ });
+ child.unref();
+ return child as never;
+ },
resolvePiGatewayModelApi: () => 'anthropic-messages',
};
}
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.ts
index 2f8b806b8e..aac432a253 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
@@ -29,6 +29,14 @@ const captured = vi.hoisted(() => ({
onEvent: null as ((event: unknown) => void) | null,
requests: [] as Array<Record<string, unknown>>,
sent: [] as Array<Record<string, unknown>>,
+ runnerLaunches: [] as Array<{
+ runId: string;
+ runDir: string;
+ runnerFile: string;
+ configFile: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ }>,
proxyRegistrations: [] as Array<{
sessionId: string;
token: string;
@@ -171,6 +179,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
captured.onEvent = null;
captured.requests = [];
captured.sent = [];
+ captured.runnerLaunches = [];
captured.proxyRegistrations = [];
captured.mcpVendorOptions = undefined;
captured.failSetModel = false;
@@ -286,6 +295,30 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
},
resolvePiGatewayModelApi: () => 'openai-responses',
resolvePiAgentHome: () => agentHome,
+ spawnPiSubagentRunner: (request) => {
+ captured.runnerLaunches.push(request);
+ const listeners = new Map<string, Array<(...args: unknown[]) => void>>();
+ const emit = (event: string, ...args: unknown[]): void => {
+ for (const listener of listeners.get(event) ?? []) listener(...args);
+ };
+ const handle = {
+ pid: 4321,
+ killed: false,
+ once(event: 'spawn' | 'error' | 'exit' | 'close', listener: (...args: unknown[]) => void) {
+ const queued = listeners.get(event) ?? [];
+ queued.push(listener);
+ listeners.set(event, queued);
+ if (event === 'spawn') queueMicrotask(listener);
+ return handle;
+ },
+ kill: () => {
+ handle.killed = true;
+ queueMicrotask(() => emit('exit', 0, 'SIGTERM'));
+ return true;
+ },
+ };
+ return handle as never;
+ },
registerPiProxySession: (sessionId, token, _resolveProviderId, options) => {
captured.proxyRegistrations.push({
sessionId,
@@ -369,6 +402,20 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
});
}
+ function fireSubagentRunnerRequest(
+ id: string,
+ action: 'launch' | 'terminate',
+ runId: string,
+ ): void {
+ captured.onEvent!({
+ type: 'extension_ui_request',
+ method: 'input',
+ id,
+ title: 'cindy:pi-subagent-runner',
+ placeholder: JSON.stringify({ action, runId }),
+ });
+ }
+
it('spawns with a private managed rg path, default prompt and no restrictive tool allowlist', async () => {
if (process.platform === 'win32') {
// Windows 的环境变量键不区分大小写,无法同时构造“仅有小写键”的进程环境。
@@ -422,6 +469,68 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {
expect(captured.env.no_proxy).toBeUndefined();
});
+ it('asks the host to launch a durable runner without treating the app executable as Node', async () => {
+ const previousNode = process.env.ELECTRON_RUN_AS_NODE;
+ const previousLegacy = process.env.CINDY_PI_SUBAGENT_NODE;
+ process.env.ELECTRON_RUN_AS_NODE = '1';
+ process.env.CINDY_PI_SUBAGENT_NODE = '/Applications/Cindy.app/Contents/MacOS/Cindy';
+ try {
+ await start();
+ expect(captured.env.CINDY_PI_SUBAGENT_NODE).toBeUndefined();
+ expect(captured.env.ELECTRON_RUN_AS_NODE).toBeUndefined();
+ const runRoot = captured.env.CINDY_PI_SUBAGENT_RUN_ROOT;
+ const ownerId = captured.env.CINDY_PI_SUBAGENT_OWNER_ID;
+ expect(runRoot).toBeTruthy();
+ expect(ownerId).toBeTruthy();
+
+ const runId = '123e4567-e89b-42d3-a456-4266141740aa';
+ const runDir = path.join(runRoot!, runId);
+ mkdirSync(runDir, { recursive: true });
+ writeFileSync(path.join(runDir, 'runner.cjs'), "'use strict';\n");
+ writeFileSync(path.join(runDir, 'config.json'), '{}\n');
+ writeFileSync(path.join(runDir, 'status.json'), `${JSON.stringify({
+ version: 1,
+ runId,
+ taskId: 'tool-runner-host',
+ parentSessionId: 's1',
+ runtimeOwnerId: ownerId,
+ runnerInstanceId: `launch-pending-${runId}`,
+ state: 'queued',
+ startedAt: Date.now(),
+ updatedAt: Date.now(),
+ tasks: [{
+ childId: `${runId}-1`,
+ sessionId: `${runId}-1`,
+ agent: 'scout',
+ status: 'queued',
+ }],
+ })}\n`);
+
+ fireSubagentRunnerRequest('runner-launch', 'launch', runId);
+ const response = await waitForResponse('runner-launch');
+ expect(JSON.parse(String(response.value))).toEqual({ ok: true, confirmed: true });
+ expect(captured.runnerLaunches).toHaveLength(1);
+ expect(captured.runnerLaunches[0]).toMatchObject({
+ runId,
+ runDir,
+ runnerFile: path.join(runDir, 'runner.cjs'),
+ configFile: path.join(runDir, 'config.json'),
+ cwd,
+ });
+ expect(captured.runnerLaunches[0]?.env.ELECTRON_RUN_AS_NODE).toBeUndefined();
+ expect(captured.runnerLaunches[0]?.env.CINDY_PI_SUBAGENT_NODE).toBeUndefined();
+
+ fireSubagentRunnerRequest('runner-stop', 'terminate', runId);
+ const stop = await waitForResponse('runner-stop');
+ expect(JSON.parse(String(stop.value))).toEqual({ ok: true, confirmed: true });
+ } finally {
+ if (previousNode === undefined) delete process.env.ELECTRON_RUN_AS_NODE;
+ else process.env.ELECTRON_RUN_AS_NODE = previousNode;
+ if (previousLegacy === undefined) delete process.env.CINDY_PI_SUBAGENT_NODE;
+ else process.env.CINDY_PI_SUBAGENT_NODE = previousLegacy;
+ }
+ });
+
it('routes chat-requested Pi extension installs into the host-managed store', async () => {
const mutatePiManagedPackage = vi.fn(async () => ({
changed: true,
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.ts
index a4872b54dd..1476fc4569 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
@@ -96,6 +96,19 @@ const noopLogger: Logger = {
child: () => noopLogger,
};
+function testSubagentRunnerHost() {
+ const handle = {
+ pid: 4321,
+ killed: false,
+ once(event: 'spawn' | 'error' | 'exit' | 'close', listener: (...args: unknown[]) => void) {
+ if (event === 'spawn') queueMicrotask(listener);
+ return handle;
+ },
+ kill: () => true,
+ };
+ return handle as never;
+}
+
describe('Pi provider-aware model routing', () => {
let agentHome = '';
@@ -289,6 +302,7 @@ describe('Pi provider-aware model routing', () => {
logger: noopLogger,
capabilityAdditions: { availableModels },
resolvePiAgentHome: () => agentHome,
+ spawnPiSubagentRunner: testSubagentRunnerHost,
resolvePiGatewayModelApi: () => 'openai-responses',
registerPiProxySession: (_sessionId, token, resolveProviderId, options) => {
if (options?.scope !== 'subagent-route') resolveProxyProviderId = resolveProviderId;
@@ -581,6 +595,7 @@ describe('Pi provider-aware model routing', () => {
}],
},
resolvePiAgentHome: () => agentHome,
+ spawnPiSubagentRunner: testSubagentRunnerHost,
resolvePiNativeProviders: async () => ({
providers: [
{
@@ -655,6 +670,7 @@ describe('Pi provider-aware model routing', () => {
],
},
resolvePiAgentHome: () => agentHome,
+ spawnPiSubagentRunner: testSubagentRunnerHost,
resolvePiNativeProviders: async () => ({
providers: [
{
@@ -821,6 +837,7 @@ describe('Pi provider-aware model routing', () => {
}],
},
resolvePiAgentHome: () => agentHome,
+ spawnPiSubagentRunner: testSubagentRunnerHost,
resolvePiNativeProviders: async () => ({
providers: [{
id: 'xai',
@@ -873,6 +890,7 @@ describe('Pi provider-aware model routing', () => {
}],
},
resolvePiAgentHome: () => agentHome,
+ spawnPiSubagentRunner: testSubagentRunnerHost,
resolvePiNativeProviders: async () => ({
providers: [{
id: 'xai',
@@ -2365,6 +2383,7 @@ describe('Pi provider-aware model routing', () => {
availableModels,
},
resolvePiAgentHome: () => agentHome,
+ spawnPiSubagentRunner: testSubagentRunnerHost,
resolvePiGatewayModelApi: () => 'anthropic-messages',
resolvePiNativeProviders,
});
diff --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.ts
index 2e30d894d8..b3f73e6abf 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
@@ -176,6 +176,18 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
},
resolvePiGatewayModelApi: () => 'openai-responses',
resolvePiAgentHome: () => agentHome,
+ spawnPiSubagentRunner: () => {
+ const handle = {
+ pid: 4321,
+ killed: false,
+ once(event: 'spawn' | 'error' | 'exit' | 'close', listener: (...args: unknown[]) => void) {
+ if (event === 'spawn') queueMicrotask(listener);
+ return handle;
+ },
+ kill: () => true,
+ };
+ return handle as never;
+ },
registerPiProxySession: () => () => {
// Detached Subagent leases intentionally dispose after close. Ignore a previous
// test's late lease callback instead of charging it to the next test's counters.
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts
index 8b70ead9e8..8a4f49b5d9 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts
@@ -10,6 +10,7 @@ import {
controlPiSubagentRuns,
hasActivePiSubagentRunsSync,
killVerifiedPiSubagentRunner,
+ verifyPiSubagentRunnerIdentity,
listPiSubagentRunDiagnostics,
listPiSubagentRuns,
acquirePiSubagentLaunchFence,
@@ -27,6 +28,8 @@ import {
piSubagentRuntimeOwnerId,
requestStopAllPiSubagentRunsSync,
readPiSubagentTranscriptPage,
+ PiSubagentRunnerExitUnconfirmedError,
+ recordPiSubagentRunnerFailure,
resumePiSubagentRun,
stopAllPiSubagentRunsForExit,
stopAndRemovePiSubagentRuns,
@@ -132,6 +135,7 @@ vi.mock('node:fs/promises', async (importOriginal) => {
});
const roots: string[] = [];
+const noopRunnerLaunch = async (): Promise<void> => undefined;
async function makeRoot(): Promise<string> {
const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-pi-subagent-runs-'));
@@ -187,6 +191,43 @@ afterEach(async () => {
});
describe('PI durable subagent run store', () => {
+ it('records a host-observed runner failure without rewriting completed child results', async () => {
+ const root = await makeRoot();
+ const runId = '123e4567-e89b-42d3-a456-4266141740ab';
+ const runDir = path.join(root, runId);
+ const completedChild = `${runId}-1`;
+ const runningChild = `${runId}-2`;
+ await mkdir(runDir, { recursive: true });
+ await writeFile(path.join(runDir, 'config.json'), `${JSON.stringify({
+ version: 1,
+ runId,
+ taskId: 'tool-host-failure',
+ parentSessionId: 'session-1',
+ runtimeOwnerId: 'owner-a',
+ runDir,
+ cwd: root,
+ binary: '/pi',
+ tasks: [
+ { childId: completedChild, sessionId: completedChild, agent: 'scout', task: 'a', tools: 'read', profilePrompt: 'a', provider: 'cindy' },
+ { childId: runningChild, sessionId: runningChild, agent: 'scout', task: 'b', tools: 'read', profilePrompt: 'b', provider: 'cindy' },
+ ],
+ })}\n`);
+ await writeFile(path.join(runDir, 'status.json'), `${JSON.stringify({
+ ...status(runId),
+ taskId: 'tool-host-failure',
+ tasks: [
+ { childId: completedChild, sessionId: completedChild, agent: 'scout', status: 'completed', output: 'done', endedAt: 30 },
+ { childId: runningChild, sessionId: runningChild, agent: 'scout', status: 'running' },
+ ],
+ })}\n`);
+
+ await recordPiSubagentRunnerFailure(runDir, 'host process exited');
+ const [recorded] = await listPiSubagentRuns(root);
+ expect(recorded?.state).toBe('failed');
+ expect(recorded?.tasks[0]).toMatchObject({ status: 'completed', output: 'done', endedAt: 30 });
+ expect(recorded?.tasks[1]).toMatchObject({ status: 'failed', error: 'host process exited' });
+ });
+
it('derives a contained parent-session root and rejects traversal ids', () => {
expect(piSubagentRunRoot('/agent-home', 'session-1')).toBe(
path.join('/agent-home', 'runtime', 'pi-subagent-runs', 'session-1'),
@@ -220,7 +261,8 @@ describe('PI durable subagent run store', () => {
await writeStatus(root, status(runId, { state: 'completed' }));
await writePiSubagentDeletedTombstone(agentHome, 'session-1');
await expect(resumePiSubagentRun(root, 'tool-1', 'continue', {
- nodeExecutable: process.execPath,
+ launchRunner: noopRunnerLaunch,
+ env: {},
runtimeOwnerId: 'owner-a',
permissionSnapshot: { mode: 'ask', readOnlyRoots: [] },
})).rejects.toThrow(/parent task was deleted/i);
@@ -231,7 +273,7 @@ describe('PI durable subagent run store', () => {
.replace(/\r\n/g, '\n');
const claimed = source.indexOf('async function resumeClaimedPiSubagentRun(');
const publish = source.indexOf("state: 'queued'", claimed);
- const spawned = source.indexOf('spawn(launch.nodeExecutable', claimed);
+ const spawned = source.indexOf('await launch.launchRunner', claimed);
const firstTombstone = source.indexOf(
'isPiSubagentDeletedTombstonePresent(agentHome, path.basename(root))',
claimed,
@@ -246,11 +288,24 @@ describe('PI durable subagent run store', () => {
);
expect(publish).toBeGreaterThan(claimed);
expect(firstTombstone).toBeGreaterThan(publish);
+ expect(source.indexOf('recordPiSubagentRunnerFailure(runDir', spawned))
+ .toBeGreaterThan(spawned);
+ expect(source.indexOf('instanceof PiSubagentRunnerExitUnconfirmedError', spawned))
+ .toBeGreaterThan(spawned);
+ expect(source.indexOf('instanceof PiSubagentRunnerExitUnconfirmedError', spawned))
+ .toBeLessThan(source.indexOf('recordPiSubagentRunnerFailure(runDir', spawned));
expect(lastStaging).toBeGreaterThan(firstTombstone);
expect(lastTombstone).toBeGreaterThan(lastStaging);
expect(spawned).toBeGreaterThan(lastTombstone);
});
+ it('keeps unconfirmed runner-exit errors distinguishable from ordinary launch failures', () => {
+ const error = new PiSubagentRunnerExitUnconfirmedError('PI Subagent runner did not become ready');
+ expect(error).toBeInstanceOf(Error);
+ expect(error).toBeInstanceOf(PiSubagentRunnerExitUnconfirmedError);
+ expect(error.name).toBe('PiSubagentRunnerExitUnconfirmedError');
+ });
+
it('reports UUID-contained corrupt runs without trusting disk PIDs', async () => {
const root = await makeRoot();
const runId = '123e4567-e89b-42d3-a456-426614174099';
@@ -448,6 +503,47 @@ describe('PI durable subagent run store', () => {
]);
});
+ it('asks ps for untruncated arguments so utility-process command lines still match', () => {
+ stubAliveRunner();
+ const seen: string[][] = [];
+ childProcess.spawnSync.mockImplementation((file: unknown, args?: unknown) => {
+ if (file === 'ps' && Array.isArray(args)) seen.push(args as string[]);
+ return { status: 0, stdout: `node ${runnerScript} config.json` };
+ });
+ expect(verifyPiSubagentRunnerIdentity(expired())).toBe(true);
+ if (seen.length > 0) {
+ expect(seen[0]).toEqual(expect.arrayContaining(['-ww']));
+ }
+ });
+
+ it('treats another Subagent utility process at a recycled pid as gone', async () => {
+ stubAliveRunner();
+ childProcess.spawnSync.mockImplementation(() => ({
+ status: 0,
+ stdout: '/Applications/Cindy.app/Contents/Frameworks/Cindy Helper.app/Contents/MacOS/Cindy Helper --utility-sub-type=node /app/piSubagentRunnerProcess.js /runs/other-run/runner.cjs',
+ }));
+ const root = await makeRoot();
+ await writeStatus(root, expired());
+
+ await expect(listPiSubagentRuns(root)).resolves.toEqual([]);
+ await expect(stopPiSubagentRunsForAccountBoundary(root, { timeoutMs: 0 }))
+ .resolves.toBe(true);
+ });
+
+ it('still treats another Cindy utility process as a recycled pid', async () => {
+ stubAliveRunner();
+ childProcess.spawnSync.mockImplementation(() => ({
+ status: 0,
+ stdout: '/Applications/Cindy.app/Contents/Frameworks/Cindy Helper.app/Contents/MacOS/Cindy Helper --utility-sub-type=node /app/watcherHostProcess.js',
+ }));
+ const root = await makeRoot();
+ await writeStatus(root, expired());
+
+ await expect(listPiSubagentRuns(root)).resolves.toEqual([]);
+ await expect(stopPiSubagentRunsForAccountBoundary(root, { timeoutMs: 0 }))
+ .resolves.toBe(true);
+ });
+
it('keeps an unverifiable runner active rather than declaring it stale', async () => {
// The probe failing is not evidence the runner died. Calling it stale
// hides a live run from the sweep — which then reports a success it did
@@ -913,11 +1009,13 @@ describe('PI durable subagent run store', () => {
* default (never reaped) is the zombie/stubborn case.
*/
let sentSignals: Array<NodeJS.Signals | number> = [];
+ let sentKillPids: number[] = [];
const killSignals = (): Array<NodeJS.Signals | number> => sentSignals;
function stubKill(options: { reapedByKill?: boolean } = {}): void {
const real = process.kill.bind(process);
sentSignals = [];
+ sentKillPids = [];
let reaped = false;
const spy = vi.spyOn(process, 'kill').mockImplementation(
((pid: number, signal?: NodeJS.Signals | number) => {
@@ -926,6 +1024,7 @@ describe('PI durable subagent run store', () => {
if (!reaped) return true;
throw Object.assign(new Error('ESRCH'), { code: 'ESRCH' });
}
+ sentKillPids.push(pid);
sentSignals.push(signal ?? 'unknown');
if (options.reapedByKill) reaped = true;
return true;
@@ -990,6 +1089,32 @@ describe('PI durable subagent run store', () => {
await expect(killVerifiedPiSubagentRunner(runner())).resolves.toBe(true);
});
+ it('treats a runner that exits during the command-line probe as gone', async () => {
+ usePlatform('linux');
+ const real = process.kill.bind(process);
+ let liveChecks = 0;
+ sentSignals = [];
+ sentKillPids = [];
+ const spy = vi.spyOn(process, 'kill').mockImplementation(
+ ((pid: number, signal?: NodeJS.Signals | number) => {
+ if (Math.abs(pid) !== runnerPid) return real(pid, signal);
+ if (signal === 0) {
+ liveChecks += 1;
+ if (liveChecks === 1) return true;
+ throw Object.assign(new Error('ESRCH'), { code: 'ESRCH' });
+ }
+ sentKillPids.push(pid);
+ sentSignals.push(signal ?? 'unknown');
+ return true;
+ }) as typeof process.kill,
+ );
+ restores.push(() => spy.mockRestore());
+ stubProbes({ aliveProbes: 0 });
+
+ await expect(killVerifiedPiSubagentRunner(runner())).resolves.toBe(true);
+ expect(killSignals()).toEqual([]);
+ });
+
it('treats a zombie left by the kill as reclaimed', async () => {
usePlatform('linux');
stubKill();
@@ -1010,6 +1135,43 @@ describe('PI durable subagent run store', () => {
expect(childProcess.spawnSync.mock.calls.length).toBeGreaterThan(1);
});
+ it('signals the runner pid with SIGTERM before SIGKILL and never a process group', async () => {
+ usePlatform('linux');
+ stubKill();
+ stubProbes({ aliveProbes: Number.MAX_SAFE_INTEGER });
+
+ await expect(killVerifiedPiSubagentRunner(runner())).resolves.toBe(false);
+ expect(sentKillPids.length).toBeGreaterThan(0);
+ expect(sentKillPids.every((pid) => pid > 0)).toBe(true);
+ expect(killSignals()[0]).toBe('SIGTERM');
+ expect(killSignals()).toContain('SIGKILL');
+ });
+
+ it('waits after SIGKILL until the runner is gone', async () => {
+ usePlatform('linux');
+ stubKill();
+ let postKillProbes = 0;
+ childProcess.spawnSync.mockImplementation((...args: unknown[]) => {
+ if (args[0] === 'taskkill') return { status: 0 };
+ const killed = killSignals().includes('SIGKILL');
+ if (!killed) return { status: 0, stdout: `node ${runnerScript} config.json` };
+ postKillProbes += 1;
+ // The first post-SIGKILL listing still matches: the process has not
+ // been scheduled out yet. A single immediate probe would report false.
+ // Empty stdout is unreadable/unverifiable, not gone — use a listing
+ // that is readable and does not carry this run's script.
+ return {
+ status: 0,
+ stdout: postKillProbes <= 1 ? `node ${runnerScript} config.json` : 'other-process',
+ };
+ });
+
+ await expect(killVerifiedPiSubagentRunner(runner())).resolves.toBe(true);
+ expect(killSignals()[0]).toBe('SIGTERM');
+ expect(killSignals()).toContain('SIGKILL');
+ expect(postKillProbes).toBeGreaterThan(1);
+ });
+
it('does not report an account-boundary sweep as complete while a runner survives', async () => {
const root = await makeRoot();
usePlatform('linux');
@@ -1044,7 +1206,7 @@ describe('PI durable subagent run store', () => {
// The stop was still asked for first — the control file was written —
// and only the unconsumed mailbox escalated to a signal.
- expect(killSignals()).toContain('SIGKILL');
+ expect(killSignals()).toContain('SIGTERM');
expect(existsSync(root)).toBe(false);
});
@@ -1111,7 +1273,7 @@ describe('PI durable subagent run store', () => {
childProcess.probeDelayMs = delayMs;
restores.push(() => { childProcess.probeDelayMs = 0; });
childProcess.spawnSync.mockImplementation((...args: unknown[]) => {
- // POSIX passes ['-p', '<pid>', '-o', 'args=']; Windows embeds the pid
+ // POSIX passes ['-ww', '-p', '<pid>', '-o', 'args=']; Windows embeds the pid
// in the CIM filter. Either way it is the only all-digit fragment.
const flat = (args[1] as string[] | undefined) ?? [];
const pid = flat
@@ -1255,7 +1417,8 @@ describe('PI durable subagent run store', () => {
await writeFile(path.join(opaque, 'status.json'), '{not-json');
await expect(resumePiSubagentRun(root, 'tool-1', 'continue', {
- nodeExecutable: process.execPath,
+ launchRunner: noopRunnerLaunch,
+ env: {},
runtimeOwnerId: 'owner-a',
permissionSnapshot: { mode: 'ask', readOnlyRoots: [] },
})).rejects.toThrow(/cannot be read right now/i);
@@ -1269,7 +1432,8 @@ describe('PI durable subagent run store', () => {
}))}\n`,
);
await expect(resumePiSubagentRun(root, 'tool-1', 'continue', {
- nodeExecutable: process.execPath,
+ launchRunner: noopRunnerLaunch,
+ env: {},
runtimeOwnerId: 'owner-a',
permissionSnapshot: { mode: 'ask', readOnlyRoots: [] },
})).rejects.not.toThrow(/cannot be read right now/i);
@@ -1282,7 +1446,8 @@ describe('PI durable subagent run store', () => {
expect(isPiSubagentLaunchFenceActive(agentHome, process.pid)).toBe(true);
await expect(resumePiSubagentRun(root, 'tool-1', 'continue', {
- nodeExecutable: process.execPath,
+ launchRunner: noopRunnerLaunch,
+ env: {},
runtimeOwnerId: 'owner-a',
permissionSnapshot: { mode: 'ask', readOnlyRoots: [] },
})).rejects.toThrow(/restarting for an update/i);
@@ -1828,18 +1993,37 @@ describe('PI durable subagent run store', () => {
expect.objectContaining({ action: 'stop' }),
]);
- // And once that record names a runner this host cannot verify, the
- // second pass refuses to call the quit clean.
- await writeStatus(root, status(lateRunId, {
- state: 'running',
- runnerPid: process.pid,
- runnerScript: '/runs/never-matches.cjs',
- updatedAt: Date.now(),
+ // And once that record names a live pid whose command line cannot be
+ // read, the second pass refuses to call the quit clean. Do not use
+ // `process.pid` here: Linux `/proc/<pid>/cmdline` would bypass the
+ // spawnSync stub and treat a non-matching listing as a recycled pid.
+ const unverifiablePid = 424_424;
+ const realKill = process.kill.bind(process);
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(
+ ((pid: number, signal?: NodeJS.Signals | number) => {
+ if (pid === unverifiablePid && signal === 0) return true;
+ return realKill(pid, signal);
+ }) as typeof process.kill,
+ );
+ childProcess.spawnSync.mockImplementation(() => ({
+ status: null,
+ stdout: '',
+ error: Object.assign(new Error('ETIMEDOUT'), { code: 'ETIMEDOUT' }),
}));
- await expect(stopAllPiSubagentRunsForExit(agentHome, 0, {
- hostPid: process.pid,
- killUnresponsiveRunners: true,
- })).resolves.toBe(false);
+ try {
+ await writeStatus(root, status(lateRunId, {
+ state: 'running',
+ runnerPid: unverifiablePid,
+ runnerScript: '/runs/never-matches.cjs',
+ updatedAt: Date.now(),
+ }));
+ await expect(stopAllPiSubagentRunsForExit(agentHome, 0, {
+ hostPid: process.pid,
+ killUnresponsiveRunners: true,
+ })).resolves.toBe(false);
+ } finally {
+ killSpy.mockRestore();
+ }
});
it('sweeps only the fences whose owner is gone', async () => {
@@ -1932,7 +2116,8 @@ describe('PI durable subagent run store', () => {
const root = piSubagentRunRoot(agentHome, 'session-1');
await writeStatus(root, status(runId, { state: 'completed' }));
await expect(resumePiSubagentRun(root, 'tool-1', 'continue', {
- nodeExecutable: process.execPath,
+ launchRunner: noopRunnerLaunch,
+ env: {},
runtimeOwnerId: 'owner-a',
permissionSnapshot: { mode: 'ask', readOnlyRoots: [] },
})).rejects.toThrow(/restarting for an update/i);
diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
index 7505b1884e..feaed69a34 100644
--- a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
@@ -37,6 +37,7 @@
export const CINDY_SUBAGENT_TOOL_NAME = 'subagent';
export const CINDY_SUBAGENT_EXTENSION_FILENAME = 'cindy-subagent.ts';
+export const CINDY_SUBAGENT_RUNNER_CONTROL_TITLE = 'cindy:pi-subagent-runner';
/** Cindy 注入给子进程的 env 名:pi 二进制路径、递归深度、子代理模型。 */
export const CINDY_SUBAGENT_ENV = {
@@ -50,10 +51,8 @@ export const CINDY_SUBAGENT_ENV = {
runtimeFile: 'CINDY_PI_SUBAGENT_RUNTIME_FILE',
/** Durable run root owned by Cindy, scoped to the parent session. */
runRoot: 'CINDY_PI_SUBAGENT_RUN_ROOT',
- /** Cindy-generated CommonJS runner loaded by a real Node-compatible executable. */
+ /** Cindy-generated CommonJS runner staged into each durable run. */
runnerFile: 'CINDY_PI_SUBAGENT_RUNNER_FILE',
- /** Node, or Electron launched with ELECTRON_RUN_AS_NODE=1. */
- nodeExecutable: 'CINDY_PI_SUBAGENT_NODE',
/** Host runtime instance that owns permission sync and approval forwarding. */
ownerId: 'CINDY_PI_SUBAGENT_OWNER_ID',
} as const;
@@ -119,7 +118,7 @@ function installParentWatchdog() {
const CINDY_SUBAGENT_EXTENSION_BODY = String.raw`/**
* cindy-subagent (generated by Cindy — do not edit; overwritten on session start)
*/
-import { spawn, spawnSync } from 'node:child_process';
+import { spawnSync } from 'node:child_process';
import { createHmac } from 'node:crypto';
import { randomUUID } from 'node:crypto';
import { chmodSync, copyFileSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
@@ -131,7 +130,6 @@ const DEPTH_ENV = 'CINDY_PI_SUBAGENT_DEPTH';
const RUNTIME_FILE_ENV = 'CINDY_PI_SUBAGENT_RUNTIME_FILE';
const RUN_ROOT_ENV = 'CINDY_PI_SUBAGENT_RUN_ROOT';
const RUNNER_FILE_ENV = 'CINDY_PI_SUBAGENT_RUNNER_FILE';
-const NODE_EXECUTABLE_ENV = 'CINDY_PI_SUBAGENT_NODE';
const OWNER_ID_ENV = 'CINDY_PI_SUBAGENT_OWNER_ID';
const PERMISSION_FILE_ENV = 'CINDY_PI_PERMISSION_FILE';
const PARENT_SESSION_ENV = 'CINDY_PI_SESSION_ID';
@@ -175,6 +173,7 @@ const RENAME_RETRY_MAX_MS = 100;
// 审批通过 child RPC → durable runner → Cindy 审批 UI 往返,未获明确 allow 就 fail-closed。
const WRITE_TOOLS = 'read,grep,find,ls,edit,write,bash';
const THINKING_LEVELS = 'off|minimal|low|medium|high|xhigh|max';
+const RUNNER_CONTROL_TITLE = 'cindy:pi-subagent-runner';
const LAUNCH_RECEIPT = 'Cindy subagent launched. The agent is working in the background.';
let controlWriteSequence = 0;
const PROFILES = {
@@ -561,8 +560,7 @@ async function waitForDurableRun(launched, signal, ctx, onStatus) {
const approvalDecisions = new Map();
let stopWritten = false;
let stopDeadline = 0;
- let runnerExit = null;
- launched.exited.then(function (exit) { runnerExit = exit; });
+ let nextHostPoll = 0;
for (;;) {
let status;
try { status = JSON.parse(readFileSync(join(launched.runDir, 'status.json'), 'utf8')); } catch (err) { status = null; }
@@ -614,13 +612,22 @@ async function waitForDurableRun(launched, signal, ctx, onStatus) {
}
if (status.state === 'completed' || status.state === 'failed' || status.state === 'stopped') return status;
}
- if (runnerExit) {
- return launched.failureStatus(
- 'Durable runner exited before publishing a terminal status'
- + (runnerExit.error ? ': ' + runnerExit.error : '')
- + (runnerExit.signal ? ' (signal ' + runnerExit.signal + ')' : '')
- + (typeof runnerExit.code === 'number' ? ' (exit ' + runnerExit.code + ')' : ''),
- );
+ if (Date.now() >= nextHostPoll) {
+ nextHostPoll = Date.now() + 1000;
+ try {
+ await requestRunnerControl(ctx, 'status', launched.runId);
+ } catch (err) {
+ if (err && err.runnerExited) {
+ let latest = null;
+ try { latest = JSON.parse(readFileSync(join(launched.runDir, 'status.json'), 'utf8')); } catch (readErr) { latest = null; }
+ if (latest && (latest.state === 'completed' || latest.state === 'failed' || latest.state === 'stopped')) {
+ onStatus(latest);
+ return latest;
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ return launched.failureStatus(message);
+ }
+ }
}
if (Date.now() >= launched.deadlineAt && !stopWritten) {
stopWritten = true;
@@ -734,15 +741,44 @@ function launchFenceBlocksSpawn(runRoot, runtimeOwnerId) {
return fenceNamesLiveHost(join(fenceDir, LEGACY_LAUNCH_FENCE_FILENAME), hostPid, hostStartTimeSec);
}
-function launchDurableRun(binary, tasks, runtime, taskId, mode, context, displayTitle, interactiveOwner, timeoutMs) {
+async function requestRunnerControl(ctx, action, runId) {
+ 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 }),
+ );
+ let response;
+ try { response = JSON.parse(typeof raw === 'string' ? raw : '{}'); } catch (err) { response = null; }
+ if (response && response.exited === true) {
+ throw Object.assign(
+ new Error(typeof response.error === 'string' && response.error
+ ? response.error
+ : 'Durable runner exited'),
+ { runnerExited: true },
+ );
+ }
+ if (response && response.unconfirmed === true) {
+ throw Object.assign(
+ new Error('subagent: Cindy could not ' + action + ' the durable runner.'),
+ { unconfirmed: true },
+ );
+ }
+ if (!response || response.ok !== true) {
+ throw new Error('subagent: Cindy could not ' + action + ' the durable runner.');
+ }
+ return response;
+}
+
+async function launchDurableRun(binary, tasks, runtime, taskId, mode, context, displayTitle, interactiveOwner, timeoutMs, ctx) {
const runRoot = process.env[RUN_ROOT_ENV];
const runnerFile = process.env[RUNNER_FILE_ENV];
- const nodeExecutable = process.env[NODE_EXECUTABLE_ENV];
const configHome = process.env[CONFIG_HOME_ENV];
const sourcePermissionFile = process.env[PERMISSION_FILE_ENV];
const parentSessionId = process.env[PARENT_SESSION_ENV];
const runtimeOwnerId = process.env[OWNER_ID_ENV];
- if (!runRoot || !runnerFile || !nodeExecutable || !configHome || !sourcePermissionFile || !parentSessionId || !runtimeOwnerId) {
+ if (!runRoot || !runnerFile || !configHome || !sourcePermissionFile || !parentSessionId || !runtimeOwnerId) {
throw new Error('subagent: durable runner is unavailable for this session.');
}
const permission = readPermissionSnapshot();
@@ -877,13 +913,6 @@ function launchDurableRun(binary, tasks, runtime, taskId, mode, context, display
try { rmSync(runDir, { recursive: true, force: true }); } catch (_) { /* best effort cleanup */ }
throw err;
}
- const runner = spawn(nodeExecutable, [durableRunnerFile, configPath], {
- cwd: process.cwd(),
- env: Object.assign({}, process.env, { ELECTRON_RUN_AS_NODE: '1' }),
- detached: true,
- windowsHide: true,
- stdio: 'ignore',
- });
const failureStatus = function (message) {
const now = Date.now();
return {
@@ -919,81 +948,41 @@ function launchDurableRun(binary, tasks, runtime, taskId, mode, context, display
if (current && (current.state === 'completed' || current.state === 'failed' || current.state === 'stopped')) return;
writePrivateJson(join(runDir, 'status.json'), failureStatus(message));
} catch {
- /* No safe fallback remains when both process launch and private status persistence fail. */
+ /* No safe fallback remains when both host launch and private status persistence fail. */
}
};
- let settleExit;
- const exited = new Promise(function (resolve) { settleExit = resolve; });
- let exitSettled = false;
- const settleRunnerExit = function (exit) {
- if (exitSettled) return;
- exitSettled = true;
- settleExit(exit);
- };
- runner.once('error', function (error) {
- const message = 'Durable runner failed to start: ' + String(error);
- persistFailureIfNeeded(message);
- settleRunnerExit({ code: null, signal: null, error: String(error) });
- });
- runner.once('close', function (code, signalName) {
- const message = 'Durable runner exited before publishing a terminal status'
- + (signalName ? ' (signal ' + signalName + ')' : '')
- + (typeof code === 'number' ? ' (exit ' + code + ')' : '');
- persistFailureIfNeeded(message);
- settleRunnerExit({ code: code, signal: signalName, error: null });
- });
- runner.unref();
- // Give-up teardown for a runner that stopped answering its control mailbox.
- //
- // The runner handle belongs to a process this extension spawned itself, so
- // signalling it does not violate the runner's "never signal a pid read from
- // disk" rule. It is also the only reachable kill: the runner's children live
- // in their own process groups, so signalling the runner's group cannot touch
- // them, and their pids are deliberately not published to disk. The runner's
- // own SIGTERM handler is what reaps them — installing that listener is also
- // what stops Node from tearing the runner down without running any cleanup.
- //
- // Idempotent: repeat calls no-op once the runner has exited, and the durable
- // status write is skipped when a terminal record already exists.
+ try {
+ await requestRunnerControl(ctx, 'launch', runId);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ if (!(err && err.unconfirmed)) persistFailureIfNeeded(message);
+ throw err;
+ }
+
const terminateRunner = async function (message) {
- if (!exitSettled) {
+ let unconfirmed = false;
+ try {
+ await requestRunnerControl(ctx, 'terminate', runId);
+ } catch (err) {
+ unconfirmed = Boolean(err && err.unconfirmed);
+ /* Host-side account and exit sweeps remain the final cleanup boundary. */
+ }
+ const hardDeadline = Date.now() + RUNNER_TERMINATE_GRACE_MS;
+ while (Date.now() < hardDeadline) {
try {
- if (process.platform === 'win32') {
- if (typeof runner.pid === 'number') {
- const killed = spawnSync('taskkill', ['/PID', String(runner.pid), '/T', '/F'], {
- windowsHide: true,
- stdio: 'ignore',
- });
- // taskkill reports failure by status, not by throwing. Ignoring it
- // means waiting out the whole grace window for nothing; the handle
- // is ours, so escalate immediately (TerminateProcess does not need
- // taskkill to have walked the tree).
- if (killed.error || killed.status !== 0) runner.kill('SIGKILL');
- }
- } else {
- runner.kill('SIGTERM');
+ const current = JSON.parse(readFileSync(join(runDir, 'status.json'), 'utf8'));
+ if (current && (current.state === 'completed' || current.state === 'failed' || current.state === 'stopped')) {
+ return;
}
- } catch (err) { /* already gone */ }
- // Bounded escalation. A runner wedged past this cannot reap its children
- // either, so the residue is the same class as an externally killed runner
- // and is covered by the host-side agent-home sweeps.
- const hardDeadline = Date.now() + RUNNER_TERMINATE_GRACE_MS;
- while (!exitSettled && Date.now() < hardDeadline) {
- await new Promise(function (resolve) { setTimeout(resolve, 50); });
- }
- if (!exitSettled) {
- try { runner.kill('SIGKILL'); } catch (err) { /* already gone */ }
- }
+ } catch (err) { /* keep waiting within the bounded grace */ }
+ await new Promise(function (resolve) { setTimeout(resolve, 50); });
}
- // Converge the durable record with reality: whatever the runner did or did
- // not publish, the run must not be left reading as running.
- persistFailureIfNeeded(message);
+ if (!unconfirmed) persistFailureIfNeeded(message);
};
return {
runId: runId,
taskId: taskId,
runDir: runDir,
- exited: exited,
deadlineAt: Date.now()
+ Math.max(10000, Number.isFinite(timeoutMs) ? timeoutMs : TASK_TIMEOUT_MS)
+ 15000,
@@ -1332,7 +1321,7 @@ export default async function cindySubagent(pi: any) {
}
report('running');
- const launched = launchDurableRun(
+ const launched = await launchDurableRun(
binary,
tasks,
runtime,
@@ -1342,6 +1331,7 @@ export default async function cindySubagent(pi: any) {
typeof input.title === 'string' ? input.title : '',
wantAsync ? 'host' : 'extension',
invocation.timeoutMs,
+ ctx,
);
if (wantAsync) {
return {
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index e5115c708b..4883a28aec 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -70,6 +70,8 @@ import {
type PiExtensionUiStrings,
type PiNativeModelSpec,
type PiNativeProviderSpec,
+ type PiSubagentRunnerLaunchRequest,
+ type PiSubagentRunnerProcess,
type SendOptions,
type StartSessionOptions,
type TurnPermissionPolicy,
@@ -81,7 +83,7 @@ import {
CINDY_SUBAGENT_ENV,
CINDY_SUBAGENT_EXTENSION_FILENAME,
CINDY_SUBAGENT_EXTENSION_SOURCE,
- CINDY_SUBAGENT_TOOL_NAME,
+ CINDY_SUBAGENT_RUNNER_CONTROL_TITLE,
} from './cindy-subagent-source.js';
import {
CINDY_SUBAGENT_RUNNER_FILENAME,
@@ -94,12 +96,16 @@ import {
controlPiSubagentRuns,
countPiSubagentRunDirectories,
isPiSubagentTerminal,
+ killVerifiedPiSubagentRunner,
listPiSubagentRunDiagnostics,
listPiSubagentRunDirectoryIds,
listPiSubagentRuns,
piSubagentRunRoot,
piSubagentApprovalScope,
piSubagentRuntimeOwnerId,
+ PiSubagentRunnerExitUnconfirmedError,
+ PiSubagentRunnerHostExitedError,
+ recordPiSubagentRunnerFailure,
resumePiSubagentRun,
stopPiSubagentRunsForAccountBoundary,
syncPiSubagentPermissions,
@@ -226,8 +232,11 @@ const PI_SESSION_TOKEN_ENV = 'CINDY_PI_SESSION_TOKEN';
const PI_MCP_BRIDGE_ENV = 'CINDY_PI_MCP_BRIDGE';
const PI_SECRET_ENV_NAMES_ENV = 'CINDY_PI_SECRET_ENV_NAMES';
const PI_MANAGED_RG_PATH_ENV = 'CINDY_PI_MANAGED_RG_PATH';
+const PI_LEGACY_SUBAGENT_NODE_ENV = 'CINDY_PI_SUBAGENT_NODE';
+const PI_ELECTRON_RUN_AS_NODE_ENV = 'ELECTRON_RUN_AS_NODE';
const PI_PACKAGE_MANAGEMENT_ENV = 'CINDY_PI_PACKAGE_MANAGEMENT';
const PI_PACKAGE_MANAGEMENT_TITLE = 'cindy:pi-package';
+const PI_SUBAGENT_RUN_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const PI_BASH_PACKAGE_HOME_ENV = 'CINDY_PI_BASH_PACKAGE_HOME';
/** 轮 42 P1:models.json 内容指纹(远端 daemon 启动身份的一部分, 值无凭证)。 */
const PI_MODELS_JSON_HASH_ENV = 'CINDY_PI_MODELS_JSON_HASH';
@@ -975,6 +984,8 @@ export class PiAgent extends BaseAgent {
readonly capabilities: Capabilities;
private readonly failedStartupCleanups = new Map<string, FailedPiStartupCleanup>();
private readonly inFlightStartups = new Set<Promise<AgentSessionHandle>>();
+ private readonly subagentRunners = new Map<string, PiSubagentRunnerProcess>();
+ private readonly subagentRunnerExitErrors = new Map<string, string>();
private disposeStarted = false;
constructor(deps: AgentDeps) {
@@ -982,6 +993,115 @@ export class PiAgent extends BaseAgent {
this.capabilities = this.buildCapabilities(PiAgent.baseCapabilities());
}
+ private async launchSubagentRunner(request: PiSubagentRunnerLaunchRequest): Promise<void> {
+ const spawnRunner = this.deps.spawnPiSubagentRunner;
+ if (!spawnRunner) throw new Error('PI Subagent runner host is unavailable');
+ if (this.subagentRunners.has(request.runId)) return;
+
+ const runner = spawnRunner(request);
+ this.subagentRunners.set(request.runId, runner);
+ const recordFailure = (message: string): void => {
+ this.subagentRunnerExitErrors.set(request.runId, message);
+ if (this.subagentRunners.get(request.runId) === runner) {
+ this.subagentRunners.delete(request.runId);
+ }
+ void recordPiSubagentRunnerFailure(request.runDir, message).catch((error) => {
+ this.deps.logger.warn('pi Subagent runner failure status could not be persisted', {
+ runId: request.runId,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ });
+ };
+ runner.once('error', (error) => {
+ recordFailure(`Durable runner failed: ${error.message}`);
+ });
+ runner.once('exit', (code, signal) => {
+ recordFailure(
+ `Durable runner exited${signal ? ` with signal ${signal}` : ''}`
+ + (typeof code === 'number' ? ` with code ${code}` : ''),
+ );
+ });
+
+ await new Promise<void>((resolve, reject) => {
+ let settled = false;
+ let timedOut = false;
+ const finish = (error?: Error): void => {
+ if (settled) return;
+ settled = true;
+ if (timer) clearTimeout(timer);
+ if (error) reject(error);
+ else resolve();
+ };
+ const timer = setTimeout(() => {
+ timedOut = true;
+ void this.requestSubagentRunnerExit(runner, request.runId).then((confirmed) => {
+ finish(confirmed
+ ? new Error('PI Subagent runner did not become ready')
+ : new PiSubagentRunnerExitUnconfirmedError(
+ 'PI Subagent runner did not become ready',
+ ));
+ });
+ }, 5_000);
+ runner.once('spawn', () => {
+ if (!timedOut) finish();
+ });
+ runner.once('error', (error) => finish(error));
+ runner.once('exit', (code, signal) => {
+ finish(new Error(
+ `PI Subagent runner exited before ready${signal ? ` (${signal})` : ''}`
+ + (typeof code === 'number' ? ` (exit ${code})` : ''),
+ ));
+ });
+ });
+ }
+
+ private requestSubagentRunnerExit(
+ runner: PiSubagentRunnerProcess,
+ runId: string,
+ ): Promise<boolean> {
+ const dropHandle = (): void => {
+ if (this.subagentRunners.get(runId) === runner) {
+ this.subagentRunners.delete(runId);
+ }
+ };
+ return new Promise<boolean>((resolve) => {
+ let settled = false;
+ let killTimer: ReturnType<typeof setTimeout> | undefined;
+ const finish = (ok: boolean): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(termTimer);
+ if (killTimer) clearTimeout(killTimer);
+ resolve(ok);
+ };
+ const onGone = (): void => {
+ dropHandle();
+ finish(true);
+ };
+ runner.once('exit', onGone);
+ runner.once('close', onGone);
+ runner.kill('SIGTERM');
+ const termTimer = setTimeout(() => {
+ runner.kill('SIGKILL');
+ killTimer = setTimeout(() => finish(false), 200);
+ }, 1_500);
+ }).then((confirmed) => {
+ // Unconfirmed exit keeps the handle so a later terminate or account-boundary
+ // sweep can still reach the live process. A delayed exit/close still drops it.
+ if (confirmed) dropHandle();
+ return confirmed;
+ });
+ }
+
+ private async terminateSubagentRunner(runId: string, runDir: string): Promise<boolean> {
+ const runner = this.subagentRunners.get(runId);
+ if (!runner) {
+ const status = (await listPiSubagentRuns(path.dirname(runDir))).find((entry) => entry.runId === runId);
+ return status ? killVerifiedPiSubagentRunner(status) : false;
+ }
+ return this.requestSubagentRunnerExit(runner, runId);
+ }
+
private async retryFailedStartupCleanup(
sessionId: string,
expectedEntry?: FailedPiStartupCleanup,
@@ -1006,6 +1126,10 @@ export class PiAgent extends BaseAgent {
override async dispose(): Promise<void> {
this.disposeStarted = true;
+ const runnerSnapshot = Array.from(this.subagentRunners.entries());
+ const runnerResults = await Promise.allSettled(
+ runnerSnapshot.map(([runId, runner]) => this.requestSubagentRunnerExit(runner, runId)),
+ );
const startupSnapshot = Array.from(this.inFlightStartups);
await Promise.allSettled(startupSnapshot);
@@ -1017,9 +1141,20 @@ export class PiAgent extends BaseAgent {
this.retryFailedStartupCleanup(sessionId, entry),
),
);
- const errors = results.flatMap((result) =>
- result.status === 'rejected' ? [result.reason] : [],
- );
+ const errors = [
+ ...runnerResults.flatMap((result) => {
+ if (result.status === 'rejected') return [result.reason];
+ if (!result.value) {
+ return [new PiSubagentRunnerExitUnconfirmedError(
+ 'PI Subagent runner did not confirm exit',
+ )];
+ }
+ return [];
+ }),
+ ...results.flatMap((result) =>
+ result.status === 'rejected' ? [result.reason] : [],
+ ),
+ ];
if (errors.length > 0) {
throw new AggregateError(errors, 'Pi startup process cleanup remains unconfirmed');
}
@@ -2024,7 +2159,11 @@ export class PiAgent extends BaseAgent {
// the remote host while Cindy observes and controls an unrelated local
// directory. Keep the capability absent until the wire protocol owns those
// files remotely end-to-end.
- const localSubagentSupported = !reviewMode && !remote;
+ const localSubagentSupported = Boolean(
+ !reviewMode
+ && !remote
+ && this.deps.spawnPiSubagentRunner,
+ );
if (localSubagentSupported) {
await writeFile(subagentExtensionPath, CINDY_SUBAGENT_EXTENSION_SOURCE);
await writeFile(subagentRunnerPath, CINDY_SUBAGENT_RUNNER_SOURCE, 0o600);
@@ -2246,7 +2385,7 @@ export class PiAgent extends BaseAgent {
* 用它当"撤销开关"(上一版就是这么用的,那是个空操作,review 连点两轮)。运行期要收回子代理
* 能力只有一条可证明有效的路:终止会话。
*/
- let subagentRoutingEnabled = localSubagentSupported;
+ const subagentRoutingEnabled = localSubagentSupported;
const writeSubagentRuntimeFile = async (
next: { model?: string; provider?: string; pending?: boolean }): Promise<boolean> => {
const gen = ++subagentRuntimeWriteGen;
@@ -2680,6 +2819,7 @@ export class PiAgent extends BaseAgent {
* which is exactly what has to be over before the stop sweep runs.
*/
const piSubagentApprovalWrites = new Set<Promise<void>>();
+ const inFlightSubagentLaunches = new Set<Promise<void>>();
/**
* Publish an approval answer, keeping its mailbox-write phase awaitable and
* refusing the write itself if the account boundary went up in the meantime.
@@ -3470,6 +3610,10 @@ export class PiAgent extends BaseAgent {
sessionId: opts.sessionId,
});
}
+ while (converged && inFlightSubagentLaunches.size > 0) {
+ const launches = Promise.allSettled([...inFlightSubagentLaunches]).then(() => 'done' as const);
+ converged = await Promise.race([launches, budget]) === 'done';
+ }
try {
const stopped = await stopPiSubagentRunsForAccountBoundary(subagentRunRoot, {
runtimeOwnerId: subagentRuntimeOwnerId,
@@ -3728,7 +3872,6 @@ export class PiAgent extends BaseAgent {
[CINDY_SUBAGENT_ENV.runtimeFile]: subagentRuntimeFile,
[CINDY_SUBAGENT_ENV.runRoot]: subagentRunRoot,
[CINDY_SUBAGENT_ENV.runnerFile]: subagentRunnerPath,
- [CINDY_SUBAGENT_ENV.nodeExecutable]: process.execPath,
[CINDY_SUBAGENT_ENV.ownerId]: subagentRuntimeOwnerId,
} : {}),
// 嵌入式 runtime 不做启动期联网:关掉 pi 的版本检查与安装遥测
@@ -3742,7 +3885,14 @@ export class PiAgent extends BaseAgent {
// 不继承宿主进程里碰巧存在的同名变量;Windows 环境键大小写不敏感,必须先清掉
// 所有 casing 再写入 host 校验并 stage 后的唯一绝对路径。
for (const key of Object.keys(spawnEnv)) {
- if (key.toLowerCase() === PI_MANAGED_RG_PATH_ENV.toLowerCase()) delete spawnEnv[key];
+ const normalizedKey = key.toLowerCase();
+ if (
+ normalizedKey === PI_MANAGED_RG_PATH_ENV.toLowerCase()
+ || normalizedKey === PI_LEGACY_SUBAGENT_NODE_ENV.toLowerCase()
+ || normalizedKey === PI_ELECTRON_RUN_AS_NODE_ENV.toLowerCase()
+ ) {
+ delete spawnEnv[key];
+ }
}
if (managedRipgrepPath) spawnEnv[PI_MANAGED_RG_PATH_ENV] = managedRipgrepPath;
// models.json + settings.json 内容 hash 进 spawn env —— 远端 daemon 的
@@ -3805,6 +3955,62 @@ export class PiAgent extends BaseAgent {
remote: Boolean(opts.remoteHostId),
allowPiPackageManagement,
piPackageManagementToken,
+ controlSubagentRunner: async (action, runId) => {
+ if (!localSubagentSupported || !PI_SUBAGENT_RUN_ID_RE.test(runId)) {
+ throw new Error('PI Subagent runner request is unavailable');
+ }
+ const runDir = path.join(subagentRunRoot, runId);
+ const live = this.subagentRunners.has(runId);
+ if (action === 'status') {
+ const message = this.subagentRunnerExitErrors.get(runId);
+ if (message) throw new PiSubagentRunnerHostExitedError(message);
+ if (live) return true;
+ }
+ if (action === 'terminate' && live) {
+ return this.terminateSubagentRunner(runId, runDir);
+ }
+ const status = (await listPiSubagentRuns(subagentRunRoot))
+ .find((candidate) => candidate.runId === runId);
+ if (!status || status.runtimeOwnerId !== subagentRuntimeOwnerId) {
+ if (action === 'terminate') return false;
+ throw new Error('PI Subagent runner request does not belong to this task');
+ }
+ if (action === 'status') {
+ return true;
+ }
+ if (action === 'terminate') {
+ return this.terminateSubagentRunner(runId, runDir);
+ }
+ if (isPiSubagentTerminal(status.state)) {
+ throw new Error('PI Subagent runner request is already terminal');
+ }
+ if (accountBoundaryTeardown) {
+ throw new Error('PI Subagent runner request is unavailable');
+ }
+ const launching = this.launchSubagentRunner({
+ runId,
+ runDir,
+ runnerFile: path.join(runDir, 'runner.cjs'),
+ configFile: path.join(runDir, 'config.json'),
+ cwd: opts.workingDir,
+ env: durableSpawnEnv,
+ });
+ inFlightSubagentLaunches.add(launching);
+ try {
+ await launching;
+ } finally {
+ inFlightSubagentLaunches.delete(launching);
+ }
+ if (accountBoundaryTeardown) {
+ const confirmed = await this.terminateSubagentRunner(runId, runDir);
+ throw confirmed
+ ? new Error('PI Subagent runner request is unavailable')
+ : new PiSubagentRunnerExitUnconfirmedError(
+ 'PI Subagent runner request is unavailable',
+ );
+ }
+ return true;
+ },
emitExtensionNotification: (message, event) => {
const text = shouldRewriteContextModeDoctorNotification(
message,
@@ -4334,6 +4540,8 @@ export class PiAgent extends BaseAgent {
throw err;
}
+ const launchSubagentRunner = (request: PiSubagentRunnerLaunchRequest): Promise<void> =>
+ this.launchSubagentRunner(request);
const deps = this.deps;
const agentKind = this.kind;
@@ -5171,7 +5379,7 @@ export class PiAgent extends BaseAgent {
fs.readFile(subagentRunnerPath),
]);
const runId = await resumePiSubagentRun(subagentRunRoot, taskId, message, {
- nodeExecutable: process.execPath,
+ launchRunner: launchSubagentRunner,
env: durableSpawnEnv,
runtimeOwnerId: subagentRuntimeOwnerId,
permissionSnapshot: {
@@ -5955,6 +6163,10 @@ export class PiAgent extends BaseAgent {
remote: boolean;
allowPiPackageManagement: boolean;
piPackageManagementToken?: string;
+ controlSubagentRunner: (
+ action: 'launch' | 'terminate' | 'status',
+ runId: string,
+ ) => Promise<boolean>;
emitExtensionNotification: (message: string, event?: PiRpcEvent) => void;
notifyUnsupportedExtensionUi: (method: string, reason: 'unsupported-ui' | 'timed-dialog') => void;
/**
@@ -5994,6 +6206,71 @@ export class PiAgent extends BaseAgent {
return;
}
+ if (method === 'input' && event.title === CINDY_SUBAGENT_RUNNER_CONTROL_TITLE) {
+ const context = getPermissionCtx();
+ if (context.remote) {
+ proc.send({ type: 'extension_ui_response', id, cancelled: true });
+ return;
+ }
+ if (context.isAccountBoundaryTornDown()) {
+ proc.send({
+ type: 'extension_ui_response',
+ id,
+ value: JSON.stringify({ ok: false, unconfirmed: true }),
+ });
+ return;
+ }
+ void (async () => {
+ try {
+ const payload = JSON.parse(
+ typeof event.placeholder === 'string' ? event.placeholder : '{}',
+ ) as { action?: unknown; runId?: unknown };
+ if (
+ (payload.action !== 'launch'
+ && payload.action !== 'terminate'
+ && payload.action !== 'status')
+ || typeof payload.runId !== 'string'
+ || !PI_SUBAGENT_RUN_ID_RE.test(payload.runId)
+ ) {
+ throw new Error('Invalid PI Subagent runner request');
+ }
+ const accepted = await context.controlSubagentRunner(payload.action, payload.runId);
+ proc.send({
+ type: 'extension_ui_response',
+ id,
+ value: JSON.stringify(
+ accepted
+ ? { ok: true, confirmed: true }
+ : { ok: false, unconfirmed: true },
+ ),
+ });
+ } catch (error) {
+ if (error instanceof PiSubagentRunnerHostExitedError) {
+ proc.send({
+ type: 'extension_ui_response',
+ id,
+ value: JSON.stringify({ ok: false, exited: true, error: error.message }),
+ });
+ return;
+ }
+ this.deps.logger.warn('pi Subagent runner control failed', {
+ sessionId: context.sessionId,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ proc.send({
+ type: 'extension_ui_response',
+ id,
+ value: JSON.stringify(
+ error instanceof PiSubagentRunnerExitUnconfirmedError
+ ? { ok: false, unconfirmed: true }
+ : { ok: false, error: 'PI Subagent runner control failed' },
+ ),
+ });
+ }
+ })();
+ return;
+ }
+
if (method === 'input' && event.title === PI_PACKAGE_MANAGEMENT_TITLE) {
const context = getPermissionCtx();
const mutate = this.deps.mutatePiManagedPackage;
diff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
index 187bc2654f..5048ad3409 100644
--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
@@ -1,4 +1,4 @@
-import { execFile, spawn, spawnSync } from 'node:child_process';
+import { execFile, spawnSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import {
createReadStream,
@@ -750,7 +750,34 @@ export function isPiSubagentTerminal(state: PiSubagentRunState): boolean {
* Bounded and best-effort: an unreadable command line is indistinguishable from
* a hostile one for our purposes, and both must stop the kill.
*/
-function readProcessCommandLine(pid: number): string | null {
+function posixPsArgs(pid: number): string[] {
+ return ['-ww', '-p', String(pid), '-o', 'args='];
+}
+
+type CommandLineProbe =
+ | { status: 'unreadable' }
+ | { status: 'text'; text: string };
+
+function commandLineFromStdout(stdout: unknown): CommandLineProbe {
+ const text = typeof stdout === 'string' ? stdout.trim() : '';
+ return text.length > 0 ? { status: 'text', text } : { status: 'unreadable' };
+}
+
+function readLinuxCmdline(pid: number): CommandLineProbe | null {
+ try {
+ const raw = readFileSync(`/proc/${pid}/cmdline`);
+ const text = raw.toString('utf8').replace(/\0/g, ' ').trim();
+ return text.length > 0 ? { status: 'text', text } : { status: 'unreadable' };
+ } catch {
+ return null;
+ }
+}
+
+function readProcessCommandLine(pid: number): CommandLineProbe {
+ if (process.platform === 'linux') {
+ const fromProc = readLinuxCmdline(pid);
+ if (fromProc) return fromProc;
+ }
try {
const probe = process.platform === 'win32'
? spawnSync(
@@ -761,15 +788,14 @@ function readProcessCommandLine(pid: number): string | null {
],
{ encoding: 'utf8', timeout: 5_000, windowsHide: true },
)
- : spawnSync('ps', ['-p', String(pid), '-o', 'args='], {
+ : spawnSync('ps', posixPsArgs(pid), {
encoding: 'utf8',
timeout: 5_000,
});
- if (probe.error || probe.status !== 0) return null;
- const text = typeof probe.stdout === 'string' ? probe.stdout.trim() : '';
- return text.length > 0 ? text : null;
+ if (probe.error || probe.status !== 0) return { status: 'unreadable' };
+ return commandLineFromStdout(probe.stdout);
} catch {
- return null;
+ return { status: 'unreadable' };
}
}
@@ -789,7 +815,11 @@ const execFileAsync = promisify(execFile);
*/
const KILL_PROBE_TIMEOUT_MS = 1_000;
-async function readProcessCommandLineAsync(pid: number): Promise<string | null> {
+async function readProcessCommandLineAsync(pid: number): Promise<CommandLineProbe> {
+ if (process.platform === 'linux') {
+ const fromProc = readLinuxCmdline(pid);
+ if (fromProc) return fromProc;
+ }
try {
const { stdout } = process.platform === 'win32'
? await execFileAsync(
@@ -800,17 +830,28 @@ async function readProcessCommandLineAsync(pid: number): Promise<string | null>
],
{ encoding: 'utf8', timeout: KILL_PROBE_TIMEOUT_MS, windowsHide: true },
)
- : await execFileAsync('ps', ['-p', String(pid), '-o', 'args='], {
+ : await execFileAsync('ps', posixPsArgs(pid), {
encoding: 'utf8',
timeout: KILL_PROBE_TIMEOUT_MS,
});
- const text = typeof stdout === 'string' ? stdout.trim() : '';
- return text.length > 0 ? text : null;
+ return commandLineFromStdout(stdout);
} catch {
- return null;
+ return { status: 'unreadable' };
}
}
+/**
+ * What is at `status.runnerPid` right now?
+ *
+ * - `gone` — no live process, or the pid now runs something else. Either way
+ * the recorded runner is finished; a replacement process is not ours to touch.
+ * - `running` — the live process's command line still carries the generated
+ * runner script, whose path contains the run's UUID directory.
+ * - `unverifiable` — the pid is live but the command line could not be read (or
+ * the record predates `runnerScript`). Nothing may be concluded from it.
+ */
+type PiSubagentRunnerPresence = 'gone' | 'running' | 'unverifiable';
+
/**
* Is the process at `status.runnerPid` really this run's runner?
*
@@ -819,32 +860,45 @@ async function readProcessCommandLineAsync(pid: number): Promise<string | null>
* we cannot establish (no recorded path, no readable command line, no match)
* answers false, because the caller's next step is SIGKILL.
*/
+function classifyRunnerCommandLine(
+ commandLine: string,
+ script: string,
+): PiSubagentRunnerPresence {
+ // A readable listing is complete enough to decide. The proof is this run's
+ // generated script path (UUID directory). Another Subagent utility process
+ // at a recycled pid also contains `piSubagentRunnerProcess`, but not *this*
+ // script — that is gone, not unverifiable. Unreadable probes stay unknown.
+ return commandLine.includes(script) ? 'running' : 'gone';
+}
+
+function classifyCommandLineProbe(
+ probe: CommandLineProbe,
+ script: string,
+): PiSubagentRunnerPresence {
+ if (probe.status === 'unreadable') return 'unverifiable';
+ return classifyRunnerCommandLine(probe.text, script);
+}
+
+function resolveUnreadablePresence(pid: number): PiSubagentRunnerPresence {
+ // ps/CIM/empty output is also what a pid looks like after it exits between
+ // the liveness check and the listing. Recheck before treating that as a live
+ // process we cannot identify.
+ return isProcessAlive(pid) === false ? 'gone' : 'unverifiable';
+}
+
export function verifyPiSubagentRunnerIdentity(status: PiSubagentRunStatus): boolean {
const pid = status.runnerPid;
if (!Number.isSafeInteger(pid) || (pid ?? 0) <= 0) return false;
const script = status.runnerScript;
if (typeof script !== 'string' || script.length === 0) return false;
- const commandLine = readProcessCommandLine(pid!);
- return commandLine !== null && commandLine.includes(script);
+ return classifyCommandLineProbe(readProcessCommandLine(pid!), script) === 'running';
}
/**
- * What is at `status.runnerPid` right now?
- *
- * - `gone` — no live process, or the pid now runs something else. Either way
- * the recorded runner is finished; a replacement process is not ours to touch.
- * - `running` — the live process's command line still carries the generated
- * runner script, whose path contains the run's UUID directory.
- * - `unverifiable` — the pid is live but the command line could not be read (or
- * the record predates `runnerScript`). Nothing may be concluded from it.
+ * Synchronous mirror of `classifyRunnerPresence`.
*
* Liveness is checked before the command line so a dead pid never costs a spawn
* and never depends on a probe that a dead process cannot answer.
- */
-type PiSubagentRunnerPresence = 'gone' | 'running' | 'unverifiable';
-
-/**
- * Synchronous mirror of `classifyRunnerPresence`.
*
* Same three answers from the same evidence, in the same order — the only
* difference is the blocking probe, which the callers on the synchronous
@@ -857,9 +911,8 @@ function classifyRunnerPresenceSync(status: PiSubagentRunStatus): PiSubagentRunn
if (isProcessAlive(pid!) === false) return 'gone';
const script = status.runnerScript;
if (typeof script !== 'string' || script.length === 0) return 'unverifiable';
- const commandLine = readProcessCommandLine(pid!);
- if (commandLine === null) return 'unverifiable';
- return commandLine.includes(script) ? 'running' : 'gone';
+ const classified = classifyCommandLineProbe(readProcessCommandLine(pid!), script);
+ return classified === 'unverifiable' ? resolveUnreadablePresence(pid!) : classified;
}
async function classifyRunnerPresence(status: PiSubagentRunStatus): Promise<PiSubagentRunnerPresence> {
@@ -869,9 +922,8 @@ async function classifyRunnerPresence(status: PiSubagentRunStatus): Promise<PiSu
if (isProcessAlive(pid!) === false) return 'gone';
const script = status.runnerScript;
if (typeof script !== 'string' || script.length === 0) return 'unverifiable';
- const commandLine = await readProcessCommandLineAsync(pid!);
- if (commandLine === null) return 'unverifiable';
- return commandLine.includes(script) ? 'running' : 'gone';
+ const classified = classifyCommandLineProbe(await readProcessCommandLineAsync(pid!), script);
+ return classified === 'unverifiable' ? resolveUnreadablePresence(pid!) : classified;
}
/**
@@ -883,8 +935,10 @@ async function classifyRunnerPresence(status: PiSubagentRunStatus): Promise<PiSu
* BYOM credentials that, unlike the proxy token, cannot be revoked — so leaving
* it running past a logout keeps the outgoing account's credentials in use.
*
- * The runner is spawned detached, so it leads its own process group; killing
- * the group reaps the Pi children it owns too.
+ * The live runner must receive SIGTERM first so it can reap the Pi children it
+ * spawned. Utility-process runners are not process-group leaders; signalling
+ * `-pid` would miss those children and, on a shared group, could hit Cindy.
+ * Windows `taskkill /T` already walks the process tree.
*
* Success is *exit confirmation*, never "the signal was sent": `taskkill` fails
* by exit status rather than by throwing, and a caller that reports reclaimed
@@ -903,26 +957,17 @@ export async function killVerifiedPiSubagentRunner(status: PiSubagentRunStatus):
// ours, and we may not claim it was reclaimed either.
if (presence === 'unverifiable') return false;
const pid = status.runnerPid!;
- let signalled = false;
- try {
- if (process.platform === 'win32') {
- const killed = spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], {
- windowsHide: true,
- stdio: 'ignore',
- timeout: 5_000,
- });
- signalled = !killed.error && killed.status === 0;
- } else {
- process.kill(-pid, 'SIGKILL');
- signalled = true;
- }
- } catch { /* fall through to the single-process attempt */ }
- if (!signalled) {
- // The tree kill can fail on a permission or timing race while the runner
- // itself is still reachable — and it also "fails" when the process is
- // already gone. Neither is a verdict, so try the narrower signal and let
- // the confirmation loop decide.
+ if (process.platform === 'win32') {
+ spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], {
+ windowsHide: true,
+ stdio: 'ignore',
+ timeout: 5_000,
+ });
+ // taskkill reports failure through its exit status. A follow-up SIGKILL
+ // is what lets the confirmation loop observe a pid that actually died.
try { process.kill(pid, 'SIGKILL'); } catch { /* already gone, or unreachable */ }
+ } else {
+ try { process.kill(pid, 'SIGTERM'); } catch { /* already gone, or unreachable */ }
}
// Confirm by re-verifying identity rather than `kill(pid, 0)`: a zombie still
// "exists" for `kill(pid, 0)` and would be reported as unreclaimed forever,
@@ -930,14 +975,21 @@ export async function killVerifiedPiSubagentRunner(status: PiSubagentRunStatus):
// predicate also covers a recycled pid and, on Windows, a dead pid (the CIM
// query returns nothing) — one cross-platform judgement for "that runner is
// no longer running". Each attempt costs a `ps`/CIM spawn, so keep it short.
- for (let attempt = 0; ; attempt += 1) {
- // Same predicate as the entry check, and it must be a *positive* `gone`:
- // after the signal, a probe that simply stopped answering is not proof the
- // process died.
+ if (await waitUntilRunnerGone(status)) return true;
+ if (process.platform !== 'win32') {
+ try { process.kill(pid, 'SIGKILL'); } catch { /* already gone, or unreachable */ }
+ return waitUntilRunnerGone(status);
+ }
+ return false;
+}
+
+async function waitUntilRunnerGone(status: PiSubagentRunStatus): Promise<boolean> {
+ for (let attempt = 0; attempt < KILL_CONFIRM_ATTEMPTS; attempt += 1) {
if (await classifyRunnerPresence(status) === 'gone') return true;
- if (attempt >= KILL_CONFIRM_ATTEMPTS - 1) return false;
+ if (attempt === KILL_CONFIRM_ATTEMPTS - 1) break;
await new Promise<void>((resolve) => setTimeout(resolve, KILL_CONFIRM_INTERVAL_MS));
}
+ return await classifyRunnerPresence(status) === 'gone';
}
/**
@@ -2073,7 +2125,14 @@ interface ResumeRunnerConfig {
}
interface PiSubagentResumeLaunch {
- nodeExecutable: string;
+ launchRunner: (request: {
+ runId: string;
+ runDir: string;
+ runnerFile: string;
+ configFile: string;
+ cwd: string;
+ env: NodeJS.ProcessEnv;
+ }) => Promise<void>;
env: NodeJS.ProcessEnv;
runtimeOwnerId: string;
permissionSnapshot: unknown;
@@ -2272,6 +2331,71 @@ function isResumeConfig(value: unknown, runId: string): value is ResumeRunnerCon
&& raw.tasks.length <= 8;
}
+/** Launch/stop gave up waiting for exit; disk must stay non-terminal so sweep can still signal. */
+export class PiSubagentRunnerExitUnconfirmedError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'PiSubagentRunnerExitUnconfirmedError';
+ }
+}
+
+/** Host saw the runner exit even if status.json could not be persisted. */
+export class PiSubagentRunnerHostExitedError extends Error {
+ readonly runnerExited = true as const;
+ constructor(message: string) {
+ super(message);
+ this.name = 'PiSubagentRunnerHostExitedError';
+ }
+}
+
+/** Persist a host-observed runner failure without overwriting a real terminal result. */
+export async function recordPiSubagentRunnerFailure(
+ runDir: string,
+ message: string,
+): Promise<void> {
+ const runId = path.basename(runDir);
+ if (!RUN_DIR_RE.test(runId)) return;
+ const [configValue, statusValue] = await Promise.all([
+ readSmallJson(path.join(runDir, 'config.json')).catch(() => null),
+ readSmallJson(path.join(runDir, 'status.json')).catch(() => null),
+ ]);
+ if (!isResumeConfig(configValue, runId)) return;
+ const current = parseStatus(statusValue, runId);
+ if (current && isPiSubagentTerminal(current.state)) return;
+
+ const now = Date.now();
+ const error = message.slice(0, 4_000);
+ await writeAtomicJson(path.join(runDir, 'status.json'), {
+ version: 1,
+ runId,
+ taskId: configValue.taskId,
+ parentSessionId: configValue.parentSessionId,
+ runtimeOwnerId: configValue.runtimeOwnerId,
+ runnerInstanceId: `launch-error-${runId}`,
+ state: 'failed',
+ title: configValue.title,
+ description: configValue.description,
+ startedAt: current?.startedAt ?? now,
+ updatedAt: now,
+ endedAt: now,
+ tasks: configValue.tasks.map((task) => {
+ const previous = current?.tasks.find((candidate) => candidate.childId === task.childId);
+ const taskAlreadyTerminal = previous
+ && (previous.status === 'completed' || previous.status === 'failed' || previous.status === 'stopped');
+ return {
+ ...(previous ?? {}),
+ childId: task.childId,
+ sessionId: task.sessionId,
+ agent: task.agent,
+ title: task.title,
+ status: taskAlreadyTerminal ? previous.status : 'failed',
+ ...(!taskAlreadyTerminal ? { error } : {}),
+ endedAt: previous?.endedAt ?? now,
+ };
+ }),
+ });
+}
+
/**
* Resume the latest terminal generation on its existing PI child session ids.
* Credentials are supplied only by the live parent handle and are never copied
@@ -2542,40 +2666,23 @@ async function resumeClaimedPiSubagentRun(
await fs.rm(runDir, { recursive: true, force: true }).catch(() => undefined);
throw error;
}
- const child = spawn(launch.nodeExecutable, [runnerFile, path.join(runDir, 'config.json')], {
- cwd: sourceConfig.cwd,
- env: { ...launch.env, ELECTRON_RUN_AS_NODE: '1' },
- detached: true,
- windowsHide: true,
- stdio: 'ignore',
- });
- child.once('error', (error) => {
- const now = Date.now();
- void writeAtomicJson(path.join(runDir, 'status.json'), {
- version: 1,
+ const configFile = path.join(runDir, 'config.json');
+ try {
+ await launch.launchRunner({
runId,
- taskId: sourceConfig.taskId,
- parentSessionId: sourceConfig.parentSessionId,
- runtimeOwnerId: launch.runtimeOwnerId,
- runnerInstanceId: `launch-error-${runId}`,
- state: 'failed',
- title: config.title,
- description: config.description,
- startedAt: now,
- updatedAt: now,
- endedAt: now,
- tasks: config.tasks.map((task) => ({
- childId: task.childId,
- sessionId: task.sessionId,
- agent: task.agent,
- title: task.title,
- status: 'failed',
- error: `Durable runner failed to resume: ${String(error)}`.slice(0, 4_000),
- endedAt: now,
- })),
- }).catch(() => undefined);
- });
- child.unref();
+ runDir,
+ runnerFile,
+ configFile,
+ cwd: sourceConfig.cwd,
+ env: launch.env,
+ });
+ } catch (error) {
+ if (!(error instanceof PiSubagentRunnerExitUnconfirmedError)) {
+ const message = error instanceof Error ? error.message : String(error);
+ await recordPiSubagentRunnerFailure(runDir, message).catch(() => undefined);
+ }
+ throw error;
+ }
return runId;
}