Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PiRpc.ts

485 lines17.7 KB

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 `PiAdapter` 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 }
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 }
54​
55export type PiRpcRecord = Record<string, unknown>;
56​
57export function piRecordField(input: unknown, key: string): unknown {
58 return Predicate.isObject(input) ? input[key] : undefined;
60​
61export function piRecordString(input: unknown, key: string): string | undefined {
62 const value = piRecordField(input, key);
63 return Predicate.isString(value) ? value : undefined;
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;
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) };
81​
82export interface PiRpcSpawnOptions {
83 readonly command: string;
84 readonly args: ReadonlyArray<string>;
85 readonly cwd: string | undefined;
86 readonly env: NodeJS.ProcessEnv;
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 PiAdapter'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>;
117​
118const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
119const TERMINATION_GRACE = Duration.seconds(1);
120​
121interface PendingPiRequest {
122 readonly deferred: Deferred.Deferred<unknown, PiRpcError>;
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 };
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;
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}`;
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 }
196​
197/**
198 * Kill the pi process group: SIGTERM, short grace, then SIGKILL.
199 *
200 * `hasExited` is consulted before each signal. Once the whole group is gone
201 * its pgid can be recycled by the OS, so escalating blindly could deliver
202 * 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 /**
250 * Signal 0 probes liveness without delivering anything. On POSIX the group
251 * is probed even after pi itself exited: extension subprocesses can outlive
252 * it, and a group id is not reused while any member lives.
253 */
254 const hasExited = (): boolean => {
255 if (childExited && platform === "win32") return true;
256 try {
257 process.kill(platform === "win32" ? Number(child.pid) : -Number(child.pid), 0);
258 return false;
259 } catch {
260 return true;
261 }
262 };
263​
264 /**
265 * Windows has no process groups, so `process.kill` reaches only pi itself
266 * and leaves extension subprocesses running with inherited stdio handles.
267 * `taskkill /T` reaps the whole tree.
268 */
269 const terminateWindowsTree = Effect.gen(function* () {
270 if (hasExited()) return;
271 const taskkill = yield* spawner.spawn(
272 ChildProcess.make("taskkill", ["/PID", String(child.pid), "/T", "/F"]),
273 );
274 yield* taskkill.exitCode;
275 }).pipe(Effect.scoped, Effect.ignore);
276​
277 const terminateProcess =
278 platform === "win32" ? terminateWindowsTree : terminatePiProcess(killProcessGroup, hasExited);
279​
280 // Registered before any further setup: an interrupt or failure between the
281 // spawn and the rest of this constructor would otherwise leak a detached
282 // pi process with no finalizer to reap it.
283 yield* Scope.addFinalizer(scope, terminateProcess.pipe(Effect.ignore, Effect.uninterruptible));
284​
285 const pendingRequests = new Map<string, PendingPiRequest>();
286 const events = yield* Queue.unbounded<PiRpcRecord, PiRpcError>();
287 const outgoing = yield* Queue.unbounded<Uint8Array, PiRpcError>();
288 const transportDown = yield* Deferred.make<never, PiRpcError>();
289 const exitDeferred = yield* Deferred.make<number, PiRpcError>();
290 let nextRequestId = 0;
291​
292 const failTransport = (error: PiRpcError) =>
293 Effect.gen(function* () {
294 const claimed = yield* Deferred.fail(transportDown, error);
295 if (!claimed) return;
296 for (const [key, pending] of pendingRequests) {
297 pendingRequests.delete(key);
298 yield* Deferred.fail(pending.deferred, error);
299 }
300 // Closing `outgoing` is what makes `send` non-racy: once the writer is
301 // gone every later offer is refused rather than silently buffered.
302 yield* Queue.fail(outgoing, error);
303 yield* Queue.fail(events, error);
304 });
305​
306 const routeRecord = (record: PiRpcRecord) =>
307 Effect.gen(function* () {
308 if (record["type"] === "response" && typeof record["id"] === "string") {
309 const pending = pendingRequests.get(record["id"]);
310 if (pending !== undefined) {
311 pendingRequests.delete(record["id"]);
312 if (record["success"] === true) {
313 yield* Deferred.succeed(pending.deferred, record["data"]);
314 } else {
315 yield* Deferred.fail(
316 pending.deferred,
317 new PiRpcError({
318 operation: String(record["command"] ?? "request"),
319 detail: summarizePiError(record["error"]),
320 ...(record["error"] === undefined ? {} : { cause: record["error"] }),
321 }),
322 );
323 }
324 return;
325 }
326 }
327 yield* Queue.offer(events, record);
328 });
329​
330 // Watch exit before the reader so an immediate crash can populate
331 // `exitDeferred` before stdout-close diagnosis runs.
332 yield* child.exitCode.pipe(
333 Effect.matchEffect({
334 onFailure: (cause) =>
335 Deferred.fail(exitDeferred, new PiRpcError({ operation: "exit", cause })),
336 onSuccess: (code) =>
337 Effect.suspend(() => {
338 childExited = true;
339 return Deferred.succeed(exitDeferred, Number(code));
340 }),
341 }),
342 Effect.forkIn(scope),
343 );
344​
345 // Reader: decode stdout into LF-delimited JSON records.
346 yield* Effect.gen(function* () {
347 const frame = makeJsonlFramer();
348 yield* child.stdout.pipe(
349 Stream.decodeText(),
350 Stream.runForEach((chunk) =>
351 Effect.gen(function* () {
352 const lines = frame(chunk);
353 for (const line of lines) {
354 const record = parsePiRecord(line);
355 if (record === undefined) {
356 yield* Effect.logDebug("Dropping non-JSON pi stdout line.", {
357 lineLength: line.length,
358 });
359 continue;
360 }
361 yield* routeRecord(record);
362 }
363 }),
364 ),
365 );
366 for (const line of frame("\n")) {
367 const trailing = parsePiRecord(line);
368 if (trailing !== undefined) yield* routeRecord(trailing);
369 }
370 }).pipe(
371 Effect.matchCauseEffect({
372 onFailure: (cause) => failTransport(new PiRpcError({ operation: "read", cause })),
373 onSuccess: () =>
374 Effect.gen(function* () {
375 // Claim the stdout-close path before waiting so a broken stdin
376 // writer cannot replace the exit diagnosis with a write error.
377 diagnosingStdoutClose = true;
378 const polled = yield* Deferred.poll(exitDeferred);
379 const maybeExitCode = Option.isSome(polled)
380 ? yield* polled.value.pipe(
381 Effect.map(Option.some),
382 Effect.orElseSucceed(() => Option.none<number>()),
383 )
384 : yield* Deferred.await(exitDeferred).pipe(
385 Effect.timeoutOption(Duration.millis(250)),
386 // Adapter tests run under TestClock. A planned stdout close
387 // without an exit, for example Stop-with-restart, must not wait
388 // on that clock or the transport never fails.
389 Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),
390 Effect.orElseSucceed(() => Option.none<number>()),
391 );
392 return yield* failTransport(
393 new PiRpcError({
394 operation: "read",
395 detail: describePiStdoutClosure(
396 Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined,
397 ),
398 }),
399 );
400 }),
401 }),
402 Effect.forkIn(scope),
403 );
404​
405 // Surface stderr as debug logs; pi reserves stdout for the protocol.
406 yield* child.stderr.pipe(
407 Stream.decodeText(),
408 Stream.runForEach((chunk) =>
409 chunk.trim().length === 0
410 ? Effect.void
411 : // Length only: pi's stderr is unbounded remote output and can carry
412 // credentials or prompt text, so it never enters a log annotation.
413 Effect.logDebug("pi stderr", { stderrLength: chunk.length }),
414 ),
415 Effect.ignore,
416 Effect.forkIn(scope),
417 );
418​
419 // Writer starts after the reader so an already-closed stdout can mark
420 // diagnosis before a broken-pipe stdin claims the transport.
421 yield* Stream.fromQueue(outgoing).pipe(
422 Stream.run(child.stdin),
423 Effect.catchCause((cause) =>
424 diagnosingStdoutClose
425 ? Effect.void
426 : failTransport(new PiRpcError({ operation: "write", cause })),
427 ),
428 Effect.forkIn(scope),
429 );
430​
431 const send = (record: PiRpcRecord): Effect.Effect<void, PiRpcError> =>
432 Effect.gen(function* () {
433 const accepted = yield* Queue.offer(
434 outgoing,
435 new TextEncoder().encode(`${encodeJsonLine(record)}\n`),
436 );
437 // A refused offer means `failTransport` already closed the queue, so the
438 // write can never land; surface the transport error instead of
439 // reporting a success the caller cannot rely on.
440 if (!accepted) {
441 return yield* Deferred.await(transportDown);
442 }
443 });
444​
445 const request = (
446 record: PiRpcRecord,
447 timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
448 ): Effect.Effect<unknown, PiRpcError | PiRpcTimeoutError> =>
449 Effect.gen(function* () {
450 const id = `t3-${nextRequestId++}`;
451 const deferred = yield* Deferred.make<unknown, PiRpcError>();
452 pendingRequests.set(id, { deferred });
453 yield* send({ ...record, id }).pipe(
454 Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),
455 );
456 // Raced against the transport: a death that lands after this request was
457 // registered (or between `send`'s check and its enqueue) would otherwise
458 // leave the caller waiting out the full timeout for a reply that is
459 // never coming.
460 return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(
461 Effect.timeoutOrElse({
462 duration: Duration.millis(timeoutMs),
463 orElse: () =>
464 Effect.fail(
465 new PiRpcTimeoutError({
466 operation: String(record["type"] ?? "request"),
467 timeoutMs,
468 }),
469 ),
470 }),
471 Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),
472 Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),
473 );
474 });
475​
476 return {
477 send,
478 request,
479 events,
480 exited: Deferred.await(exitDeferred),
481 terminate: failTransport(
482 new PiRpcError({ operation: "terminate", detail: "pi process was stopped" }),
483 ).pipe(Effect.andThen(terminateProcess), Effect.ignore, Effect.uninterruptible),
484 } satisfies PiRpcConnection;
485});