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

rpc.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 `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 * as ChildProcess from "effect/process/ChildProcess";
30import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
31import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
32import { resolveSpawnCommand } from "@t3tools/shared/shell";
33​
34import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
35​
36export class PiRpcError extends Schema.TaggedError<PiRpcError>()("PiRpcError", {
37 operation: Schema.String,
38 detail: Schema.optional(Schema.String),
39 cause: Schema.optional(Schema.Defect()),
40}) {
41 override get message(): string {
42 return `Pi RPC ${this.operation} failed${this.detail === undefined ? "" : `: ${this.detail}`}.`;
43 }
45​
46export class PiRpcTimeoutError extends Schema.TaggedError<PiRpcTimeoutError>()(
47 "PiRpcTimeoutError",
48 {
49 operation: Schema.String,
50 timeoutMs: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER })),
51 },
52) {
53 override get message(): string {
54 return `Pi RPC ${this.operation} failed: timed out after ${this.timeoutMs}ms.`;
55 }
57​
58export type PiRpcRecord = Record<string, unknown>;
59​
60export function piRecordField(input: unknown, key: string): unknown {
61 return Predicate.isObject(input) ? input[key] : undefined;
63​
64export function piRecordString(input: unknown, key: string): string | undefined {
65 const value = piRecordField(input, key);
66 return Predicate.isString(value) ? value : undefined;
68​
69export function piRecordNumber(input: unknown, key: string): number | undefined {
70 const value = piRecordField(input, key);
71 return Predicate.isNumber(value) && Number.isFinite(value) ? value : undefined;
73​
74/**
75 * Splits a `provider/model` slug into the two fields `set_model` expects.
76 * Returns null for slugs without a usable separator so callers can reject the
77 * selection instead of silently leaving Pi on its configured default.
78 */
79export function parsePiModelSlug(slug: string): { provider: string; modelId: string } | null {
80 const separator = slug.indexOf("/");
81 if (separator <= 0 || separator === slug.length - 1) return null;
82 return { provider: slug.slice(0, separator), modelId: slug.slice(separator + 1) };
84​
85export interface PiRpcSpawnOptions {
86 readonly command: string;
87 readonly args: ReadonlyArray<string>;
88 readonly cwd: string | undefined;
89 readonly env: NodeJS.ProcessEnv;
91​
92export interface PiRpcConnection {
93 /** Fire-and-forget write (used for `extension_ui_response`). */
94 readonly send: (record: PiRpcRecord) => Effect.Effect<void, PiRpcError>;
95 /**
96 * Correlated request: assigns an `id`, waits for the matching response
97 * record, and returns its `data` (undefined when the command carries none).
98 * Fails on `success: false`, transport death, or timeout.
99 */
100 readonly request: (
101 record: PiRpcRecord,
102 timeoutMs?: number,
103 ) => Effect.Effect<unknown, PiRpcError | PiRpcTimeoutError>;
104 /**
105 * Session events (every non-response stdout record) in arrival order. The
106 * full queue is exposed so consumers can append order-preserving synthetic
107 * records of their own (see PiAdapterV2's settle probe).
108 */
109 readonly events: Queue.Queue<PiRpcRecord, PiRpcError>;
110 /** Resolves when the process has exited, with its exit code. */
111 readonly exited: Effect.Effect<number, PiRpcError>;
112 /**
113 * Kill the pi process group immediately (SIGTERM, grace, SIGKILL). Used by
114 * Stop-with-restart when the process may be wedged and `abort` cannot be
115 * trusted to land. The transport fails and the session manager respawns a
116 * fresh process on the next turn.
117 */
118 readonly terminate: Effect.Effect<void>;
120​
121const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
122const TERMINATION_GRACE = Duration.seconds(1);
123​
124interface PendingPiRequest {
125 readonly deferred: Deferred.Deferred<unknown, PiRpcError>;
127​
128const MAX_PI_RECORD_CHARS = 8 * 1024 * 1024;
129​
130function makeJsonlFramer() {
131 let buffer = "";
132 let dropping = false;
133 return (chunk: string): ReadonlyArray<string> => {
134 const lines: string[] = [];
135 let start = 0;
136 while (start < chunk.length) {
137 const newline = chunk.indexOf("\n", start);
138 const end = newline < 0 ? chunk.length : newline;
139 if (!dropping) {
140 if (buffer.length + end - start > MAX_PI_RECORD_CHARS) {
141 buffer = "";
142 dropping = true;
143 } else {
144 buffer += chunk.slice(start, end);
145 }
146 }
147 if (newline < 0) break;
148 if (!dropping && buffer.length > 0) {
149 lines.push(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
150 }
151 buffer = "";
152 dropping = false;
153 start = newline + 1;
154 }
155 return lines;
156 };
158​
159const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
160const decodeJsonLine = Schema.decodeSync(UnknownFromJsonString);
161const encodeJsonLine = Schema.encodeSync(UnknownFromJsonString);
162​
163const PI_ERROR_DETAIL_MAX_CHARS = 200;
164​
165/**
166 * Bounded, human-readable summary of a failed response's `error` payload.
167 * The untruncated value stays on the error's `cause`, so `message` never
168 * carries unbounded remote text while logs keep something diagnostic.
169 */
170function summarizePiError(error: unknown): string {
171 const text = typeof error === "string" ? error : JSON.stringify(error);
172 if (text === undefined) return "unknown error";
173 return text.length > PI_ERROR_DETAIL_MAX_CHARS
174 ? `${text.slice(0, PI_ERROR_DETAIL_MAX_CHARS)}…`
175 : text;
177​
178/**
179 * Stdout closure is not enough to diagnose an early crash: Pi 0.84+ can exit
180 * 1 on import before writing any protocol line. The numeric exit code is
181 * sanitized; stderr stays out of public details because it can carry
182 * credentials or prompt text.
183 */
184function describePiStdoutClosure(exitCode: number | undefined): string {
185 if (exitCode === undefined || !Number.isFinite(exitCode)) {
186 return "pi process closed stdout";
187 }
188 return `pi process exited with code ${exitCode}`;
190​
191function parsePiRecord(line: string): PiRpcRecord | undefined {
192 try {
193 const parsed: unknown = decodeJsonLine(line);
194 return Predicate.isObject(parsed) ? parsed : undefined;
195 } catch {
196 return undefined;
197 }
199​
200/**
201 * Kill the pi process group: SIGTERM, short grace, then SIGKILL.
202 *
203 * `hasExited` is consulted before each signal. Once the original child is
204 * gone its pid/pgid can be recycled by the OS, so escalating blindly could
205 * deliver SIGKILL to an unrelated process.
206 */
207const terminatePiProcess = (kill: (signal: NodeJS.Signals) => boolean, hasExited: () => boolean) =>
208 Effect.gen(function* () {
209 if (hasExited()) return;
210 if (!kill("SIGTERM")) return;
211 yield* Effect.sleep(TERMINATION_GRACE);
212 if (hasExited()) return;
213 kill("SIGKILL");
214 });
215​
216export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpawnOptions) {
217 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
218 const platform = yield* HostProcessPlatform;
219 const scope = yield* Effect.scope;
220​
221 const spawnCommand = yield* resolveSpawnCommand(options.command, [...options.args], {
222 env: options.env,
223 }).pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
224 const child = yield* spawner
225 .spawn(
226 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
227 ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
228 env: options.env,
229 extendEnv: false,
230 shell: spawnCommand.shell,
231 detached: platform !== "win32",
232 }),
233 )
234 .pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
235​
236 let childExited = false;
237 let diagnosingStdoutClose = false;
238​
239 const killProcessGroup = (signal: NodeJS.Signals): boolean => {
240 try {
241 if (platform === "win32") {
242 process.kill(Number(child.pid), signal);
243 } else {
244 signalProcessGroup(Number(child.pid), signal);
245 }
246 return true;
247 } catch {
248 return false;
249 }
250 };
251​
252 /** Signal 0 probes liveness without delivering anything. */
253 const hasExited = (): boolean => {
254 if (childExited) return true;
255 try {
256 if (platform === "win32") process.kill(Number(child.pid), 0);
257 else signalProcessGroup(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});