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