Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
test: keep Pi RPC lifecycle coverage in unit CI
DavidShen547da56c93b5
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-harness.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-harness.test.tsnew file mode 100644index 0000000000..c3b304f0cd--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-harness.test.ts@@ -0,0 +1,177 @@+import type { ChildProcess, spawn } from 'node:child_process';+import { EventEmitter } from 'node:events';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { PassThrough } from 'node:stream';+import { afterEach, describe, expect, it } from 'vitest';++import { runGetCommands } from './pi-rpc-test-harness.js';++const fixtureRoots: string[] = [];++afterEach(() => {+ for (const root of fixtureRoots.splice(0)) rmSync(root, { recursive: true, force: true });+});++function createFixture(prefix: string) {+ const root = mkdtempSync(path.join(tmpdir(), prefix));+ fixtureRoots.push(root);+ const configHome = path.join(root, 'config-home');+ const workingDir = path.join(root, 'project');+ const sessionDir = path.join(root, 'sessions');+ // Lifecycle probes only need isolated paths, not a Git repository or Pi resources.+ for (const dir of [configHome, workingDir, sessionDir]) mkdirSync(dir, { recursive: true });+ return { root, configHome, workingDir, sessionDir };+}++function createFakeNodeScript(root: string, name: string, source: string): string {+ const file = path.join(root, `${name}.mjs`);+ writeFileSync(file, source);+ chmodSync(file, 0o755);+ return file;+}++async function waitForFile(file: string, timeoutMs = 5_000): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ while (!existsSync(file)) {+ if (Date.now() >= deadline) throw new Error(`fixture readiness timed out: ${file}`);+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+}++describe('Pi RPC resource-discovery harness lifecycle', () => {+ it('reports a missing binary and still lets the fixture clean up', async () => {+ const fixture = createFixture('pi-rpc-missing-');+ const missing = path.join(fixture.root, 'missing-pi');+ await expect(runGetCommands({+ binaryPath: missing,+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ })).rejects.toMatchObject({ code: 'binary_unavailable' });+ expect(existsSync(fixture.configHome)).toBe(true);+ rmSync(fixture.root, { recursive: true, force: true });+ expect(existsSync(fixture.root)).toBe(false);+ });++ it('kills a silent process after the RPC timeout', async () => {+ const fixture = createFixture('pi-rpc-timeout-');+ const silent = createFakeNodeScript(fixture.root, 'silent-pi', 'setInterval(() => {}, 60_000);\n');+ await expect(runGetCommands({+ binaryPath: process.execPath,+ binaryPrefixArgs: [silent],+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ rpcTimeoutMs: 200,+ exitTimeoutMs: 500,+ })).rejects.toMatchObject({ code: 'rpc_timeout' });+ });++ it('reports a startup timeout separately from an RPC timeout', async () => {+ const fixture = createFixture('pi-rpc-startup-timeout-');+ const neverSpawns = (() => {+ const fakeChild = new EventEmitter() as ChildProcess;+ const stdin = new PassThrough();+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ Object.assign(fakeChild, {+ stdin,+ stdout,+ stderr,+ exitCode: null,+ signalCode: null,+ kill: () => {+ queueMicrotask(() => fakeChild.emit('close', null, 'SIGTERM'));+ return true;+ },+ });+ return fakeChild;+ }) as typeof spawn;+ await expect(runGetCommands({+ binaryPath: 'fixture-pi',+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ spawnProcess: neverSpawns,+ startupTimeoutMs: 10,+ rpcTimeoutMs: 5_000,+ exitTimeoutMs: 50,+ })).rejects.toMatchObject({ code: 'startup_timeout' });+ });++ it.skipIf(process.platform === 'win32')('escalates to SIGKILL when a timed-out process ignores SIGTERM', async () => {+ const fixture = createFixture('pi-rpc-kill-');+ const marker = path.join(fixture.root, 'process-lifecycle.txt');+ const stubborn = createFakeNodeScript(+ fixture.root,+ 'stubborn-pi',+ [+ "import { appendFileSync } from 'node:fs';",+ `const marker = ${JSON.stringify(marker)};`,+ "process.on('SIGTERM', () => appendFileSync(marker, 'sigterm\\n'));",+ "appendFileSync(marker, `started:${process.pid}\\n`);",+ 'setInterval(() => {}, 60_000);',+ ].join('\n'),+ );++ await expect(runGetCommands({+ binaryPath: process.execPath,+ binaryPrefixArgs: [stubborn],+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ beforeRpcRequest: () => waitForFile(marker),+ rpcTimeoutMs: 200,+ exitTimeoutMs: 500,+ })).rejects.toMatchObject({ code: 'rpc_timeout' });++ const lifecycle = readFileSync(marker, 'utf8').trim().split('\n');+ expect(lifecycle).toHaveLength(2);+ expect(lifecycle[1]).toBe('sigterm');+ const pid = Number(lifecycle[0]?.slice('started:'.length));+ let processLookupError: NodeJS.ErrnoException | undefined;+ try {+ process.kill(pid, 0);+ } catch (error) {+ processLookupError = error as NodeJS.ErrnoException;+ }+ expect(processLookupError?.code).toBe('ESRCH');+ });++ it('reports a process that exits before responding', async () => {+ const fixture = createFixture('pi-rpc-exit-');+ const exiting = createFakeNodeScript(fixture.root, 'exit-pi', 'process.exit(17);\n');+ await expect(runGetCommands({+ binaryPath: process.execPath,+ binaryPrefixArgs: [exiting],+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ })).rejects.toMatchObject({ code: 'process_exited', details: { exitCode: 17 } });+ });++ it('rejects malformed RPC stdout and captures bounded stderr', async () => {+ const fixture = createFixture('pi-rpc-invalid-');+ const invalid = createFakeNodeScript(+ fixture.root,+ 'invalid-pi',+ "process.stderr.write('fixture stderr\\n'); process.stdout.write('not-json\\n'); setInterval(() => {}, 60_000);\n",+ );+ await expect(runGetCommands({+ binaryPath: process.execPath,+ binaryPrefixArgs: [invalid],+ cwd: fixture.workingDir,+ configHome: fixture.configHome,+ sessionDir: fixture.sessionDir,+ approve: false,+ exitTimeoutMs: 500,+ })).rejects.toMatchObject({ code: 'invalid_response', details: { stderr: 'fixture stderr\n' } });+ });+});diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.tsindex 58c44c5bcc..2a3b7229bb 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts@@ -6,10 +6,8 @@* `--approve` 当作生产策略;它只是与 `--no-approve` 组成可重复的 trust 观测对照。*/-import { execFileSync, spawn, type ChildProcess } from 'node:child_process';-import { EventEmitter } from 'node:events';+import { execFileSync } from 'node:child_process';import {- chmodSync,existsSync,mkdirSync,mkdtempSync,@@ -20,13 +18,12 @@ import {} from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';-import { PassThrough } from 'node:stream';-import { StringDecoder } from 'node:string_decoder';import { fileURLToPath } from 'node:url';import { afterEach, describe, expect, it } from 'vitest';import { scanPiCustomizations } from '../customization-scanner.js';import { capturePiRuntimeCapabilityManifest } from '../runtime-capabilities.js';+import { runGetCommands, type PiCommand } from './pi-rpc-test-harness.js';const __dirname = path.dirname(fileURLToPath(import.meta.url));const REPO_ROOT = path.resolve(__dirname, '../../../../../..');@@ -39,57 +36,6 @@ const PI_BINARY = path.join(process.platform === 'win32' ? 'pi.exe' : 'pi',);-const SAFE_ENV_KEYS = [- 'PATH',- 'Path',- 'SystemRoot',- 'SYSTEMROOT',- 'ComSpec',- 'COMSPEC',- 'PATHEXT',- 'TMPDIR',- 'TMP',- 'TEMP',- 'LANG',- 'LC_ALL',-] as const;--const DEFAULT_STARTUP_TIMEOUT_MS = 5_000;-const DEFAULT_RPC_TIMEOUT_MS = 5_000;-const DEFAULT_EXIT_TIMEOUT_MS = 1_000;-const MAX_STDERR_CHARS = 2_000;--type FailureCode =- | 'binary_unavailable'- | 'cleanup_timeout'- | 'invalid_response'- | 'process_exited'- | 'rpc_timeout'- | 'startup_timeout';--class PiRpcHarnessError extends Error {- constructor(- readonly code: FailureCode,- message: string,- readonly details: { stderr: string; exitCode?: number | null; signal?: NodeJS.Signals | null },- ) {- super(`[${code}] ${message}`);- this.name = 'PiRpcHarnessError';- }-}--interface PiCommand {- name?: unknown;- description?: unknown;- source?: unknown;- sourceInfo?: {- baseDir?: unknown;- scope?: unknown;- source?: unknown;- path?: unknown;- };-}-interface NormalizedSkill {name: string;description: string;@@ -107,60 +53,12 @@ interface Fixture {normalizedRoots: Array<{ root: string; label: string }>;}-interface RunOptions {- binaryPath: string;- binaryPrefixArgs?: string[];- cwd: string;- configHome: string;- sessionDir: string;- approve: boolean;- /** Additional CLI resource gates/explicit paths under test. */- extraArgs?: string[];- /** The hard-gate probe disables offline mode so it cannot mask install attempts. */- offline?: boolean;- extraEnv?: NodeJS.ProcessEnv;- beforeRpcRequest?: () => Promise<void>;- spawnProcess?: typeof spawn;- startupTimeoutMs?: number;- rpcTimeoutMs?: number;- exitTimeoutMs?: number;-}--interface RunResult {- commands: PiCommand[];- stderr: string;-}-const fixtureRoots: string[] = [];afterEach(() => {for (const root of fixtureRoots.splice(0)) rmSync(root, { recursive: true, force: true });});-function createSafeEnv(- root: string,- configHome: string,- options: Pick<RunOptions, 'offline' | 'extraEnv'> = {},-): NodeJS.ProcessEnv {- const env: NodeJS.ProcessEnv = {};- for (const key of SAFE_ENV_KEYS) {- if (process.env[key] !== undefined) env[key] = process.env[key];- }-- const home = path.join(root, 'home');- const xdg = path.join(root, 'xdg-config');- mkdirSync(home, { recursive: true });- mkdirSync(xdg, { recursive: true });- env.HOME = home;- env.USERPROFILE = home;- env.XDG_CONFIG_HOME = xdg;- env.PI_CODING_AGENT_DIR = configHome;- if (options.offline !== false) env.PI_OFFLINE = '1';- env.PI_TELEMETRY = '0';- env.NO_COLOR = '1';- return { ...env, ...options.extraEnv };-}-function writeSkill(dir: string, name: string): void {mkdirSync(dir, { recursive: true });writeFileSync(@@ -231,7 +129,7 @@ async function createFixture(prefix = 'pi-rpc-fixture-'): Promise<Fixture> {try {execFileSync('git', ['init', '--quiet', repoRoot]);} catch {- // Lifecycle-only cases still need a bounded repo marker in minimal images.+ // Keep a bounded repo marker when Git is unavailable in minimal images.mkdirSync(path.join(repoRoot, '.git'), { recursive: true });}writeDummyModels(configHome);@@ -281,375 +179,6 @@ function normalizeSkills(commands: PiCommand[], fixture: Fixture): NormalizedSki.sort((a, b) => a.name.localeCompare(b.name));}-function piArgs(options: Pick<RunOptions, 'sessionDir' | 'approve' | 'extraArgs'>): string[] {- return [- '--mode', 'rpc',- '--provider', 'dummy',- '--model', 'dummy-model',- '--session-dir', options.sessionDir,- '--no-context-files',- options.approve ? '--approve' : '--no-approve',- ...(options.extraArgs ?? []),- ];-}--function appendStderr(current: string, chunk: Buffer | string): string {- const next = current + chunk.toString();- return next.length <= MAX_STDERR_CHARS ? next : next.slice(-MAX_STDERR_CHARS);-}--function waitForClose(- closePromise: Promise<{ code: number | null; signal: NodeJS.Signals | null }>,- timeoutMs: number,-): Promise<boolean> {- return new Promise<boolean>((resolve) => {- let settled = false;- const finish = (closed: boolean) => {- if (settled) return;- settled = true;- clearTimeout(timer);- resolve(closed);- };- const timer = setTimeout(() => finish(false), timeoutMs);- void closePromise.then(() => finish(true));- });-}--async function terminateProcess(- child: ChildProcess,- closePromise: Promise<{ code: number | null; signal: NodeJS.Signals | null }>,- timeoutMs: number,- stderr: string,-): Promise<void> {- if (child.exitCode !== null || child.signalCode !== null) return;- try { child.kill('SIGTERM'); } catch { /* the close event remains authoritative */ }- if (await waitForClose(closePromise, timeoutMs)) return;-- try { child.kill('SIGKILL'); } catch { /* the close event remains authoritative */ }- if (await waitForClose(closePromise, timeoutMs)) return;-- throw new PiRpcHarnessError(- 'cleanup_timeout',- `Pi process did not exit after SIGTERM and SIGKILL (${timeoutMs}ms each)`,- { stderr, exitCode: child.exitCode, signal: child.signalCode },- );-}--async function runGetCommands(options: RunOptions): Promise<RunResult> {- let child: ChildProcess | undefined;- let stderr = '';- let pendingError: PiRpcHarnessError | undefined;- let result: RunResult | undefined;- let operationError: unknown;- let operationFailed = false;- let cleanupError: unknown;- let closeResolve!: (value: { code: number | null; signal: NodeJS.Signals | null }) => void;- const closePromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => {- closeResolve = resolve;- });-- try {- child = (options.spawnProcess ?? spawn)(- options.binaryPath,- [...(options.binaryPrefixArgs ?? []), ...piArgs(options)],- {- cwd: options.cwd,- env: createSafeEnv(path.dirname(options.configHome), options.configHome, options),- stdio: ['pipe', 'pipe', 'pipe'],- },- );-- child.stderr?.on('data', (chunk) => { stderr = appendStderr(stderr, chunk); });- child.on('close', (code, signal) => closeResolve({ code, signal }));-- result = await new Promise<RunResult>((resolve, reject) => {- const decoder = new StringDecoder('utf8');- let stdout = '';- let settled = false;- const startupTimer = setTimeout(() => {- fail(new PiRpcHarnessError('startup_timeout', `Pi did not spawn within ${options.startupTimeoutMs ?? DEFAULT_STARTUP_TIMEOUT_MS}ms`, { stderr }));- }, options.startupTimeoutMs ?? DEFAULT_STARTUP_TIMEOUT_MS);- let rpcTimer: NodeJS.Timeout | undefined;-- const cleanup = () => {- if (startupTimer) clearTimeout(startupTimer);- if (rpcTimer) clearTimeout(rpcTimer);- child?.stdout?.removeListener('data', onStdout);- child?.removeListener('error', onError);- child?.removeListener('close', onClose);- };- const fail = (error: PiRpcHarnessError) => {- if (settled) return;- settled = true;- pendingError = error;- cleanup();- reject(error);- };- const succeed = (commands: PiCommand[]) => {- if (settled) return;- settled = true;- cleanup();- resolve({ commands, stderr });- };- const onError = (error: NodeJS.ErrnoException) => {- fail(new PiRpcHarnessError(- error.code === 'ENOENT' ? 'binary_unavailable' : 'process_exited',- error.code === 'ENOENT' ? `Pi binary unavailable: ${options.binaryPath}` : `Pi spawn failed: ${error.message}`,- { stderr },- ));- };- const onStdinError = (error: NodeJS.ErrnoException) => {- fail(new PiRpcHarnessError(- 'process_exited',- `Pi RPC stdin failed: ${error.message}`,- { stderr, exitCode: child?.exitCode, signal: child?.signalCode },- ));- };- const onClose = (code: number | null, signal: NodeJS.Signals | null) => {- if (!settled) {- fail(new PiRpcHarnessError(- 'process_exited',- `Pi exited before get_commands response (code=${code}, signal=${signal})`,- { stderr, exitCode: code, signal },- ));- }- };- const onStdout = (chunk: Buffer | string) => {- stdout += typeof chunk === 'string' ? chunk : decoder.write(chunk);- while (true) {- const newline = stdout.indexOf('\n');- if (newline === -1) break;- let line = stdout.slice(0, newline);- stdout = stdout.slice(newline + 1);- if (line.endsWith('\r')) line = line.slice(0, -1);- if (!line.trim()) continue;- let frame: unknown;- try {- frame = JSON.parse(line);- } catch {- fail(new PiRpcHarnessError('invalid_response', `Pi returned non-JSON stdout: ${line.slice(0, 200)}`, { stderr }));- return;- }- if (!frame || typeof frame !== 'object') continue;- const response = frame as { id?: unknown; type?: unknown; success?: unknown; data?: unknown; error?: unknown };- if (response.type !== 'response' || response.id !== 'fixture-get-commands') continue;- if (response.success !== true) {- fail(new PiRpcHarnessError('invalid_response', `get_commands failed: ${String(response.error ?? 'unknown')}`, { stderr }));- return;- }- const data = response.data as { commands?: unknown } | undefined;- if (!Array.isArray(data?.commands)) {- fail(new PiRpcHarnessError('invalid_response', 'get_commands response has no commands array', { stderr }));- return;- }- succeed(data.commands as PiCommand[]);- return;- }- };-- child!.once('error', onError);- child!.once('close', onClose);- child!.stdin?.on('error', onStdinError);- child!.stdout?.on('data', onStdout);- child!.once('spawn', () => {- void (async () => {- if (settled) return;- clearTimeout(startupTimer);- try {- await options.beforeRpcRequest?.();- if (settled) return;- child!.stdin?.write(JSON.stringify({ type: 'get_commands', id: 'fixture-get-commands' }) + '\n');- } catch (error) {- fail(new PiRpcHarnessError('process_exited', `Pi RPC setup/write failed: ${String(error)}`, { stderr }));- return;- }- rpcTimer = setTimeout(() => {- fail(new PiRpcHarnessError('rpc_timeout', `get_commands timed out after ${options.rpcTimeoutMs ?? DEFAULT_RPC_TIMEOUT_MS}ms`, { stderr }));- }, options.rpcTimeoutMs ?? DEFAULT_RPC_TIMEOUT_MS);- })();- });- });- } catch (error) {- operationFailed = true;- operationError = error;- }-- if (child) {- try {- await terminateProcess(- child,- closePromise,- options.exitTimeoutMs ?? DEFAULT_EXIT_TIMEOUT_MS,- stderr,- );- } catch (error) {- cleanupError = error;- }- }- if (pendingError) {- pendingError.details.stderr = stderr;- }- if (cleanupError) {- throw cleanupError;- }- if (operationFailed) {- throw operationError;- }- if (!result) throw new Error('Pi RPC harness completed without a result');- return result;-}--function createFakeNodeScript(root: string, name: string, source: string): string {- const file = path.join(root, `${name}.mjs`);- writeFileSync(file, source);- chmodSync(file, 0o755);- return file;-}--async function waitForFile(file: string, timeoutMs = 5_000): Promise<void> {- const deadline = Date.now() + timeoutMs;- while (!existsSync(file)) {- if (Date.now() >= deadline) throw new Error(`fixture readiness timed out: ${file}`);- await new Promise((resolve) => setTimeout(resolve, 10));- }-}--describe('Pi RPC resource-discovery harness lifecycle', () => {- it('reports a missing binary and still lets the fixture clean up', async () => {- const fixture = await createFixture('pi-rpc-missing-');- const missing = path.join(fixture.root, 'missing-pi');- await expect(runGetCommands({- binaryPath: missing,- cwd: fixture.workingDir,- configHome: fixture.configHome,- sessionDir: fixture.sessionDir,- approve: false,- })).rejects.toMatchObject({ code: 'binary_unavailable' });- expect(existsSync(fixture.configHome)).toBe(true);- rmSync(fixture.root, { recursive: true, force: true });- expect(existsSync(fixture.root)).toBe(false);- });-- it('kills a silent process after the RPC timeout', async () => {- const fixture = await createFixture('pi-rpc-timeout-');- const silent = createFakeNodeScript(fixture.root, 'silent-pi', 'setInterval(() => {}, 60_000);\n');- await expect(runGetCommands({- binaryPath: process.execPath,- binaryPrefixArgs: [silent],- cwd: fixture.workingDir,- configHome: fixture.configHome,- sessionDir: fixture.sessionDir,- approve: false,- rpcTimeoutMs: 200,- exitTimeoutMs: 500,- })).rejects.toMatchObject({ code: 'rpc_timeout' });- });-- it('reports a startup timeout separately from an RPC timeout', async () => {- const fixture = await createFixture('pi-rpc-startup-timeout-');- const neverSpawns = (() => {- const fakeChild = new EventEmitter() as ChildProcess;- const stdin = new PassThrough();- const stdout = new PassThrough();- const stderr = new PassThrough();- Object.assign(fakeChild, {- stdin,- stdout,- stderr,- exitCode: null,- signalCode: null,- kill: () => {- queueMicrotask(() => fakeChild.emit('close', null, 'SIGTERM'));- return true;- },- });- return fakeChild;- }) as typeof spawn;- await expect(runGetCommands({- binaryPath: 'fixture-pi',- cwd: fixture.workingDir,- configHome: fixture.configHome,- sessionDir: fixture.sessionDir,- approve: false,- spawnProcess: neverSpawns,- startupTimeoutMs: 10,- rpcTimeoutMs: 5_000,- exitTimeoutMs: 50,- })).rejects.toMatchObject({ code: 'startup_timeout' });- });-- it.skipIf(process.platform === 'win32')('escalates to SIGKILL when a timed-out process ignores SIGTERM', async () => {- const fixture = await createFixture('pi-rpc-kill-');- const marker = path.join(fixture.root, 'process-lifecycle.txt');- const stubborn = createFakeNodeScript(- fixture.root,- 'stubborn-pi',- [- "import { appendFileSync } from 'node:fs';",- `const marker = ${JSON.stringify(marker)};`,- "process.on('SIGTERM', () => appendFileSync(marker, 'sigterm\\n'));",- "appendFileSync(marker, `started:${process.pid}\\n`);",- 'setInterval(() => {}, 60_000);',- ].join('\n'),- );-- await expect(runGetCommands({- binaryPath: process.execPath,- binaryPrefixArgs: [stubborn],- cwd: fixture.workingDir,- configHome: fixture.configHome,- sessionDir: fixture.sessionDir,- approve: false,- beforeRpcRequest: () => waitForFile(marker),- rpcTimeoutMs: 200,- exitTimeoutMs: 500,- })).rejects.toMatchObject({ code: 'rpc_timeout' });-- const lifecycle = readFileSync(marker, 'utf8').trim().split('\n');- expect(lifecycle).toHaveLength(2);- expect(lifecycle[1]).toBe('sigterm');- const pid = Number(lifecycle[0]?.slice('started:'.length));- let processLookupError: NodeJS.ErrnoException | undefined;- try {- process.kill(pid, 0);- } catch (error) {- processLookupError = error as NodeJS.ErrnoException;- }- expect(processLookupError?.code).toBe('ESRCH');- });-- it('reports a process that exits before responding', async () => {- const fixture = await createFixture('pi-rpc-exit-');- const exiting = createFakeNodeScript(fixture.root, 'exit-pi', 'process.exit(17);\n');- await expect(runGetCommands({- binaryPath: process.execPath,- binaryPrefixArgs: [exiting],- cwd: fixture.workingDir,- configHome: fixture.configHome,- sessionDir: fixture.sessionDir,- approve: false,- })).rejects.toMatchObject({ code: 'process_exited', details: { exitCode: 17 } });- });-- it('rejects malformed RPC stdout and captures bounded stderr', async () => {- const fixture = await createFixture('pi-rpc-invalid-');- const invalid = createFakeNodeScript(- fixture.root,- 'invalid-pi',- "process.stderr.write('fixture stderr\\n'); process.stdout.write('not-json\\n'); setInterval(() => {}, 60_000);\n",- );- await expect(runGetCommands({- binaryPath: process.execPath,- binaryPrefixArgs: [invalid],- cwd: fixture.workingDir,- configHome: fixture.configHome,- sessionDir: fixture.sessionDir,- approve: false,- exitTimeoutMs: 500,- })).rejects.toMatchObject({ code: 'invalid_response', details: { stderr: 'fixture stderr\n' } });- });-});-describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts', () => {it('records isolated global skills and omits unapproved project resources', async () => {const fixture = await createFixture('pi-rpc-no-trust-');diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-test-harness.ts b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-test-harness.tsnew file mode 100644index 0000000000..14e3d06611--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-test-harness.ts@@ -0,0 +1,322 @@+// Shared test-only RPC harness: lifecycle tests use Node fixtures; integration tests use Pi.+import { spawn, type ChildProcess } from 'node:child_process';+import { mkdirSync } from 'node:fs';+import path from 'node:path';+import { StringDecoder } from 'node:string_decoder';++const SAFE_ENV_KEYS = [+ 'PATH',+ 'Path',+ 'SystemRoot',+ 'SYSTEMROOT',+ 'ComSpec',+ 'COMSPEC',+ 'PATHEXT',+ 'TMPDIR',+ 'TMP',+ 'TEMP',+ 'LANG',+ 'LC_ALL',+] as const;++const DEFAULT_STARTUP_TIMEOUT_MS = 5_000;+const DEFAULT_RPC_TIMEOUT_MS = 5_000;+const DEFAULT_EXIT_TIMEOUT_MS = 1_000;+const MAX_STDERR_CHARS = 2_000;++type FailureCode =+ | 'binary_unavailable'+ | 'cleanup_timeout'+ | 'invalid_response'+ | 'process_exited'+ | 'rpc_timeout'+ | 'startup_timeout';++class PiRpcHarnessError extends Error {+ constructor(+ readonly code: FailureCode,+ message: string,+ readonly details: { stderr: string; exitCode?: number | null; signal?: NodeJS.Signals | null },+ ) {+ super(`[${code}] ${message}`);+ this.name = 'PiRpcHarnessError';+ }+}++export interface PiCommand {+ name?: unknown;+ description?: unknown;+ source?: unknown;+ sourceInfo?: {+ baseDir?: unknown;+ scope?: unknown;+ source?: unknown;+ path?: unknown;+ };+}++interface RunOptions {+ binaryPath: string;+ binaryPrefixArgs?: string[];+ cwd: string;+ configHome: string;+ sessionDir: string;+ approve: boolean;+ /** Additional CLI resource gates/explicit paths under test. */+ extraArgs?: string[];+ /** The hard-gate probe disables offline mode so it cannot mask install attempts. */+ offline?: boolean;+ extraEnv?: NodeJS.ProcessEnv;+ beforeRpcRequest?: () => Promise<void>;+ spawnProcess?: typeof spawn;+ startupTimeoutMs?: number;+ rpcTimeoutMs?: number;+ exitTimeoutMs?: number;+}++interface RunResult {+ commands: PiCommand[];+ stderr: string;+}++function createSafeEnv(+ root: string,+ configHome: string,+ options: Pick<RunOptions, 'offline' | 'extraEnv'> = {},+): NodeJS.ProcessEnv {+ const env: NodeJS.ProcessEnv = {};+ for (const key of SAFE_ENV_KEYS) {+ if (process.env[key] !== undefined) env[key] = process.env[key];+ }++ const home = path.join(root, 'home');+ const xdg = path.join(root, 'xdg-config');+ mkdirSync(home, { recursive: true });+ mkdirSync(xdg, { recursive: true });+ env.HOME = home;+ env.USERPROFILE = home;+ env.XDG_CONFIG_HOME = xdg;+ env.PI_CODING_AGENT_DIR = configHome;+ if (options.offline !== false) env.PI_OFFLINE = '1';+ env.PI_TELEMETRY = '0';+ env.NO_COLOR = '1';+ return { ...env, ...options.extraEnv };+}++function piArgs(options: Pick<RunOptions, 'sessionDir' | 'approve' | 'extraArgs'>): string[] {+ return [+ '--mode', 'rpc',+ '--provider', 'dummy',+ '--model', 'dummy-model',+ '--session-dir', options.sessionDir,+ '--no-context-files',+ options.approve ? '--approve' : '--no-approve',+ ...(options.extraArgs ?? []),+ ];+}++function appendStderr(current: string, chunk: Buffer | string): string {+ const next = current + chunk.toString();+ return next.length <= MAX_STDERR_CHARS ? next : next.slice(-MAX_STDERR_CHARS);+}++function waitForClose(+ closePromise: Promise<{ code: number | null; signal: NodeJS.Signals | null }>,+ timeoutMs: number,+): Promise<boolean> {+ return new Promise<boolean>((resolve) => {+ let settled = false;+ const finish = (closed: boolean) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(closed);+ };+ const timer = setTimeout(() => finish(false), timeoutMs);+ void closePromise.then(() => finish(true));+ });+}++async function terminateProcess(+ child: ChildProcess,+ closePromise: Promise<{ code: number | null; signal: NodeJS.Signals | null }>,+ timeoutMs: number,+ stderr: string,+): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) return;+ try { child.kill('SIGTERM'); } catch { /* the close event remains authoritative */ }+ if (await waitForClose(closePromise, timeoutMs)) return;++ try { child.kill('SIGKILL'); } catch { /* the close event remains authoritative */ }+ if (await waitForClose(closePromise, timeoutMs)) return;++ throw new PiRpcHarnessError(+ 'cleanup_timeout',+ `Pi process did not exit after SIGTERM and SIGKILL (${timeoutMs}ms each)`,+ { stderr, exitCode: child.exitCode, signal: child.signalCode },+ );+}++export async function runGetCommands(options: RunOptions): Promise<RunResult> {+ let child: ChildProcess | undefined;+ let stderr = '';+ let pendingError: PiRpcHarnessError | undefined;+ let result: RunResult | undefined;+ let operationError: unknown;+ let operationFailed = false;+ let cleanupError: unknown;+ let closeResolve!: (value: { code: number | null; signal: NodeJS.Signals | null }) => void;+ const closePromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => {+ closeResolve = resolve;+ });++ try {+ child = (options.spawnProcess ?? spawn)(+ options.binaryPath,+ [...(options.binaryPrefixArgs ?? []), ...piArgs(options)],+ {+ cwd: options.cwd,+ env: createSafeEnv(path.dirname(options.configHome), options.configHome, options),+ stdio: ['pipe', 'pipe', 'pipe'],+ },+ );++ child.stderr?.on('data', (chunk) => { stderr = appendStderr(stderr, chunk); });+ child.on('close', (code, signal) => closeResolve({ code, signal }));++ result = await new Promise<RunResult>((resolve, reject) => {+ const decoder = new StringDecoder('utf8');+ let stdout = '';+ let settled = false;+ const startupTimer = setTimeout(() => {+ fail(new PiRpcHarnessError('startup_timeout', `Pi did not spawn within ${options.startupTimeoutMs ?? DEFAULT_STARTUP_TIMEOUT_MS}ms`, { stderr }));+ }, options.startupTimeoutMs ?? DEFAULT_STARTUP_TIMEOUT_MS);+ let rpcTimer: NodeJS.Timeout | undefined;++ const cleanup = () => {+ if (startupTimer) clearTimeout(startupTimer);+ if (rpcTimer) clearTimeout(rpcTimer);+ child?.stdout?.removeListener('data', onStdout);+ child?.removeListener('error', onError);+ child?.removeListener('close', onClose);+ };+ const fail = (error: PiRpcHarnessError) => {+ if (settled) return;+ settled = true;+ pendingError = error;+ cleanup();+ reject(error);+ };+ const succeed = (commands: PiCommand[]) => {+ if (settled) return;+ settled = true;+ cleanup();+ resolve({ commands, stderr });+ };+ const onError = (error: NodeJS.ErrnoException) => {+ fail(new PiRpcHarnessError(+ error.code === 'ENOENT' ? 'binary_unavailable' : 'process_exited',+ error.code === 'ENOENT' ? `Pi binary unavailable: ${options.binaryPath}` : `Pi spawn failed: ${error.message}`,+ { stderr },+ ));+ };+ const onStdinError = (error: NodeJS.ErrnoException) => {+ fail(new PiRpcHarnessError(+ 'process_exited',+ `Pi RPC stdin failed: ${error.message}`,+ { stderr, exitCode: child?.exitCode, signal: child?.signalCode },+ ));+ };+ const onClose = (code: number | null, signal: NodeJS.Signals | null) => {+ if (!settled) {+ fail(new PiRpcHarnessError(+ 'process_exited',+ `Pi exited before get_commands response (code=${code}, signal=${signal})`,+ { stderr, exitCode: code, signal },+ ));+ }+ };+ const onStdout = (chunk: Buffer | string) => {+ stdout += typeof chunk === 'string' ? chunk : decoder.write(chunk);+ while (true) {+ const newline = stdout.indexOf('\n');+ if (newline === -1) break;+ let line = stdout.slice(0, newline);+ stdout = stdout.slice(newline + 1);+ if (line.endsWith('\r')) line = line.slice(0, -1);+ if (!line.trim()) continue;+ let frame: unknown;+ try {+ frame = JSON.parse(line);+ } catch {+ fail(new PiRpcHarnessError('invalid_response', `Pi returned non-JSON stdout: ${line.slice(0, 200)}`, { stderr }));+ return;+ }+ if (!frame || typeof frame !== 'object') continue;+ const response = frame as { id?: unknown; type?: unknown; success?: unknown; data?: unknown; error?: unknown };+ if (response.type !== 'response' || response.id !== 'fixture-get-commands') continue;+ if (response.success !== true) {+ fail(new PiRpcHarnessError('invalid_response', `get_commands failed: ${String(response.error ?? 'unknown')}`, { stderr }));+ return;+ }+ const data = response.data as { commands?: unknown } | undefined;+ if (!Array.isArray(data?.commands)) {+ fail(new PiRpcHarnessError('invalid_response', 'get_commands response has no commands array', { stderr }));+ return;+ }+ succeed(data.commands as PiCommand[]);+ return;+ }+ };++ child!.once('error', onError);+ child!.once('close', onClose);+ child!.stdin?.on('error', onStdinError);+ child!.stdout?.on('data', onStdout);+ child!.once('spawn', () => {+ void (async () => {+ if (settled) return;+ clearTimeout(startupTimer);+ try {+ await options.beforeRpcRequest?.();+ if (settled) return;+ child!.stdin?.write(JSON.stringify({ type: 'get_commands', id: 'fixture-get-commands' }) + '\n');+ } catch (error) {+ fail(new PiRpcHarnessError('process_exited', `Pi RPC setup/write failed: ${String(error)}`, { stderr }));+ return;+ }+ rpcTimer = setTimeout(() => {+ fail(new PiRpcHarnessError('rpc_timeout', `get_commands timed out after ${options.rpcTimeoutMs ?? DEFAULT_RPC_TIMEOUT_MS}ms`, { stderr }));+ }, options.rpcTimeoutMs ?? DEFAULT_RPC_TIMEOUT_MS);+ })();+ });+ });+ } catch (error) {+ operationFailed = true;+ operationError = error;+ }++ if (child) {+ try {+ await terminateProcess(+ child,+ closePromise,+ options.exitTimeoutMs ?? DEFAULT_EXIT_TIMEOUT_MS,+ stderr,+ );+ } catch (error) {+ cleanupError = error;+ }+ }+ if (pendingError) {+ pendingError.details.stderr = stderr;+ }+ if (cleanupError) {+ throw cleanupError;+ }+ if (operationFailed) {+ throw operationError;+ }+ if (!result) throw new Error('Pi RPC harness completed without a result');+ return result;+}diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjsindex dfb6f0fe06..3ccb7f7d63 100644--- a/scripts/__tests__/test-workspaces.test.mjs+++ b/scripts/__tests__/test-workspaces.test.mjs@@ -252,6 +252,22 @@ test("real agent integration tests are explicit tiers outside unit", () => {]);});+test("Pi RPC lifecycle stays in unit while binary resource discovery stays in integration", () => {+ const makerCore = manifest.workspaces.find(+ (workspace) => workspace.cwd === "packages/maker-core",+ );+ const testDir = "packages/maker-core/src/agents/pi/__tests__";+ const files = fs.readdirSync(path.join(ROOT, testDir))+ .filter((file) => file.startsWith("pi-rpc-"))+ .map((file) => `${testDir}/${file}`);+ assert.deepEqual(selectFilesForTier(makerCore, makerCore.tiers.unit, files), [+ `${testDir}/pi-rpc-harness.test.ts`,+ ]);+ assert.deepEqual(selectFilesForTier(makerCore, makerCore.tiers.integration, files), [+ `${testDir}/pi-rpc-resource-discovery.integration.test.ts`,+ ]);+});+test("unit tier pins an explicit vitest pool, forks only by documented exception", () => {// The default forks pool recycles one child process per test file, which on// 2026-07-30 sustained ~21 LaunchServices check-ins/second and took down