Open History to see the last commit
1/**
2 * PiRpc — stdio JSONL transport for the Pi coding agent's RPC mode.
3 *
4 * Spawns `pi --mode rpc` and speaks Pi's line-delimited JSON protocol:
5 * requests go to stdin as `{"type": "...", "id": "..."}` records, responses
6 * come back as `{"type": "response", "id": ..., "success": ...}` and are
7 * correlated by `id`; every other stdout record is a session event and is
8 * surfaced on the `events` queue in arrival order.
9 *
10 * Framing follows Pi's spec: LF-delimited only, with a trailing `\r`
11 * stripped. Lines are split manually (never with `readline`, which also
12 * splits on U+2028/U+2029 and would corrupt frames). Records that fail to
13 * parse as JSON are dropped with a debug log rather than failing the
14 * transport, so a chatty extension cannot take the session down.
15 *
16 * Used by `PiAdapterV2` for sessions and by `PiTextGeneration` /
17 * `PiProvider` for ephemeral one-shot processes.
18 */
19import * as Clock from "effect/Clock";
20import * as Deferred from "effect/Deferred";
21import * as Duration from "effect/Duration";
22import * as Effect from "effect/Effect";
23import * as Option from "effect/Option";
24import * as Predicate from "effect/Predicate";
25import * as Queue from "effect/Queue";
26import * as Scope from "effect/Scope";
27import * as Schema from "effect/Schema";
28import * as Stream from "effect/Stream";
29import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
30import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
31import { resolveSpawnCommand } from "@t3tools/shared/shell";
32
33export class PiRpcError extends Schema.TaggedError<PiRpcError>()("PiRpcError", {
34 operation: Schema.String,
35 detail: Schema.optional(Schema.String),
36 cause: Schema.optional(Schema.Defect()),
37}) {
38 override get message(): string {
39 return `Pi RPC ${this.operation} failed${this.detail === undefined ? "" : `: ${this.detail}`}.`;
40 }
41}
42
43export class PiRpcTimeoutError extends Schema.TaggedError<PiRpcTimeoutError>()(
44 "PiRpcTimeoutError",
45 {
46 operation: Schema.String,
47 timeoutMs: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER })),
48 },
49) {
50 override get message(): string {
51 return `Pi RPC ${this.operation} failed: timed out after ${this.timeoutMs}ms.`;
52 }
53}
54
55export type PiRpcRecord = Record<string, unknown>;
56
57export function piRecordField(input: unknown, key: string): unknown {
58 return Predicate.isObject(input) ? input[key] : undefined;
59}
60
61export function piRecordString(input: unknown, key: string): string | undefined {
62 const value = piRecordField(input, key);
63 return Predicate.isString(value) ? value : undefined;
64}
65
66export function piRecordNumber(input: unknown, key: string): number | undefined {
67 const value = piRecordField(input, key);
68 return Predicate.isNumber(value) && Number.isFinite(value) ? value : undefined;
69}
70
71/**
72 * Splits a `provider/model` slug into the two fields `set_model` expects.
73 * Returns null for slugs without a usable separator so callers can reject the
74 * selection instead of silently leaving Pi on its configured default.
75 */
76export function parsePiModelSlug(slug: string): { provider: string; modelId: string } | null {
77 const separator = slug.indexOf("/");
78 if (separator <= 0 || separator === slug.length - 1) return null;
79 return { provider: slug.slice(0, separator), modelId: slug.slice(separator + 1) };
80}
81
82export interface PiRpcSpawnOptions {
83 readonly command: string;
84 readonly args: ReadonlyArray<string>;
85 readonly cwd: string | undefined;
86 readonly env: NodeJS.ProcessEnv;
87}
88
89export interface PiRpcConnection {
90 /** Fire-and-forget write (used for `extension_ui_response`). */
91 readonly send: (record: PiRpcRecord) => Effect.Effect<void, PiRpcError>;
92 /**
93 * Correlated request: assigns an `id`, waits for the matching response
94 * record, and returns its `data` (undefined when the command carries none).
95 * Fails on `success: false`, transport death, or timeout.
96 */
97 readonly request: (
98 record: PiRpcRecord,
99 timeoutMs?: number,
100 ) => Effect.Effect<unknown, PiRpcError | PiRpcTimeoutError>;
101 /**
102 * Session events (every non-response stdout record) in arrival order. The
103 * full queue is exposed so consumers can append order-preserving synthetic
104 * records of their own (see PiAdapterV2's settle probe).
105 */
106 readonly events: Queue.Queue<PiRpcRecord, PiRpcError>;
107 /** Resolves when the process has exited, with its exit code. */
108 readonly exited: Effect.Effect<number, PiRpcError>;
109 /**
110 * Kill the pi process group immediately (SIGTERM, grace, SIGKILL). Used by
111 * Stop-with-restart when the process may be wedged and `abort` cannot be
112 * trusted to land. The transport fails and the session manager respawns a
113 * fresh process on the next turn.
114 */
115 readonly terminate: Effect.Effect<void>;
116}
117
118const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
119const TERMINATION_GRACE = Duration.seconds(1);
120
121interface PendingPiRequest {
122 readonly deferred: Deferred.Deferred<unknown, PiRpcError>;
123}
124
125const MAX_PI_RECORD_CHARS = 8 * 1024 * 1024;
126
127function makeJsonlFramer() {
128 let buffer = "";
129 let dropping = false;
130 return (chunk: string): ReadonlyArray<string> => {
131 const lines: string[] = [];
132 let start = 0;
133 while (start < chunk.length) {
134 const newline = chunk.indexOf("\n", start);
135 const end = newline < 0 ? chunk.length : newline;
136 if (!dropping) {
137 if (buffer.length + end - start > MAX_PI_RECORD_CHARS) {
138 buffer = "";
139 dropping = true;
140 } else {
141 buffer += chunk.slice(start, end);
142 }
143 }
144 if (newline < 0) break;
145 if (!dropping && buffer.length > 0) {
146 lines.push(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
147 }
148 buffer = "";
149 dropping = false;
150 start = newline + 1;
151 }
152 return lines;
153 };
154}
155
156const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
157const decodeJsonLine = Schema.decodeSync(UnknownFromJsonString);
158const encodeJsonLine = Schema.encodeSync(UnknownFromJsonString);
159
160const PI_ERROR_DETAIL_MAX_CHARS = 200;
161
162/**
163 * Bounded, human-readable summary of a failed response's `error` payload.
164 * The untruncated value stays on the error's `cause`, so `message` never
165 * carries unbounded remote text while logs keep something diagnostic.
166 */
167function summarizePiError(error: unknown): string {
168 const text = typeof error === "string" ? error : JSON.stringify(error);
169 if (text === undefined) return "unknown error";
170 return text.length > PI_ERROR_DETAIL_MAX_CHARS
171 ? `${text.slice(0, PI_ERROR_DETAIL_MAX_CHARS)}…`
172 : text;
173}
174
175/**
176 * Stdout closure is not enough to diagnose an early crash: Pi 0.84+ can exit
177 * 1 on import before writing any protocol line. The numeric exit code is
178 * sanitized; stderr stays out of public details because it can carry
179 * credentials or prompt text.
180 */
181function describePiStdoutClosure(exitCode: number | undefined): string {
182 if (exitCode === undefined || !Number.isFinite(exitCode)) {
183 return "pi process closed stdout";
184 }
185 return `pi process exited with code ${exitCode}`;
186}
187
188function parsePiRecord(line: string): PiRpcRecord | undefined {
189 try {
190 const parsed: unknown = decodeJsonLine(line);
191 return Predicate.isObject(parsed) ? parsed : undefined;
192 } catch {
193 return undefined;
194 }
195}
196
197/**
198 * Kill the pi process group: SIGTERM, short grace, then SIGKILL.
199 *
200 * `hasExited` is consulted before each signal. Once the original child is
201 * gone its pid/pgid can be recycled by the OS, so escalating blindly could
202 * deliver SIGKILL to an unrelated process.
203 */
204const terminatePiProcess = (kill: (signal: NodeJS.Signals) => boolean, hasExited: () => boolean) =>
205 Effect.gen(function* () {
206 if (hasExited()) return;
207 if (!kill("SIGTERM")) return;
208 yield* Effect.sleep(TERMINATION_GRACE);
209 if (hasExited()) return;
210 kill("SIGKILL");
211 });
212
213export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpawnOptions) {
214 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
215 const platform = yield* HostProcessPlatform;
216 const scope = yield* Effect.scope;
217
218 const spawnCommand = yield* resolveSpawnCommand(options.command, [...options.args], {
219 env: options.env,
220 }).pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
221 const child = yield* spawner
222 .spawn(
223 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
224 ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
225 env: options.env,
226 extendEnv: false,
227 shell: spawnCommand.shell,
228 detached: platform !== "win32",
229 }),
230 )
231 .pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
232
233 let childExited = false;
234 let diagnosingStdoutClose = false;
235
236 const killProcessGroup = (signal: NodeJS.Signals): boolean => {
237 try {
238 if (platform === "win32") {
239 process.kill(Number(child.pid), signal);
240 } else {
241 process.kill(-Number(child.pid), signal);
242 }
243 return true;
244 } catch {
245 return false;
246 }
247 };
248
249 /** Signal 0 probes liveness without delivering anything. */
250 const hasExited = (): boolean => {
251 if (childExited) return true;
252 try {
253 process.kill(platform === "win32" ? Number(child.pid) : -Number(child.pid), 0);
254 return false;
255 } catch {
256 return true;
257 }
258 };
259
260 /**
261 * Windows has no process groups, so `process.kill` reaches only pi itself
262 * and leaves extension subprocesses running with inherited stdio handles.
263 * `taskkill /T` reaps the whole tree.
264 */
265 const terminateWindowsTree = Effect.gen(function* () {
266 if (hasExited()) return;
267 const taskkill = yield* spawner.spawn(
268 ChildProcess.make("taskkill", ["/PID", String(child.pid), "/T", "/F"]),
269 );
270 yield* taskkill.exitCode;
271 }).pipe(Effect.scoped, Effect.ignore);
272
273 const terminateProcess =
274 platform === "win32" ? terminateWindowsTree : terminatePiProcess(killProcessGroup, hasExited);
275
276 // Registered before any further setup: an interrupt or failure between the
277 // spawn and the rest of this constructor would otherwise leak a detached
278 // pi process with no finalizer to reap it.
279 yield* Scope.addFinalizer(scope, terminateProcess.pipe(Effect.ignore, Effect.uninterruptible));
280
281 const pendingRequests = new Map<string, PendingPiRequest>();
282 const events = yield* Queue.unbounded<PiRpcRecord, PiRpcError>();
283 const outgoing = yield* Queue.unbounded<Uint8Array, PiRpcError>();
284 const transportDown = yield* Deferred.make<never, PiRpcError>();
285 const exitDeferred = yield* Deferred.make<number, PiRpcError>();
286 let nextRequestId = 0;
287
288 const failTransport = (error: PiRpcError) =>
289 Effect.gen(function* () {
290 const claimed = yield* Deferred.fail(transportDown, error);
291 if (!claimed) return;
292 for (const [key, pending] of pendingRequests) {
293 pendingRequests.delete(key);
294 yield* Deferred.fail(pending.deferred, error);
295 }
296 // Closing `outgoing` is what makes `send` non-racy: once the writer is
297 // gone every later offer is refused rather than silently buffered.
298 yield* Queue.fail(outgoing, error);
299 yield* Queue.fail(events, error);
300 });
301
302 const routeRecord = (record: PiRpcRecord) =>
303 Effect.gen(function* () {
304 if (record["type"] === "response" && typeof record["id"] === "string") {
305 const pending = pendingRequests.get(record["id"]);
306 if (pending !== undefined) {
307 pendingRequests.delete(record["id"]);
308 if (record["success"] === true) {
309 yield* Deferred.succeed(pending.deferred, record["data"]);
310 } else {
311 yield* Deferred.fail(
312 pending.deferred,
313 new PiRpcError({
314 operation: String(record["command"] ?? "request"),
315 detail: summarizePiError(record["error"]),
316 ...(record["error"] === undefined ? {} : { cause: record["error"] }),
317 }),
318 );
319 }
320 return;
321 }
322 }
323 yield* Queue.offer(events, record);
324 });
325
326 // Watch exit before the reader so an immediate crash can populate
327 // `exitDeferred` before stdout-close diagnosis runs.
328 yield* child.exitCode.pipe(
329 Effect.matchEffect({
330 onFailure: (cause) =>
331 Deferred.fail(exitDeferred, new PiRpcError({ operation: "exit", cause })),
332 onSuccess: (code) =>
333 Effect.suspend(() => {
334 childExited = true;
335 return Deferred.succeed(exitDeferred, Number(code));
336 }),
337 }),
338 Effect.forkIn(scope),
339 );
340
341 // Reader: decode stdout into LF-delimited JSON records.
342 yield* Effect.gen(function* () {
343 const frame = makeJsonlFramer();
344 yield* child.stdout.pipe(
345 Stream.decodeText(),
346 Stream.runForEach((chunk) =>
347 Effect.gen(function* () {
348 const lines = frame(chunk);
349 for (const line of lines) {
350 const record = parsePiRecord(line);
351 if (record === undefined) {
352 yield* Effect.logDebug("Dropping non-JSON pi stdout line.", {
353 lineLength: line.length,
354 });
355 continue;
356 }
357 yield* routeRecord(record);
358 }
359 }),
360 ),
361 );
362 for (const line of frame("\n")) {
363 const trailing = parsePiRecord(line);
364 if (trailing !== undefined) yield* routeRecord(trailing);
365 }
366 }).pipe(
367 Effect.matchCauseEffect({
368 onFailure: (cause) => failTransport(new PiRpcError({ operation: "read", cause })),
369 onSuccess: () =>
370 Effect.gen(function* () {
371 // Claim the stdout-close path before waiting so a broken stdin
372 // writer cannot replace the exit diagnosis with a write error.
373 diagnosingStdoutClose = true;
374 const polled = yield* Deferred.poll(exitDeferred);
375 const maybeExitCode = Option.isSome(polled)
376 ? yield* polled.value.pipe(
377 Effect.map(Option.some),
378 Effect.orElseSucceed(() => Option.none<number>()),
379 )
380 : yield* Deferred.await(exitDeferred).pipe(
381 Effect.timeoutOption(Duration.millis(250)),
382 // Adapter tests run under TestClock. A planned stdout close
383 // without an exit, for example Stop-with-restart, must not wait
384 // on that clock or the transport never fails.
385 Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),
386 Effect.orElseSucceed(() => Option.none<number>()),
387 );
388 return yield* failTransport(
389 new PiRpcError({
390 operation: "read",
391 detail: describePiStdoutClosure(
392 Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined,
393 ),
394 }),
395 );
396 }),
397 }),
398 Effect.forkIn(scope),
399 );
400
401 // Surface stderr as debug logs; pi reserves stdout for the protocol.
402 yield* child.stderr.pipe(
403 Stream.decodeText(),
404 Stream.runForEach((chunk) =>
405 chunk.trim().length === 0
406 ? Effect.void
407 : // Length only: pi's stderr is unbounded remote output and can carry
408 // credentials or prompt text, so it never enters a log annotation.
409 Effect.logDebug("pi stderr", { stderrLength: chunk.length }),
410 ),
411 Effect.ignore,
412 Effect.forkIn(scope),
413 );
414
415 // Writer starts after the reader so an already-closed stdout can mark
416 // diagnosis before a broken-pipe stdin claims the transport.
417 yield* Stream.fromQueue(outgoing).pipe(
418 Stream.run(child.stdin),
419 Effect.catchCause((cause) =>
420 diagnosingStdoutClose
421 ? Effect.void
422 : failTransport(new PiRpcError({ operation: "write", cause })),
423 ),
424 Effect.forkIn(scope),
425 );
426
427 const send = (record: PiRpcRecord): Effect.Effect<void, PiRpcError> =>
428 Effect.gen(function* () {
429 const accepted = yield* Queue.offer(
430 outgoing,
431 new TextEncoder().encode(`${encodeJsonLine(record)}\n`),
432 );
433 // A refused offer means `failTransport` already closed the queue, so the
434 // write can never land; surface the transport error instead of
435 // reporting a success the caller cannot rely on.
436 if (!accepted) {
437 return yield* Deferred.await(transportDown);
438 }
439 });
440
441 const request = (
442 record: PiRpcRecord,
443 timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
444 ): Effect.Effect<unknown, PiRpcError | PiRpcTimeoutError> =>
445 Effect.gen(function* () {
446 const id = `t3-${nextRequestId++}`;
447 const deferred = yield* Deferred.make<unknown, PiRpcError>();
448 pendingRequests.set(id, { deferred });
449 yield* send({ ...record, id }).pipe(
450 Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),
451 );
452 // Raced against the transport: a death that lands after this request was
453 // registered (or between `send`'s check and its enqueue) would otherwise
454 // leave the caller waiting out the full timeout for a reply that is
455 // never coming.
456 return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(
457 Effect.timeoutOrElse({
458 duration: Duration.millis(timeoutMs),
459 orElse: () =>
460 Effect.fail(
461 new PiRpcTimeoutError({
462 operation: String(record["type"] ?? "request"),
463 timeoutMs,
464 }),
465 ),
466 }),
467 Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),
468 Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),
469 );
470 });
471
472 return {
473 send,
474 request,
475 events,
476 exited: Deferred.await(exitDeferred),
477 terminate: failTransport(
478 new PiRpcError({ operation: "terminate", detail: "pi process was stopped" }),
479 ).pipe(Effect.andThen(terminateProcess), Effect.ignore, Effect.uninterruptible),
480 } satisfies PiRpcConnection;
481});