Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(heterogeneous-agents): run pi over the RPC transport with cross-turn process reuse (#18346)

Northword1e5fd6270a12
diff --git a/apps/cli/src/commands/hetero.startup.test.ts b/apps/cli/src/commands/hetero.startup.test.ts
new file mode 100644
index 00000000000..e23c0ef81b3
--- /dev/null
+++ b/apps/cli/src/commands/hetero.startup.test.ts
@@ -0,0 +1,103 @@
+import { spawn } from 'node:child_process';
+import { once } from 'node:events';
+import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { describe, expect, it } from 'vitest';
+
+const cliEntry = fileURLToPath(new URL('../index.ts', import.meta.url));
+
+describe.skipIf(process.platform === 'win32')(
+ 'Pi startup cancellation across real processes',
+ () => {
+ it.each(['SIGINT', 'SIGTERM', 'double-SIGINT'] as const)(
+ 'cleans up a hung handshake on %s before a handle exists',
+ async (signal) => {
+ const directory = await mkdtemp(path.join(tmpdir(), 'pi-startup-'));
+ const pidFile = path.join(directory, 'pid');
+ const executable = path.join(directory, 'pi.mjs');
+ await writeFile(
+ executable,
+ `#!/usr/bin/env node
+import { writeFile } from 'node:fs/promises';
+if (process.argv.includes('--version')) { console.log('0.85.1'); process.exit(0); }
+process.stdin.resume();
+process.on('SIGINT', () => {});
+process.on('SIGTERM', () => {});
+setInterval(() => {}, 1000);
+await writeFile(${JSON.stringify(pidFile)}, String(process.pid));
+`,
+ );
+ await chmod(executable, 0o700);
+ const child = spawn(
+ 'bun',
+ [
+ '--no-env-file',
+ cliEntry,
+ 'hetero',
+ 'exec',
+ '--type',
+ 'pi',
+ '--command',
+ executable,
+ '--cwd',
+ directory,
+ '--prompt',
+ 'must not reach the model',
+ '--operation-id',
+ 'startup-regression',
+ ],
+ {
+ cwd: directory,
+ env: { PATH: process.env.PATH, HOME: directory, NODE_ENV: 'test' },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ },
+ );
+ const exited = once(child, 'close');
+ let stderr = '';
+ child.stderr.on('data', (chunk) => (stderr += chunk));
+ child.stdout.resume();
+ let piPid: number | undefined;
+ try {
+ await expect
+ .poll(
+ async () => {
+ try {
+ piPid = Number(await readFile(pidFile, 'utf8'));
+ return piPid;
+ } catch {
+ return undefined;
+ }
+ },
+ { timeout: 15000 },
+ )
+ .toBeTruthy();
+ child.kill(signal === 'SIGTERM' ? 'SIGTERM' : 'SIGINT');
+ if (signal === 'double-SIGINT') {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ child.kill('SIGINT');
+ }
+ const [code] = await exited;
+ expect(code, stderr).toBe(
+ signal === 'SIGTERM' ? 143 : signal === 'double-SIGINT' ? 137 : 130,
+ );
+ expect(() => process.kill(piPid!, 0)).toThrow();
+ } finally {
+ child.kill('SIGKILL');
+ if (piPid) {
+ try {
+ process.kill(-piPid, 'SIGKILL');
+ } catch {
+ /* already reaped */
+ }
+ }
+ await exited;
+ await rm(directory, { force: true, recursive: true });
+ }
+ },
+ 25000,
+ );
+ },
+);
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index 3b20023cee5..3cb62bafc59 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -12,10 +12,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { registerHeteroCommand, SUPPORTED_AGENT_TYPES } from './hetero';
-const { mockResolveHeteroSpawnCommand, mockSpawnAgent } = vi.hoisted(() => ({
- mockResolveHeteroSpawnCommand: vi.fn(),
- mockSpawnAgent: vi.fn(),
-}));
+const { mockCreatePiRpcAgentHandle, mockResolveHeteroSpawnCommand, mockSpawnAgent } = vi.hoisted(
+ () => ({
+ mockCreatePiRpcAgentHandle: vi.fn(),
+ mockResolveHeteroSpawnCommand: vi.fn(),
+ mockSpawnAgent: vi.fn(),
+ }),
+);
const { mockGetTrpcClient, mockHeteroFinishMutate, mockHeteroIngestMutate } = vi.hoisted(() => ({
mockGetTrpcClient: vi.fn(),
mockHeteroFinishMutate: vi.fn(),
@@ -33,6 +36,12 @@ vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({
resolveHeteroSpawnCommand: mockResolveHeteroSpawnCommand,
}));
+vi.mock('@lobechat/heterogeneous-agents/rpc', () => ({
+ createPiRpcAgentHandle: mockCreatePiRpcAgentHandle,
+ toPiRpcPrompt: (input: unknown) =>
+ Promise.resolve({ text: typeof input === 'string' ? input : JSON.stringify(input) }),
+}));
+
vi.mock('../api/client', () => ({
getTrpcClient: mockGetTrpcClient,
}));
@@ -113,6 +122,7 @@ describe('hetero exec command', () => {
return { command: command ?? defaultCommand };
},
);
+ mockCreatePiRpcAgentHandle.mockReset();
mockSpawnAgent.mockReset();
mockHeteroIngestMutate.mockReset();
mockHeteroFinishMutate.mockReset();
@@ -226,14 +236,18 @@ describe('hetero exec command', () => {
expect(call.operationId).toMatch(/^[0-9a-f-]{36}$/i);
});
- it('keeps the agent in the detached wrapper process group when requested by dispatch', async () => {
- vi.stubEnv(HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV, '1');
- mockSpawnAgent.mockReturnValue(createFakeHandle());
+ it.each(['codex', 'pi'])(
+ 'keeps %s in the wrapper process group when requested by dispatch',
+ async (agentType) => {
+ vi.stubEnv(HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV, '1');
+ const spawn = agentType === 'pi' ? mockCreatePiRpcAgentHandle : mockSpawnAgent;
+ spawn.mockReturnValue(createFakeHandle());
- await runCmd(['hetero', 'exec', '--type', 'codex', '--prompt', 'do thing']);
+ await runCmd(['hetero', 'exec', '--type', agentType, '--prompt', 'do thing']);
- expect(mockSpawnAgent).toHaveBeenCalledWith(expect.objectContaining({ detached: false }));
- });
+ expect(spawn).toHaveBeenCalledWith(expect.objectContaining({ detached: false }));
+ },
+ );
it('does not duplicate Unix group signals inside an inherited wrapper group', async () => {
vi.stubEnv(HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV, '1');
@@ -272,6 +286,45 @@ describe('hetero exec command', () => {
await command;
});
+ it('binds cancellation while the async Pi factory is still awaiting startup and escalates a second SIGINT', async () => {
+ const signalHandlers = new Map<string, () => void>();
+ vi.spyOn(process, 'on').mockImplementation(((event: string, listener: () => void) => {
+ if (event === 'SIGINT' || event === 'SIGTERM') signalHandlers.set(event, listener);
+ return process;
+ }) as typeof process.on);
+ vi.spyOn(process, 'off').mockImplementation(((event: string) => {
+ signalHandlers.delete(event);
+ return process;
+ }) as typeof process.off);
+
+ const cancel = vi.fn().mockResolvedValue(undefined);
+ let rejectFactory: ((error: Error) => void) | undefined;
+ mockCreatePiRpcAgentHandle.mockImplementation(
+ (options: { onStartupControl?: (control: { cancel: typeof cancel }) => void }) => {
+ options.onStartupControl?.({ cancel });
+ return new Promise((_resolve, reject) => {
+ rejectFactory = reject;
+ });
+ },
+ );
+
+ const command = runCmd(['hetero', 'exec', '--type', 'pi', '--prompt', 'hi']);
+ for (let index = 0; index < 20 && !signalHandlers.get('SIGINT'); index += 1) {
+ await Promise.resolve();
+ }
+ signalHandlers.get('SIGINT')?.();
+ signalHandlers.get('SIGINT')?.();
+ for (let index = 0; index < 20 && cancel.mock.calls.length === 0; index += 1) {
+ await Promise.resolve();
+ }
+
+ expect(cancel.mock.calls).toEqual([['SIGKILL']]);
+ rejectFactory!(new Error('Pi RPC session is closed'));
+ await command;
+ expect(exitSpy).toHaveBeenCalledWith(137);
+ expect(signalHandlers.size).toBe(0);
+ });
+
it('runs Qoder with its default command and forwards model and effort', async () => {
mockSpawnAgent.mockReturnValue(createFakeHandle());
@@ -791,8 +844,12 @@ describe('hetero exec command', () => {
);
});
- it('runs Pi with model, resume, and native args while ignoring effort and speed', async () => {
- mockSpawnAgent.mockReturnValue(createFakeHandle());
+ it('runs Pi over the RPC transport with model, resume, and native args while ignoring effort and speed', async () => {
+ vi.stubEnv('HOME', '/pi-test-home');
+ vi.stubEnv('PI_CODING_AGENT_DIR', '/pi-test-config');
+ vi.stubEnv('ANTHROPIC_API_KEY', 'test-only-key');
+ mockResolveHeteroSpawnCommand.mockResolvedValue({ command: 'pi', pathEnv: '/pi-custom-bin' });
+ mockCreatePiRpcAgentHandle.mockResolvedValue(createFakeHandle());
await runCmd([
'hetero',
@@ -814,11 +871,20 @@ describe('hetero exec command', () => {
]);
expect(mockResolveHeteroSpawnCommand).toHaveBeenCalledWith('pi', undefined);
- expect(mockSpawnAgent).toHaveBeenCalledWith(
+ expect(mockSpawnAgent).not.toHaveBeenCalled();
+ expect(mockCreatePiRpcAgentHandle).toHaveBeenCalledWith(
expect.objectContaining({
- agentType: 'pi',
- command: 'pi',
- extraArgs: ['--provider', 'anthropic', '--model', 'anthropic/claude-sonnet-4-5'],
+ args: ['--provider', 'anthropic', '--model', 'anthropic/claude-sonnet-4-5'],
+ commandPath: 'pi',
+ env: expect.objectContaining({
+ HOME: '/pi-test-home',
+ PI_CODING_AGENT_DIR: '/pi-test-config',
+ ANTHROPIC_API_KEY: 'test-only-key',
+ PATH: '/pi-custom-bin',
+ }),
+ operationId: expect.any(String),
+ onRawStdout: undefined,
+ onStartupControl: expect.any(Function),
resumeSessionId: 'pi-session-1',
}),
);
@@ -973,6 +1039,7 @@ describe('hetero exec command', () => {
for (let i = 0; i < 20 && !sigintHandler; i += 1) await Promise.resolve();
sigintHandler?.();
+ await Promise.resolve();
expect(kill).toHaveBeenCalledWith('SIGINT');
expect(mockHeteroFinishMutate).not.toHaveBeenCalled();
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 0d3eec4e79e..413d3f5243f 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -9,11 +9,17 @@ import {
HETEROGENEOUS_AGENT_CONFIGS,
isLocalHeterogeneousType,
LOCAL_HETEROGENEOUS_AGENT_TYPES,
+ type LocalHeterogeneousAgentType,
} from '@lobechat/heterogeneous-agents';
import { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';
import { LobeBuiltinMcpServer } from '@lobechat/heterogeneous-agents/builtinMcp';
import { HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV } from '@lobechat/heterogeneous-agents/protocol';
import { resolveHeteroSpawnCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';
+import {
+ createPiRpcAgentHandle,
+ type PiRpcStartupControl,
+ toPiRpcPrompt,
+} from '@lobechat/heterogeneous-agents/rpc';
import type {
AgentContentBlock,
AgentImageSource,
@@ -74,6 +80,56 @@ const SUPPORTED_AGENT_COMMANDS = HETEROGENEOUS_AGENT_CONFIGS.map(
const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';
const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';
+/**
+ * Runtime selection registry for `lh hetero exec` β€” the CLI counterpart of
+ * the desktop controller's `runtimeDispatchers`. Long-lived bidirectional
+ * runtimes (pi RPC) register a spawn factory here; every other agent uses the
+ * generic one-shot `spawnAgent`. A future agent adopting an RPC mode only
+ * adds one entry β€” no dispatch edit.
+ */
+const spawnRuntimeRegistry: Partial<
+ Record<
+ LocalHeterogeneousAgentType,
+ (
+ spawnOpts: Parameters<typeof spawnAgent>[0],
+ lifecycle?: {
+ onRawStdout?: (chunk: Buffer) => void;
+ onStartupControl?: (control: PiRpcStartupControl) => void;
+ },
+ ) => Promise<Awaited<ReturnType<typeof spawnAgent>>>
+ >
+> = {
+ pi: async (spawnOpts, lifecycle) =>
+ createPiRpcAgentHandle({
+ args: spawnOpts.extraArgs ?? [],
+ commandPath: spawnOpts.command!,
+ cwd: spawnOpts.cwd ?? process.cwd(),
+ detached: spawnOpts.detached,
+ env: { ...process.env, ...spawnOpts.env },
+ operationId: spawnOpts.operationId,
+ onRawStdout: lifecycle?.onRawStdout,
+ onStartupControl: lifecycle?.onStartupControl,
+ prompt: await toPiRpcPrompt(spawnOpts.prompt),
+ resumeSessionId: spawnOpts.resumeSessionId,
+ uploadImage: spawnOpts.uploadImage,
+ }),
+};
+
+/**
+ * Spawn via the registered runtime factory, or the generic one-shot spawn.
+ * `onRawStdout` (raw-dump tee) reaches both generic and registered runtimes;
+ * RPC runtimes must install it before their eager handshake.
+ */
+const spawnAgentOrRuntime = (
+ spawnOpts: Parameters<typeof spawnAgent>[0],
+ onRawStdout?: (chunk: Buffer) => void,
+ onStartupControl?: (control: PiRpcStartupControl) => void,
+): Promise<Awaited<ReturnType<typeof spawnAgent>>> => {
+ const runtimeFactory = spawnRuntimeRegistry[spawnOpts.agentType as LocalHeterogeneousAgentType];
+ if (runtimeFactory) return runtimeFactory(spawnOpts, { onRawStdout, onStartupControl });
+ return spawnAgent({ ...spawnOpts, onRawStdout });
+};
+
/**
* Patterns that indicate a `--resume <sessionId>` run should be retried
* without `--resume`. Two classes of failure:
@@ -715,17 +771,93 @@ const exec = async (options: ExecOptions): Promise<void> => {
terminalErrorData: Record<string, unknown> | undefined;
terminalErrorMessage: string | undefined;
}> => {
+ // Own terminal signals before the async factory starts. Pi exposes its
+ // startup control synchronously once constructed; cancellation received
+ // during prompt normalization is remembered and applied at that point.
+ const inheritsWrapperProcessGroup =
+ process.platform !== 'win32' && process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] === '1';
+ let interrupted = false;
+ let cancellationSignal: NodeJS.Signals | undefined;
+ let handle: Awaited<ReturnType<typeof spawnAgent>> | undefined;
+ let startupControl: PiRpcStartupControl | undefined;
+ const cancellations: Promise<void>[] = [];
+ let cancellationError: unknown;
+ const cancelStartup = (control: PiRpcStartupControl, signal: NodeJS.Signals) => {
+ cancellations.push(
+ control.cancel(signal).catch((error) => {
+ cancellationError ??= error;
+ log.error(
+ 'Failed to cancel agent:',
+ error instanceof Error ? error.message : String(error),
+ );
+ }),
+ );
+ };
+ const drainCancellation = async () => {
+ await Promise.all(cancellations);
+ if (cancellationError) throw cancellationError;
+ };
+ const applyCancellation = (signal: NodeJS.Signals) => {
+ cancellationSignal = signal;
+ if (inheritsWrapperProcessGroup) return;
+ if (startupControl) cancelStartup(startupControl, signal);
+ else handle?.kill(signal);
+ };
+ const onSigint = () => {
+ const signal = interrupted ? 'SIGKILL' : 'SIGINT';
+ interrupted = true;
+ applyCancellation(signal);
+ };
+ const onSigterm = () => {
+ interrupted = true;
+ applyCancellation('SIGTERM');
+ };
+ const removeSignalListeners = () => {
+ process.off('SIGINT', onSigint);
+ process.off('SIGTERM', onSigterm);
+ };
+ process.on('SIGINT', onSigint);
+ process.on('SIGTERM', onSigterm);
+
// One raw-dump file pair per spawn attempt (the resume retry is a second
// attempt). The stdout tee runs inside `spawnAgent` before the adapter.
const dumpAttempt = rawDump?.openAttempt(runLabel);
// `spawnAgent` is async and can reject DURING image normalization β€” fetch
- // failures, missing local --image paths, decode errors.
- let handle: Awaited<ReturnType<typeof spawnAgent>>;
+ // failures, missing local --image paths, decode errors. The runtime
+ // registry picks the transport: pi runs over RPC, everything else spawns
+ // one-shot (same handle shape, so the event loop below is unchanged).
try {
- handle = await spawnAgent({ ...spawnOpts, onRawStdout: dumpAttempt?.writeStdout });
+ handle = await spawnAgentOrRuntime(spawnOpts, dumpAttempt?.writeStdout, (control) => {
+ startupControl = control;
+ if (cancellationSignal && !inheritsWrapperProcessGroup) {
+ cancelStartup(control, cancellationSignal);
+ }
+ });
+ if (cancellationSignal && !startupControl && !inheritsWrapperProcessGroup) {
+ handle.kill(cancellationSignal);
+ }
} catch (err) {
- await dumpAttempt?.close();
+ try {
+ await drainCancellation();
+ await dumpAttempt?.close();
+ } finally {
+ removeSignalListeners();
+ }
+ if (cancellationSignal) {
+ return {
+ cancelled: true,
+ code: null,
+ ingestError: false,
+ resumeNotFound: false,
+ sawTerminalError: false,
+ sessionId: undefined,
+ signal: cancellationSignal,
+ stderrContent: '',
+ terminalErrorData: undefined,
+ terminalErrorMessage: undefined,
+ };
+ }
const message = err instanceof Error ? err.message : String(err);
const errnoCode =
typeof err === 'object' && err && 'code' in err && typeof err.code === 'string'
@@ -773,31 +905,6 @@ const exec = async (options: ExecOptions): Promise<void> => {
return { code: 1, signal: null as NodeJS.Signals | null };
});
- // Direct CLI runs own a detached child group and forward terminal signals.
- // Device-dispatched wrappers share their outer detached group, so the
- // gateway cancellation owner signals that group directly instead.
- const inheritsWrapperProcessGroup =
- process.platform !== 'win32' && process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] === '1';
- let interrupted = false;
- const onSigint = () => {
- if (inheritsWrapperProcessGroup) {
- interrupted = true;
- return;
- }
- if (interrupted) {
- handle.kill('SIGKILL');
- return;
- }
- interrupted = true;
- handle.kill('SIGINT');
- };
- const onSigterm = () => {
- interrupted = true;
- if (!inheritsWrapperProcessGroup) handle.kill('SIGTERM');
- };
- process.on('SIGINT', onSigint);
- process.on('SIGTERM', onSigterm);
-
// Stream events. Each event is optionally written as JSONL and pushed
// into the ingester. When intercepting resume errors, a matching
// `error` event is withheld from the ingester and flags a retry instead.
@@ -875,15 +982,22 @@ const exec = async (options: ExecOptions): Promise<void> => {
}
}
await dumpAttempt?.close();
+ try {
+ await drainCancellation();
+ } finally {
+ removeSignalListeners();
+ }
process.exit(1);
- } finally {
- process.off('SIGINT', onSigint);
- process.off('SIGTERM', onSigterm);
}
const { code, signal } = await exit;
await stderrEnded;
await dumpAttempt?.close();
+ try {
+ await drainCancellation();
+ } finally {
+ removeSignalListeners();
+ }
// Fallback stderr detection: CC may exit non-zero without emitting a
// result event (e.g. it writes to stderr and quits immediately).
diff --git a/apps/cli/src/commands/verify.test.ts b/apps/cli/src/commands/verify.test.ts
index cde41010d19..fd137c5dbd6 100644
--- a/apps/cli/src/commands/verify.test.ts
+++ b/apps/cli/src/commands/verify.test.ts
@@ -1202,6 +1202,18 @@ describe('originFromEnv β€” in-app provenance', () => {
});
});
+ it('retains conversation provenance for persistent Pi without an authoring operation', () => {
+ process.env.LOBEHUB_AGENT_ID = 'agt_pi';
+ process.env.LOBEHUB_TOPIC_ID = 'tpc_pi';
+ delete process.env.LOBEHUB_OPERATION_ID;
+
+ expect(originFromEnv()).toEqual({
+ agentId: 'agt_pi',
+ operationId: undefined,
+ topicId: 'tpc_pi',
+ });
+ });
+
it('never takes its operationId from --operation, which names the run under TEST', () => {
// `--operation` links the session to the Agent Run being verified; origin is
// the run that AUTHORED the report. Conflating them attributes the report to
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 16828d0984f..1136c3676f7 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -52,6 +52,11 @@ import {
readClaudeCodeIdentity,
} from '@lobechat/heterogeneous-agents/quota-sampler';
import { isLoginShellTimeoutStatus } from '@lobechat/heterogeneous-agents/resolveCliCommand';
+import {
+ type PiRpcImage,
+ PiRpcSession,
+ type PiRpcSessionCallbacks,
+} from '@lobechat/heterogeneous-agents/rpc';
import type { AgentStreamEvent, UsageData } from '@lobechat/heterogeneous-agents/spawn';
import {
AcpRpcResponseError,
@@ -84,6 +89,7 @@ import {
isCursorAcpSessionNotFoundError,
isDevinAcpSessionNotFoundError,
isDroidAcpSessionNotFoundError,
+ normalizeImage,
readCodexSessionModel,
resolveCliSpawnPlan,
resolveCodexInitialModel,
@@ -119,6 +125,7 @@ import {
createLambdaFileStorePort,
type RemoteServerAuth,
} from '@/modules/heterogeneousAgent/fileStorePort';
+import { PiRpcPool } from '@/modules/heterogeneousAgent/piRpcPool';
import type { HostedProviderBinding } from '@/modules/heterogeneousAgent/providerBindingHost';
import {
gcHostedProviderBindingProfiles,
@@ -208,6 +215,16 @@ const CLI_ERROR_LINE_PATTERN = /^(?:error:|Error:|Usage:)/;
const HETERO_SESSION_COMPLETE_GRACE_MS = 1_000;
const HETERO_RUNTIME_LAB_ENABLED_VALUES = new Set(['1', 'true', 'yes', 'on']);
+const readPositiveEnvMs = (name: string, fallback: number): number => {
+ const raw = process.env[name];
+ if (!raw) return fallback;
+ const value = Number(raw);
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+};
+
+/** Default idle grace before a pooled pi RPC process is closed (5 min). */
+const PI_RPC_POOL_DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1000;
+
const waitForHeteroSessionCompleteGrace = () =>
new Promise<void>((resolve) => setTimeout(resolve, HETERO_SESSION_COMPLETE_GRACE_MS));
@@ -333,6 +350,18 @@ interface GetSessionInfoParams {
sessionId: string;
}
+/**
+ * A runtime dispatcher decides whether it handles a prompt for its agent
+ * type. Returns `true` when handled (the caller returns early); `false` when
+ * the caller should fall through to the generic CLI spawn. Entries live in
+ * the `runtimeDispatchers` registry so long-lived runtimes (pi RPC, codex
+ * app-server, ACP sessions, Claude SDK) select themselves by agent type.
+ */
+type HeterogeneousRuntimeDispatcher = (
+ params: SendPromptParams,
+ session: AgentSession,
+) => Promise<boolean>;
+
interface GetCodexQuotaParams {
command?: string;
env?: Record<string, string>;
@@ -383,6 +412,8 @@ interface AgentSession {
modelSource?: string;
modelVerificationLastAttemptAt?: number;
modelVerificationLastAttemptSessionId?: string;
+ /** Active pi RPC run (per-run process; cleared when the run settles). */
+ piRpcSession?: PiRpcSession;
process?: ChildProcess;
/**
* Absolute CLI path resolved by spawn preflight detection. Used for spawn()
@@ -473,9 +504,98 @@ export default class HeterogeneousAgentCtr {
getAccessToken: async () => (await this.remoteServerConfigCtr?.getAccessToken()) ?? null,
getServerUrl: async () => (await this.remoteServerConfigCtr?.getRemoteServerUrl()) ?? null,
};
+ this.piRpcPool = new PiRpcPool({
+ // Read per-construction so tests can inject a tiny idle window.
+ idleTimeoutMs: readPositiveEnvMs(
+ 'LOBE_PI_RPC_IDLE_TIMEOUT_MS',
+ PI_RPC_POOL_DEFAULT_IDLE_TIMEOUT_MS,
+ ),
+ onReap: (key, reason) => logger.info('Reaped pooled Pi RPC process:', { key, reason }),
+ });
}
private sessions = new Map<string, AgentSession>();
+
+ /**
+ * Runtime selection registry β€” the heterogeneous-agent counterpart of the
+ * adapter registry. Each entry decides whether it handles a prompt for its
+ * agent type and returns `true` when it did (the caller then returns early
+ * instead of falling through to the generic CLI spawn). Long-lived runtimes
+ * (pi RPC, codex app-server, ACP sessions, Claude SDK) register here so a
+ * future agent adopting an RPC mode only adds one entry β€” no dispatch edit.
+ */
+ private readonly runtimeDispatchers: Partial<
+ Record<HeterogeneousCliAgentType, HeterogeneousRuntimeDispatcher>
+ > = {
+ 'claude-code': async (params, session) => {
+ if (!(session.useClaudeCodeSdk || this.isClaudeCodeSdkLabEnabled)) return false;
+ try {
+ await this.sendPromptWithClaudeSdk(params, session);
+ return true;
+ } finally {
+ // Also clean up failures before the SDK run starts.
+ await session.hostedProviderBinding?.cleanup();
+ }
+ },
+ 'codex': async (params, session) => {
+ if (
+ session.hostedProviderBinding ||
+ session.codexAppServerFallback ||
+ !(session.useCodexAppServer || this.isCodexAppServerLabEnabled)
+ ) {
+ return false;
+ }
+ const unsupportedArgs = getCodexAppServerUnsupportedArgs(session.args, {
+ resume: !!session.agentSessionId,
+ });
+ if (unsupportedArgs.length === 0) {
+ // `true` = app-server handled the prompt; `false` = fall through to
+ // the generic `codex exec` spawn.
+ return this.sendPromptWithCodexAppServer(params, session);
+ }
+ if (session.agentSessionId) {
+ const message = `Codex app-server cannot safely resume this session without dropping CLI arguments: ${unsupportedArgs.join(', ')}`;
+ this.broadcast('heteroAgentSessionError', { error: message, sessionId: session.sessionId });
+ throw new Error(message);
+ }
+ session.codexAppServerFallback = true;
+ logger.warn('Falling back to codex exec because app-server cannot preserve CLI args:', {
+ sessionId: session.sessionId,
+ unsupportedArgs,
+ });
+ return false;
+ },
+ 'cursor': async (params, session) => {
+ await this.sendPromptWithCursorAcp(params, session);
+ return true;
+ },
+ 'devin': async (params, session) => {
+ await this.sendPromptWithDevinAcp(params, session);
+ return true;
+ },
+ 'droid': async (params, session) => {
+ await this.sendPromptWithDroidAcp(params, session);
+ return true;
+ },
+ 'grok-build': async (params, session) => {
+ await this.sendPromptWithGrokAcp(params, session);
+ return true;
+ },
+ 'trae': async (params, session) => {
+ await this.sendPromptWithTraeAcp(params, session);
+ return true;
+ },
+ // Pi runs exclusively over the RPC transport β€” there is no json fallback.
+ 'pi': async (params, session) => {
+ try {
+ await this.sendPromptWithPiRpc(params, session);
+ return true;
+ } finally {
+ await session.hostedProviderBinding?.cleanup();
+ }
+ },
+ };
+
/** Device-gateway CLI wrappers keyed by their server operation id. */
private lhHeteroExecTasks = new Map<string, LhHeteroExecTask>();
/**
@@ -496,6 +616,9 @@ export default class HeterogeneousAgentCtr {
private builtinMcpStartPromise?: Promise<LobeBuiltinMcpServer>;
/** One lazy, long-lived native Codex app-server connection shared by thread sessions. */
private codexAppServerClient?: CodexAppServerClient;
+ /** Cross-turn pi RPC process pool (reuse + idle reaping). */
+ private readonly piRpcPool: PiRpcPool;
+ private shuttingDown = false;
// Fresh window sits under the renderer's 2-minute auto-refresh so each
// scheduled poll reaches the usage API instead of a cache echo.
private readonly claudeCodeQuotaCache = new QuotaSnapshotCache<ClaudeCodeQuotaSnapshot>({
@@ -1549,62 +1672,13 @@ export default class HeterogeneousAgentCtr {
}
}
- if (
- session.agentType === 'claude-code' &&
- (session.useClaudeCodeSdk || this.isClaudeCodeSdkLabEnabled)
- ) {
- try {
- return await this.sendPromptWithClaudeSdk(params, session);
- } finally {
- // The SDK helper owns cleanup once `run()` starts; this outer guard
- // also covers input/trace/session construction failures before that try/finally.
- await session.hostedProviderBinding?.cleanup();
- }
- }
-
- if (
- session.agentType === 'codex' &&
- !session.hostedProviderBinding &&
- !session.codexAppServerFallback &&
- (session.useCodexAppServer || this.isCodexAppServerLabEnabled)
- ) {
- const unsupportedArgs = getCodexAppServerUnsupportedArgs(session.args, {
- resume: !!session.agentSessionId,
- });
- if (unsupportedArgs.length === 0) {
- if (await this.sendPromptWithCodexAppServer(params, session)) return;
- } else if (session.agentSessionId) {
- const message = `Codex app-server cannot safely resume this session without dropping CLI arguments: ${unsupportedArgs.join(', ')}`;
- this.broadcast('heteroAgentSessionError', { error: message, sessionId: session.sessionId });
- throw new Error(message);
- } else {
- session.codexAppServerFallback = true;
- logger.warn('Falling back to codex exec because app-server cannot preserve CLI args:', {
- sessionId: session.sessionId,
- unsupportedArgs,
- });
- }
- }
-
- if (session.agentType === 'grok-build') {
- return this.sendPromptWithGrokAcp(params, session);
- }
-
- if (session.agentType === 'cursor') {
- return this.sendPromptWithCursorAcp(params, session);
- }
-
- if (session.agentType === 'droid') {
- return this.sendPromptWithDroidAcp(params, session);
- }
-
- if (session.agentType === 'devin') {
- return this.sendPromptWithDevinAcp(params, session);
- }
-
- if (session.agentType === 'trae') {
- return this.sendPromptWithTraeAcp(params, session);
- }
+ // Long-lived runtimes (pi RPC, codex app-server, ACP sessions, Claude
+ // SDK) select themselves via the runtime registry. A dispatcher that
+ // returns `true` handled the prompt; `false` falls through to the generic
+ // CLI spawn below.
+ const runtimeDispatcher =
+ this.runtimeDispatchers[session.agentType as HeterogeneousCliAgentType];
+ if (runtimeDispatcher && (await runtimeDispatcher(params, session))) return;
// Stand up the AskUserQuestion MCP bridge for supported prompts BEFORE
// building the spawn plan so the driver can wire the temp config path
@@ -2576,6 +2650,203 @@ export default class HeterogeneousAgentCtr {
});
}
+ /**
+ * Pi RPC host callbacks for one run. Built per run (not per process) so a
+ * pooled process can be rebound to the current IPC session and trace.
+ */
+ private buildPiRpcCallbacks(
+ session: AgentSession,
+ traceSession: CliTraceSession | undefined,
+ operationId: string,
+ shellOperationId: string | null,
+ ): PiRpcSessionCallbacks {
+ return {
+ operationId,
+ sessionId: session.sessionId,
+ shellOperationId,
+ onEvents: async (events) => {
+ for (const event of events) {
+ this.broadcast('heteroAgentEvent', {
+ event,
+ sessionId: session.sessionId,
+ });
+ }
+ },
+ onRuntimeStatus: (status) => {
+ this.broadcast('heteroAgentRuntimeStatus', status);
+ },
+ onSessionId: (agentSessionId) => {
+ if (agentSessionId !== session.agentSessionId) session.agentSessionId = agentSessionId;
+ },
+ onStderr: (data) => this.appendCliTraceFile(traceSession, 'stderr.log', data),
+ };
+ }
+
+ /**
+ * Pi over the RPC transport β€” the only pi execution path (no json fallback).
+ *
+ * The first prompt spawns a process; settled runs hand it to the pool for
+ * follow-up turns. A pool miss resumes the native session via --session-id.
+ */
+ private async sendPromptWithPiRpc(
+ params: SendPromptParams,
+ session: AgentSession,
+ ): Promise<void> {
+ const cwd = this.resolveSessionWorkingDirectory(session);
+ const spawnEnv = this.buildSessionSpawnEnv(session);
+ const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);
+
+ // Text + base64 images for the RPC `prompt` command (no `@path` temp files).
+ const promptBlocks = buildHeterogeneousPrompt({
+ imageList: params.imageList,
+ prompt: params.prompt,
+ systemContext: params.systemContext,
+ });
+ const text: string[] = [];
+ const images: PiRpcImage[] = [];
+ for (const block of promptBlocks) {
+ if (block.type === 'text') {
+ if (block.text) text.push(block.text);
+ continue;
+ }
+ try {
+ const image = await normalizeImage(block.source, { cacheDir: this.fileCacheDir });
+ images.push({
+ data: image.buffer.toString('base64'),
+ mimeType: image.mediaType,
+ type: 'image',
+ });
+ } catch (error) {
+ // A broken attachment must not silently drop the image from the
+ // prompt β€” surface it like the Codex/Grok paths do.
+ throw new Error(
+ `Failed to attach image(s) to Pi RPC prompt: ${this.getErrorMessage(error) || 'Unknown error'}`,
+ { cause: error },
+ );
+ }
+ }
+
+ const traceSession = await this.createCliTraceSession({
+ cliArgs: ['--mode', 'rpc', ...session.args],
+ cwd,
+ imageList: params.imageList ?? [],
+ session,
+ stdinPayload: '',
+ });
+ void this.writeCliTraceFile(traceSession, 'prompt.txt', params.prompt);
+
+ if (session.cancelledByUs) {
+ await this.completeCancelledSessionBeforeLaunch(session);
+ return;
+ }
+
+ // Cross-turn reuse: the pool keeps one `pi --mode rpc` process alive per
+ // `cwd::nativeSessionId`. The first turn spawns (no native id yet); later
+ // turns resume with `--session-id` and hit the pool instead of respawning.
+ const poolKey = session.agentSessionId ? `${cwd}::${session.agentSessionId}` : undefined;
+ // Extensions that cache env or launch unawaited work after settlement can
+ // opt out per agent without losing RPC or disabling their custom tools.
+ const reuse = spawnEnv.LOBE_PI_RPC_REUSE !== '0';
+ const callbacks = this.buildPiRpcCallbacks(
+ session,
+ traceSession,
+ params.operationId,
+ spawnEnv.LOBEHUB_OPERATION_ID ?? null,
+ );
+ // Fingerprint the runtime options that shape the spawned process (command
+ // path, args, env) so a pool hit under changed settings β€” model/provider,
+ // proxy env, cwd env β€” spawns fresh instead of reusing stale config.
+ const spawnFingerprint = [
+ commandPath,
+ cwd,
+ JSON.stringify(session.args ?? []),
+ JSON.stringify(
+ Object.entries(spawnEnv)
+ .filter(([key]) => key !== 'LOBEHUB_OPERATION_ID')
+ .sort(),
+ ),
+ ].join('::');
+ if (this.shuttingDown) throw new Error('Application is shutting down');
+ const pooledSession = poolKey ? this.piRpcPool.acquire(poolKey, spawnFingerprint) : undefined;
+ const rpcSession =
+ pooledSession ??
+ new PiRpcSession({
+ args: session.args,
+ commandPath,
+ cwd,
+ env: spawnEnv,
+ resumeSessionId: session.agentSessionId,
+ autoCloseOnSettle: !reuse,
+ uploadImage: this.uploadResultImage,
+ ...callbacks,
+ });
+ // A pooled process carries the callbacks of the run that spawned it β€”
+ // rebind to THIS run's IPC session / trace or events would broadcast to
+ // a stale sessionId.
+ if (pooledSession) pooledSession.rebind(callbacks);
+ session.piRpcSession = rpcSession;
+
+ logger.info(pooledSession ? 'Reusing pooled Pi RPC process:' : 'Starting Pi RPC session:', {
+ commandPath,
+ cwd,
+ pooled: !!pooledSession,
+ sessionId: session.sessionId,
+ });
+
+ try {
+ const { aborted } = await rpcSession.run({
+ text: text.join('\n\n'),
+ ...(images.length > 0 ? { images } : {}),
+ });
+ if (session.piRpcSession === rpcSession) session.piRpcSession = undefined;
+ // Hand the process to the pool for the next turn (native id known now).
+ // A fresh process without a native id cannot be keyed β€” recycle it.
+ if (session.agentSessionId && reuse) {
+ const key = `${cwd}::${session.agentSessionId}`;
+ if (!pooledSession) this.piRpcPool.register(key, rpcSession, spawnFingerprint);
+ this.piRpcPool.release(rpcSession);
+ } else if (!pooledSession) {
+ await rpcSession.close().catch(() => {
+ /* best-effort */
+ });
+ }
+ void this.writeCliTraceJson(traceSession, 'exit.json', {
+ aborted,
+ finishedAt: new Date().toISOString(),
+ pooled: !!pooledSession,
+ transport: 'pi-rpc',
+ });
+ await this.flushCliTrace(traceSession);
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ } catch (error) {
+ if (session.piRpcSession === rpcSession) session.piRpcSession = undefined;
+ // The run failed β€” the process is not reusable; close and drop it.
+ this.piRpcPool.remove(rpcSession);
+ logger.error('Pi RPC session error:', error);
+ void this.writeCliTraceJson(traceSession, 'process-error.json', {
+ message: this.getErrorMessage(error),
+ name: error instanceof Error ? error.name : 'Error',
+ transport: 'pi-rpc',
+ });
+ await this.flushCliTrace(traceSession);
+
+ // A user-initiated cancel resolves the run as `aborted`, so reaching the
+ // catch means a genuine failure β€” unless we tore the process down.
+ if (session.cancelledByUs) {
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ return;
+ }
+ const sessionError = this.getSessionErrorPayload(error, session);
+ this.broadcast('heteroAgentSessionError', {
+ error: sessionError,
+ sessionId: session.sessionId,
+ });
+ throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {
+ cause: error,
+ });
+ }
+ }
+
private async verifyCodexSessionModel({
env,
pipeline,
@@ -3124,6 +3395,12 @@ export default class HeterogeneousAgentCtr {
await session.traeAcpSession.interrupt();
return;
}
+ if (session.piRpcSession) {
+ // Resolves only after settlement or confirmed shutdown. Propagate a
+ // failed shutdown so "Send now" cannot start another native writer.
+ await session.piRpcSession.abort();
+ return;
+ }
if (session.sdkSession) {
session.sdkSession.close();
return;
@@ -3190,6 +3467,12 @@ export default class HeterogeneousAgentCtr {
session.traeAcpSession.close();
}
+ if (session.piRpcSession) {
+ session.cancelledByUs = true;
+ // Healthy settled processes remain pooled; failed cancellation closes them.
+ await session.piRpcSession.abort();
+ }
+
if (session.sdkSession) {
session.cancelledByUs = true;
session.sdkSession.close();
@@ -3261,10 +3544,21 @@ export default class HeterogeneousAgentCtr {
* harnesses, OS shutdown) where Electron's lifecycle events never fire.
*/
afterAppReady() {
- electronApp.on('before-quit', () => {
+ let quitReady = false;
+ electronApp.on('before-quit', (event) => {
+ if (quitReady) return;
+ event.preventDefault();
+ if (this.shuttingDown) return;
+ this.shuttingDown = true;
+ const piClosing: Promise<void>[] = [];
this.unlinkPendingInterventionConfigsSync();
for (const [, session] of this.sessions) {
session.hostedProviderBinding?.cleanupSync();
+ // First-turn processes have not reached the pool yet.
+ if (session.piRpcSession) {
+ session.cancelledByUs = true;
+ piClosing.push(session.piRpcSession.close());
+ }
if (session.devinAcpSession) {
session.cancelledByUs = true;
session.devinAcpSession.close();
@@ -3300,6 +3594,8 @@ export default class HeterogeneousAgentCtr {
}
this.codexAppServerClient?.close();
this.codexAppServerClient = undefined;
+ // Pooled pi processes outlive their IPC sessions β€” reap them on quit.
+ piClosing.push(this.piRpcPool.closeAll());
this.sessions.clear();
// The exit handlers will tear each per-op intervention down, but if
// CC's stdio close races shutdown we'd leave the MCP server bound to
@@ -3308,6 +3604,13 @@ export default class HeterogeneousAgentCtr {
void this.builtinMcpServer?.stop().catch((err) => {
logger.warn('AskUserQuestion MCP server stop error:', err);
});
+ void Promise.allSettled(piClosing).then((results) => {
+ for (const result of results) {
+ if (result.status === 'rejected') logger.warn('Pi RPC shutdown failed:', result.reason);
+ }
+ quitReady = true;
+ electronApp.quit();
+ });
});
const onSignal = (signal: NodeJS.Signals) => {
@@ -3320,10 +3623,11 @@ export default class HeterogeneousAgentCtr {
/* during late shutdown app.quit may throw β€” fine */
}
// Last-resort exit if Electron is wedged and won't quit on its own.
- setTimeout(() => process.exit(signal === 'SIGINT' ? 130 : 143), 1000).unref();
+ // Allow EOF β†’ TERM β†’ KILL (up to seven seconds) to complete first.
+ setTimeout(() => process.exit(signal === 'SIGINT' ? 130 : 143), 10_000).unref();
};
- process.on('SIGTERM', onSignal);
- process.on('SIGINT', onSignal);
+ process.on('SIGTERM', () => onSignal('SIGTERM'));
+ process.on('SIGINT', () => onSignal('SIGINT'));
}
/**
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index fae02f7f52f..503f23b9eab 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -111,6 +111,7 @@ vi.mock('electron', () => ({
getPath: vi.fn((name: string) => (name === 'desktop' ? FAKE_DESKTOP_PATH : `/fake/${name}`)),
isPackaged: false,
on: vi.fn(),
+ quit: vi.fn(),
},
ipcMain: { handle: vi.fn() },
}));
@@ -159,6 +160,11 @@ const {
traeAcpSessionConstructMock,
traeAcpSessionInterruptMock,
traeAcpSessionRunMock,
+ piRpcSessionAbortMock,
+ piRpcSessionCloseMock,
+ piRpcSessionConstructMock,
+ piRpcSessionRebindMock,
+ piRpcSessionRunMock,
} = vi.hoisted(() => ({
claudeSdkSessionCloseMock: vi.fn(),
claudeSdkSessionConstructMock: vi.fn(),
@@ -193,6 +199,11 @@ const {
traeAcpSessionConstructMock: vi.fn(),
traeAcpSessionInterruptMock: vi.fn(),
traeAcpSessionRunMock: vi.fn(),
+ piRpcSessionAbortMock: vi.fn(),
+ piRpcSessionCloseMock: vi.fn(),
+ piRpcSessionConstructMock: vi.fn(),
+ piRpcSessionRebindMock: vi.fn(),
+ piRpcSessionRunMock: vi.fn(),
}));
vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
@@ -545,6 +556,46 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
};
});
+vi.mock('@lobechat/heterogeneous-agents/rpc', () => {
+ class MockPiRpcSession {
+ isReusable = true;
+ constructor(private readonly options: any) {
+ piRpcSessionConstructMock(options);
+ }
+
+ async abort() {
+ return piRpcSessionAbortMock();
+ }
+
+ async close() {
+ piRpcSessionCloseMock();
+ }
+
+ rebind(callbacks: any) {
+ piRpcSessionRebindMock(callbacks);
+ }
+
+ async run() {
+ if (piRpcSessionRunMock.getMockImplementation()) {
+ return piRpcSessionRunMock(this.options);
+ }
+ const now = Date.now();
+ this.options.onSessionId('pi_sess_1');
+ await this.options.onEvents([
+ {
+ data: { reason: 'complete', transport: 'pi-rpc' },
+ stepIndex: 0,
+ timestamp: now,
+ type: 'agent_runtime_end',
+ },
+ ]);
+ return { aborted: false };
+ }
+ }
+
+ return { PiRpcSession: MockPiRpcSession };
+});
+
const { consumeCodexRateLimitResetCreditMock, fetchCodexQuotaMock } = vi.hoisted(() => ({
consumeCodexRateLimitResetCreditMock: vi.fn(),
fetchCodexQuotaMock: vi.fn(),
@@ -716,6 +767,11 @@ describe('HeterogeneousAgentCtr', () => {
traeAcpSessionConstructMock.mockReset();
traeAcpSessionInterruptMock.mockReset();
traeAcpSessionRunMock.mockReset();
+ piRpcSessionAbortMock.mockReset();
+ piRpcSessionCloseMock.mockReset();
+ piRpcSessionConstructMock.mockReset();
+ piRpcSessionRebindMock.mockReset();
+ piRpcSessionRunMock.mockReset();
droidAcpSessionCloseMock.mockReset();
droidAcpSessionConstructMock.mockReset();
droidAcpSessionInterruptMock.mockReset();
@@ -726,6 +782,7 @@ describe('HeterogeneousAgentCtr', () => {
vi.mocked(statSync).mockReturnValue(asDirectory);
delete process.env.LOBE_CLAUDE_CODE_SDK;
delete process.env.LOBE_CODEX_APP_SERVER;
+ delete process.env.LOBE_PI_RPC_IDLE_TIMEOUT_MS;
});
afterEach(async () => {
@@ -2455,7 +2512,6 @@ describe('HeterogeneousAgentCtr', () => {
});
it('injects a Pi operation token into its Responses credential env', async () => {
- nextFakeProc = createFakeProc().proc;
const ctr = new HeterogeneousAgentCtr({
appStoragePath,
storeManager: { get: vi.fn() },
@@ -2483,15 +2539,18 @@ describe('HeterogeneousAgentCtr', () => {
operationId: 'op-server-default-pi',
topicId: 'topic-1',
});
- expect(spawnCalls[0].args).toEqual(
- expect.arrayContaining([
- '--provider',
- 'lobehub-server-default',
- '--model',
- 'lobehub/kimi-k2.6',
- ]),
+ expect(piRpcSessionConstructMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: expect.arrayContaining([
+ '--provider',
+ 'lobehub-server-default',
+ '--model',
+ 'lobehub/kimi-k2.6',
+ ]),
+ env: expect.objectContaining({ LOBEHUB_PI_API_KEY: 'operation-token' }),
+ }),
);
- expect(spawnCalls[0].options.env.LOBEHUB_PI_API_KEY).toBe('operation-token');
+ expect(spawnCalls).toHaveLength(0);
expect(settleServerDefaultOperationMock).toHaveBeenCalledWith(expect.any(Object), {
cancelled: false,
operationId: 'op-server-default-pi',
@@ -4115,6 +4174,264 @@ describe('HeterogeneousAgentCtr', () => {
});
});
+ describe('sendPrompt (pi rpc)', () => {
+ it('routes pi prompts through the RPC transport with resume args and captures the native session id', async () => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([
+ {
+ isDestroyed: () => false,
+ webContents: { send },
+ },
+ ]);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'pi',
+ args: ['--provider', 'anthropic'],
+ command: 'pi',
+ resumeSessionId: 'prev_sess',
+ });
+
+ await ctr.sendPrompt({ operationId: 'op-pi', prompt: 'hello pi', sessionId });
+
+ expect(piRpcSessionConstructMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: ['--provider', 'anthropic'],
+ commandPath: 'pi',
+ operationId: 'op-pi',
+ resumeSessionId: 'prev_sess',
+ uploadImage: expect.any(Function),
+ }),
+ );
+ expect(spawnCalls).toHaveLength(0);
+ // Native session id captured for the next turn's resume.
+ const sessionInfo = await ctr.getSessionInfo({ sessionId });
+ expect(sessionInfo.agentSessionId).toBe('pi_sess_1');
+ expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });
+ });
+
+ it('waits for RPC cancellation instead of killing the process tree', async () => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([
+ {
+ isDestroyed: () => false,
+ webContents: { send },
+ },
+ ]);
+ let resolveRun: ((result: { aborted: boolean }) => void) | undefined;
+ piRpcSessionRunMock.mockImplementation(
+ () =>
+ new Promise<{ aborted: boolean }>((resolve) => {
+ resolveRun = resolve;
+ }),
+ );
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'pi',
+ command: 'pi',
+ });
+
+ const sendPromise = ctr.sendPrompt({ operationId: 'op-pi-abort', prompt: 'work', sessionId });
+ await vi.waitFor(() => expect(piRpcSessionConstructMock).toHaveBeenCalled());
+
+ let finishAbort!: () => void;
+ piRpcSessionAbortMock.mockReturnValue(
+ new Promise<void>((resolve) => (finishAbort = resolve)),
+ );
+ const confirmed = vi.fn();
+ const cancellation = ctr.cancelSession({ sessionId }).then(confirmed);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(piRpcSessionAbortMock).toHaveBeenCalled();
+ expect(confirmed).not.toHaveBeenCalled();
+ expect(spawnCalls).toHaveLength(0);
+ // The run resolves as aborted β†’ the session completes, not errors.
+ resolveRun?.({ aborted: true });
+ await sendPromise;
+ finishAbort();
+ await cancellation;
+ expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });
+ });
+
+ it.each(['cancelSession', 'stopSession'] as const)(
+ 'does not confirm %s when Pi shutdown fails',
+ async (method) => {
+ let finishRun!: (result: { aborted: boolean }) => void;
+ piRpcSessionRunMock.mockReturnValue(
+ new Promise<{ aborted: boolean }>((resolve) => (finishRun = resolve)),
+ );
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({ agentType: 'pi', command: 'pi' });
+ const run = ctr.sendPrompt({ operationId: 'op-pi', prompt: 'work', sessionId });
+ await vi.waitFor(() => expect(piRpcSessionRunMock).toHaveBeenCalled());
+ piRpcSessionAbortMock.mockRejectedValue(new Error('still alive after SIGKILL'));
+
+ await expect(ctr[method]({ sessionId })).rejects.toThrow('still alive after SIGKILL');
+
+ finishRun({ aborted: true });
+ await run;
+ },
+ );
+
+ it('reuses the pooled process across turns of the same conversation', async () => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([
+ {
+ isDestroyed: () => false,
+ webContents: { send },
+ },
+ ]);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+
+ // Turn 1: no native id yet β†’ spawn a fresh process.
+ const env = { LOBEHUB_AGENT_ID: 'agent-pi', LOBEHUB_TOPIC_ID: 'topic-pi' };
+ const first = await ctr.startSession({
+ agentType: 'pi',
+ command: 'pi',
+ env: { ...env, LOBEHUB_OPERATION_ID: 'op-1' },
+ });
+ await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId: first.sessionId });
+ await ctr.stopSession({ sessionId: first.sessionId });
+
+ // Turn 2: resumes with the native id captured on turn 1 β†’ the pool
+ // returns the SAME PiRpcSession instead of constructing a new one.
+ const second = await ctr.startSession({
+ agentType: 'pi',
+ command: 'pi',
+ env: { ...env, LOBEHUB_OPERATION_ID: 'op-2' },
+ resumeSessionId: 'pi_sess_1',
+ });
+ await ctr.sendPrompt({ operationId: 'op-2', prompt: 'second', sessionId: second.sessionId });
+ await ctr.stopSession({ sessionId: second.sessionId });
+
+ expect(piRpcSessionConstructMock).toHaveBeenCalledTimes(1);
+ expect(piRpcSessionConstructMock.mock.calls[0][0].shellOperationId).toBe('op-1');
+ expect(piRpcSessionRebindMock.mock.calls[0][0].shellOperationId).toBe('op-2');
+ expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', {
+ sessionId: first.sessionId,
+ });
+ expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', {
+ sessionId: second.sessionId,
+ });
+ });
+
+ it.each([
+ {
+ firstOptions: { args: ['--provider', 'anthropic'] },
+ secondOptions: { args: ['--provider', 'openai'] },
+ },
+ {
+ firstOptions: { env: { PI_ACCEPTANCE_CONFIG: 'first' } },
+ secondOptions: { env: { PI_ACCEPTANCE_CONFIG: 'second' } },
+ },
+ {
+ firstOptions: { env: { LOBEHUB_TOPIC_ID: 'topic-1' } },
+ secondOptions: { env: { LOBEHUB_TOPIC_ID: 'topic-2' } },
+ },
+ ])(
+ 'spawns fresh when runtime options change between turns: $secondOptions',
+ async ({ firstOptions, secondOptions }) => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([
+ {
+ isDestroyed: () => false,
+ webContents: { send },
+ },
+ ]);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+
+ // Turn 1 with one runtime configuration.
+ const first = await ctr.startSession({
+ ...firstOptions,
+ agentType: 'pi',
+ command: 'pi',
+ });
+ await ctr.sendPrompt({ operationId: 'op-1', prompt: 'first', sessionId: first.sessionId });
+ await ctr.stopSession({ sessionId: first.sessionId });
+
+ // A changed argument or explicit env value must invalidate the pool hit.
+ const second = await ctr.startSession({
+ ...secondOptions,
+ agentType: 'pi',
+ command: 'pi',
+ resumeSessionId: 'pi_sess_1',
+ });
+ await ctr.sendPrompt({
+ operationId: 'op-2',
+ prompt: 'second',
+ sessionId: second.sessionId,
+ });
+ await ctr.stopSession({ sessionId: second.sessionId });
+
+ expect(piRpcSessionConstructMock).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it('reaps an idle pooled pi process after the grace window', async () => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([
+ {
+ isDestroyed: () => false,
+ webContents: { send },
+ },
+ ]);
+ process.env.LOBE_PI_RPC_IDLE_TIMEOUT_MS = '60';
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({ agentType: 'pi', command: 'pi' });
+ await ctr.sendPrompt({ operationId: 'op-idle', prompt: 'x', sessionId });
+
+ // The process is released to the pool; after the idle window it is
+ // closed (graceful EOF) even though no IPC session references it.
+ await vi.waitFor(() => expect(piRpcSessionCloseMock).toHaveBeenCalled(), { timeout: 2_000 });
+ });
+
+ it('surfaces pi RPC failures as session errors without a json fallback', async () => {
+ const send = vi.fn();
+ mockGetAllWindows.mockReturnValue([
+ {
+ isDestroyed: () => false,
+ webContents: { send },
+ },
+ ]);
+ piRpcSessionRunMock.mockRejectedValue(new Error('pi RPC exited unexpectedly (code 1)'));
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'pi',
+ command: 'pi',
+ });
+
+ await expect(
+ ctr.sendPrompt({ operationId: 'op-pi-err', prompt: 'x', sessionId }),
+ ).rejects.toThrow('pi RPC exited unexpectedly');
+ expect(send).toHaveBeenCalledWith(
+ 'heteroAgentSessionError',
+ expect.objectContaining({ sessionId }),
+ );
+ // No spawn of `pi --mode json` happened β€” pi is RPC-only.
+ expect(spawnCalls).toHaveLength(0);
+ });
+ });
+
describe('pre-launch cancellation for local transports', () => {
beforeEach(() => {
spawnCalls.length = 0;
@@ -4162,6 +4479,14 @@ describe('HeterogeneousAgentCtr', () => {
runMock: traeAcpSessionRunMock,
useCodexAppServer: false,
},
+ {
+ agentType: 'pi',
+ command: 'pi',
+ constructMock: piRpcSessionConstructMock,
+ label: 'Pi RPC',
+ runMock: piRpcSessionRunMock,
+ useCodexAppServer: false,
+ },
] as const)(
'does not start $label when cancelled during transport preparation',
async ({ agentType, command, constructMock, runMock, useCodexAppServer }) => {
@@ -4252,7 +4577,7 @@ describe('HeterogeneousAgentCtr', () => {
const [spawnCall] = spawnCalls;
expect(spawnCall.command).toBe(process.execPath);
expect(spawnCall.args.slice(0, 7)).toEqual([
- '/fake/cli/dist/index.js',
+ path.normalize('/fake/cli/dist/index.js'),
'hetero',
'exec',
'--type',
@@ -4378,7 +4703,7 @@ describe('HeterogeneousAgentCtr', () => {
} as any);
await expect(ctr.spawnLhHeteroExec(params)).resolves.toEqual({
- reason: 'Embedded CLI not found at /fake/cli/dist/index.js',
+ reason: `Embedded CLI not found at ${path.normalize('/fake/cli/dist/index.js')}`,
status: 'rejected',
});
expect(spawnCalls).toHaveLength(0);
@@ -4834,13 +5159,58 @@ describe('HeterogeneousAgentCtr', () => {
const captureRegisteredHandler = (
registerSpy: ReturnType<typeof vi.fn> | ReturnType<typeof vi.spyOn>,
eventName: string,
- ): (() => void) => {
+ ): ((event?: { preventDefault: () => void }) => void) => {
const calls = (registerSpy as any).mock.calls as Array<[string, () => void]>;
const match = calls.findLast(([evt]) => evt === eventName);
if (!match) throw new Error(`no handler registered for "${eventName}"`);
return match[1];
};
+ it('holds quit until both an unpooled Pi run and the pool have closed', async () => {
+ const electron = (await import('electron')) as any;
+ electron.app.on.mockClear();
+ electron.app.quit.mockClear();
+ vi.spyOn(process, 'on').mockImplementation(() => process);
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({ agentType: 'pi', command: 'pi' });
+ const session = (ctr as any).sessions.get(sessionId);
+ let finishActive!: () => void;
+ let finishPool!: () => void;
+ const close = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishActive = resolve;
+ }),
+ );
+ session.piRpcSession = { close };
+ vi.spyOn((ctr as any).piRpcPool, 'closeAll').mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ finishPool = resolve;
+ }),
+ );
+ ctr.afterAppReady();
+ const beforeQuit = captureRegisteredHandler(electron.app.on, 'before-quit');
+ const event = { preventDefault: vi.fn() };
+ beforeQuit(event);
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(close).toHaveBeenCalledOnce();
+ expect(session.cancelledByUs).toBe(true);
+ beforeQuit(event);
+ expect(close).toHaveBeenCalledOnce();
+ finishActive();
+ await Promise.resolve();
+ expect(electron.app.quit).not.toHaveBeenCalled();
+ finishPool();
+ await vi.waitFor(() => expect(electron.app.quit).toHaveBeenCalledOnce());
+ event.preventDefault.mockClear();
+ beforeQuit(event);
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ });
+
it('before-quit closes a running TRAE ACP session', async () => {
const electron = (await import('electron')) as any;
electron.app.on.mockClear();
@@ -4854,7 +5224,7 @@ describe('HeterogeneousAgentCtr', () => {
ctr.afterAppReady();
const beforeQuit = captureRegisteredHandler(electron.app.on, 'before-quit');
- beforeQuit();
+ beforeQuit({ preventDefault: vi.fn() });
expect(traeAcpSessionCloseMock).toHaveBeenCalledOnce();
expect(session.cancelledByUs).toBe(true);
@@ -4875,7 +5245,7 @@ describe('HeterogeneousAgentCtr', () => {
ctr.afterAppReady();
const beforeQuit = captureRegisteredHandler(electron.app.on, 'before-quit');
- beforeQuit();
+ beforeQuit({ preventDefault: vi.fn() });
await expect(access(fileA)).rejects.toThrow();
await expect(access(fileB)).rejects.toThrow();
@@ -4949,7 +5319,7 @@ describe('HeterogeneousAgentCtr', () => {
ctr.afterAppReady();
const beforeQuit = captureRegisteredHandler(electron.app.on, 'before-quit');
- expect(() => beforeQuit()).not.toThrow();
+ expect(() => beforeQuit({ preventDefault: vi.fn() })).not.toThrow();
});
});
});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/pi.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/pi.test.ts
index 45313deb8ad..b9d9aa2fde7 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/pi.test.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/pi.test.ts
@@ -1,28 +1,9 @@
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import { getHeterogeneousAgentDriver } from '../index';
-import type {
- HeterogeneousAgentBuildPlanHelpers,
- HeterogeneousAgentBuildPlanParams,
- PrepareProviderBindingContext,
-} from '../types';
+import type { PrepareProviderBindingContext } from '../types';
import { piDriver, sanitizePiProviderBindingArgs } from './pi';
-const buildAgentInput = vi.fn(async () => ({
- args: ['@/tmp/image.png'],
- stdin: 'raw prompt',
-}));
-const helpers: HeterogeneousAgentBuildPlanHelpers = { buildAgentInput };
-
-const buildParams = (
- overrides: Partial<HeterogeneousAgentBuildPlanParams> = {},
-): HeterogeneousAgentBuildPlanParams => ({
- args: [],
- helpers,
- promptInput: 'raw prompt',
- ...overrides,
-});
-
const bindingContext = (
protocol: PrepareProviderBindingContext['resolution']['protocol'] = 'openai-chat-completions',
): PrepareProviderBindingContext => ({
@@ -112,26 +93,10 @@ describe('piDriver', () => {
expect(content).not.toContain('stale-token');
});
- it('is registered and composes base, resume, configured, and input args in order', async () => {
+ it('is registered but rejects the legacy CLI spawn plan β€” pi is RPC-only', async () => {
expect(getHeterogeneousAgentDriver('pi')).toBe(piDriver);
- const plan = await piDriver.buildSpawnPlan(
- buildParams({ args: ['--provider', 'anthropic'], resumeSessionId: 'pi-session-exact' }),
- );
-
- expect(buildAgentInput).toHaveBeenCalledWith('pi', 'raw prompt');
- expect(plan).toEqual({
- args: [
- '--mode',
- 'json',
- '--session-id',
- 'pi-session-exact',
- '--provider',
- 'anthropic',
- '@/tmp/image.png',
- ],
- stdinPayload: 'raw prompt',
- });
+ await expect(piDriver.buildSpawnPlan({} as any)).rejects.toThrow(/RPC transport only/);
});
it.each([
@@ -184,23 +149,6 @@ describe('piDriver', () => {
});
expect(content).not.toContain('bound-key');
expect(content).not.toContain('argv-secret');
-
- const spawnPlan = await piDriver.buildSpawnPlan(
- buildParams({ args: plan.args, resumeSessionId: 'pi-session-exact' }),
- );
- expect(spawnPlan.args).toEqual([
- '--mode',
- 'json',
- '--session-id',
- 'pi-session-exact',
- '--provider',
- 'lobehub-profile-digest',
- '--model',
- 'vendor/model-test',
- '--thinking',
- 'high',
- '@/tmp/image.png',
- ]);
});
it('uses conservative Pi metadata defaults when server model metadata is unavailable', async () => {
@@ -248,17 +196,13 @@ describe('piDriver', () => {
context.args = ['--', '--provider', 'message-provider'];
const plan = await piDriver.prepareProviderBinding!(context);
- const spawnPlan = await piDriver.buildSpawnPlan(buildParams({ args: plan.args }));
- expect(spawnPlan.args).toEqual([
- '--mode',
- 'json',
+ expect(plan.args).toEqual([
'--provider',
'lobehub-profile-digest',
'--model',
'vendor/model-test',
'--',
- '@/tmp/image.png',
]);
});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/pi.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/pi.ts
index 791f40eadb2..db6054859db 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/pi.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/pi.ts
@@ -1,7 +1,6 @@
import path from 'node:path';
import type { HeterogeneousProviderBindingProtocol } from '@lobechat/heterogeneous-agents';
-import { PI_BASE_ARGS } from '@lobechat/heterogeneous-agents/spawn';
import { formatServerDefaultHeterogeneousModel } from '@lobechat/types';
import type { HeterogeneousAgentBuildPlanParams, HeterogeneousAgentDriver } from '../types';
@@ -59,24 +58,12 @@ const sanitizePiProviderBindingEnv = (source: Record<string, string> | undefined
return env;
};
+/** Pi uses RPC exclusively; the driver still owns managed provider profiles. */
export const piDriver: HeterogeneousAgentDriver = {
- async buildSpawnPlan({
- args,
- helpers,
- promptInput,
- resumeSessionId,
- }: HeterogeneousAgentBuildPlanParams) {
- const inputPlan = await helpers.buildAgentInput('pi', promptInput);
-
- return {
- args: [
- ...PI_BASE_ARGS,
- ...(resumeSessionId ? ['--session-id', resumeSessionId] : []),
- ...args,
- ...inputPlan.args,
- ],
- stdinPayload: inputPlan.stdin,
- };
+ async buildSpawnPlan(_params: HeterogeneousAgentBuildPlanParams) {
+ throw new Error(
+ 'pi runs over the RPC transport only β€” use PiRpcSession / createPiRpcAgentHandle, not the CLI spawn path',
+ );
},
prepareProviderBinding({ args, env, profileDir, resolution }) {
if (!resolution.endpoint) throw new Error('Pi provider binding requires an API endpoint.');
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/piRpcPool.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/piRpcPool.test.ts
new file mode 100644
index 00000000000..51216d980c6
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/piRpcPool.test.ts
@@ -0,0 +1,171 @@
+import type { PiRpcSession } from '@lobechat/heterogeneous-agents/rpc';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { PiRpcPool } from './piRpcPool';
+
+vi.mock('@/utils/logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+
+const createSession = (running = false) => {
+ const close = vi.fn().mockResolvedValue(undefined);
+ const session = {
+ close,
+ isReusable: !running,
+ isRunning: running,
+ } as unknown as PiRpcSession;
+ return { close, session };
+};
+
+describe('PiRpcPool', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('evicts an idle process that died rather than returning it', () => {
+ const pool = new PiRpcPool({ idleTimeoutMs: 100 });
+ const { session, close } = createSession();
+ pool.register('dead', session);
+ Object.defineProperty(session, 'isReusable', { value: false });
+ expect(pool.acquire('dead')).toBeUndefined();
+ expect(close).toHaveBeenCalledOnce();
+ });
+
+ it('awaits in-progress closes and prevents late registration during shutdown', async () => {
+ const pool = new PiRpcPool({ idleTimeoutMs: 100 });
+ const { session, close } = createSession();
+ let finish!: () => void;
+ close.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ pool.register('first', session);
+ pool.remove(session);
+ const finished = vi.fn();
+ const shutdown = pool.closeAll();
+ void Promise.resolve(shutdown).then(finished);
+ await Promise.resolve();
+ expect(finished).not.toHaveBeenCalled();
+ const late = createSession();
+ pool.register('late', late.session);
+ expect(late.close).toHaveBeenCalledOnce();
+ expect(pool.acquire('late')).toBeUndefined();
+ finish();
+ await shutdown;
+ expect(finished).toHaveBeenCalledOnce();
+ });
+
+ it('acquires the idle pooled process for the same key and never mixes keys', () => {
+ const pool = new PiRpcPool({ idleTimeoutMs: 60_000 });
+ const { session: a1 } = createSession();
+ const { session: b1 } = createSession();
+
+ pool.register('cwd::sess-a', a1);
+ pool.register('cwd::sess-b', b1);
+
+ // Topic A's second turn reuses A's process, topic B's reuses B's.
+ expect(pool.acquire('cwd::sess-a')).toBe(a1);
+ expect(pool.acquire('cwd::sess-b')).toBe(b1);
+ // A never-visited key spawns fresh (undefined).
+ expect(pool.acquire('cwd::sess-c')).toBeUndefined();
+ });
+
+ it('never reuses a process spawned under different runtime options', () => {
+ const pool = new PiRpcPool({ idleTimeoutMs: 60_000 });
+ const { session: a1 } = createSession();
+ pool.register('cwd::sess-a', a1, 'fingerprint-v1');
+
+ // Same key + same fingerprint β†’ reuse.
+ expect(pool.acquire('cwd::sess-a', 'fingerprint-v1')).toBe(a1);
+ // Same key, different runtime options β†’ spawn fresh (undefined).
+ expect(pool.acquire('cwd::sess-a', 'fingerprint-v2')).toBeUndefined();
+ });
+
+ it('rejects acquisition of a busy process rather than allowing a second writer', () => {
+ const pool = new PiRpcPool({ idleTimeoutMs: 60_000 });
+ const { session, close } = createSession();
+ pool.register('cwd::sess-a', session);
+
+ // Registered while idle, then acquired for an active follow-up turn.
+ pool.acquire('cwd::sess-a');
+ Object.defineProperty(session, 'isRunning', { value: true });
+ expect(() => pool.acquire('cwd::sess-a')).toThrow('active run');
+ expect(close).not.toHaveBeenCalled();
+ });
+
+ it('reaps exactly the idle key β€” other keys are untouched', () => {
+ const reaped: string[] = [];
+ const pool = new PiRpcPool({ idleTimeoutMs: 100, onReap: (key) => void reaped.push(key) });
+ const { close: closeA, session: a1 } = createSession();
+ const { session: b1 } = createSession();
+
+ pool.register('cwd::sess-a', a1);
+ pool.register('cwd::sess-b', b1);
+ pool.release(a1);
+
+ vi.advanceTimersByTime(150);
+ expect(closeA).toHaveBeenCalledTimes(1);
+ expect(reaped).toEqual(['cwd::sess-a']);
+ // B is still alive and reusable.
+ expect(pool.acquire('cwd::sess-b')).toBe(b1);
+ expect(pool.acquire('cwd::sess-a')).toBeUndefined();
+ });
+
+ it('remove() closes a fresh session that never reached the pool', () => {
+ const pool = new PiRpcPool({ idleTimeoutMs: 60_000 });
+ const { close: closeA, session: a1 } = createSession();
+
+ // Failed before register() β€” remove must still tear the process down.
+ pool.remove(a1);
+ expect(closeA).toHaveBeenCalledTimes(1);
+ });
+
+ it('remove() closes only the failed session, not its siblings', () => {
+ const pool = new PiRpcPool({ idleTimeoutMs: 60_000 });
+ const { close: closeA, session: a1 } = createSession();
+ const { close: closeB, session: b1 } = createSession();
+
+ pool.register('cwd::sess-a', a1);
+ pool.register('cwd::sess-b', b1);
+ pool.release(a1);
+ pool.release(b1);
+
+ pool.remove(a1);
+ expect(closeA).toHaveBeenCalledTimes(1);
+ expect(closeB).not.toHaveBeenCalled();
+ expect(pool.acquire('cwd::sess-b')).toBe(b1);
+ });
+
+ it('acquire clears the idle timer so an active reuse is not reaped', () => {
+ const pool = new PiRpcPool({ idleTimeoutMs: 100 });
+ const { session: a1 } = createSession();
+
+ pool.register('cwd::sess-a', a1);
+ pool.release(a1);
+ // Reuse before the window elapses.
+ const reused = pool.acquire('cwd::sess-a');
+ vi.advanceTimersByTime(500);
+ expect(reused).toBe(a1);
+ // No close happened despite the original timer elapsing (it was cleared).
+ expect(pool.acquire('cwd::sess-a')).toBe(a1);
+ });
+
+ it('closeAll shuts down every pooled process', async () => {
+ const pool = new PiRpcPool({ idleTimeoutMs: 60_000 });
+ const { close: closeA, session: a1 } = createSession();
+ const { close: closeB, session: b1 } = createSession();
+
+ pool.register('cwd::sess-a', a1);
+ pool.register('cwd::sess-b', b1);
+ await pool.closeAll();
+
+ expect(closeA).toHaveBeenCalledTimes(1);
+ expect(closeB).toHaveBeenCalledTimes(1);
+ expect(pool.acquire('cwd::sess-a')).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/piRpcPool.ts b/apps/desktop/src/main/modules/heterogeneousAgent/piRpcPool.ts
new file mode 100644
index 00000000000..fc27eefad9b
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/piRpcPool.ts
@@ -0,0 +1,148 @@
+import type { PiRpcSession } from '@lobechat/heterogeneous-agents/rpc';
+
+import { createLogger } from '@/utils/logger';
+
+const logger = createLogger('PiRpcPool');
+
+/**
+ * Cross-turn process pool for pi RPC runs.
+ *
+ * The renderer creates a fresh Electron IPC session per run, so a pi process
+ * cannot be tied to one IPC session's lifetime. This pool keeps one
+ * `pi --mode rpc` process alive across runs of the same conversation (keyed
+ * by `cwd::nativeSessionId`) and reaps idle processes after a grace period β€”
+ * the Codex app-server model applied to pi's single-session processes.
+ *
+ * Lifecycle:
+ * acquire(key) β†’ reused idle process, or undefined (caller spawns)
+ * register(key, s) β†’ hand a freshly spawned process to the pool
+ * release(s) β†’ run settled; arm the idle reaper
+ * remove(s) β†’ run failed; close and drop
+ * closeAll() β†’ before-quit
+ *
+ * Callers must await cancellation of the previous run before acquiring again.
+ * A busy entry is an error, never a cache miss that permits a second writer.
+ */
+export class PiRpcPool {
+ private readonly entries = new Map<string, PiRpcPoolEntry>();
+ private readonly bySession = new Map<PiRpcSession, PiRpcPoolEntry>();
+ private readonly closing = new Set<Promise<void>>();
+ private shuttingDown = false;
+
+ constructor(
+ private readonly options: {
+ /** Idle grace before a pooled process is closed (EOF-first). */
+ idleTimeoutMs: number;
+ /** Observability hook, e.g. logging reaps. */
+ onReap?: (key: string, reason: 'idle' | 'replaced' | 'removed' | 'shutdown') => void;
+ },
+ ) {}
+
+ /** Reuse an idle pooled process for `key`, or `undefined` to spawn fresh. */
+ acquire(key: string, spawnFingerprint?: string): PiRpcSession | undefined {
+ const entry = this.entries.get(key);
+ // A process spawned under different runtime options (command path, args,
+ // env) must not be reused β€” mirrors Codex app-server's canReuseFor.
+ if (!entry) return undefined;
+ if (entry.session.isRunning) throw new Error('Pi session still has an active run');
+ if (!entry.session.isReusable) {
+ this.reap(entry, 'removed');
+ return undefined;
+ }
+ if (spawnFingerprint !== undefined && entry.spawnFingerprint !== spawnFingerprint) {
+ return undefined;
+ }
+
+ if (entry.idleTimer) {
+ clearTimeout(entry.idleTimer);
+ entry.idleTimer = undefined;
+ }
+ entry.lastUsedAt = Date.now();
+ return entry.session;
+ }
+
+ /** Hand a freshly spawned process to the pool under `key`. */
+ register(key: string, session: PiRpcSession, spawnFingerprint?: string): void {
+ if (this.shuttingDown || !session.isReusable) {
+ this.closeSession(session);
+ return;
+ }
+ const existing = this.entries.get(key);
+ if (existing && existing.session !== session) {
+ // A replacement under the same key only happens after the previous
+ // process was reaped (idle), failed, or was spawned under different
+ // runtime options (spawnFingerprint mismatch). Runs of one conversation
+ // are strictly serial on a single device, so the old process is never
+ // busy here; reap it unconditionally for consistency.
+ this.reap(existing, 'replaced');
+ }
+ const entry: PiRpcPoolEntry = { key, lastUsedAt: Date.now(), session, spawnFingerprint };
+ this.entries.set(key, entry);
+ this.bySession.set(session, entry);
+ }
+
+ /** The run settled β€” arm the idle reaper for this process. */
+ release(session: PiRpcSession): void {
+ const entry = this.bySession.get(session);
+ if (!entry) return;
+ if (!session.isReusable) {
+ this.reap(entry, 'removed');
+ return;
+ }
+ entry.lastUsedAt = Date.now();
+ if (entry.idleTimer) clearTimeout(entry.idleTimer);
+ entry.idleTimer = setTimeout(() => this.reap(entry, 'idle'), this.options.idleTimeoutMs);
+ entry.idleTimer.unref?.();
+ }
+
+ /** The run failed β€” close the process and drop it. */
+ remove(session: PiRpcSession): void {
+ const entry = this.bySession.get(session);
+ if (!entry) {
+ // Never registered β€” a fresh process that failed before the success
+ // handoff. Close it directly or the pi child would outlive the run.
+ this.closeSession(session);
+ return;
+ }
+ this.reap(entry, 'removed');
+ }
+
+ /** Close every pooled process (before-quit). */
+ async closeAll(): Promise<void> {
+ this.shuttingDown = true;
+ for (const entry of this.entries.values()) this.reap(entry, 'shutdown');
+ while (this.closing.size > 0) await Promise.all(this.closing);
+ }
+
+ private reap(entry: PiRpcPoolEntry, reason: 'idle' | 'replaced' | 'removed' | 'shutdown'): void {
+ if (entry.idleTimer) {
+ clearTimeout(entry.idleTimer);
+ entry.idleTimer = undefined;
+ }
+ if (this.entries.get(entry.key) === entry) this.entries.delete(entry.key);
+ if (this.bySession.get(entry.session) === entry) this.bySession.delete(entry.session);
+ this.options.onReap?.(entry.key, reason);
+ this.closeSession(entry.session);
+ }
+
+ private closeSession(session: PiRpcSession): void {
+ const closing = session
+ .close()
+ .catch((error) => {
+ logger.warn('Failed to close Pi RPC process:', error);
+ })
+ .finally(() => {
+ this.closing.delete(closing);
+ });
+ this.closing.add(closing);
+ }
+}
+
+interface PiRpcPoolEntry {
+ idleTimer?: ReturnType<typeof setTimeout>;
+ key: string;
+ lastUsedAt: number;
+ session: PiRpcSession;
+ /** Runtime options the process was spawned with (command path, args, env). */
+ spawnFingerprint?: string;
+}
diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.json
index 6864206de73..2532166b47f 100644
--- a/packages/heterogeneous-agents/package.json
+++ b/packages/heterogeneous-agents/package.json
@@ -13,6 +13,7 @@
"./quota": "./src/quota/index.ts",
"./quota-sampler": "./src/quota-sampler/index.ts",
"./resolveCliCommand": "./src/spawn/resolveCliCommand.ts",
+ "./rpc": "./src/rpc/index.ts",
"./scanHost": "./src/scan/scanHost.ts",
"./spawn": "./src/spawn/index.ts",
"./transcript": "./src/transcript/index.ts",
diff --git a/packages/heterogeneous-agents/src/rpc/index.ts b/packages/heterogeneous-agents/src/rpc/index.ts
new file mode 100644
index 00000000000..a1c95a1aaa7
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/index.ts
@@ -0,0 +1,41 @@
+/**
+ * Pi RPC transport β€” `pi --mode rpc` JSONL client + per-run session wrapper.
+ *
+ * Replaces the legacy one-shot `--mode json` spawn for the desktop pi path:
+ * a long-lived bidirectional process with command/response correlation, the
+ * extension UI sub-protocol, and graceful EOF-based shutdown.
+ */
+export {
+ createPiRpcAgentHandle,
+ type PiRpcAgentHandle,
+ type PiRpcAgentHandleOptions,
+ type PiRpcStartupControl,
+ toPiRpcPrompt,
+} from './piRpcAgentHandle';
+export { PiRpcClient, PiRpcConnectionError, PiRpcResponseError } from './piRpcClient';
+export {
+ PI_RPC_DEFAULT_REQUEST_TIMEOUT_MS,
+ PI_RPC_HANDSHAKE_TIMEOUT_MS,
+ PI_RPC_MIN_CLI_VERSION,
+ type PiAgentSettledEvent,
+ type PiExtensionUiDialogMethod,
+ type PiExtensionUiFireAndForgetMethod,
+ type PiExtensionUiRequest,
+ type PiExtensionUiResponse,
+ type PiMessageEndEvent,
+ type PiMessageUpdateEvent,
+ type PiRpcCommand,
+ type PiRpcEvent,
+ type PiRpcImage,
+ type PiRpcResponse,
+ type PiRpcStateData,
+ type PiSessionEvent,
+ type PiStreamingBehavior,
+} from './piRpcProtocol';
+export {
+ type PiRpcPromptInput,
+ PiRpcSession,
+ type PiRpcSessionCallbacks,
+ type PiRpcSessionOptions,
+} from './piRpcSession';
+export { RpcStdioClient, RpcStdioConnectionError } from './rpcStdioClient';
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcAgentHandle.test.ts b/packages/heterogeneous-agents/src/rpc/piRpcAgentHandle.test.ts
new file mode 100644
index 00000000000..fa8eac0e713
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/piRpcAgentHandle.test.ts
@@ -0,0 +1,238 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createPiRpcAgentHandle, toPiRpcPrompt } from './piRpcAgentHandle';
+import type { PiRpcEvent } from './piRpcProtocol';
+
+const mocks = vi.hoisted(() => ({
+ clientInstances: [] as any[],
+ command: vi.fn(),
+ start: vi.fn(),
+ close: vi.fn(),
+ abort: vi.fn(),
+}));
+
+vi.mock('./piRpcClient', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return {
+ ...actual,
+ PiRpcClient: class MockPiRpcClient {
+ static instances = mocks.clientInstances;
+ onEvent?: (event: PiRpcEvent) => void | Promise<void>;
+ constructor(readonly options: any) {
+ this.onEvent = options.onEvent;
+ mocks.clientInstances.push(this);
+ }
+ get pid() {
+ return 123_456;
+ }
+ get isReady() {
+ return true;
+ }
+ get sessionId() {
+ return undefined;
+ }
+ start = mocks.start;
+ command = mocks.command;
+ close = mocks.close;
+ abort = mocks.abort;
+ setOperationContext = async () => {};
+ clearOperationContext = async () => {};
+ },
+ };
+});
+
+const emit = (event: PiRpcEvent) => {
+ const client = mocks.clientInstances.at(-1)!;
+ return client.onEvent!(event);
+};
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ mocks.clientInstances.length = 0;
+ mocks.start.mockReset();
+ mocks.command.mockReset();
+ mocks.close.mockReset();
+ mocks.abort.mockReset();
+});
+
+describe('toPiRpcPrompt', () => {
+ it('rejects unreadable attachments instead of silently sending an incomplete prompt', async () => {
+ await expect(
+ toPiRpcPrompt([
+ { type: 'text', text: 'describe this' },
+ { type: 'image', source: { type: 'path', path: '/nonexistent-pi-test-image.png' } },
+ ]),
+ ).rejects.toThrow();
+ });
+
+ it('joins text blocks and leaves image-less prompts image-free', async () => {
+ await expect(toPiRpcPrompt('hello')).resolves.toEqual({ text: 'hello' });
+ await expect(
+ toPiRpcPrompt([
+ { text: 'one', type: 'text' },
+ { text: 'two', type: 'text' },
+ ]),
+ ).resolves.toEqual({ text: 'one\n\ntwo' });
+ });
+});
+
+describe('createPiRpcAgentHandle', () => {
+ it('preserves prompt failure diagnostics in stderr and exits nonzero', async () => {
+ mocks.start.mockResolvedValue(undefined);
+ mocks.close.mockResolvedValue(undefined);
+ mocks.command.mockRejectedValue(new Error('prompt rejected: invalid model'));
+ const handle = await createPiRpcAgentHandle({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ operationId: 'op-error',
+ prompt: { text: 'x' },
+ });
+ let stderr = '';
+ handle.stderr.on('data', (data) => {
+ stderr += data;
+ });
+ await expect(handle.exit).resolves.toEqual({ code: 1, signal: null });
+ expect(stderr).toContain('prompt rejected: invalid model');
+ expect(mocks.close).toHaveBeenCalled();
+ });
+
+ it('streams adapted events, resolves exit on settle, and reports the native session id', async () => {
+ mocks.start.mockResolvedValue(undefined);
+ mocks.command.mockImplementation((command: { type: string }) => {
+ if (command.type === 'get_state') {
+ return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
+ }
+ return Promise.resolve({ success: true, type: 'response', command: command.type });
+ });
+ mocks.close.mockResolvedValue(undefined);
+
+ const handle = await createPiRpcAgentHandle({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ operationId: 'op-cli',
+ prompt: { text: 'inspect the repo' },
+ });
+
+ const collected: string[] = [];
+ const consume = (async () => {
+ for await (const event of handle.events) {
+ if (event.type === 'stream_chunk' && event.data.chunkType === 'text') {
+ collected.push(event.data.content);
+ }
+ }
+ })();
+
+ await emit({ type: 'session', id: 'native-1' });
+ await emit({
+ assistantMessageEvent: { contentIndex: 0, delta: 'Hi', type: 'text_delta' },
+ type: 'message_update',
+ });
+ await emit({ type: 'agent_settled' });
+
+ await consume;
+ await expect(handle.exit).resolves.toEqual({ code: 0, signal: null });
+ expect(collected.join('')).toBe('Hi');
+ expect(handle.sessionId).toBe('native-1');
+ });
+
+ it('rejects on spawn/handshake failure so the CLI can classify it', async () => {
+ mocks.start.mockRejectedValue(new Error('pi did not answer the RPC handshake'));
+ await expect(
+ createPiRpcAgentHandle({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ operationId: 'op-cli',
+ prompt: { text: 'x' },
+ }),
+ ).rejects.toThrow(/handshake/);
+ });
+
+ it('exposes startup cancellation before awaiting the handshake and closes instead of aborting', async () => {
+ let rejectStart: ((error: Error) => void) | undefined;
+ mocks.start.mockReturnValue(
+ new Promise<void>((_resolve, reject) => {
+ rejectStart = reject;
+ }),
+ );
+ mocks.close.mockResolvedValue(undefined);
+ let control: { cancel: (signal: NodeJS.Signals) => Promise<void> } | undefined;
+
+ const creating = createPiRpcAgentHandle({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onStartupControl: (value) => {
+ control = value;
+ },
+ operationId: 'op-startup-cancel',
+ prompt: { text: 'x' },
+ });
+
+ expect(control).toBeDefined();
+ await control!.cancel('SIGINT');
+ expect(mocks.close).toHaveBeenCalledOnce();
+ expect(mocks.abort).not.toHaveBeenCalled();
+ rejectStart!(new Error('Pi RPC session is closed'));
+ await expect(creating).rejects.toThrow('closed');
+ });
+
+ it('forces startup shutdown on SIGKILL and installs raw stdout before start', async () => {
+ mocks.start.mockResolvedValue(undefined);
+ mocks.close.mockResolvedValue(undefined);
+ mocks.command.mockResolvedValue({ success: true, type: 'response' });
+ const onRawStdout = vi.fn();
+ let control: { cancel: (signal: NodeJS.Signals) => Promise<void> } | undefined;
+
+ const creating = createPiRpcAgentHandle({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onRawStdout,
+ onStartupControl: (value) => {
+ control = value;
+ },
+ operationId: 'op-force',
+ prompt: { text: 'x' },
+ });
+ // Session construction (and therefore raw tee installation) happened
+ // before startup control became observable and before the eager await.
+ expect(mocks.clientInstances).toHaveLength(1);
+ await control!.cancel('SIGKILL');
+ // PiRpcSession owns propagation of `{ force: true }` to the transport.
+ expect(mocks.close).toHaveBeenCalledOnce();
+ await expect(creating).rejects.toThrow('closed');
+ });
+
+ it('maps kill(SIGINT) to a graceful abort', async () => {
+ mocks.start.mockResolvedValue(undefined);
+ mocks.command.mockImplementation((command: { type: string }) => {
+ if (command.type === 'get_state') {
+ return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
+ }
+ return Promise.resolve({ success: true, type: 'response', command: command.type });
+ });
+ mocks.close.mockResolvedValue(undefined);
+
+ const handle = await createPiRpcAgentHandle({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ operationId: 'op-cli',
+ prompt: { text: 'x' },
+ });
+
+ handle.kill('SIGINT');
+ expect(mocks.abort).toHaveBeenCalled();
+ await emit({ type: 'agent_settled' });
+ await handle.exit;
+ });
+});
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcAgentHandle.ts b/packages/heterogeneous-agents/src/rpc/piRpcAgentHandle.ts
new file mode 100644
index 00000000000..8fe4fb8a10e
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/piRpcAgentHandle.ts
@@ -0,0 +1,204 @@
+import { PassThrough } from 'node:stream';
+
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+
+import type { AgentPromptInput } from '../protocol';
+import type { UploadHeterogeneousImage } from '../spawn/agentStreamPipeline';
+import { normalizeImage } from '../spawn/input/normalizeImage';
+import type { PiRpcImage } from './piRpcProtocol';
+import { PiRpcSession } from './piRpcSession';
+
+/** Options mirroring the `spawnAgent` shape the CLI passes for one agent run. */
+export interface PiRpcAgentHandleOptions {
+ args: string[];
+ commandPath: string;
+ cwd: string;
+ detached?: boolean;
+ env: NodeJS.ProcessEnv;
+ /** Raw RPC stdout tee, installed before the process is spawned. */
+ onRawStdout?: (chunk: Buffer) => void;
+ /** Exposes cancellation synchronously, before the eager startup await. */
+ onStartupControl?: (control: PiRpcStartupControl) => void;
+ operationId: string;
+ /** Text + base64 images for the RPC `prompt` command. */
+ prompt: { text: string; images?: PiRpcImage[] };
+ resumeSessionId?: string;
+ uploadImage?: UploadHeterogeneousImage;
+}
+
+export interface PiRpcStartupControl {
+ cancel: (signal: NodeJS.Signals) => Promise<void>;
+}
+
+/**
+ * Result shaped like `spawnAgent`'s `SpawnAgentHandle` so the `lh hetero exec`
+ * CLI can route pi runs through the RPC transport without changing its event
+ * loop, signal handling, or finish/classification plumbing.
+ */
+export interface PiRpcAgentHandle {
+ events: AsyncIterable<AgentStreamEvent>;
+ exit: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
+ kill: (signal?: NodeJS.Signals) => void;
+ pid: number | undefined;
+ readonly sessionId: string | undefined;
+ stderr: NodeJS.ReadableStream;
+}
+
+interface EventQueue {
+ [Symbol.asyncIterator]: () => AsyncIterator<AgentStreamEvent>;
+ close: () => void;
+ push: (batch: AgentStreamEvent[]) => void;
+}
+
+/** Buffered async iterator with a close signal β€” bridges push to pull. */
+const createEventQueue = (): EventQueue => {
+ const items: AgentStreamEvent[] = [];
+ const waiters: Array<() => void> = [];
+ let closed = false;
+
+ const notify = () => {
+ for (const waiter of waiters.splice(0)) waiter();
+ };
+
+ return {
+ push(batch) {
+ items.push(...batch);
+ notify();
+ },
+ close() {
+ closed = true;
+ notify();
+ },
+ async *[Symbol.asyncIterator]() {
+ while (true) {
+ while (items.length > 0) {
+ yield items.shift()!;
+ }
+ if (closed) return;
+ await new Promise<void>((resolve) => waiters.push(resolve));
+ }
+ },
+ };
+};
+
+/**
+ * Convert `AgentPromptInput` (string | text/image blocks) into the RPC prompt
+ * payload: text blocks joined, image blocks normalized to base64 (URL fetch /
+ * path read / base64 passthrough, cached under the agent cache dir).
+ */
+export const toPiRpcPrompt = async (
+ input: AgentPromptInput,
+ options: { cacheDir?: string } = {},
+): Promise<{ images?: PiRpcImage[]; text: string }> => {
+ const blocks = typeof input === 'string' ? [{ text: input, type: 'text' as const }] : input;
+ const text: string[] = [];
+ const images: PiRpcImage[] = [];
+
+ for (const block of blocks) {
+ if (block.type === 'text') {
+ if (block.text) text.push(block.text);
+ continue;
+ }
+ const image = await normalizeImage(block.source, options);
+ images.push({
+ data: image.buffer.toString('base64'),
+ mimeType: image.mediaType,
+ type: 'image',
+ });
+ }
+
+ return {
+ ...(images.length > 0 ? { images } : {}),
+ text: text.join('\n\n'),
+ };
+};
+
+/**
+ * Spawn one pi run over the RPC transport and expose it as a `spawnAgent`
+ *-shaped handle. Eagerly starts the process + handshake (rejects on
+ * spawn/handshake failure β€” the CLI surfaces it via its existing catch), then
+ * runs the prompt. `kill('SIGINT')` maps to a graceful `abort`; other signals
+ * escalate through the EOF-first shutdown.
+ */
+export const createPiRpcAgentHandle = async (
+ options: PiRpcAgentHandleOptions,
+): Promise<PiRpcAgentHandle> => {
+ const queue = createEventQueue();
+ const stderr = new PassThrough();
+ let nativeSessionId: string | undefined;
+ let runStarted = false;
+ let cancelledSignal: NodeJS.Signals | undefined;
+
+ const sessionOptions = {
+ args: options.args,
+ commandPath: options.commandPath,
+ cwd: options.cwd,
+ detached: options.detached,
+ env: options.env,
+ operationId: options.operationId,
+ resumeSessionId: options.resumeSessionId,
+ sessionId: options.operationId,
+ uploadImage: options.uploadImage,
+ onEvents: (events: AgentStreamEvent[]) => queue.push(events),
+ onRawStdout: options.onRawStdout,
+ onRuntimeStatus: () => {
+ /* no-op β€” the CLI surfaces state via events */
+ },
+ onSessionId: (id: string) => {
+ nativeSessionId = id;
+ },
+ onStderr: (data: string) => {
+ stderr.write(data);
+ },
+ };
+ const session = new PiRpcSession(sessionOptions);
+
+ const cancel = async (signal: NodeJS.Signals) => {
+ cancelledSignal = signal;
+ if (signal === 'SIGKILL') {
+ await session.close({ force: true });
+ } else if (signal === 'SIGTERM' || !runStarted) {
+ await session.close();
+ } else {
+ await session.abort();
+ }
+ };
+ options.onStartupControl?.({ cancel });
+
+ // Eager spawn + handshake: a missing/broken pi install rejects here so the
+ // CLI's existing spawn-failure classification runs.
+ await session.start();
+
+ runStarted = true;
+ const exit = session
+ .run(options.prompt)
+ .then(() => {
+ queue.close();
+ stderr.end();
+ return cancelledSignal
+ ? { code: null, signal: cancelledSignal }
+ : { code: 0, signal: null as NodeJS.Signals | null };
+ })
+ .catch((error) => {
+ queue.close();
+ stderr.end(`${error instanceof Error ? error.message : String(error)}\n`);
+ return cancelledSignal
+ ? { code: null, signal: cancelledSignal }
+ : { code: 1, signal: null as NodeJS.Signals | null };
+ });
+
+ return {
+ events: queue,
+ exit,
+ kill: (signal) => {
+ void cancel(signal ?? 'SIGINT').catch(() => {
+ /* legacy synchronous handle contract is best-effort */
+ });
+ },
+ pid: session.pid,
+ get sessionId() {
+ return nativeSessionId;
+ },
+ stderr,
+ };
+};
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcClient.test.ts b/packages/heterogeneous-agents/src/rpc/piRpcClient.test.ts
new file mode 100644
index 00000000000..80538c31a05
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/piRpcClient.test.ts
@@ -0,0 +1,366 @@
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { PiRpcClient, PiRpcConnectionError, PiRpcResponseError } from './piRpcClient';
+import type { PiRpcEvent } from './piRpcProtocol';
+
+const { execFileMock, spawnMock } = vi.hoisted(() => ({
+ execFileMock: vi.fn(),
+ spawnMock: vi.fn(),
+}));
+
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return {
+ ...actual,
+ execFile: (...args: unknown[]) => {
+ const probe = execFileMock(...args);
+ if (probe) return probe;
+ const exited = new EventEmitter();
+ queueMicrotask(() => exited.emit('close', 0, null));
+ return exited;
+ },
+ spawn: spawnMock,
+ };
+});
+
+const originalPlatform = process.platform;
+
+const createProcess = () => {
+ const child = new EventEmitter() as any;
+ const stdout = new PassThrough();
+ const writes: Array<Record<string, unknown>> = [];
+ child.pid = 123_456;
+ child.killed = false;
+ child.exitCode = null;
+ child.signalCode = null;
+ child.kill = vi.fn(() => true);
+ child.stdout = stdout;
+ child.stderr = new PassThrough();
+ child.stdin = {
+ once: vi.fn(),
+ end: vi.fn(() => {
+ // Simulate pi exiting cleanly on EOF.
+ setTimeout(() => child.emit('close', 0, null), 1);
+ }),
+ write: vi.fn((chunk: string) => {
+ writes.push(JSON.parse(chunk.trim()));
+ return true;
+ }),
+ };
+ return { child, stdout, writes };
+};
+
+/** Fixture: an RPC process that answers the startup `get_state` handshake. */
+const createReadyClient = async (
+ options: Partial<ConstructorParameters<typeof PiRpcClient>[0]> = {},
+) => {
+ const { child, stdout, writes } = createProcess();
+ spawnMock.mockReturnValue(child);
+ const events: unknown[] = [];
+ const client = new PiRpcClient({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onEvent: (event: PiRpcEvent) => void events.push(event),
+ onStderr: vi.fn(),
+ ...options,
+ } as any);
+ const started = client.start();
+ // Answer the handshake as soon as get_state is written.
+ await vi.waitFor(() => {
+ const getState = writes.find((w) => w.type === 'get_state');
+ expect(getState).toBeTruthy();
+ });
+ const getState = writes.find((w) => w.type === 'get_state')!;
+ stdout.write(
+ `${JSON.stringify({ command: 'get_state', data: { sessionId: 'sess-1' }, id: getState.id, success: true, type: 'response' })}\n`,
+ );
+ await started;
+ return { child, client, events, stdout, writes };
+};
+
+beforeEach(() => {
+ execFileMock.mockImplementation((_command, _args, _options, callback) => {
+ callback(null, '0.80.5\n', '');
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ execFileMock.mockReset();
+ spawnMock.mockReset();
+ Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform });
+});
+
+describe('PiRpcClient', () => {
+ it('does not probe or spawn when cancelled before startup', async () => {
+ const client = new PiRpcClient({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onEvent: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ await client.close();
+ await expect(client.start()).rejects.toThrow('closed by host');
+ expect(execFileMock).not.toHaveBeenCalled();
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it('waits for a cancelled version probe to actually close and never starts RPC', async () => {
+ const probe = Object.assign(new EventEmitter(), { pid: 1234 });
+ execFileMock.mockImplementation((_command, _args, options, callback) => {
+ options.signal.addEventListener('abort', () => callback(new Error('aborted'), '', ''));
+ return probe;
+ });
+ const client = new PiRpcClient({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onEvent: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ const start = client.start().catch((error) => error);
+ await vi.waitFor(() => expect(execFileMock).toHaveBeenCalled());
+ const confirmed = vi.fn();
+ const close = client.close().then(confirmed);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(confirmed).not.toHaveBeenCalled();
+ probe.emit('close', null, 'SIGKILL');
+ await close;
+ expect(await start).toBeInstanceOf(PiRpcConnectionError);
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it('captures the raw handshake before the ready client is returned', async () => {
+ const raw: Buffer[] = [];
+ const { client } = await createReadyClient({ onRawStdout: (chunk) => raw.push(chunk) });
+ expect(JSON.parse(Buffer.concat(raw).toString()).command).toBe('get_state');
+ await client.close();
+ });
+
+ it('bounds abort even when ordinary command timeouts are disabled', async () => {
+ const { client } = await createReadyClient({ requestTimeoutMs: false });
+ vi.useFakeTimers();
+ const rejected = vi.fn();
+ const request = client.abort().catch(rejected);
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(rejected).toHaveBeenCalledWith(expect.any(PiRpcConnectionError));
+ const closed = client.close();
+ await vi.advanceTimersByTimeAsync(1);
+ await Promise.all([request, closed]);
+ });
+
+ it.each([false, true])('preserves detached=%s through the Pi transport', async (detached) => {
+ Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' });
+ const { child, client } = await createReadyClient({ detached, closeGraceMs: 1 });
+ expect(spawnMock.mock.calls[0][2].detached).toBe(detached);
+ child.stdin.end.mockImplementation(() => {});
+ const groupKill = vi.spyOn(process, 'kill').mockImplementation(() => {
+ child.emit('close', null, 'SIGTERM');
+ return true;
+ });
+ child.kill.mockImplementation(() => {
+ child.emit('close', null, 'SIGTERM');
+ return true;
+ });
+ await client.close();
+ if (detached) expect(groupKill).toHaveBeenCalledWith(-child.pid, 'SIGTERM');
+ else {
+ expect(groupKill).not.toHaveBeenCalled();
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ }
+ });
+
+ it.each(['0.79.0', '0.80.4', '0.80.5-rc.1', 'unknown'])(
+ 'rejects unsupported Pi %s before spawning RPC',
+ async (version) => {
+ execFileMock.mockImplementation((_command, _args, _options, callback) =>
+ callback(null, version, ''),
+ );
+ const client = new PiRpcClient({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onEvent: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ await expect(client.start()).rejects.toThrow(/0\.80\.5.*upgrade/i);
+ expect(spawnMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['0.80.5', 'v0.81.0', '1.0.0', '0.80.5+build.1'])(
+ 'accepts supported Pi %s using the spawn environment',
+ async (version) => {
+ execFileMock.mockImplementation((_command, _args, _options, callback) =>
+ callback(null, version, ''),
+ );
+ const { client } = await createReadyClient({
+ env: { ...process.env, PATH: '/custom', HOME: '/test-home' },
+ });
+ expect(execFileMock).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.arrayContaining(['--version']),
+ expect.objectContaining({
+ cwd: '/workspace',
+ env: expect.objectContaining({ PATH: '/custom', HOME: '/test-home' }),
+ timeout: 5000,
+ }),
+ expect.any(Function),
+ );
+ await client.start();
+ expect(execFileMock).toHaveBeenCalledTimes(1);
+ await client.close();
+ },
+ );
+
+ it('notifies the session of idle process death and revokes readiness', async () => {
+ const onError = vi.fn();
+ const { child, client } = await createReadyClient({ onError });
+ child.emit('close', 1, null);
+ expect(client.isReady).toBe(false);
+ await vi.waitFor(() => expect(onError).toHaveBeenCalledWith(expect.any(PiRpcConnectionError)));
+ await client.close();
+ });
+
+ it('spawns `pi --mode rpc` with LF-only framing and correlates responses', async () => {
+ const { child, client, stdout, writes } = await createReadyClient();
+
+ const first = client.command<{ value: string }>({ type: 'get_commands' });
+ const second = client.command<{ value: string }>({ type: 'get_available_models' });
+ const firstId = writes.at(-2)!.id;
+ const secondId = writes.at(-1)!.id;
+
+ // Split one line across chunks to prove LF-only framing (no readline).
+ const secondLine = `${JSON.stringify({
+ command: 'get_available_models',
+ data: { value: 'two' },
+ id: secondId,
+ success: true,
+ type: 'response',
+ })}\n`;
+ stdout.write(secondLine.slice(0, 10));
+ stdout.write(secondLine.slice(10));
+ stdout.write(
+ `${JSON.stringify({
+ command: 'get_commands',
+ data: { value: 'one' },
+ id: firstId,
+ success: true,
+ type: 'response',
+ })}\n`,
+ );
+
+ await expect(Promise.all([first, second])).resolves.toEqual([
+ expect.objectContaining({ data: { value: 'one' }, success: true }),
+ expect.objectContaining({ data: { value: 'two' }, success: true }),
+ ]);
+ // The spawned target must be pi: the bare `pi` binary on Unix, or a
+ // resolved node shim (node.exe + script path) on Windows β€” assert on the
+ // command + first argv together so both platforms hold.
+ const [spawnCommand, spawnArgs] = spawnMock.mock.calls[0] as [string, string[]];
+ expect(`${spawnCommand} ${spawnArgs[0] ?? ''}`.toLowerCase()).toContain('pi');
+ expect(spawnArgs).toEqual(expect.arrayContaining(['--mode', 'rpc']));
+ await client.close();
+ expect(child.stdin.end).toHaveBeenCalled();
+ });
+
+ it('exposes the native session id from the get_state handshake (RPC has no session event)', async () => {
+ const { client } = await createReadyClient();
+ expect(client.sessionId).toBe('sess-1');
+ await client.close();
+ });
+
+ it('rejects on `success: false` responses with the command name', async () => {
+ const { client, stdout, writes } = await createReadyClient();
+ const request = client.command({ type: 'set_model', provider: 'x', modelId: 'y' });
+ stdout.write(
+ `${JSON.stringify({
+ command: 'set_model',
+ error: 'Model not found: x/y',
+ id: writes.at(-1)!.id,
+ success: false,
+ type: 'response',
+ })}\n`,
+ );
+ await expect(request).rejects.toThrow(PiRpcResponseError);
+ await expect(request).rejects.toThrow(/set_model.*Model not found/);
+ await client.close();
+ });
+
+ it('answers extension UI dialogs and cancels them without a handler', async () => {
+ const { client, stdout, writes } = await createReadyClient({
+ onExtensionUiRequest: (request) =>
+ request.method === 'select'
+ ? { cancelled: false, id: request.id, value: 'Allow', type: 'extension_ui_response' }
+ : undefined,
+ });
+ stdout.write(
+ `${JSON.stringify({ id: 'ext-1', method: 'select', options: ['Allow', 'Block'], title: 'Allow?', type: 'extension_ui_request' })}\n`,
+ );
+ stdout.write(
+ `${JSON.stringify({ id: 'ext-2', method: 'confirm', message: 'Sure?', title: 'Confirm', type: 'extension_ui_request' })}\n`,
+ );
+ await vi.waitFor(() => {
+ expect(writes.some((w) => w.type === 'extension_ui_response' && w.id === 'ext-1')).toBe(true);
+ expect(
+ writes.some(
+ (w) => w.type === 'extension_ui_response' && w.id === 'ext-2' && w.cancelled === true,
+ ),
+ ).toBe(true);
+ });
+ await client.close();
+ });
+
+ it('rejects commands when the process dies before responding', async () => {
+ const { child, client, stdout } = await createReadyClient();
+ const request = client.command({ type: 'get_messages' });
+ stdout.end();
+ child.emit('close', 1, null);
+ await expect(request).rejects.toThrow(PiRpcConnectionError);
+ await expect(request).rejects.toThrow(/exited unexpectedly/);
+ await client.close();
+ });
+
+ it('hard-fails the handshake when get_state never answers', async () => {
+ const { child } = createProcess();
+ spawnMock.mockReturnValue(child);
+ const client = new PiRpcClient({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ handshakeTimeoutMs: 100,
+ onEvent: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ const started = client.start();
+ await expect(started).rejects.toThrow(PiRpcConnectionError);
+ await expect(started).rejects.toThrow(/handshake/);
+ });
+
+ it('gracefully closes via stdin EOF and escalates only when exit stalls', async () => {
+ Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' });
+ const { child, client } = await createReadyClient({ closeGraceMs: 50 });
+ vi.spyOn(process, 'kill').mockImplementation(() => {
+ setTimeout(() => child.emit('close', null, 'SIGTERM'), 1);
+ return true;
+ });
+ // Override the simulated clean-exit so the process lingers.
+ child.stdin.end = vi.fn(() => {
+ /* no exit */
+ });
+ await client.close();
+ // SIGTERM escalation attempted after the grace window.
+ expect(process.kill).toHaveBeenCalledWith(-child.pid, 'SIGTERM');
+ });
+});
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcClient.ts b/packages/heterogeneous-agents/src/rpc/piRpcClient.ts
new file mode 100644
index 00000000000..4a7ffbd42bd
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/piRpcClient.ts
@@ -0,0 +1,426 @@
+import { execFile } from 'node:child_process';
+
+import { resolveCliSpawnPlan } from '../spawn/cliSpawn';
+import { PiOperationContextUnavailableError, PiRpcOperationContext } from './piRpcOperationContext';
+import {
+ PI_RPC_ABORT_TIMEOUT_MS,
+ PI_RPC_DEFAULT_REQUEST_TIMEOUT_MS,
+ PI_RPC_HANDSHAKE_TIMEOUT_MS,
+ PI_RPC_MIN_CLI_VERSION,
+ type PiExtensionUiRequest,
+ type PiExtensionUiResponse,
+ type PiRpcCommand,
+ type PiRpcEvent,
+ type PiRpcResponse,
+} from './piRpcProtocol';
+import { RpcStdioClient, RpcStdioConnectionError } from './rpcStdioClient';
+
+/** Error thrown when a pi RPC command fails (`success: false` response). */
+export class PiRpcResponseError extends Error {
+ constructor(
+ readonly command: string,
+ readonly rpcError: string,
+ ) {
+ super(`Pi RPC command failed (${command}): ${rpcError}`);
+ this.name = 'PiRpcResponseError';
+ }
+}
+
+/** Error thrown when the pi process dies or the connection breaks. */
+export class PiRpcConnectionError extends Error {
+ constructor(
+ message: string,
+ readonly options?: { phase?: 'spawn' | 'handshake' | 'run'; stderr?: string },
+ ) {
+ super(message);
+ this.name = 'PiRpcConnectionError';
+ }
+}
+
+export interface PiRpcClientOptions {
+ /** Extra CLI args after `--mode rpc` (e.g. `--session-id <id>`, `--provider`). */
+ args: string[];
+ /** How long to wait for a clean exit after `stdin.end()` before escalating. */
+ closeGraceMs?: number;
+ /** Absolute (or resolved) path to the `pi` executable. */
+ commandPath: string;
+ cwd: string;
+ detached?: boolean;
+ env: NodeJS.ProcessEnv;
+ /** Startup handshake timeout (`get_state`). */
+ handshakeTimeoutMs?: number;
+ onError?: (error: PiRpcConnectionError) => void;
+ /**
+ * Invoked for every parsed agent event from stdout. Events never carry an
+ * `id`; the host correlates them to the active run itself.
+ */
+ onEvent: (event: PiRpcEvent) => void | Promise<void>;
+ /**
+ * Invoked for extension UI requests. Dialog methods (`select` / `confirm` /
+ * `input` / `editor`) block until the returned response (or the request's
+ * own `timeout`) is delivered. When the host returns `undefined` or omits
+ * the handler, dialogs are cancelled (`cancelled: true`) so a run never
+ * hangs on an unrenderable prompt. Fire-and-forget methods are surfaced
+ * here too but never answered.
+ */
+ onExtensionUiRequest?: (
+ request: PiExtensionUiRequest,
+ ) => Promise<PiExtensionUiResponse | undefined> | PiExtensionUiResponse | undefined;
+ onRawStdout?: (chunk: Buffer) => void;
+ onStderr: (data: string) => void | Promise<void>;
+ /** Enable the private per-turn env bridge for a pooled process. */
+ operationContext?: boolean;
+ /** Default response timeout per command. `false` disables the timeout. */
+ requestTimeoutMs?: number | false;
+}
+
+const DEFAULT_CLOSE_GRACE_MS = 3_000;
+const DIALOG_METHODS = new Set(['select', 'confirm', 'input', 'editor']);
+
+/**
+ * Protocol layer for `pi --mode rpc`, built on the generic
+ * {@link RpcStdioClient} transport.
+ *
+ * Adds the pi wire schema to the transport: commands are `{ type, … }`
+ * payloads answered by `{ type: 'response', command, success, … }` records
+ * (a `success: false` response rejects with `PiRpcResponseError`), agent
+ * events and the extension UI sub-protocol flow through `onMessage`, and a
+ * `get_state` handshake hard-fails when pi is missing or too old to speak
+ * RPC. Closing is graceful-first (EOF β†’ SIGTERM β†’ SIGKILL).
+ */
+export class PiRpcClient {
+ private readonly transport: RpcStdioClient;
+ private readonly options: PiRpcClientOptions;
+ private handshakeResolved = false;
+ private handshakeSessionId?: string;
+ private startPromise?: Promise<void>;
+ private readonly probeAbort = new AbortController();
+ private probeExit?: Promise<void>;
+ private closePromise?: Promise<void>;
+ private readonly operationContext?: PiRpcOperationContext;
+
+ constructor(options: PiRpcClientOptions) {
+ this.options = options;
+ if (options.operationContext) this.operationContext = new PiRpcOperationContext();
+ this.transport = new RpcStdioClient({
+ args: [
+ '--mode',
+ 'rpc',
+ ...options.args,
+ ...(this.operationContext ? ['-e', this.operationContext.path] : []),
+ ],
+ closeGraceMs: options.closeGraceMs ?? DEFAULT_CLOSE_GRACE_MS,
+ commandPath: options.commandPath,
+ cwd: options.cwd,
+ detached: options.detached,
+ env: options.env,
+ isResponse: (message) => message?.type === 'response',
+ onError: (error) => {
+ this.operationContext?.cancel(error);
+ options.onError?.(this.toConnectionError(error));
+ },
+ onMessage: (message) => this.handleNonResponse(message),
+ onRawStdout: options.onRawStdout,
+ onStderr: options.onStderr,
+ requestTimeoutMs: options.requestTimeoutMs,
+ });
+ }
+
+ get pid(): number | undefined {
+ return this.transport.pid;
+ }
+
+ get isClosed(): boolean {
+ return this.transport.isClosed;
+ }
+
+ /** True once the startup handshake succeeded (`get_state` answered). */
+ get isReady(): boolean {
+ return this.handshakeResolved && !this.transport.isClosed;
+ }
+
+ /**
+ * The native pi session id reported by the `get_state` handshake.
+ *
+ * Note: RPC mode never emits the `{type:'session'}` header that the legacy
+ * `--mode json` stream starts with β€” the session id only exists in the
+ * `get_state` response β€” so this is the ONLY reliable source for it.
+ */
+ get sessionId(): string | undefined {
+ return this.handshakeSessionId;
+ }
+
+ /**
+ * Spawn the process and complete the startup handshake. Rejects with a
+ * `PiRpcConnectionError` when pi cannot start or does not answer
+ * `get_state` within the handshake timeout β€” the hard-fail guarantee: an
+ * unsupported / broken pi install surfaces as a clear error instead of a
+ * silent hang.
+ */
+ start(): Promise<void> {
+ this.startPromise ??= this.startProcess();
+ return this.startPromise;
+ }
+
+ private async startProcess(): Promise<void> {
+ try {
+ this.assertOpen();
+ await this.checkVersion();
+ this.assertOpen();
+ await this.operationContext?.prepare();
+ this.assertOpen();
+ await this.transport.start();
+ this.assertOpen();
+ await this.performHandshake();
+ if (this.operationContext) {
+ try {
+ const response = await this.command<{ commands: { name: string; source: string }[] }>(
+ { type: 'get_commands' },
+ PI_RPC_HANDSHAKE_TIMEOUT_MS,
+ );
+ if (
+ !response.data?.commands.some(
+ (command) =>
+ command.name === this.operationContext!.commandName &&
+ command.source === 'extension',
+ )
+ ) {
+ throw new Error('Pi did not load the operation context extension');
+ }
+ } catch (error) {
+ this.assertOpen();
+ throw new PiOperationContextUnavailableError('Pi operation context unavailable', {
+ cause: error,
+ });
+ }
+ }
+ } catch (error) {
+ // The process never reached a usable state β€” do not leave it running.
+ await this.close();
+ throw error instanceof PiRpcConnectionError ||
+ error instanceof PiOperationContextUnavailableError
+ ? error
+ : this.toConnectionError(error);
+ }
+ }
+
+ private assertOpen(): void {
+ if (this.probeAbort.signal.aborted)
+ throw new PiRpcConnectionError('Pi RPC client closed by host');
+ }
+
+ private async checkVersion(): Promise<void> {
+ const plan = await resolveCliSpawnPlan(this.options.commandPath, ['--version']);
+ this.assertOpen();
+ let version: string;
+ try {
+ version = await new Promise<string>((resolve, reject) => {
+ const probe = execFile(
+ plan.command,
+ plan.args,
+ {
+ cwd: this.options.cwd,
+ env: this.options.env,
+ killSignal: 'SIGKILL',
+ signal: this.probeAbort.signal,
+ timeout: 5000,
+ windowsHide: true,
+ },
+ (error, stdout) => {
+ if (error) reject(error);
+ else resolve(stdout.trim());
+ },
+ );
+ this.probeExit = new Promise<void>((resolveExit) => {
+ probe.once('close', () => resolveExit());
+ probe.once('error', () => {
+ if (!probe.pid) resolveExit();
+ });
+ });
+ });
+ } catch {
+ throw new PiRpcConnectionError(
+ `Cannot verify Pi version. Pi >= ${PI_RPC_MIN_CLI_VERSION} is required; upgrade pi or check the install.`,
+ { phase: 'spawn' },
+ );
+ }
+ // Require a stable CLI release. get_state alone is not capability
+ // negotiation: older releases answer it but never emit agent_settled.
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:\+[\dA-Za-z.-]+)?$/.exec(version);
+ const minimum = PI_RPC_MIN_CLI_VERSION.split('.').map(Number);
+ const difference =
+ match
+ ?.slice(1)
+ .map(Number)
+ .map((part, index) => part - minimum[index])
+ .find((part) => part !== 0) ?? 0;
+ if (!match || difference < 0) {
+ throw new PiRpcConnectionError(
+ `Pi >= ${PI_RPC_MIN_CLI_VERSION} (stable) is required; upgrade pi to use RPC.`,
+ { phase: 'spawn' },
+ );
+ }
+ }
+
+ /**
+ * Send a command and await its response. Rejects on `success: false`,
+ * timeout, or connection failure. Note: for `prompt`, pi answers as soon as
+ * the message is accepted/queued β€” the run's outcome arrives as events.
+ */
+ async command<T = any>(
+ command: PiRpcCommand,
+ timeoutMs?: number | false,
+ ): Promise<PiRpcResponse<T>> {
+ try {
+ const response = await this.transport.request<PiRpcResponse<T>>(
+ command,
+ timeoutMs ?? this.options.requestTimeoutMs ?? PI_RPC_DEFAULT_REQUEST_TIMEOUT_MS,
+ command.type,
+ );
+ if (!response.success) {
+ throw new PiRpcResponseError(response.command, response.error ?? 'Unknown error');
+ }
+ return response;
+ } catch (error) {
+ if (error instanceof RpcStdioConnectionError) {
+ throw this.toConnectionError(error);
+ }
+ throw error;
+ }
+ }
+
+ /** Bound the abort ACK independently of ordinary command timeout settings. */
+ async abort(): Promise<void> {
+ await this.command({ type: 'abort' }, PI_RPC_ABORT_TIMEOUT_MS);
+ }
+
+ /**
+ * Graceful close: send EOF, wait for pi to exit, escalate only if needed.
+ * Resolves when the child is gone (or was never spawned).
+ */
+ close(options?: { force?: boolean }): Promise<void> {
+ this.probeAbort.abort();
+ this.operationContext?.cancel(new PiRpcConnectionError('Pi RPC client closed by host'));
+ const transportClose = this.transport.close(options);
+ this.closePromise ??= (async () => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.all([
+ transportClose,
+ Promise.race([
+ this.probeExit ?? Promise.resolve(),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () =>
+ reject(
+ new PiRpcConnectionError('Pi version probe did not exit after cancellation'),
+ ),
+ PI_RPC_ABORT_TIMEOUT_MS,
+ );
+ }),
+ ]),
+ ]);
+ await this.operationContext?.dispose();
+ } finally {
+ clearTimeout(timer);
+ }
+ })();
+ return this.closePromise;
+ }
+
+ async setOperationContext(value: string | null): Promise<void> {
+ await this.operationContext?.update('set', value, (command, timeout) =>
+ this.command(command, timeout),
+ );
+ }
+
+ async clearOperationContext(): Promise<void> {
+ await this.operationContext?.update('clear', null, (command, timeout) =>
+ this.command(command, timeout),
+ );
+ }
+
+ private async performHandshake(): Promise<void> {
+ // No command-level timeout on the handshake β€” the watchdog below owns it
+ // so the failure message is deterministic.
+ const handshake = this.command<{ sessionId?: string; sessionFile?: string }>(
+ { type: 'get_state' },
+ false,
+ );
+ const timeout = setTimeout(() => {
+ // Reject the pending handshake directly; start() then recycles the
+ // process. The message must be deterministic β€” no generic timeout text.
+ this.transport.abortPendingRequests(
+ new PiRpcConnectionError(
+ 'pi did not answer the RPC handshake (get_state) β€” upgrade pi or check the install',
+ { phase: 'handshake' },
+ ),
+ );
+ }, this.options.handshakeTimeoutMs ?? PI_RPC_HANDSHAKE_TIMEOUT_MS);
+ timeout.unref?.();
+
+ try {
+ const response = await handshake;
+ clearTimeout(timeout);
+ if (!response.success) {
+ throw new PiRpcConnectionError(
+ `pi RPC handshake failed: ${response.error ?? 'get_state returned success: false'}`,
+ { phase: 'handshake', stderr: this.transport.stderrText },
+ );
+ }
+ this.handshakeResolved = true;
+ if (typeof response.data?.sessionId === 'string') {
+ this.handshakeSessionId = response.data.sessionId;
+ }
+ } catch (error) {
+ clearTimeout(timeout);
+ throw error;
+ }
+ }
+
+ /** Everything that is not a command response: events + extension UI. */
+ private async handleNonResponse(message: Record<string, unknown>): Promise<void> {
+ if (message.type === 'extension_ui_request') {
+ await this.handleExtensionUiRequest(message as unknown as PiExtensionUiRequest);
+ return;
+ }
+ await this.options.onEvent(message as PiRpcEvent);
+ }
+
+ private async handleExtensionUiRequest(request: PiExtensionUiRequest): Promise<void> {
+ if (this.operationContext?.consume(request)) return;
+ const method = request.method;
+ if (!DIALOG_METHODS.has(method)) {
+ // Fire-and-forget β€” surface to the host, never answer.
+ await this.options.onExtensionUiRequest?.(request);
+ return;
+ }
+
+ let response: PiExtensionUiResponse | undefined;
+ try {
+ response = await this.options.onExtensionUiRequest?.(request);
+ } catch {
+ response = undefined;
+ }
+ // No host handler (or it declined) β†’ cancel so the extension unblocks.
+ this.transport.notify(
+ (response ?? { cancelled: true, id: request.id, type: 'extension_ui_response' }) as Record<
+ string,
+ unknown
+ >,
+ );
+ }
+
+ private toConnectionError(error: unknown): PiRpcConnectionError {
+ const phase =
+ error instanceof RpcStdioConnectionError && error.options?.phase === 'spawn'
+ ? 'spawn'
+ : 'run';
+ const message = error instanceof Error ? error.message : String(error);
+ const stderr = error instanceof RpcStdioConnectionError ? error.options?.stderr : undefined;
+ return new PiRpcConnectionError(message, {
+ phase,
+ stderr: stderr ?? this.transport.stderrText,
+ });
+ }
+}
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcOperationContext.test.ts b/packages/heterogeneous-agents/src/rpc/piRpcOperationContext.test.ts
new file mode 100644
index 00000000000..c1a79444103
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/piRpcOperationContext.test.ts
@@ -0,0 +1,129 @@
+import { readFile, stat } from 'node:fs/promises';
+import { runInNewContext } from 'node:vm';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { PiRpcOperationContext } from './piRpcOperationContext';
+import type { PiRpcCommand, PiRpcResponse } from './piRpcProtocol';
+
+const contexts: PiRpcOperationContext[] = [];
+const createContext = () => {
+ const context = new PiRpcOperationContext();
+ contexts.push(context);
+ return context;
+};
+
+afterEach(async () => {
+ await Promise.all(contexts.splice(0).map((context) => context.dispose()));
+ vi.useRealTimers();
+});
+
+describe('Pi operation context', () => {
+ it('requires matching instance, action and turn confirmation, not ordinary RPC success', async () => {
+ vi.useFakeTimers();
+ const context = createContext();
+ const other = createContext();
+ const send = vi.fn().mockResolvedValue({ type: 'response', command: 'prompt', success: true });
+ const done = vi.fn();
+ const pending = context.update('set', 'operation-B', send).then(done);
+ const request = {
+ type: 'extension_ui_request' as const,
+ method: 'setStatus' as const,
+ id: 'ui',
+ statusKey: other.commandName,
+ statusText: '{"action":"set","sequence":1}',
+ };
+ expect(context.consume(request)).toBe(false);
+ context.consume({
+ ...request,
+ statusKey: context.commandName,
+ statusText: '{"action":"clear","sequence":1}',
+ });
+ context.consume({
+ ...request,
+ statusKey: context.commandName,
+ statusText: '{"action":"set","sequence":0}',
+ });
+ await vi.advanceTimersByTimeAsync(1);
+ expect(done).not.toHaveBeenCalled();
+ context.consume({ ...request, statusKey: context.commandName });
+ await pending;
+ expect(done).toHaveBeenCalledOnce();
+ const rejected = context.update('clear', null, send);
+ const assertion = expect(rejected).rejects.toThrow('acknowledgment timed out');
+ await vi.advanceTimersByTimeAsync(5000);
+ await assertion;
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('executes the shipped extension with isolated env, changing identity across turns and rejecting stale cleanup', async () => {
+ const load = async () => {
+ const context = createContext();
+ await context.prepare();
+ const env: Record<string, string> = {};
+ let handler!: (args: string, ctx: unknown) => Promise<void>;
+ const source = await readFile(context.path, 'utf8');
+ const install = runInNewContext(`(${source.replace('export default ', '')})`, {
+ process: { env },
+ });
+ install({
+ registerCommand: (_name: string, options: { handler: typeof handler }) =>
+ (handler = options.handler),
+ });
+ const extensionCtx = {
+ isIdle: () => true,
+ ui: {
+ setStatus: (statusKey: string, statusText: string) =>
+ context.consume({
+ type: 'extension_ui_request',
+ method: 'setStatus',
+ id: 'status',
+ statusKey,
+ statusText,
+ }),
+ },
+ };
+ const send = async (command: PiRpcCommand): Promise<PiRpcResponse> => {
+ if (command.type !== 'prompt') throw new Error('Unexpected command');
+ await handler(command.message.slice(command.message.indexOf(' ') + 1), extensionCtx);
+ return { type: 'response', command: 'prompt', success: true };
+ };
+ return { context, env, extensionCtx, handler, send };
+ };
+ const [a, b] = await Promise.all([load(), load()]);
+ await Promise.all([
+ a.context.update('set', 'topic-A-turn-1', a.send),
+ b.context.update('set', 'topic-B-turn-1', b.send),
+ ]);
+ expect(a.env.LOBEHUB_OPERATION_ID).toBe('topic-A-turn-1');
+ expect(b.env.LOBEHUB_OPERATION_ID).toBe('topic-B-turn-1');
+ await a.context.update('clear', null, a.send);
+ expect(a.env.LOBEHUB_OPERATION_ID).toBeUndefined();
+ await a.context.update('set', 'topic-A-turn-2', a.send);
+ await expect(a.handler('{"action":"clear","sequence":1}', a.extensionCtx)).rejects.toThrow(
+ 'Stale operation cleanup',
+ );
+ expect(a.env.LOBEHUB_OPERATION_ID).toBe('topic-A-turn-2');
+ expect(b.env.LOBEHUB_OPERATION_ID).toBe('topic-B-turn-1');
+ await a.context.update('clear', null, a.send);
+ await a.context.update('set', '', a.send);
+ expect(a.env.LOBEHUB_OPERATION_ID).toBe('');
+ await a.context.update('clear', null, a.send);
+ await a.context.update('set', null, a.send);
+ expect(a.env.LOBEHUB_OPERATION_ID).toBeUndefined();
+ });
+
+ it('cancels pending confirmation and removes resources even during preparation', async () => {
+ const context = createContext();
+ const preparation = context.prepare();
+ const update = context.update('set', 'op', async () => ({
+ type: 'response',
+ command: 'prompt',
+ success: true,
+ }));
+ const rejected = expect(update).rejects.toThrow('closed');
+ await context.dispose();
+ await Promise.all([preparation, rejected]);
+ await expect(stat(context.path)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+});
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcOperationContext.ts b/packages/heterogeneous-agents/src/rpc/piRpcOperationContext.ts
new file mode 100644
index 00000000000..7fde0a3d4f2
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/piRpcOperationContext.ts
@@ -0,0 +1,120 @@
+import { randomUUID } from 'node:crypto';
+import { mkdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import type { PiExtensionUiRequest, PiRpcCommand, PiRpcResponse } from './piRpcProtocol';
+
+const CONTEXT_TIMEOUT_MS = 5000;
+
+export class PiOperationContextUnavailableError extends Error {}
+
+/** A private extension command, never a model message or a replacement bash tool. */
+export class PiRpcOperationContext {
+ readonly commandName = `lobe-operation-${randomUUID()}`;
+ private readonly directory = path.join(tmpdir(), this.commandName);
+ readonly path = path.join(this.directory, 'operation.mjs');
+ private preparation?: Promise<void>;
+ private sequence = 0;
+ private closed = false;
+ private pending?: { acknowledgment: string; reject: (error: Error) => void; resolve: () => void };
+
+ prepare(): Promise<void> {
+ this.preparation ??= this.writeExtension();
+ return this.preparation;
+ }
+
+ private async writeExtension(): Promise<void> {
+ if (this.closed) throw new Error('Pi operation context is closed');
+ await mkdir(this.directory, { mode: 0o700 });
+ // Keep this source self-contained: Electron bundles this module, while Pi
+ // loads the generated extension in its own process with its own env.
+ await writeFile(
+ this.path,
+ `export default function(pi) {
+ const command = ${JSON.stringify(this.commandName)};
+ let sequence = 0;
+ let active = false;
+ pi.registerCommand(command, {
+ description: 'LobeHub internal operation context',
+ handler: async (args, ctx) => {
+ const input = JSON.parse(args);
+ if (!ctx.isIdle() || !Number.isSafeInteger(input.sequence)) throw new Error('Pi is not idle');
+ if (input.action === 'set') {
+ if (active || input.sequence !== sequence + 1) throw new Error('Stale operation context');
+ if (input.value !== null && typeof input.value !== 'string') throw new Error('Invalid operation ID');
+ if (input.value === null) delete process.env.LOBEHUB_OPERATION_ID;
+ else process.env.LOBEHUB_OPERATION_ID = input.value;
+ sequence = input.sequence;
+ active = true;
+ } else if (input.action === 'clear') {
+ if (!active || input.sequence !== sequence) throw new Error('Stale operation cleanup');
+ delete process.env.LOBEHUB_OPERATION_ID;
+ active = false;
+ } else throw new Error('Invalid context action');
+ ctx.ui.setStatus(command, JSON.stringify({ action: input.action, sequence }));
+ },
+ });
+}
+`,
+ { mode: 0o600 },
+ );
+ }
+
+ async update(
+ action: 'set' | 'clear',
+ value: string | null,
+ send: (command: PiRpcCommand, timeout: number) => Promise<PiRpcResponse>,
+ ): Promise<void> {
+ if (this.closed) throw new Error('Pi operation context is closed');
+ if (this.pending) throw new Error('Pi operation context update already pending');
+ if (action === 'set') this.sequence += 1;
+ const sequence = this.sequence;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const acknowledgment = new Promise<void>((resolve, reject) => {
+ this.pending = { acknowledgment: JSON.stringify({ action, sequence }), reject, resolve };
+ timer = setTimeout(
+ () => reject(new Error('Pi operation context acknowledgment timed out')),
+ CONTEXT_TIMEOUT_MS,
+ );
+ });
+ try {
+ // Register the waiter BEFORE writing: Pi can emit the status before its
+ // ordinary prompt response, which alone does not prove handler success.
+ await Promise.all([
+ acknowledgment,
+ send(
+ {
+ type: 'prompt',
+ message: `/${this.commandName} ${JSON.stringify({ action, sequence, value })}`,
+ },
+ CONTEXT_TIMEOUT_MS,
+ ),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ this.pending = undefined;
+ }
+ }
+
+ consume(request: PiExtensionUiRequest): boolean {
+ if (request.method !== 'setStatus' || request.statusKey !== this.commandName) return false;
+ if (request.statusText === this.pending?.acknowledgment) this.pending?.resolve();
+ return true;
+ }
+
+ cancel(error: Error): void {
+ this.closed = true;
+ this.pending?.reject(error);
+ }
+
+ async dispose(): Promise<void> {
+ this.cancel(new Error('Pi operation context is closed'));
+ // Startup can be cancelled during the async file write. Wait for it before
+ // deleting so a late write cannot recreate a leaked extension directory.
+ await this.preparation?.catch(() => {
+ // The startup caller reports the original preparation failure.
+ });
+ await rm(this.directory, { force: true, recursive: true });
+ }
+}
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcProtocol.ts b/packages/heterogeneous-agents/src/rpc/piRpcProtocol.ts
new file mode 100644
index 00000000000..6f1dc685df8
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/piRpcProtocol.ts
@@ -0,0 +1,181 @@
+/**
+ * Pi RPC protocol wire types.
+ *
+ * `pi --mode rpc` speaks a JSONL command/response protocol over stdio:
+ * commands are JSON objects on stdin (one per line), responses and agent
+ * events are JSON objects on stdout. Responses carry `type: 'response'` and
+ * echo the optional `id` of the command they answer; events stream
+ * asynchronously and carry no id.
+ *
+ * See pi's `docs/rpc.md` for the authoritative protocol description.
+ */
+
+/** Base64-encoded image attachment for a prompt / steer / follow_up command. */
+export interface PiRpcImage {
+ /** Base64-encoded image bytes. */
+ data: string;
+ /** IANA media type, e.g. `image/png`. */
+ mimeType: string;
+ type: 'image';
+}
+
+/** How a prompt is delivered while the agent is already streaming. */
+export type PiStreamingBehavior = 'steer' | 'followUp';
+
+/** Commands the host can send to a `pi --mode rpc` process. */
+export type PiRpcCommand =
+ | {
+ id?: string;
+ type: 'prompt';
+ message: string;
+ images?: PiRpcImage[];
+ streamingBehavior?: PiStreamingBehavior;
+ }
+ | { id?: string; type: 'steer'; message: string; images?: PiRpcImage[] }
+ | { id?: string; type: 'follow_up'; message: string; images?: PiRpcImage[] }
+ | { id?: string; type: 'abort' }
+ | { id?: string; type: 'abort_retry' }
+ | { id?: string; type: 'new_session'; parentSession?: string }
+ | { id?: string; type: 'switch_session'; sessionPath: string }
+ | { id?: string; type: 'get_state' }
+ | { id?: string; type: 'get_messages' }
+ | { id?: string; type: 'get_entries'; since?: string }
+ | { id?: string; type: 'get_tree' }
+ | { id?: string; type: 'get_commands' }
+ | { id?: string; type: 'get_available_models' }
+ | { id?: string; type: 'get_session_stats' }
+ | { id?: string; type: 'get_available_thinking_levels' }
+ | { id?: string; type: 'set_model'; provider: string; modelId: string }
+ | { id?: string; type: 'set_thinking_level'; level: string }
+ | { id?: string; type: 'set_steering_mode'; mode: 'all' | 'one-at-a-time' }
+ | { id?: string; type: 'set_follow_up_mode'; mode: 'all' | 'one-at-a-time' }
+ | { id?: string; type: 'compact'; customInstructions?: string }
+ | { id?: string; type: 'set_auto_compaction'; enabled: boolean }
+ | { id?: string; type: 'set_auto_retry'; enabled: boolean }
+ | { id?: string; type: 'bash'; command: string }
+ | { id?: string; type: 'abort_bash' }
+ | { id?: string; type: 'set_session_name'; name: string };
+
+/** Response to a command. `success: false` carries a human-readable `error`. */
+export interface PiRpcResponse<T = any> {
+ command: string;
+ data?: T;
+ error?: string;
+ id?: string;
+ success: boolean;
+ type: 'response';
+}
+
+/** Subset of `get_state` data the host uses for handshake / diagnostics. */
+export interface PiRpcStateData {
+ isCompacting?: boolean;
+ isStreaming?: boolean;
+ messageCount?: number;
+ model?: { id?: string; name?: string } | null;
+ pendingMessageCount?: number;
+ sessionFile?: string;
+ sessionId?: string;
+ sessionName?: string;
+ thinkingLevel?: string;
+}
+
+/** Dialog methods that block until the host answers with a response. */
+export type PiExtensionUiDialogMethod = 'select' | 'confirm' | 'input' | 'editor';
+/** Fire-and-forget methods β€” the host may display or ignore them. */
+export type PiExtensionUiFireAndForgetMethod =
+ 'notify' | 'setStatus' | 'setWidget' | 'setTitle' | 'set_editor_text';
+
+/**
+ * A request emitted by an extension via the extension UI protocol. Dialog
+ * methods block on stdout until the host sends a matching
+ * `extension_ui_response` on stdin; fire-and-forget methods never get one.
+ */
+export interface PiExtensionUiRequest {
+ /** Correlation id β€” must be echoed by the response. */
+ id: string;
+ message?: string;
+ method: PiExtensionUiDialogMethod | PiExtensionUiFireAndForgetMethod;
+ notifyType?: 'info' | 'warning' | 'error';
+ options?: string[];
+ placeholder?: string;
+ prefill?: string;
+ statusKey?: string;
+ statusText?: string;
+ /** Dialog methods may auto-resolve server-side when this elapses. */
+ timeout?: number;
+ title?: string;
+ type: 'extension_ui_request';
+ widgetKey?: string;
+ widgetLines?: string[];
+ widgetPlacement?: 'aboveEditor' | 'belowEditor';
+}
+
+/** The host's answer to a dialog `extension_ui_request`. */
+export interface PiExtensionUiResponse {
+ /** Cancel β€” pi resolves the extension with `undefined` / `false`. */
+ cancelled?: boolean;
+ /** Confirmation answer (confirm). */
+ confirmed?: boolean;
+ id: string;
+ type: 'extension_ui_response';
+ /** Value answer (select / input / editor). */
+ value?: string;
+}
+
+/** A raw agent event emitted by the RPC process (subset used by the host). */
+export interface PiRpcEvent {
+ [key: string]: any;
+ type: string;
+}
+
+/** The `session` event that reports the native pi session id at startup. */
+export interface PiSessionEvent extends PiRpcEvent {
+ id: string;
+ type: 'session';
+}
+
+/** The `agent_settled` event β€” the whole prompt (incl. recovery) is done. */
+export interface PiAgentSettledEvent extends PiRpcEvent {
+ type: 'agent_settled';
+}
+
+/** A `message_update` event (delta stream). */
+export interface PiMessageUpdateEvent extends PiRpcEvent {
+ assistantMessageEvent?: {
+ type: string;
+ /** Present on `type: 'error'` updates: the failure detail. */
+ error?: {
+ errorMessage?: string;
+ message?: string;
+ model?: string;
+ provider?: string;
+ stopReason?: string;
+ [key: string]: any;
+ };
+ reason?: string;
+ [key: string]: any;
+ };
+ type: 'message_update';
+}
+
+/** A `message_end` event (authoritative message snapshot). */
+export interface PiMessageEndEvent extends PiRpcEvent {
+ message?: {
+ role?: string;
+ stopReason?: string;
+ [key: string]: any;
+ };
+ type: 'message_end';
+}
+
+/** First npm release with agent_settled, idle abort and --session-id open-or-create. */
+export const PI_RPC_MIN_CLI_VERSION = '0.80.5';
+
+/** Default timeout for a command response (pi resolves `prompt` on accept). */
+export const PI_RPC_DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
+
+/** Timeout for the startup handshake (`get_state`). */
+export const PI_RPC_HANDSHAKE_TIMEOUT_MS = 15_000;
+
+/** Graceful cancellation must confirm settlement before falling back to process shutdown. */
+export const PI_RPC_ABORT_TIMEOUT_MS = 5_000;
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcSession.test.ts b/packages/heterogeneous-agents/src/rpc/piRpcSession.test.ts
new file mode 100644
index 00000000000..b46ad17043a
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/piRpcSession.test.ts
@@ -0,0 +1,564 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { PiOperationContextUnavailableError } from './piRpcOperationContext';
+import type { PiRpcEvent } from './piRpcProtocol';
+import { PiRpcSession } from './piRpcSession';
+
+const mocks = vi.hoisted(() => ({
+ clientInstances: [] as any[],
+ clientSessionId: { value: undefined as string | undefined },
+ command: vi.fn(),
+ start: vi.fn(),
+ close: vi.fn(),
+ abort: vi.fn(),
+ setOperationContext: vi.fn(),
+ clearOperationContext: vi.fn(),
+}));
+
+vi.mock('./piRpcClient', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return {
+ ...actual,
+ PiRpcClient: class MockPiRpcClient {
+ static instances = mocks.clientInstances;
+ onEvent?: (event: PiRpcEvent) => void | Promise<void>;
+ constructor(readonly options: any) {
+ this.onEvent = options.onEvent;
+ mocks.clientInstances.push(this);
+ }
+ get pid() {
+ return 123_456;
+ }
+ get isClosed() {
+ return false;
+ }
+ get isReady() {
+ return true;
+ }
+ get sessionId() {
+ return mocks.clientSessionId.value;
+ }
+ start = mocks.start;
+ command = mocks.command;
+ close = mocks.close;
+ abort = mocks.abort;
+ setOperationContext = mocks.setOperationContext;
+ clearOperationContext = mocks.clearOperationContext;
+ },
+ };
+});
+
+const createSession = (overrides: Partial<ConstructorParameters<typeof PiRpcSession>[0]> = {}) => {
+ const events: AgentStreamEvent[] = [];
+ const statuses: string[] = [];
+ const sessionIds: string[] = [];
+ const session = new PiRpcSession({
+ args: [],
+ commandPath: 'pi',
+ cwd: '/workspace',
+ env: { ...process.env },
+ operationId: 'op-1',
+ sessionId: 'lobe-session-1',
+ onEvents: (batch) => void events.push(...batch),
+ onRuntimeStatus: (status) => void statuses.push(status.state),
+ onSessionId: (id) => void sessionIds.push(id),
+ onStderr: vi.fn(),
+ ...overrides,
+ });
+ return { events, session, sessionIds, statuses };
+};
+
+const emit = (session: PiRpcSession, event: PiRpcEvent) => {
+ const client = mocks.clientInstances.at(-1)!;
+ return client.onEvent!(event);
+};
+
+beforeEach(() => {
+ mocks.start.mockResolvedValue(undefined);
+ mocks.close.mockResolvedValue(undefined);
+ mocks.setOperationContext.mockResolvedValue(undefined);
+ mocks.clearOperationContext.mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ mocks.clientInstances.length = 0;
+ mocks.clientSessionId.value = undefined;
+ mocks.start.mockReset();
+ mocks.command.mockReset();
+ mocks.close.mockReset();
+ mocks.abort.mockReset();
+ mocks.setOperationContext.mockReset();
+ mocks.clearOperationContext.mockReset();
+ vi.useRealTimers();
+});
+
+describe('PiRpcSession', () => {
+ it('waits for identity installation before prompting and cleanup before reuse', async () => {
+ let installed!: () => void;
+ let cleared!: () => void;
+ mocks.command.mockResolvedValue({ success: true });
+ mocks.setOperationContext.mockReturnValue(
+ new Promise<void>((resolve) => (installed = resolve)),
+ );
+ mocks.clearOperationContext.mockReturnValue(
+ new Promise<void>((resolve) => (cleared = resolve)),
+ );
+ const { session } = createSession({ autoCloseOnSettle: false, shellOperationId: 'shell-op-A' });
+ const run = session.run({ text: 'work' });
+ await vi.waitFor(() => expect(mocks.setOperationContext).toHaveBeenCalledWith('shell-op-A'));
+ expect(mocks.command).not.toHaveBeenCalled();
+ installed();
+ await vi.waitFor(() =>
+ expect(mocks.command).toHaveBeenCalledWith({ type: 'prompt', message: 'work' }),
+ );
+ await emit(session, { type: 'agent_settled' });
+ await vi.waitFor(() => expect(mocks.clearOperationContext).toHaveBeenCalled());
+ expect(session.isReusable).toBe(false);
+ await expect(session.run({ text: 'too early' })).rejects.toThrow('active run');
+ cleared();
+ await run;
+ expect(session.isReusable).toBe(true);
+ await session.close();
+ });
+
+ it('never prompts when identity installation fails and never reuses failed cleanup', async () => {
+ const { session } = createSession({ autoCloseOnSettle: false });
+ mocks.setOperationContext.mockRejectedValue(new Error('missing context acknowledgment'));
+ await expect(session.run({ text: 'must not execute' })).rejects.toThrow('missing context');
+ expect(mocks.command).not.toHaveBeenCalled();
+ expect(session.isReusable).toBe(false);
+
+ mocks.setOperationContext.mockResolvedValue(undefined);
+ mocks.clearOperationContext.mockRejectedValue(new Error('clear failed'));
+ mocks.command.mockResolvedValue({ success: true });
+ const next = createSession({ autoCloseOnSettle: false }).session;
+ const run = next.run({ text: 'execute once' });
+ await vi.waitFor(() => expect(mocks.command).toHaveBeenCalled());
+ await emit(next, { type: 'agent_settled' });
+ await expect(run).resolves.toEqual({ aborted: false });
+ expect(next.isReusable).toBe(false);
+ expect(mocks.command).toHaveBeenCalledOnce();
+ });
+
+ it('falls back once before the user prompt when the extension is unavailable', async () => {
+ mocks.start.mockRejectedValueOnce(new PiOperationContextUnavailableError('no extension'));
+ mocks.command.mockResolvedValue({ success: true });
+ const { session } = createSession({ autoCloseOnSettle: false });
+ const run = session.run({ text: 'once' });
+ await vi.waitFor(() => expect(mocks.command).toHaveBeenCalled());
+ expect(mocks.clientInstances.map((client) => client.options.operationContext)).toEqual([
+ true,
+ false,
+ ]);
+ await emit(session, { type: 'agent_settled' });
+ await run;
+ expect(mocks.command).toHaveBeenCalledOnce();
+ expect(session.isReusable).toBe(false);
+ });
+
+ it('waits beyond the abort ACK until settlement before allowing reuse', async () => {
+ const { session } = createSession({ autoCloseOnSettle: false });
+ mocks.command.mockResolvedValue({ success: true });
+ mocks.abort.mockResolvedValue(undefined);
+ const run = session.run({ text: 'first' });
+ await vi.waitFor(() => expect(mocks.command).toHaveBeenCalled());
+ const cancelled = vi.fn();
+ const cancellation = session.abort().then(cancelled);
+ await vi.waitFor(() => expect(mocks.abort).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(cancelled).not.toHaveBeenCalled();
+ expect(session.isReusable).toBe(false);
+ await emit(session, { type: 'agent_settled' });
+ await cancellation;
+ await expect(run).resolves.toEqual({ aborted: true });
+ expect(session.isReusable).toBe(true);
+ expect(mocks.close).not.toHaveBeenCalled();
+ await session.close();
+ });
+
+ it.each(['no-ack', 'no-settlement', 'rejected'])(
+ 'closes before confirming cancellation when abort has %s',
+ async (failure) => {
+ vi.useFakeTimers();
+ const { session } = createSession({ autoCloseOnSettle: false });
+ mocks.command.mockResolvedValue({ success: true });
+ if (failure === 'no-ack') mocks.abort.mockReturnValue(new Promise(() => {}));
+ else if (failure === 'rejected') mocks.abort.mockRejectedValue(new Error('abort refused'));
+ else mocks.abort.mockResolvedValue(undefined);
+ let finishClose!: () => void;
+ mocks.close.mockReturnValue(new Promise<void>((resolve) => (finishClose = resolve)));
+ const run = session.run({ text: 'work' });
+ await vi.advanceTimersByTimeAsync(0);
+ const confirmed = vi.fn();
+ const cancellation = session.abort().then(confirmed);
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(mocks.close).toHaveBeenCalledOnce();
+ expect(confirmed).not.toHaveBeenCalled();
+ finishClose();
+ await cancellation;
+ await run;
+ expect(session.isReusable).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ },
+ );
+
+ it('rejects cancellation when process shutdown cannot be confirmed', async () => {
+ const { session } = createSession({ autoCloseOnSettle: false });
+ mocks.command.mockResolvedValue({ success: true });
+ mocks.abort.mockRejectedValue(new Error('abort refused'));
+ mocks.close.mockRejectedValue(new Error('still alive after SIGKILL'));
+ const run = session.run({ text: 'work' });
+ await vi.waitFor(() => expect(mocks.command).toHaveBeenCalled());
+ await expect(session.abort()).rejects.toThrow('still alive after SIGKILL');
+ await run;
+ expect(session.isReusable).toBe(false);
+ });
+
+ it('seeds stream provenance from the handshake on every pooled turn', async () => {
+ mocks.clientSessionId.value = 'native-rpc-session';
+ mocks.command.mockResolvedValue({ success: true });
+ const { events, session } = createSession({ autoCloseOnSettle: false });
+ for (const text of ['first', 'second']) {
+ mocks.command.mockClear();
+ const run = session.run({ text });
+ await vi.waitFor(() => expect(mocks.command).toHaveBeenCalled());
+ await emit(session, { type: 'turn_start' });
+ await emit(session, { type: 'agent_settled' });
+ await run;
+ }
+ expect(
+ events.filter((event) => event.type === 'stream_start').map((event) => event.data.sessionId),
+ ).toEqual(['native-rpc-session', 'native-rpc-session']);
+ await session.close();
+ });
+
+ it('waits for recovery after assistant errors and resolves the recovered run', async () => {
+ const { events, session } = createSession({ autoCloseOnSettle: false });
+ mocks.command.mockResolvedValue({ success: true });
+ const run = session.run({ text: 'recover' });
+ const finished = vi.fn();
+ void run.then(finished, finished);
+ await vi.waitFor(() => expect(mocks.command).toHaveBeenCalled());
+ await emit(session, {
+ type: 'message_update',
+ assistantMessageEvent: {
+ type: 'error',
+ error: { stopReason: 'error', errorMessage: 'overflow' },
+ },
+ });
+ await emit(session, { type: 'agent_end' });
+ await emit(session, { type: 'auto_retry_start', attempt: 1, delayMs: 10, maxAttempts: 3 });
+ expect(finished).not.toHaveBeenCalled();
+ expect(session.isRunning).toBe(true);
+ expect(events.some((event) => event.type === 'error')).toBe(false);
+ await emit(session, { type: 'turn_start' });
+ await emit(session, {
+ type: 'message_end',
+ message: {
+ role: 'assistant',
+ stopReason: 'stop',
+ content: [{ type: 'text', text: 'recovered' }],
+ },
+ });
+ await emit(session, { type: 'agent_settled' });
+ await expect(run).resolves.toEqual({ aborted: false });
+ expect(events.some((event) => event.type === 'error')).toBe(false);
+ await session.close();
+ });
+
+ it('rejects immediately on transport death after prompt acknowledgement', async () => {
+ const { session } = createSession({ autoCloseOnSettle: false });
+ mocks.command.mockResolvedValue({ success: true });
+ const run = session.run({ text: 'hello' });
+ const result = expect(run).rejects.toThrow('process died');
+ await vi.waitFor(() => expect(mocks.command).toHaveBeenCalled());
+ mocks.clientInstances.at(-1).options.onError(new Error('process died'));
+ await result;
+ expect(session.isRunning).toBe(false);
+ expect(session.isReusable).toBe(false);
+ expect(mocks.close).toHaveBeenCalled();
+ });
+
+ it('cleans up a rejected prompt in pooled mode', async () => {
+ vi.useFakeTimers();
+ const { session } = createSession({ autoCloseOnSettle: false });
+ mocks.command.mockRejectedValue(new Error('prompt rejected'));
+ await expect(session.run({ text: 'hello' })).rejects.toThrow('prompt rejected');
+ expect(session.isRunning).toBe(false);
+ expect(mocks.close).toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('reserves the session during startup and closes safely before startup finishes', async () => {
+ let finishStart!: () => void;
+ mocks.start.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ finishStart = resolve;
+ }),
+ );
+ const { session } = createSession({ autoCloseOnSettle: false });
+ const run = session.run({ text: 'first' });
+ void run.catch(() => {});
+ expect(session.isRunning).toBe(true);
+ await expect(session.run({ text: 'second' })).rejects.toThrow('active run');
+ await session.close();
+ finishStart();
+ await expect(run).rejects.toThrow('closed');
+ expect(mocks.command).not.toHaveBeenCalled();
+ });
+
+ it('runs a prompt and resolves on agent_settled, broadcasting stream events', async () => {
+ const { events, session, sessionIds } = createSession();
+ mocks.clientSessionId.value = 'pi-sess-1';
+ mocks.start.mockResolvedValue(undefined);
+ mocks.command.mockImplementation((command: { type: string }) => {
+ if (command.type === 'get_state')
+ return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
+ if (command.type === 'prompt')
+ return Promise.resolve({ success: true, type: 'response', command: 'prompt', id: '1' });
+ return Promise.resolve({ success: true, type: 'response', command: command.type });
+ });
+ mocks.close.mockResolvedValue(undefined);
+
+ const runPromise = session.run({ text: 'hello' });
+ const client = mocks.clientInstances.at(-1)!;
+ expect(client).toBeTruthy();
+
+ // RPC mode reports the native session id via the get_state handshake,
+ // not a `{type:'session'}` event.
+ await emit(session, {
+ assistantMessageEvent: { contentIndex: 0, delta: 'Hi ', type: 'text_delta' },
+ type: 'message_update',
+ });
+ await emit(session, {
+ assistantMessageEvent: { contentIndex: 0, delta: 'there', type: 'text_delta' },
+ type: 'message_update',
+ });
+ await emit(session, { type: 'agent_settled' });
+
+ await expect(runPromise).resolves.toEqual({ aborted: false });
+ expect(sessionIds).toContain('pi-sess-1');
+ // text deltas flowed through the real PiAdapter β†’ AgentStreamEvent stream.
+ const textChunks = events.filter(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'text',
+ );
+ expect(textChunks.map((e) => e.data.content).join('')).toBe('Hi there');
+ // agent_runtime_end terminal event emitted by the adapter on settled.
+ expect(events.some((e) => e.type === 'agent_runtime_end')).toBe(true);
+ // The run closes its own process.
+ expect(mocks.close).toHaveBeenCalled();
+ });
+
+ it('waits for cancellation to settle before accepting the next pooled turn', async () => {
+ const { session, events } = createSession({ autoCloseOnSettle: false });
+ mocks.start.mockResolvedValue(undefined);
+ mocks.command.mockImplementation((command: { type: string }) => {
+ if (command.type === 'get_state')
+ return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
+ return Promise.resolve({ success: true, type: 'response', command: command.type });
+ });
+ mocks.close.mockResolvedValue(undefined);
+
+ const runPromise = session.run({ text: 'hello' });
+ await vi.waitFor(() => expect(mocks.command).toHaveBeenCalled());
+ await emit(session, {
+ assistantMessageEvent: { reason: 'aborted', type: 'error' },
+ type: 'message_update',
+ });
+ expect(session.isRunning).toBe(true);
+ await expect(session.run({ text: 'too early' })).rejects.toThrow('active run');
+ await emit(session, { type: 'agent_end' });
+ await emit(session, { type: 'agent_settled' });
+ await expect(runPromise).resolves.toEqual({ aborted: true });
+ const next = session.run({ text: 'next turn' });
+ await emit(session, {
+ type: 'message_update',
+ assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: 'next reply' },
+ });
+ await emit(session, { type: 'agent_settled' });
+ await expect(next).resolves.toEqual({ aborted: false });
+ expect(
+ events.some((event) => event.type === 'stream_chunk' && event.data.content === 'next reply'),
+ ).toBe(true);
+ expect(session.isReusable).toBe(true);
+ await session.close();
+ });
+
+ it('keeps the settled result when it arrives before the prompt ACK', async () => {
+ let acknowledge!: (response: { success: boolean }) => void;
+ mocks.command.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ acknowledge = resolve;
+ }),
+ );
+ const { session } = createSession();
+ const run = session.run({ text: 'fast reply' });
+ const finished = vi.fn();
+ void run.then(finished);
+ await vi.waitFor(() => expect(mocks.command).toHaveBeenCalled());
+ await emit(session, { type: 'agent_settled' });
+ expect(finished).not.toHaveBeenCalled();
+ acknowledge({ success: true });
+ await expect(run).resolves.toEqual({ aborted: false });
+ });
+
+ it('rejects on a terminal error event and still recycles the process', async () => {
+ const { events, session } = createSession();
+ mocks.start.mockResolvedValue(undefined);
+ mocks.command.mockImplementation((command: { type: string }) => {
+ if (command.type === 'get_state')
+ return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
+ return Promise.resolve({ success: true, type: 'response', command: command.type });
+ });
+ mocks.close.mockResolvedValue(undefined);
+
+ const runPromise = session.run({ text: 'hello' });
+ await emit(session, {
+ assistantMessageEvent: {
+ error: { errorMessage: 'usage limit reached', stopReason: 'error' },
+ type: 'error',
+ },
+ type: 'message_update',
+ });
+ await emit(session, { type: 'agent_settled' });
+ await expect(runPromise).rejects.toThrow('usage limit reached');
+ expect(mocks.close).toHaveBeenCalled();
+ expect(events.some((e) => e.type === 'error')).toBe(true);
+ });
+
+ it('streams events on EVERY run of a reused process (fresh adapter per run)', async () => {
+ const { events, session } = createSession({ autoCloseOnSettle: false });
+ mocks.start.mockResolvedValue(undefined);
+ mocks.command.mockImplementation((command: { type: string }) => {
+ if (command.type === 'get_state') {
+ return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
+ }
+ return Promise.resolve({ success: true, type: 'response', command: command.type });
+ });
+ mocks.close.mockResolvedValue(undefined);
+
+ const runTextChunks = async () => {
+ const runPromise = session.run({ text: 'x' });
+ await vi.waitFor(() => expect(session.isRunning).toBe(true));
+ await emit(session, {
+ assistantMessageEvent: { contentIndex: 0, delta: 'reply', type: 'text_delta' },
+ type: 'message_update',
+ });
+ await emit(session, { type: 'agent_settled' });
+ await runPromise;
+ };
+
+ // Turn 1 streams normally.
+ await runTextChunks();
+ // Turn 2 reuses the SAME process β€” the stateful PiAdapter is replaced
+ // per run, so its text must still reach the host.
+ await runTextChunks();
+
+ const textChunks = events.filter(
+ (e) => e.type === 'stream_chunk' && e.data.chunkType === 'text',
+ );
+ expect(textChunks.map((e) => e.data.content)).toEqual(['reply', 'reply']);
+ expect(mocks.close).not.toHaveBeenCalled();
+ await session.close();
+ });
+
+ it('rebinds host callbacks so a pooled process targets a new IPC session', async () => {
+ const { session } = createSession({ autoCloseOnSettle: false });
+ mocks.start.mockResolvedValue(undefined);
+ mocks.command.mockImplementation((command: { type: string }) => {
+ if (command.type === 'get_state') {
+ return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
+ }
+ return Promise.resolve({ success: true, type: 'response', command: command.type });
+ });
+ mocks.close.mockResolvedValue(undefined);
+
+ const rebound: string[] = [];
+ const onRuntimeStatus = vi.fn();
+ session.rebind({
+ operationId: 'op-2',
+ sessionId: 'lobe-session-2',
+ onEvents: (batch) => {
+ for (const event of batch) expect(event.operationId).toBe('op-2');
+ rebound.push(...batch.map((e) => e.type));
+ },
+ onRuntimeStatus,
+ onSessionId: vi.fn(),
+ onStderr: vi.fn(),
+ });
+
+ const runPromise = session.run({ text: 'x' });
+ await emit(session, {
+ assistantMessageEvent: { contentIndex: 0, delta: 'hi', type: 'text_delta' },
+ type: 'message_update',
+ });
+ await emit(session, { type: 'agent_settled' });
+ await runPromise;
+
+ // Events flow to the rebound callback, not the original one.
+ expect(rebound).toContain('stream_chunk');
+ expect(onRuntimeStatus).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operationId: 'op-2',
+ sessionId: 'lobe-session-2',
+ state: 'running',
+ }),
+ );
+ await session.close();
+ });
+
+ it('keeps the process alive across runs when autoCloseOnSettle is false', async () => {
+ const { session } = createSession({ autoCloseOnSettle: false });
+ mocks.start.mockResolvedValue(undefined);
+ mocks.command.mockImplementation((command: { type: string }) => {
+ if (command.type === 'get_state') {
+ return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
+ }
+ return Promise.resolve({ success: true, type: 'response', command: command.type });
+ });
+ mocks.close.mockResolvedValue(undefined);
+
+ // Turn 1 settles without closing the process.
+ const first = session.run({ text: 'first' });
+ await vi.waitFor(() => expect(session.isRunning).toBe(true));
+ await emit(session, { type: 'agent_settled' });
+ await expect(first).resolves.toEqual({ aborted: false });
+ expect(session.isRunning).toBe(false);
+ expect(mocks.close).not.toHaveBeenCalled();
+
+ // Turn 2 reuses the same session/process.
+ const second = session.run({ text: 'second' });
+ await vi.waitFor(() => expect(session.isRunning).toBe(true));
+ await emit(session, { type: 'agent_settled' });
+ await expect(second).resolves.toEqual({ aborted: false });
+ expect(session.isRunning).toBe(false);
+ expect(mocks.close).not.toHaveBeenCalled();
+
+ // The host owns close() in pooled mode.
+ await session.close();
+ expect(mocks.close).toHaveBeenCalled();
+ });
+
+ it('forwards extension UI requests to the host', async () => {
+ const handler = vi.fn().mockReturnValue(undefined);
+ const { session } = createSession({ onExtensionUiRequest: handler });
+ mocks.start.mockResolvedValue(undefined);
+ mocks.command.mockImplementation((command: { type: string }) => {
+ if (command.type === 'get_state')
+ return Promise.resolve({ success: true, type: 'response', command: 'get_state' });
+ return Promise.resolve({ success: true, type: 'response', command: command.type });
+ });
+ mocks.close.mockResolvedValue(undefined);
+
+ const runPromise = session.run({ text: 'hello' });
+ // Extension UI requests are intercepted by the RPC client (covered in
+ // piRpcClient.test.ts) and never surface as agent events.
+ await emit(session, { type: 'agent_settled' });
+ await runPromise;
+ expect(handler).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/rpc/piRpcSession.ts b/packages/heterogeneous-agents/src/rpc/piRpcSession.ts
new file mode 100644
index 00000000000..e99b4ecabe8
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/piRpcSession.ts
@@ -0,0 +1,449 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+
+import { AgentStreamPipeline, type UploadHeterogeneousImage } from '../spawn/agentStreamPipeline';
+import type { HeterogeneousAgentRuntimeStatus } from '../spawn/claudeAgentSdkSession';
+import { PiRpcClient, PiRpcConnectionError, PiRpcResponseError } from './piRpcClient';
+import { PiOperationContextUnavailableError } from './piRpcOperationContext';
+import {
+ PI_RPC_ABORT_TIMEOUT_MS,
+ type PiExtensionUiRequest,
+ type PiExtensionUiResponse,
+ type PiMessageEndEvent,
+ type PiMessageUpdateEvent,
+ type PiRpcCommand,
+ type PiRpcEvent,
+ type PiRpcImage,
+ type PiSessionEvent,
+} from './piRpcProtocol';
+
+/** Text + base64 image content for a single prompt. */
+export interface PiRpcPromptInput {
+ images?: PiRpcImage[];
+ text: string;
+}
+
+export interface PiRpcSessionOptions {
+ /** Extra CLI args (user/provider-configured), e.g. `--provider`, `--model`. */
+ args: string[];
+ /**
+ * When true (default), `run()` recycles its process once the run settles
+ * (per-run lifecycle β€” one run owns one process). When false, the process
+ * survives the run so the host can reuse it for follow-up turns; the host
+ * owns `close()` (e.g. an idle reaper). `run()` stays re-entrant: call it
+ * again for the next turn on the same session.
+ */
+ autoCloseOnSettle?: boolean;
+ /** Absolute (or resolved) path to the `pi` executable. */
+ commandPath: string;
+ cwd: string;
+ detached?: boolean;
+ env: NodeJS.ProcessEnv;
+ /** How long a run may go without any event before it is considered stale. */
+ inactivityTimeoutMs?: number;
+ onEvents: (events: AgentStreamEvent[]) => void | Promise<void>;
+ /** Extension UI dialogs β€” return a response to answer, or `undefined` to cancel. */
+ onExtensionUiRequest?: (
+ request: PiExtensionUiRequest,
+ ) => Promise<PiExtensionUiResponse | undefined> | PiExtensionUiResponse | undefined;
+ onRawStdout?: (chunk: Buffer) => void;
+ onRuntimeStatus: (status: HeterogeneousAgentRuntimeStatus) => void;
+ /** Freshest native pi session id (RPC mode: from the get_state handshake). */
+ onSessionId: (sessionId: string) => void;
+ onStderr: (data: string) => void | Promise<void>;
+ /** Renderer-side operation id stamped onto every emitted event. */
+ operationId: string;
+ /** Native pi session id to resume (`--session-id <id>` at spawn). */
+ resumeSessionId?: string;
+ /** LobeHub session id β€” used for runtime status and diagnostics only. */
+ sessionId: string;
+ /** Effective child-visible identity, including user env overrides. null deletes it. */
+ shellOperationId?: string | null;
+ /** Uploader for base64 tool_result images (see `AgentStreamPipelineOptions`). */
+ uploadImage?: UploadHeterogeneousImage;
+}
+
+/** Host callbacks a pooled process can be rebound to between runs. */
+export interface PiRpcSessionCallbacks {
+ onEvents: (events: AgentStreamEvent[]) => void | Promise<void>;
+ onRuntimeStatus: (status: HeterogeneousAgentRuntimeStatus) => void;
+ onSessionId: (sessionId: string) => void;
+ onStderr: (data: string) => void | Promise<void>;
+ operationId: string;
+ sessionId: string;
+ shellOperationId?: string | null;
+}
+
+const DEFAULT_INACTIVITY_TIMEOUT_MS = 10 * 60 * 1000;
+const ABORTED_REASON = 'aborted';
+
+const isTerminalAbortedEvent = (event: PiRpcEvent): boolean => {
+ if (event.type === 'message_update') {
+ const update = (event as PiMessageUpdateEvent).assistantMessageEvent;
+ if (update?.type !== 'error') return false;
+ return update.reason === ABORTED_REASON || update.error?.stopReason === ABORTED_REASON;
+ }
+ if (event.type === 'message_end') {
+ const message = (event as PiMessageEndEvent).message;
+ return message?.stopReason === ABORTED_REASON;
+ }
+ return false;
+};
+
+/**
+ * One Pi RPC process, optionally reused across sequential prompt runs.
+ * AgentStreamPipeline owns retry/error semantics; only agent_settled releases
+ * the process for reuse. Connection failures close it instead.
+ */
+export class PiRpcSession {
+ private callbacks: PiRpcSessionCallbacks;
+ private client: PiRpcClient;
+ private pipeline: AgentStreamPipeline;
+ private readonly inactivityTimeoutMs: number;
+ private aborted = false;
+ private lastEventAt = Date.now();
+ private inactivityTimer?: NodeJS.Timeout;
+ private resolveRun?: (result: { aborted: boolean }) => void;
+ private rejectRun?: (error: Error) => void;
+ private runStarted = false;
+ private runPromise?: Promise<{ aborted: boolean }>;
+ private abortPromise?: Promise<void>;
+ private startPromise?: Promise<void>;
+ private closePromise?: Promise<void>;
+ private closed = false;
+ private reuseDisabled = false;
+
+ constructor(private readonly options: PiRpcSessionOptions) {
+ this.callbacks = options;
+ this.inactivityTimeoutMs = options.inactivityTimeoutMs ?? DEFAULT_INACTIVITY_TIMEOUT_MS;
+ this.pipeline = this.createPipeline();
+ this.client = this.createClient(options.autoCloseOnSettle === false);
+ }
+
+ private createClient(
+ operationContext: boolean,
+ resumeSessionId = this.options.resumeSessionId,
+ ): PiRpcClient {
+ const options = this.options;
+ return new PiRpcClient({
+ // Resume the native pi session when one is known β€” mirrors the legacy
+ // `--session-id` resume of the json path.
+ args: [...(resumeSessionId ? ['--session-id', resumeSessionId] : []), ...options.args],
+ commandPath: options.commandPath,
+ cwd: options.cwd,
+ detached: options.detached,
+ env: options.env,
+ onError: (error) => this.failRun(error),
+ onEvent: (event) => this.handleEvent(event),
+ onExtensionUiRequest: options.onExtensionUiRequest,
+ onRawStdout: options.onRawStdout,
+ onStderr: (data) => this.callbacks.onStderr(data),
+ operationContext,
+ });
+ }
+
+ get pid(): number | undefined {
+ return this.client.pid;
+ }
+
+ /**
+ * Rebind the host callbacks β€” required when a pooled process is reused by
+ * a later run whose IPC session (and trace) differs from the run that
+ * spawned the process.
+ */
+ rebind(callbacks: PiRpcSessionCallbacks): void {
+ if (this.runStarted) throw new Error('PiRpcSession already has an active run');
+ this.callbacks = callbacks;
+ }
+
+ private createPipeline(): AgentStreamPipeline {
+ return new AgentStreamPipeline({
+ agentType: 'pi',
+ cwd: this.options.cwd,
+ operationId: this.callbacks.operationId,
+ uploadImage: this.options.uploadImage,
+ });
+ }
+
+ /** True while a prompt run is in flight β€” the pool won't reuse a busy session. */
+ get isRunning(): boolean {
+ return this.runStarted;
+ }
+
+ get isReusable(): boolean {
+ return !this.closed && !this.reuseDisabled && !this.runStarted && this.client.isReady;
+ }
+
+ /**
+ * Start the RPC process and handshake. Idempotent. Rejects with a
+ * `PiRpcConnectionError` on spawn/handshake failure (hard-fail).
+ */
+ start(): Promise<void> {
+ if (this.closed) return Promise.reject(new PiRpcConnectionError('Pi RPC session is closed'));
+ this.startPromise ??= this.startClient().then(() => {
+ if (this.closed) throw new PiRpcConnectionError('Pi RPC session is closed');
+ const sessionId = this.client.sessionId;
+ if (sessionId) this.callbacks.onSessionId(sessionId);
+ this.emitStatus('idle');
+ });
+ return this.startPromise;
+ }
+
+ private async startClient(): Promise<void> {
+ try {
+ await this.client.start();
+ } catch (error) {
+ if (!(error instanceof PiOperationContextUnavailableError) || this.closed) throw error;
+ // start() has confirmed the old process is gone. No user prompt has
+ // been sent, so one non-pooled RPC attempt cannot duplicate model work.
+ this.reuseDisabled = true;
+ console.warn('[PiRpcSession] Operation extension unavailable; using single-turn RPC:', error);
+ this.client = this.createClient(false, this.client.sessionId);
+ await this.client.start();
+ }
+ }
+
+ /**
+ * Run one prompt to completion. Resolves `{ aborted: false }` on
+ * `agent_settled`; `{ aborted: true }` when the run was interrupted;
+ * rejects on error / process death. Failed runs always close the process.
+ */
+ run(prompt: PiRpcPromptInput): Promise<{ aborted: boolean }> {
+ if (this.runStarted) return Promise.reject(new Error('PiRpcSession already has an active run'));
+ if (this.closed) return Promise.reject(new PiRpcConnectionError('Pi RPC session is closed'));
+ this.runStarted = true;
+ this.abortPromise = undefined;
+ this.runPromise = this.runPrompt(prompt);
+ return this.runPromise;
+ }
+
+ private async runPrompt(prompt: PiRpcPromptInput): Promise<{ aborted: boolean }> {
+ // Reserve before awaiting startup. Each turn needs a fresh PiAdapter.
+ this.pipeline = this.createPipeline();
+ this.aborted = false;
+ let contextInstalled = false;
+ const completion = new Promise<{ aborted: boolean }>((resolve, reject) => {
+ this.resolveRun = resolve;
+ this.rejectRun = reject;
+ });
+ const sendPrompt = async () => {
+ await this.start();
+ if (this.closed) throw new PiRpcConnectionError('Pi RPC session is closed');
+ const sessionId = this.client.sessionId;
+ if (sessionId) await this.pushEvent({ id: sessionId, type: 'session' }, this.pipeline);
+ // Cancellation may arrive during startup or pipeline initialization.
+ if (this.aborted) {
+ this.settleRun({ aborted: true });
+ return;
+ }
+ await this.client.setOperationContext(this.callbacks.shellOperationId ?? null);
+ contextInstalled = true;
+ if (this.closed) throw new PiRpcConnectionError('Pi RPC session is closed');
+ if (this.aborted) {
+ this.settleRun({ aborted: true });
+ return;
+ }
+ this.armInactivityTimer();
+ this.emitStatus('running');
+ const command: PiRpcCommand = {
+ type: 'prompt',
+ message: prompt.text,
+ ...(prompt.images?.length ? { images: prompt.images } : {}),
+ };
+ const response = await this.client.command(command);
+ if (!response.success) {
+ throw new PiRpcResponseError('prompt', response.error ?? 'Unknown error');
+ }
+ };
+ let failed = false;
+ try {
+ // Observe both promises immediately: process death may precede the ACK,
+ // and agent_settled may arrive before command() resumes.
+ const [result] = await Promise.all([completion, sendPrompt()]);
+ this.clearInactivityTimer();
+ if (contextInstalled && !this.closed) {
+ try {
+ await this.client.clearOperationContext();
+ } catch (error) {
+ console.error('[PiRpcSession] Operation cleanup failed; discarding process:', error);
+ await this.close();
+ }
+ }
+ return result;
+ } catch (error) {
+ failed = true;
+ throw error;
+ } finally {
+ this.clearInactivityTimer();
+ this.resolveRun = undefined;
+ this.rejectRun = undefined;
+ if (failed || this.reuseDisabled || this.options.autoCloseOnSettle !== false) {
+ await this.close().catch(() => {
+ /* best-effort cleanup */
+ });
+ }
+ this.runStarted = false;
+ }
+ }
+
+ /** Confirm run completion, or confirmed process shutdown, before returning. */
+ abort(): Promise<void> {
+ if (this.abortPromise) return this.abortPromise;
+ if (!this.runStarted || !this.runPromise) return this.closePromise ?? Promise.resolve();
+ this.aborted = true;
+ this.abortPromise = this.abortRun(this.runPromise);
+ return this.abortPromise;
+ }
+
+ private async abortRun(run: Promise<{ aborted: boolean }>): Promise<void> {
+ if (!this.client.isReady) {
+ await this.close();
+ return;
+ }
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ Promise.all([this.client.abort(), run]),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new PiRpcConnectionError('Pi cancellation did not settle in time')),
+ PI_RPC_ABORT_TIMEOUT_MS,
+ );
+ }),
+ ]);
+ } catch (error) {
+ console.error('[PiRpcSession] Graceful cancellation failed; closing process:', error);
+ // Failure to confirm shutdown must reject all the way to the operation
+ // cancellation gate; otherwise it can start a second native writer.
+ await this.close();
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ }
+
+ /** Close the underlying process (graceful EOF β†’ escalate). */
+ close(options?: { force?: boolean }): Promise<void> {
+ if (this.closePromise) {
+ if (options?.force)
+ void this.client
+ .close(options)
+ .catch((error) => console.error('[PiRpcSession] Forced close failed:', error));
+ return this.closePromise;
+ }
+ this.closed = true;
+ this.clearInactivityTimer();
+ this.closePromise = this.client.close(options).finally(() => {
+ this.settleRun({ aborted: true });
+ this.emitStatus('closed');
+ });
+ return this.closePromise;
+ }
+
+ /** Send a follow-up message while the process is (briefly) alive. */
+ async followUp(message: string, images?: PiRpcImage[]): Promise<void> {
+ await this.client.command({
+ type: 'follow_up',
+ message,
+ ...(images?.length ? { images } : {}),
+ });
+ }
+
+ /** Send a steering message while the process is (briefly) alive. */
+ async steer(message: string, images?: PiRpcImage[]): Promise<void> {
+ await this.client.command({ type: 'steer', message, ...(images?.length ? { images } : {}) });
+ }
+
+ /** Manually compact the session context. */
+ async compact(customInstructions?: string): Promise<void> {
+ await this.client.command({
+ type: 'compact',
+ ...(customInstructions ? { customInstructions } : {}),
+ });
+ }
+
+ private async handleEvent(event: PiRpcEvent): Promise<void> {
+ if (this.closed) return;
+ this.lastEventAt = Date.now();
+
+ // Capture the pipeline for THIS event β€” `run()` swaps in a fresh pipeline
+ // (new PiAdapter per run) after start(), and push + flush must stay on
+ // the same instance or a deferred adapter error would be flushed against
+ // an empty state.
+ const pipeline = this.pipeline;
+
+ if (event.type === 'session') {
+ const sessionEvent = event as PiSessionEvent;
+ if (typeof sessionEvent.id === 'string') this.callbacks.onSessionId(sessionEvent.id);
+ return;
+ }
+
+ if (!this.runStarted) return;
+ this.armInactivityTimer();
+ if (isTerminalAbortedEvent(event)) this.aborted = true;
+ const events = await this.pushEvent(event, pipeline);
+ if (event.type !== 'agent_settled') return;
+ const error = events.find((item) => item.type === 'error');
+ if (error) this.failRun(new Error(error.data.message ?? 'Pi run failed'));
+ else this.settleRun({ aborted: this.aborted });
+ }
+
+ private async pushEvent(
+ event: PiRpcEvent,
+ pipeline: AgentStreamPipeline,
+ ): Promise<AgentStreamEvent[]> {
+ // Serialize back to a JSONL line and reuse the same pipeline the legacy
+ // CLI path uses β€” PiAdapter consumes the identical event shapes.
+ const line = `${JSON.stringify(event)}\n`;
+ const events = await pipeline.push(line);
+ if (pipeline.sessionId) this.callbacks.onSessionId(pipeline.sessionId);
+ await this.callbacks.onEvents(events);
+ return events;
+ }
+
+ private settleRun(result: { aborted: boolean }): void {
+ const resolve = this.resolveRun;
+ this.resolveRun = undefined;
+ this.rejectRun = undefined;
+ resolve?.(result);
+ }
+
+ private failRun(error: Error): void {
+ const reject = this.rejectRun;
+ this.resolveRun = undefined;
+ this.rejectRun = undefined;
+ reject?.(error);
+ }
+
+ private armInactivityTimer(): void {
+ this.clearInactivityTimer();
+ this.inactivityTimer = setTimeout(() => {
+ if (!this.runStarted) return;
+ const error = new PiRpcConnectionError(
+ `Pi RPC produced no events for ${this.inactivityTimeoutMs}ms`,
+ { phase: 'run' },
+ );
+ this.emitStatus('stale');
+ this.failRun(error);
+ void this.close().catch(() => {
+ /* best-effort */
+ });
+ }, this.inactivityTimeoutMs);
+ this.inactivityTimer.unref?.();
+ }
+
+ private clearInactivityTimer(): void {
+ if (!this.inactivityTimer) return;
+ clearTimeout(this.inactivityTimer);
+ this.inactivityTimer = undefined;
+ }
+
+ private emitStatus(state: HeterogeneousAgentRuntimeStatus['state']): void {
+ this.callbacks.onRuntimeStatus({
+ activeTasks: [],
+ lastEventAt: this.lastEventAt,
+ operationId: this.callbacks.operationId,
+ sessionId: this.callbacks.sessionId,
+ state,
+ transport: 'pi-rpc',
+ });
+ }
+}
diff --git a/packages/heterogeneous-agents/src/rpc/rpcStdioClient.test.ts b/packages/heterogeneous-agents/src/rpc/rpcStdioClient.test.ts
new file mode 100644
index 00000000000..d44f59f50db
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/rpcStdioClient.test.ts
@@ -0,0 +1,405 @@
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { RpcStdioClient, RpcStdioConnectionError } from './rpcStdioClient';
+
+const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }));
+const originalPlatform = process.platform;
+
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return { ...actual, spawn: spawnMock };
+});
+
+const createProcess = () => {
+ const child = new EventEmitter() as any;
+ const stdout = new PassThrough();
+ const writes: Array<Record<string, unknown>> = [];
+ child.pid = 123_456;
+ child.killed = false;
+ child.exitCode = null;
+ child.signalCode = null;
+ child.kill = vi.fn(() => true);
+ child.stdout = stdout;
+ child.stderr = new PassThrough();
+ child.stdin = {
+ once: vi.fn(),
+ end: vi.fn(() => {
+ setTimeout(() => child.emit('close', 0, null), 1);
+ }),
+ write: vi.fn((chunk: string) => {
+ writes.push(JSON.parse(chunk.trim()));
+ return true;
+ }),
+ };
+ return { child, stdout, writes };
+};
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ spawnMock.mockReset();
+ Object.defineProperty(process, 'platform', { value: originalPlatform });
+});
+
+/**
+ * The transport is protocol-agnostic: the default `isResponse` matches
+ * JSON-RPC-2.0-shaped responses (has `id`, no `method`), so an ACP-style
+ * protocol can ride it unchanged. pi supplies its own `isResponse`.
+ */
+describe('RpcStdioClient (generic transport)', () => {
+ it('decodes UTF-8 across byte boundaries without treating Unicode separators as framing', async () => {
+ const { child, stdout } = createProcess();
+ spawnMock.mockReturnValue(child);
+ const onMessage = vi.fn();
+ const onStderr = vi.fn();
+ const client = new RpcStdioClient({
+ args: [],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onMessage,
+ onStderr,
+ });
+ await client.start();
+ const message = { text: 'δΈ­ζ–‡πŸ™‚\u2028next\u2029line' };
+ for (const byte of Buffer.from(`${JSON.stringify(message)}\r\n`))
+ stdout.write(Buffer.from([byte]));
+ for (const byte of Buffer.from('ι”™θ――πŸ™‚')) child.stderr.write(Buffer.from([byte]));
+ child.stderr.end();
+ await vi.waitFor(() => expect(onMessage).toHaveBeenCalledWith(message));
+ expect(onMessage).toHaveBeenCalledTimes(1);
+ expect(onStderr.mock.calls.map(([text]) => text).join('')).toBe('ι”™θ――πŸ™‚');
+ expect(client.stderrText).toBe('ι”™θ――πŸ™‚');
+ await client.close();
+ });
+
+ it('keeps a surrogate-safe bounded stderr tail while forwarding the full decoded stream', async () => {
+ const { child } = createProcess();
+ spawnMock.mockReturnValue(child);
+ const onStderr = vi.fn();
+ const client = new RpcStdioClient({
+ args: [],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onMessage: vi.fn(),
+ onStderr,
+ });
+ await client.start();
+
+ child.stderr.write('old');
+ for (const byte of Buffer.from('πŸ™‚')) child.stderr.write(Buffer.from([byte]));
+ child.stderr.write('a'.repeat(5000));
+ child.stderr.write('a'.repeat(3191));
+ child.stderr.end();
+
+ await vi.waitFor(() =>
+ expect(onStderr.mock.calls.flat().join('')).toBe(`oldπŸ™‚${'a'.repeat(8191)}`),
+ );
+ expect(client.stderrText).toBe('a'.repeat(8191));
+ expect(client.stderrText.length).toBeLessThanOrEqual(8192);
+ expect(client.stderrText.charCodeAt(0)).not.toBeGreaterThanOrEqual(0xdc00);
+ await client.close();
+ });
+
+ it('tees every original stdout chunk before parsing or the closed guard and ignores sink errors', async () => {
+ const { child, stdout } = createProcess();
+ child.stdin.end.mockImplementation(() => {});
+ spawnMock.mockReturnValue(child);
+ const rawChunks: Buffer[] = [];
+ const onMessage = vi.fn();
+ const client = new RpcStdioClient({
+ args: [],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onMessage,
+ onRawStdout: (chunk) => {
+ rawChunks.push(chunk);
+ throw new Error('diagnostic sink failed');
+ },
+ onStderr: vi.fn(),
+ });
+ await client.start();
+
+ const handshake = Buffer.from('{"type":"ready"}\n');
+ const diagnostic = Buffer.from('not json\n');
+ stdout.write(handshake);
+ stdout.write(diagnostic);
+ await vi.waitFor(() => expect(onMessage).toHaveBeenCalledWith({ type: 'ready' }));
+
+ const closed = client.close();
+ const shutdownTail = Buffer.from([0xff, 0x00, 0x0a]);
+ stdout.write(shutdownTail);
+ child.emit('close', 0, null);
+ await closed;
+
+ expect(rawChunks).toEqual([handshake, diagnostic, shutdownTail]);
+ });
+
+ it('reports a fatal exit once even without pending requests and becomes unusable', async () => {
+ const { child } = createProcess();
+ spawnMock.mockReturnValue(child);
+ const onError = vi.fn();
+ const client = new RpcStdioClient({
+ args: [],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onError,
+ onMessage: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ await client.start();
+ child.stderr.write('process crashed');
+ child.emit('close', 1, null);
+ await vi.waitFor(() => expect(onError).toHaveBeenCalledTimes(1));
+ expect(onError.mock.calls[0][0].message).toContain('exited unexpectedly');
+ expect(client.isClosed).toBe(true);
+ child.emit('error', new Error('late error'));
+ expect(onError).toHaveBeenCalledTimes(1);
+ await client.close();
+ expect(child.stdin.end).not.toHaveBeenCalled();
+ });
+
+ it('shares close completion and waits for SIGKILL and the actual close event', async () => {
+ vi.useFakeTimers();
+ const { child } = createProcess();
+ child.stdin.end.mockImplementation(() => {});
+ spawnMock.mockReturnValue(child);
+ // Exercise the direct-child fallback: killed means signalled, not exited.
+ vi.spyOn(process, 'kill').mockImplementation(() => {
+ throw new Error('no process group');
+ });
+ child.kill.mockImplementation(() => {
+ child.killed = true;
+ return true;
+ });
+ const client = new RpcStdioClient({
+ args: [],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ closeGraceMs: 50,
+ onMessage: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ await client.start();
+ const close = client.close();
+ expect(client.close()).toBe(close);
+ const finished = vi.fn();
+ void close.then(finished);
+ await vi.advanceTimersByTimeAsync(50);
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(finished).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');
+ expect(finished).not.toHaveBeenCalled();
+ child.emit('close', null, 'SIGKILL');
+ await close;
+ expect(finished).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('upgrades a pending graceful close to immediate force without later signaling TERM', async () => {
+ vi.useFakeTimers();
+ const { child } = createProcess();
+ child.stdin.end.mockImplementation(() => {});
+ spawnMock.mockReturnValue(child);
+ const client = new RpcStdioClient({
+ args: [],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ closeGraceMs: 50,
+ detached: false,
+ onMessage: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ await client.start();
+
+ const graceful = client.close();
+ const forced = client.close({ force: true });
+ expect(forced).toBe(graceful);
+ expect(child.kill).toHaveBeenCalledTimes(1);
+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');
+
+ const finished = vi.fn();
+ void forced.then(finished);
+ await vi.advanceTimersByTimeAsync(100);
+ expect(child.kill).toHaveBeenCalledTimes(1);
+ expect(finished).not.toHaveBeenCalled();
+ child.emit('close', null, 'SIGKILL');
+ await forced;
+ expect(finished).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it.each(['error', 'nonzero'])(
+ 'falls back when Windows taskkill fails asynchronously (%s)',
+ async (failure) => {
+ vi.useFakeTimers();
+ const { child } = createProcess();
+ child.stdin.end.mockImplementation(() => {});
+ spawnMock.mockReturnValue(child);
+ const client = new RpcStdioClient({
+ args: [],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ closeGraceMs: 50,
+ onMessage: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ await client.start();
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ const killer = new EventEmitter();
+ spawnMock.mockReturnValue(killer);
+ child.kill.mockImplementation(() => {
+ child.emit('close', null, 'SIGTERM');
+ return true;
+ });
+ const closed = client.close();
+ await vi.advanceTimersByTimeAsync(50);
+ if (failure === 'error') killer.emit('error', new Error('taskkill unavailable'));
+ else killer.emit('exit', 1);
+ await closed;
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(vi.getTimerCount()).toBe(0);
+ },
+ );
+
+ it('rejects bounded shutdown if no close follows SIGKILL', async () => {
+ vi.useFakeTimers();
+ const { child } = createProcess();
+ child.stdin.end.mockImplementation(() => {});
+ spawnMock.mockReturnValue(child);
+ vi.spyOn(process, 'kill').mockReturnValue(true);
+ const client = new RpcStdioClient({
+ args: [],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ closeGraceMs: 50,
+ onMessage: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ await client.start();
+ const result = expect(client.close()).rejects.toThrow('did not exit after SIGKILL');
+ await vi.advanceTimersByTimeAsync(4050);
+ await result;
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('correlates JSON-RPC-2.0-shaped responses by id and routes notifications to onMessage', async () => {
+ const { child, stdout, writes } = createProcess();
+ spawnMock.mockReturnValue(child);
+ const messages: unknown[] = [];
+ const client = new RpcStdioClient({
+ args: ['agent', 'stdio'],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onMessage: (message) => void messages.push(message),
+ onStderr: vi.fn(),
+ });
+ await client.start();
+
+ // A notification (no id) must go to onMessage, never resolve a request.
+ stdout.write(`${JSON.stringify({ method: 'initialized' })}\n`);
+
+ const first = client.request<{ result: { value: string } }>({ method: 'first' });
+ const second = client.request<{ result: { value: string } }>({ method: 'second' });
+ const firstId = writes.at(-2)!.id;
+ const secondId = writes.at(-1)!.id;
+
+ stdout.write(`${JSON.stringify({ id: secondId, jsonrpc: '2.0', result: { value: 'two' } })}\n`);
+ const firstLine = `${JSON.stringify({
+ id: firstId,
+ jsonrpc: '2.0',
+ result: { value: 'one' },
+ })}\n`;
+ // Split one line across chunks to prove LF-only framing (no readline).
+ stdout.write(firstLine.slice(0, 9));
+ stdout.write(firstLine.slice(9));
+
+ // The transport delivers the RAW response message β€” interpreting `result`
+ // vs `error` is the protocol layer's job.
+ await expect(Promise.all([first, second])).resolves.toEqual([
+ expect.objectContaining({ jsonrpc: '2.0', result: { value: 'one' } }),
+ expect.objectContaining({ jsonrpc: '2.0', result: { value: 'two' } }),
+ ]);
+ expect(messages).toEqual([{ method: 'initialized' }]);
+ await client.close();
+ expect(child.stdin.end).toHaveBeenCalled();
+ });
+
+ it('rejects pending requests when the child dies, with stderr attached', async () => {
+ const { child, stdout, writes } = createProcess();
+ spawnMock.mockReturnValue(child);
+ const client = new RpcStdioClient({
+ args: ['agent', 'stdio'],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onMessage: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ await client.start();
+
+ const request = client.request({ method: 'authenticate' });
+ // `first` never gets its response β€” the process dies instead.
+ expect(writes).toHaveLength(1); // request id already written
+ stdout.end();
+ child.emit('close', 1, null);
+
+ await expect(request).rejects.toThrow(RpcStdioConnectionError);
+ await expect(request).rejects.toThrow(/exited unexpectedly/);
+ await client.close();
+ });
+
+ it('rejects pending requests on host close so callers never hang', async () => {
+ const { child, client } = (() => {
+ const { child } = createProcess();
+ spawnMock.mockReturnValue(child);
+ const messages: unknown[] = [];
+ const c = new RpcStdioClient({
+ args: ['agent', 'stdio'],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onMessage: (message) => void messages.push(message),
+ onStderr: vi.fn(),
+ });
+ return { child, client: c };
+ })();
+ await client.start();
+
+ const pending = client.request({ method: 'never-answered' });
+ const closed = client.close();
+ await expect(pending).rejects.toThrow(/closed by host/);
+ await closed;
+ expect(child.stdin.end).toHaveBeenCalled();
+ });
+
+ it('notify() writes fire-and-forget messages', async () => {
+ const { child, writes } = createProcess();
+ spawnMock.mockReturnValue(child);
+ const client = new RpcStdioClient({
+ args: ['agent', 'stdio'],
+ commandPath: 'agent',
+ cwd: '/workspace',
+ env: { ...process.env },
+ onMessage: vi.fn(),
+ onStderr: vi.fn(),
+ });
+ await client.start();
+
+ client.notify({ method: 'initialized' });
+ expect(writes.at(-1)).toEqual({ method: 'initialized' });
+ await client.close();
+ });
+});
diff --git a/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts b/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts
new file mode 100644
index 00000000000..4f5156976a6
--- /dev/null
+++ b/packages/heterogeneous-agents/src/rpc/rpcStdioClient.ts
@@ -0,0 +1,428 @@
+import type { ChildProcess } from 'node:child_process';
+import { spawn } from 'node:child_process';
+import { StringDecoder } from 'node:string_decoder';
+
+import { resolveCliSpawnPlan } from '../spawn/cliSpawn';
+
+/**
+ * Protocol-agnostic JSONL RPC transport over a child process's stdio.
+ *
+ * Owns everything that is the same for every CLI RPC protocol (pi `--mode
+ * rpc`, ACP, codex app-server, …): spawning via `resolveCliSpawnPlan`,
+ * LF-only framing, request/response correlation by `id`, timeout + deadline
+ * handling, stderr routing, and graceful EOF-first shutdown with signal
+ * escalation. The wire schema stays in a thin protocol layer on top (e.g.
+ * `PiRpcClient`) which supplies the `isResponse` discriminator and interprets
+ * response payloads.
+ *
+ * Framing note: records split on `\n` only (a trailing `\r` is stripped).
+ * Node's `readline` is NOT protocol-compliant for JSONL RPC streams because
+ * it also splits on U+2028/U+2029, which are valid inside JSON strings.
+ */
+
+/** Error thrown when the child dies, a request times out, or the client closes. */
+export class RpcStdioConnectionError extends Error {
+ constructor(
+ message: string,
+ readonly options?: { phase?: 'spawn' | 'run'; stderr?: string },
+ ) {
+ super(message);
+ this.name = 'RpcStdioConnectionError';
+ }
+}
+
+interface PendingRequest {
+ label: string;
+ reject: (error: Error) => void;
+ resolve: (message: Record<string, unknown>) => void;
+ timeout?: ReturnType<typeof setTimeout>;
+}
+
+export interface RpcStdioClientOptions {
+ /** CLI args (protocol-specific flags included). */
+ args: string[];
+ /** How long to wait for a clean exit after `stdin.end()` before escalating. */
+ closeGraceMs?: number;
+ /** Absolute (or resolved) path to the executable. */
+ commandPath: string;
+ cwd: string;
+ /** False keeps the child in a device wrapper's process group. Defaults to true on Unix. */
+ detached?: boolean;
+ env: NodeJS.ProcessEnv;
+ /**
+ * Discriminates a response to a client request from a notification/event.
+ * A message passing this predicate whose `id` matches a pending request
+ * resolves it. Default: JSON-RPC-2.0-shaped messages (has `id`, no
+ * `method`); pi passes `(m) => m?.type === 'response'`.
+ */
+ isResponse?: (message: Record<string, unknown>) => boolean;
+ /** Fatal transport errors, including exits after a command was accepted. */
+ onError?: (error: Error) => void;
+ /**
+ * Invoked for every parsed message that is NOT the response to a pending
+ * request β€” i.e. notifications, events, and server-initiated requests.
+ */
+ onMessage: (message: Record<string, unknown>) => void | Promise<void>;
+ /** Receives each original stdout chunk before decoding or protocol handling. */
+ onRawStdout?: (chunk: Buffer) => void;
+ onStderr: (data: string) => void | Promise<void>;
+ /** Default per-request timeout. `false` disables it. */
+ requestTimeoutMs?: number | false;
+}
+
+const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
+const DEFAULT_CLOSE_GRACE_MS = 3_000;
+const ESCALATE_KILL_MS = 2_000;
+/** Maximum retained stderr tail, measured in JavaScript UTF-16 code units. */
+const STDERR_TAIL_MAX_UTF16_CODE_UNITS = 8192;
+
+const defaultIsResponse = (message: Record<string, unknown>): boolean =>
+ 'id' in message && !('method' in message);
+
+export class RpcStdioClient {
+ private readonly pendingRequests = new Map<string, PendingRequest>();
+ private child?: ChildProcess;
+ private closePromise?: Promise<void>;
+ private closed = false;
+ private exited = false;
+ private fatalError?: Error;
+ private forceShutdown?: () => void;
+ private messageQueue: Promise<void> = Promise.resolve();
+ private nextRequestId = 0;
+ private readonly stderrDecoder = new StringDecoder('utf8');
+ private stderrTail = '';
+ private readonly stdoutDecoder = new StringDecoder('utf8');
+ private stdoutBuffer = '';
+
+ constructor(private readonly options: RpcStdioClientOptions) {}
+
+ get pid(): number | undefined {
+ return this.child?.pid;
+ }
+
+ get isClosed(): boolean {
+ return this.closed || this.exited || !!this.fatalError;
+ }
+
+ get stderrText(): string {
+ return this.stderrTail;
+ }
+
+ /**
+ * Spawn the child (no protocol handshake β€” the protocol layer owns that).
+ * Rejects with `RpcStdioConnectionError` when the spawn itself fails.
+ */
+ async start(): Promise<void> {
+ if (this.child || this.closed) return;
+
+ const spawnPlan = await resolveCliSpawnPlan(this.options.commandPath, this.options.args);
+ if (this.closed) return;
+ const child = spawn(spawnPlan.command, spawnPlan.args, {
+ cwd: this.options.cwd,
+ detached: process.platform !== 'win32' && (this.options.detached ?? true),
+ env: this.options.env,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ this.child = child;
+
+ child.stdin?.once('error', (error) => {
+ if (!this.closed) this.fail(this.toError(error));
+ });
+ child.stdout?.on('data', (chunk: Buffer) => this.consumeStdout(chunk));
+ child.stdout?.once('end', () => this.consumeRemainingStdout());
+ child.stdout?.once('error', (error) => this.fail(this.toError(error)));
+ child.stderr?.on('data', (chunk: Buffer) => {
+ this.consumeStderr(this.stderrDecoder.write(chunk));
+ });
+ child.stderr?.once('end', () => this.consumeStderr(this.stderrDecoder.end()));
+ child.once('error', (error) => {
+ this.fail(
+ new RpcStdioConnectionError(`Failed to start RPC process: ${error.message}`, {
+ phase: 'spawn',
+ }),
+ );
+ });
+ child.once('close', (code, signal) => {
+ this.exited = true;
+ if (this.closed) return;
+ const error = new RpcStdioConnectionError(
+ `RPC process exited unexpectedly (code ${code ?? 'null'}, signal ${signal ?? 'null'})`,
+ { phase: 'run', stderr: this.stderrText },
+ );
+ // Node may emit process exit before stdout fully drains. `close` waits
+ // for stdio, then this queue wait lets a final structured RPC error win
+ // over the less useful process-exit fallback.
+ this.messageQueue = this.messageQueue.then(() => this.fail(error));
+ });
+ }
+
+ /**
+ * Send a payload and await the matching response. Assigns a numeric `id`
+ * when the payload lacks one; the response must pass `isResponse` and echo
+ * that `id`. Rejects on timeout, host close, or process death. The payload
+ * is delivered to the child verbatim β€” interpretation is the protocol
+ * layer's job.
+ */
+ request<T = unknown>(
+ payload: Record<string, unknown>,
+ timeoutMs?: number | false,
+ label = String(payload.type ?? payload.method ?? 'request'),
+ ): Promise<T> {
+ if (this.fatalError) throw this.fatalError;
+ if (this.closed) throw new RpcStdioConnectionError('RPC client is closed');
+ if (!this.child?.stdin) throw new RpcStdioConnectionError('RPC stdin is unavailable');
+
+ const id = String(++this.nextRequestId);
+ const message = { ...payload, id };
+ return new Promise<T>((resolve, reject) => {
+ const pending: PendingRequest = {
+ label,
+ reject,
+ resolve: (response) => resolve(response as T),
+ };
+ const timeout = timeoutMs ?? this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
+ if (timeout !== false) {
+ pending.timeout = setTimeout(() => {
+ this.pendingRequests.delete(id);
+ reject(new RpcStdioConnectionError(`RPC request timed out: ${label}`, { phase: 'run' }));
+ }, timeout);
+ pending.timeout.unref?.();
+ }
+ this.pendingRequests.set(id, pending);
+ try {
+ this.writeMessage(message);
+ } catch (error) {
+ if (this.pendingRequests.get(id) === pending) this.pendingRequests.delete(id);
+ if (pending.timeout) clearTimeout(pending.timeout);
+ reject(this.toError(error));
+ }
+ });
+ }
+
+ /** Fire-and-forget write β€” no response is awaited. */
+ notify(payload: Record<string, unknown>): void {
+ if (this.closed || !this.child?.stdin) return;
+ this.writeMessage(payload);
+ }
+
+ /**
+ * Graceful close: send EOF, wait for the child to exit, escalate to SIGTERM
+ * then SIGKILL only if it lingers. Pending requests reject with
+ * 'closed by host'. Resolves once the child is gone (or was never spawned).
+ * `force` skips directly to SIGKILL and upgrades an in-progress graceful
+ * close while preserving its shared completion promise.
+ */
+ close(options?: { force?: boolean }): Promise<void> {
+ if (this.closePromise) {
+ if (options?.force) this.forceShutdown?.();
+ return this.closePromise;
+ }
+ this.closed = true;
+ this.rejectPendingRequests(new RpcStdioConnectionError('RPC client closed by host'));
+ this.closePromise = this.shutdown(options?.force);
+ return this.closePromise;
+ }
+
+ private consumeStdout(chunk: Buffer): void {
+ try {
+ this.options.onRawStdout?.(chunk);
+ } catch {
+ // Raw output is diagnostic-only and must never affect the agent.
+ }
+ if (this.closed) return;
+ this.stdoutBuffer += this.stdoutDecoder.write(chunk);
+
+ let newlineIndex: number;
+ while ((newlineIndex = this.stdoutBuffer.indexOf('\n')) !== -1) {
+ const line = this.stdoutBuffer.slice(0, newlineIndex);
+ this.stdoutBuffer = this.stdoutBuffer.slice(newlineIndex + 1);
+ this.enqueueLine(line);
+ }
+ }
+
+ private consumeStderr(text: string): void {
+ if (!text) return;
+ this.stderrTail += text;
+ if (this.stderrTail.length > STDERR_TAIL_MAX_UTF16_CODE_UNITS) {
+ this.stderrTail = this.stderrTail.slice(-STDERR_TAIL_MAX_UTF16_CODE_UNITS);
+ const firstCodeUnit = this.stderrTail.charCodeAt(0);
+ if (firstCodeUnit >= 0xdc00 && firstCodeUnit <= 0xdfff)
+ this.stderrTail = this.stderrTail.slice(1);
+ }
+ void Promise.resolve()
+ .then(() => this.options.onStderr(text))
+ .catch((error) => this.fail(this.toError(error)));
+ }
+
+ private consumeRemainingStdout(): void {
+ if (this.closed) {
+ this.stdoutBuffer = '';
+ return;
+ }
+ this.stdoutBuffer += this.stdoutDecoder.end();
+ if (!this.stdoutBuffer) return;
+ const line = this.stdoutBuffer;
+ this.stdoutBuffer = '';
+ this.enqueueLine(line);
+ }
+
+ private enqueueLine(rawLine: string): void {
+ if (this.closed) return;
+ const line = rawLine.replace(/\r$/, '');
+ if (!line.trim()) return;
+
+ this.messageQueue = this.messageQueue
+ .then(() => this.handleLine(line))
+ .catch((error) => this.fail(this.toError(error)));
+ }
+
+ private async handleLine(line: string): Promise<void> {
+ let message: unknown;
+ try {
+ message = JSON.parse(line) as unknown;
+ } catch {
+ // One non-JSON diagnostic line must not corrupt framing.
+ return;
+ }
+ if (!message || typeof message !== 'object' || Array.isArray(message)) return;
+
+ const record = message as Record<string, unknown>;
+ if (this.options.isResponse?.(record) ?? defaultIsResponse(record)) {
+ const key = record.id;
+ if (key === undefined) return;
+ const pending = this.pendingRequests.get(String(key));
+ if (!pending) return;
+
+ this.pendingRequests.delete(String(key));
+ if (pending.timeout) clearTimeout(pending.timeout);
+ pending.resolve(record);
+ return;
+ }
+
+ await this.options.onMessage(record);
+ }
+
+ private writeMessage(message: Record<string, unknown>): void {
+ if (!this.child?.stdin || this.closed) {
+ throw new RpcStdioConnectionError('RPC stdin is unavailable');
+ }
+ this.child.stdin.write(`${JSON.stringify(message)}\n`);
+ }
+
+ private async shutdown(force = false): Promise<void> {
+ const child = this.child;
+ if (!child || this.exited) return;
+
+ await new Promise<void>((resolve, reject) => {
+ let timer: ReturnType<typeof setTimeout>;
+ const onClose = () => {
+ clearTimeout(timer);
+ this.forceShutdown = undefined;
+ resolve();
+ };
+ const rejectAfterKillDeadline = () => {
+ timer = setTimeout(() => {
+ child.off('close', onClose);
+ this.forceShutdown = undefined;
+ reject(new RpcStdioConnectionError('RPC process did not exit after SIGKILL'));
+ }, ESCALATE_KILL_MS);
+ };
+ const forceNow = () => {
+ clearTimeout(timer);
+ this.terminateChild(child, 'SIGKILL');
+ if (this.exited) return;
+ rejectAfterKillDeadline();
+ };
+ child.once('close', onClose);
+ this.forceShutdown = forceNow;
+ if (force) {
+ forceNow();
+ } else {
+ timer = setTimeout(() => {
+ this.terminateChild(child, 'SIGTERM');
+ if (this.exited) return;
+ timer = setTimeout(() => {
+ this.terminateChild(child, 'SIGKILL');
+ if (this.exited) return;
+ rejectAfterKillDeadline();
+ }, ESCALATE_KILL_MS);
+ }, this.options.closeGraceMs ?? DEFAULT_CLOSE_GRACE_MS);
+ try {
+ child.stdin?.end();
+ } catch {
+ // A broken stdin still needs the signal escalation above.
+ }
+ }
+ });
+ }
+
+ private fail(error: Error): void {
+ if (this.closed || this.fatalError) return;
+ this.fatalError = error;
+ this.rejectPendingRequests(error);
+ this.options.onError?.(error);
+ }
+
+ /**
+ * Reject every in-flight request with `error` WITHOUT closing the process.
+ * Used by protocol layers to abort a specific handshake/watchdog wait while
+ * keeping the transport usable (or to let the caller decide the shutdown).
+ */
+ abortPendingRequests(error: Error): void {
+ this.rejectPendingRequests(error);
+ }
+
+ private rejectPendingRequests(error: Error): void {
+ for (const [, pending] of this.pendingRequests) {
+ if (pending.timeout) clearTimeout(pending.timeout);
+ pending.reject(error);
+ }
+ this.pendingRequests.clear();
+ }
+
+ private terminateChild(child: ChildProcess, signal: NodeJS.Signals): void {
+ if (!child.pid || this.exited) return;
+
+ if (process.platform === 'win32') {
+ const killChild = () => {
+ try {
+ child.kill(signal);
+ } catch {
+ // The exit event may still be draining.
+ }
+ };
+ try {
+ const killer = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
+ stdio: 'ignore',
+ });
+ killer.once('error', killChild);
+ killer.once('exit', (code) => {
+ if (code !== 0) killChild();
+ });
+ } catch {
+ killChild();
+ }
+ return;
+ }
+
+ if (this.options.detached !== false) {
+ try {
+ process.kill(-child.pid, signal);
+ return;
+ } catch {
+ // Fall back to the child when its own process group is gone.
+ }
+ }
+
+ // An inherited group belongs to the wrapper, not this transport.
+ try {
+ child.kill(signal);
+ } catch {
+ /* already gone */
+ }
+ }
+
+ private toError(error: unknown): Error {
+ return error instanceof Error ? error : new Error(String(error));
+ }
+}
diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
index 90eb0bfd342..0bb45dfcdbe 100644
--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
@@ -144,6 +144,7 @@ export interface HeterogeneousAgentRuntimeStatus {
| 'cursor-acp'
| 'droid-acp'
| 'devin-acp'
+ | 'pi-rpc'
| 'trae-acp';
}
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index fc49bd90b30..034444923ff 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -83,6 +83,16 @@ export {
isCursorAcpSessionNotFoundError,
normalizeCursorQuestion,
} from './cursorAcpSession';
+export {
+ buildDevinAcpArgs,
+ buildDevinAcpPrompt,
+ type DevinAcpImagePromptBlock,
+ type DevinAcpPromptBlock,
+ DevinAcpSession,
+ type DevinAcpSessionOptions,
+ type DevinAcpTextPromptBlock,
+ isDevinAcpSessionNotFoundError,
+} from './devinAcpSession';
export {
buildDroidAcpArgs,
buildDroidAcpPrompt,
@@ -97,16 +107,6 @@ export {
type ListDroidAcpModelsOptions,
parseDroidAcpModelCatalog,
} from './droidAcpSession';
-export {
- buildDevinAcpArgs,
- buildDevinAcpPrompt,
- type DevinAcpImagePromptBlock,
- type DevinAcpPromptBlock,
- DevinAcpSession,
- type DevinAcpSessionOptions,
- type DevinAcpTextPromptBlock,
- isDevinAcpSessionNotFoundError,
-} from './devinAcpSession';
export {
createFileStoreImageUploader,
type FileStoreCreateFileInput,
@@ -159,7 +159,6 @@ export {
CODEX_REQUIRED_ARGS,
KIMI_CODE_BASE_ARGS,
OPENCODE_BASE_ARGS,
- PI_BASE_ARGS,
QODER_BASE_ARGS,
type QoderSpawnArgsOptions,
spawnAgent,
diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts
index 434ec49656e..3397fdad70d 100644
--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.test.ts
@@ -283,31 +283,10 @@ describe('buildAgentInput', () => {
});
describe('pi', () => {
- it('uses raw text stdin and @path image arguments', async () => {
- const filePath = path.join(tmp, 'pi input.png');
- await writeFile(filePath, PNG_BYTES);
- const plan = await buildAgentInput('pi', [
- { text: 'first', type: 'text' },
- { source: { path: filePath, type: 'path' }, type: 'image' },
- { text: 'second', type: 'text' },
- ]);
-
- expect(plan).toEqual({ args: [`@${filePath}`], stdin: 'first\n\nsecond' });
- });
-
- it('materializes base64 images through the shared path-input helper', async () => {
- const plan = await buildAgentInput(
- 'pi',
- [
- {
- source: { data: PNG_BYTES.toString('base64'), mediaType: 'image/png', type: 'base64' },
- type: 'image',
- },
- ],
- { cacheDir: tmp },
+ it('rejects the legacy stdin/args input β€” pi is RPC-only', async () => {
+ await expect(buildAgentInput('pi', [{ text: 'first', type: 'text' }])).rejects.toThrow(
+ /RPC transport only/,
);
- expect(plan.args).toHaveLength(1);
- expect(plan.args[0]).toMatch(/^@.*\.png$/);
});
});
diff --git a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts
index 843bd3d2f77..62e8e0e3be8 100644
--- a/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts
+++ b/packages/heterogeneous-agents/src/spawn/input/buildAgentInput.ts
@@ -132,15 +132,12 @@ const buildOpenCodeInput = async (
};
};
-const buildPiInput = async (
- blocks: AgentContentBlock[],
- options: BuildAgentInputOptions,
-): Promise<AgentInputPlan> => {
- const imagePaths = await resolvePathInputImagePaths(blocks, options);
- return {
- args: imagePaths.map((imagePath) => `@${imagePath}`),
- stdin: collectText(blocks),
- };
+const buildPiInput = async (): Promise<AgentInputPlan> => {
+ // pi runs exclusively over the RPC transport (PiRpcSession /
+ // createPiRpcAgentHandle) β€” the legacy `--mode json` stdin input is gone.
+ throw new Error(
+ 'pi runs over the RPC transport only β€” use PiRpcSession / createPiRpcAgentHandle',
+ );
};
const buildKimiCodeInput = (blocks: AgentContentBlock[]): AgentInputPlan => {
@@ -207,7 +204,7 @@ export const buildAgentInput = async (
return buildOpenCodeInput(blocks, options);
}
case 'pi': {
- return buildPiInput(blocks, options);
+ return buildPiInput();
}
case 'qoder': {
return buildQoderInput(blocks, options);
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
index b20cd13a3c5..d2d369bbea5 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts
@@ -14,6 +14,7 @@ let nextFakeProc: any = null;
const tempDirs: string[] = [];
const platformMock = vi.mocked(os.platform);
+const originalPlatform = process.platform;
const execFileMock = vi.mocked(childProcess.execFile);
const detectHeterogeneousCliCommandMock = vi.mocked(
resolveCliCommand.detectHeterogeneousCliCommand,
@@ -345,11 +346,16 @@ describe('spawnAgent', () => {
nextFakeProc = null;
platformMock.mockReturnValue('linux');
execFileMock.mockReset();
+ // ACP/stdio sessions read `process.platform` directly (unlike the CLI
+ // spawn plan which uses `os.platform()`), so pin it too β€” otherwise the
+ // signal-path tests exercise the win32 taskkill branch on Windows hosts.
+ Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' });
detectHeterogeneousCliCommandMock.mockResolvedValue({ available: true, path: 'traecli' });
});
afterEach(async () => {
nextFakeProc = null;
+ Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform });
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
});
@@ -1250,35 +1256,18 @@ describe('spawnAgent', () => {
]);
});
- it('spawns Pi in JSON mode, resumes its native session, and sends images as @path args', async () => {
- const dir = await mkdtemp(path.join(os.tmpdir(), 'lobe-pi-spawn-'));
- tempDirs.push(dir);
- const imagePath = path.join(dir, 'input.png');
- await writeFile(imagePath, 'image');
- nextFakeProc = createFakeProc().proc;
+ it('rejects spawning Pi via the legacy CLI path β€” pi is RPC-only', async () => {
const { spawnAgent } = await import('./spawnAgent');
- await spawnAgent({
- agentType: 'pi',
- extraArgs: ['--provider', 'anthropic'],
- operationId: 'op-pi',
- prompt: [
- { text: 'continue', type: 'text' },
- { source: { path: imagePath, type: 'path' }, type: 'image' },
- ],
- resumeSessionId: 'pi-session-previous',
- });
-
- expect(spawnCalls[0]).toMatchObject({ command: 'pi' });
- expect(spawnCalls[0].args).toEqual([
- '--mode',
- 'json',
- '--session-id',
- 'pi-session-previous',
- `@${imagePath}`,
- '--provider',
- 'anthropic',
- ]);
- expect((nextFakeProc as any).stdin.write.mock.calls[0][0]).toBe('continue');
+ await expect(
+ spawnAgent({
+ agentType: 'pi',
+ extraArgs: ['--provider', 'anthropic'],
+ operationId: 'op-pi',
+ prompt: 'continue',
+ resumeSessionId: 'pi-session-previous',
+ }),
+ ).rejects.toThrow(/RPC transport only/);
+ expect(spawnCalls).toHaveLength(0);
});
it('seeds a real Codex resumed stream with the previous cumulative usage from the session file', async () => {
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index fdb7c4f39b0..3d3a95c177e 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -1,5 +1,6 @@
import type { ChildProcess } from 'node:child_process';
import { spawn } from 'node:child_process';
+import { platform } from 'node:os';
import path from 'node:path';
import { PassThrough } from 'node:stream';
@@ -11,8 +12,8 @@ import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStrea
import { isPathLikeCommand, resolveCliSpawnPlan } from './cliSpawn';
import { readCodexSessionModel, resolveCodexInitialModel } from './codexModel';
import { buildCursorAcpPrompt, CursorAcpSession } from './cursorAcpSession';
-import { buildDroidAcpPrompt, DroidAcpSession } from './droidAcpSession';
import { buildDevinAcpPrompt, DevinAcpSession } from './devinAcpSession';
+import { buildDroidAcpPrompt, DroidAcpSession } from './droidAcpSession';
import { buildGrokAcpPrompt, GrokAcpSession } from './grokAcpSession';
import type { AgentPromptInput, BuildAgentInputOptions } from './input';
import { buildAgentInput } from './input';
@@ -213,7 +214,6 @@ export const AMP_BASE_ARGS = [
] as const;
export const OPENCODE_BASE_ARGS = ['run', '--format', 'json', '--thinking', '--auto'] as const;
-export const PI_BASE_ARGS = ['--mode', 'json'] as const;
export const KIMI_CODE_BASE_ARGS = ['--output-format', 'stream-json'] as const;
export const QODER_BASE_ARGS = [
'-p',
@@ -296,12 +296,13 @@ const buildOpenCodeArgs = ({ extraArgs, inputArgs, resumeSessionId }: BuildSpawn
...extraArgs,
];
-const buildPiArgs = ({ extraArgs, inputArgs, resumeSessionId }: BuildSpawnArgsParams) => [
- ...PI_BASE_ARGS,
- ...(resumeSessionId ? ['--session-id', resumeSessionId] : []),
- ...inputArgs,
- ...extraArgs,
-];
+const buildPiArgs = (_params: BuildSpawnArgsParams): never => {
+ // pi runs exclusively over the RPC transport (PiRpcSession /
+ // createPiRpcAgentHandle). Reaching the legacy json spawn is a bug.
+ throw new Error(
+ 'pi runs over the RPC transport only β€” use PiRpcSession / createPiRpcAgentHandle',
+ );
+};
const buildKimiCodeArgs = ({ extraArgs, inputArgs, resumeSessionId }: BuildSpawnArgsParams) => [
...KIMI_CODE_BASE_ARGS,
@@ -366,7 +367,7 @@ const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals, detached: b
// to a direct signal. Tree-kill via `taskkill` is what the desktop
// controller does for end-user CC, but the CLI's primary use case is
// sandbox + Unix dev terminals, so keep this minimal.
- if (process.platform === 'win32') {
+ if (platform() === 'win32') {
try {
proc.kill(signal);
} catch {
@@ -706,7 +707,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
const initialCumulativeUsage = resumedCodexSession?.cumulativeUsage;
const cliSpawnPlan = await resolveCliSpawnPlan(command, args);
- const detached = process.platform !== 'win32' && (options.detached ?? true);
+ const detached = platform() !== 'win32' && (options.detached ?? true);
const proc = spawn(cliSpawnPlan.command, cliSpawnPlan.args, {
cwd,
detached,
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 54e5248049c..f0ebc49cd82 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -676,6 +676,51 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
return { get, store };
}
+ it.each([
+ { provider: { command: 'pi', type: 'pi' }, expectedOperations: ['op-1', 'op-2'] },
+ { provider: { command: 'claude', type: 'claude-code' }, expectedOperations: ['op-1', 'op-2'] },
+ {
+ provider: { command: 'pi', env: { LOBEHUB_OPERATION_ID: 'user-override' }, type: 'pi' },
+ expectedOperations: ['user-override', 'user-override'],
+ },
+ ] satisfies {
+ provider: HeterogeneousProviderConfig;
+ expectedOperations: (string | undefined)[];
+ }[])(
+ 'preserves each turn identity and user env overrides: $provider',
+ async ({ provider, expectedOperations }) => {
+ for (const operationId of ['op-1', 'op-2']) {
+ await runWithEvents(
+ [
+ () =>
+ ipc.emitStreamEvent('ipc-sess-1', {
+ data: { reason: 'complete' },
+ operationId,
+ type: 'agent_runtime_end',
+ }),
+ ],
+ {
+ params: { heterogeneousProvider: provider, operationId },
+ store: createMockStore({ topicDataMap: {} }),
+ },
+ );
+ }
+
+ const environments = mockStartSession.mock.calls.map(([params]) => params.env);
+ expect(environments).toEqual(
+ expectedOperations.map((operationId) => ({
+ LOBEHUB_AGENT_ID: 'agent-1',
+ ...(operationId ? { LOBEHUB_OPERATION_ID: operationId } : {}),
+ LOBEHUB_TOPIC_ID: 'topic-1',
+ })),
+ );
+ expect(mockSendPrompt.mock.calls.map(([params]) => params.operationId)).toEqual([
+ 'op-1',
+ 'op-2',
+ ]);
+ },
+ );
+
it('releases all IPC subscriptions after a run settles', async () => {
await runWithEvents([ccInit(), ccResult()]);