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