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

rpc.ts

438 lines15.3 KB

1/**
2 * Framing follows Pi's spec: LF-delimited only, with a trailing `\r` stripped.
3 * Lines are split manually (never with `readline`, which also splits on
4 * U+2028/U+2029 and would corrupt frames).
5 */
6import * as Clock from "effect/Clock";
7import * as Deferred from "effect/Deferred";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Predicate from "effect/Predicate";
12import * as Queue from "effect/Queue";
13import * as Scope from "effect/Scope";
14import * as Schema from "effect/Schema";
15import * as Stream from "effect/Stream";
16import * as ChildProcess from "effect/process/ChildProcess";
17import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18import * as HostProcess from "@t3tools/shared/HostProcess";
19import { resolveSpawnCommand } from "@t3tools/shared/shell";
20import {
21 MAX_TOOL_OUTPUT_IMAGES,
22 MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH,
23} from "@t3tools/shared/toolOutput";
24​
25import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
26​
27export class PiRpcError extends Schema.TaggedError<PiRpcError>()("PiRpcError", {
28 operation: Schema.String,
29 detail: Schema.optional(Schema.String),
30 cause: Schema.optional(Schema.Defect()),
31}) {
32 override get message(): string {
33 return `Pi RPC ${this.operation} failed${this.detail === undefined ? "" : `: ${this.detail}`}.`;
34 }
36​
37export class PiRpcTimeoutError extends Schema.TaggedError<PiRpcTimeoutError>()(
38 "PiRpcTimeoutError",
39 {
40 operation: Schema.String,
41 timeoutMs: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER })),
42 },
43) {
44 override get message(): string {
45 return `Pi RPC ${this.operation} failed: timed out after ${this.timeoutMs}ms.`;
46 }
48​
49export type PiRpcRecord = Record<string, unknown>;
50​
51export function piRecordField(input: unknown, key: string): unknown {
52 return Predicate.isObject(input) ? input[key] : undefined;
54​
55export function piRecordString(input: unknown, key: string): string | undefined {
56 const value = piRecordField(input, key);
57 return Predicate.isString(value) ? value : undefined;
59​
60export function piRecordNumber(input: unknown, key: string): number | undefined {
61 const value = piRecordField(input, key);
62 return Predicate.isNumber(value) && Number.isFinite(value) ? value : undefined;
64​
65export function parsePiModelSlug(slug: string): { provider: string; modelId: string } | null {
66 const separator = slug.indexOf("/");
67 if (separator <= 0 || separator === slug.length - 1) return null;
68 return { provider: slug.slice(0, separator), modelId: slug.slice(separator + 1) };
70​
71export interface PiRpcSpawnOptions {
72 readonly command: string;
73 readonly args: ReadonlyArray<string>;
74 readonly cwd: string | undefined;
75 readonly env: NodeJS.ProcessEnv;
77​
78export interface PiRpcConnection {
79 readonly send: (record: PiRpcRecord) => Effect.Effect<void, PiRpcError>;
80 readonly request: (
81 record: PiRpcRecord,
82 timeoutMs?: number,
83 ) => Effect.Effect<unknown, PiRpcError | PiRpcTimeoutError>;
84 readonly events: Queue.Queue<PiRpcRecord, PiRpcError>;
85 readonly exited: Effect.Effect<number, PiRpcError>;
86 readonly terminate: Effect.Effect<void>;
88​
89const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
90const TERMINATION_GRACE = Duration.seconds(1);
91​
92interface PendingPiRequest {
93 readonly deferred: Deferred.Deferred<unknown, PiRpcError>;
95​
96// MCP completion events carry images in both model content and the script
97// CallToolResult. Allow the shared image budget twice, plus bounded JSON/text
98// overhead, before dropping an extension's oversized record.
99const MAX_PI_RECORD_CHARS =
100 2 * MAX_TOOL_OUTPUT_IMAGES * MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH + 8 * 1024 * 1024;
101​
102function makeJsonlFramer() {
103 let buffer = "";
104 let dropping = false;
105 return (chunk: string): ReadonlyArray<string> => {
106 const lines: string[] = [];
107 let start = 0;
108 while (start < chunk.length) {
109 const newline = chunk.indexOf("\n", start);
110 const end = newline < 0 ? chunk.length : newline;
111 if (!dropping) {
112 if (buffer.length + end - start > MAX_PI_RECORD_CHARS) {
113 buffer = "";
114 dropping = true;
115 } else {
116 buffer += chunk.slice(start, end);
117 }
118 }
119 if (newline < 0) break;
120 if (!dropping && buffer.length > 0) {
121 lines.push(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
122 }
123 buffer = "";
124 dropping = false;
125 start = newline + 1;
126 }
127 return lines;
128 };
130​
131const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
132const decodeJsonLine = Schema.decodeSync(UnknownFromJsonString);
133const encodeJsonLine = Schema.encodeSync(UnknownFromJsonString);
134​
135const PI_ERROR_DETAIL_MAX_CHARS = 200;
136​
137function summarizePiError(error: unknown): string {
138 const text = typeof error === "string" ? error : JSON.stringify(error);
139 if (text === undefined) return "unknown error";
140 return text.length > PI_ERROR_DETAIL_MAX_CHARS
141 ? `${text.slice(0, PI_ERROR_DETAIL_MAX_CHARS)}…`
142 : text;
144​
145/**
146 * Stdout closure is not enough to diagnose an early crash: Pi 0.84+ can exit 1
147 * on import before writing any protocol line.
148 */
149function describePiStdoutClosure(exitCode: number | undefined): string {
150 if (exitCode === undefined || !Number.isFinite(exitCode)) {
151 return "pi process closed stdout";
152 }
153 return `pi process exited with code ${exitCode}`;
155​
156function parsePiRecord(line: string): PiRpcRecord | undefined {
157 try {
158 const parsed: unknown = decodeJsonLine(line);
159 return Predicate.isObject(parsed) ? parsed : undefined;
160 } catch {
161 return undefined;
162 }
164​
165/**
166 * `hasExited` is consulted before each signal. Once the original child is
167 * gone its pid/pgid can be recycled by the OS, so escalating blindly could
168 * deliver SIGKILL to an unrelated process.
169 */
170const terminatePiProcess = Effect.fn("PiRpc.terminatePiProcess")(function* (
171 kill: (signal: NodeJS.Signals) => boolean,
172 hasExited: () => boolean,
173) {
174 if (hasExited()) return;
175 if (!kill("SIGTERM")) return;
176 yield* Effect.sleep(TERMINATION_GRACE);
177 if (hasExited()) return;
178 kill("SIGKILL");
179});
180​
181export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpawnOptions) {
182 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
183 const platform = yield* HostProcess.Platform;
184 const scope = yield* Effect.scope;
185​
186 const spawnCommand = yield* resolveSpawnCommand(options.command, [...options.args], {
187 env: options.env,
188 }).pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
189 const child = yield* spawner
190 .spawn(
191 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
192 ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
193 env: options.env,
194 extendEnv: false,
195 shell: spawnCommand.shell,
196 detached: platform !== "win32",
197 }),
198 )
199 .pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
200​
201 let childExited = false;
202 let diagnosingStdoutClose = false;
203​
204 const killProcessGroup = (signal: NodeJS.Signals): boolean => {
205 try {
206 if (platform === "win32") {
207 process.kill(Number(child.pid), signal);
208 } else {
209 signalProcessGroup(Number(child.pid), signal);
210 }
211 return true;
212 } catch {
213 return false;
214 }
215 };
216​
217 const hasExited = (): boolean => {
218 if (childExited) return true;
219 try {
220 if (platform === "win32") process.kill(Number(child.pid), 0);
221 else signalProcessGroup(Number(child.pid), 0);
222 return false;
223 } catch {
224 return true;
225 }
226 };
227​
228 /**
229 * Windows has no process groups, so `process.kill` reaches only pi itself
230 * and leaves extension subprocesses running with inherited stdio handles.
231 * `taskkill /T` reaps the whole tree.
232 */
233 const terminateWindowsTree = Effect.gen(function* () {
234 if (hasExited()) return;
235 const taskkill = yield* spawner.spawn(
236 ChildProcess.make("taskkill", ["/PID", String(child.pid), "/T", "/F"]),
237 );
238 yield* taskkill.exitCode;
239 }).pipe(Effect.scoped, Effect.ignore);
240​
241 const terminateProcess =
242 platform === "win32" ? terminateWindowsTree : terminatePiProcess(killProcessGroup, hasExited);
243​
244 // Registered before any further setup: an interrupt or failure between the
245 // spawn and the rest of this constructor would otherwise leak a detached
246 // pi process with no finalizer to reap it.
247 yield* Scope.addFinalizer(scope, terminateProcess.pipe(Effect.ignore, Effect.uninterruptible));
248​
249 const pendingRequests = new Map<string, PendingPiRequest>();
250 const events = yield* Queue.unbounded<PiRpcRecord, PiRpcError>();
251 const outgoing = yield* Queue.unbounded<Uint8Array, PiRpcError>();
252 const transportDown = yield* Deferred.make<never, PiRpcError>();
253 const exitDeferred = yield* Deferred.make<number, PiRpcError>();
254 let nextRequestId = 0;
255​
256 const failTransport = Effect.fn("PiRpc.failTransport")(function* (error: PiRpcError) {
257 const claimed = yield* Deferred.fail(transportDown, error);
258 if (!claimed) return;
259 for (const [key, pending] of pendingRequests) {
260 pendingRequests.delete(key);
261 yield* Deferred.fail(pending.deferred, error);
262 }
263 yield* Queue.fail(outgoing, error);
264 yield* Queue.fail(events, error);
265 });
266​
267 const routeRecord =
268 /* Protocol records and writes include streaming deltas; avoid a span per record. */
269 Effect.fnUntraced(function* (record: PiRpcRecord) {
270 if (record["type"] === "response" && typeof record["id"] === "string") {
271 const pending = pendingRequests.get(record["id"]);
272 if (pending !== undefined) {
273 pendingRequests.delete(record["id"]);
274 if (record["success"] === true) {
275 yield* Deferred.succeed(pending.deferred, record["data"]);
276 } else {
277 yield* Deferred.fail(
278 pending.deferred,
279 new PiRpcError({
280 operation: String(record["command"] ?? "request"),
281 detail: summarizePiError(record["error"]),
282 ...(record["error"] === undefined ? {} : { cause: record["error"] }),
283 }),
284 );
285 }
286 return;
287 }
288 }
289 yield* Queue.offer(events, record);
290 });
291​
292 // Watch exit before the reader so an immediate crash can populate
293 // `exitDeferred` before stdout-close diagnosis runs.
294 yield* child.exitCode.pipe(
295 Effect.matchEffect({
296 onFailure: (cause) =>
297 Deferred.fail(exitDeferred, new PiRpcError({ operation: "exit", cause })),
298 onSuccess: (code) =>
299 Effect.suspend(() => {
300 childExited = true;
301 return Deferred.succeed(exitDeferred, Number(code));
302 }),
303 }),
304 Effect.forkIn(scope),
305 );
306​
307 yield* Effect.gen(function* () {
308 const frame = makeJsonlFramer();
309 yield* child.stdout.pipe(
310 Stream.decodeText(),
311 Stream.runForEach((chunk) =>
312 Effect.gen(function* () {
313 const lines = frame(chunk);
314 for (const line of lines) {
315 const record = parsePiRecord(line);
316 if (record === undefined) {
317 yield* Effect.logDebug("Dropping non-JSON pi stdout line.", {
318 lineLength: line.length,
319 });
320 continue;
321 }
322 yield* routeRecord(record);
323 }
324 }),
325 ),
326 );
327 for (const line of frame("\n")) {
328 const trailing = parsePiRecord(line);
329 if (trailing !== undefined) yield* routeRecord(trailing);
330 }
331 }).pipe(
332 Effect.matchCauseEffect({
333 onFailure: (cause) => failTransport(new PiRpcError({ operation: "read", cause })),
334 onSuccess: () =>
335 Effect.gen(function* () {
336 // Claim the stdout-close path before waiting so a broken stdin
337 // writer cannot replace the exit diagnosis with a write error.
338 diagnosingStdoutClose = true;
339 const polled = yield* Deferred.poll(exitDeferred);
340 const maybeExitCode = Option.isSome(polled)
341 ? yield* polled.value.pipe(
342 Effect.map(Option.some),
343 Effect.orElseSucceed(() => Option.none<number>()),
344 )
345 : yield* Deferred.await(exitDeferred).pipe(
346 Effect.timeoutOption(Duration.millis(250)),
347 // Adapter tests run under TestClock. A planned stdout close
348 // without an exit, for example Stop-with-restart, must not wait
349 // on that clock or the transport never fails.
350 Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),
351 Effect.orElseSucceed(() => Option.none<number>()),
352 );
353 return yield* failTransport(
354 new PiRpcError({
355 operation: "read",
356 detail: describePiStdoutClosure(
357 Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined,
358 ),
359 }),
360 );
361 }),
362 }),
363 Effect.forkIn(scope),
364 );
365​
366 yield* child.stderr.pipe(
367 Stream.decodeText(),
368 Stream.runForEach((chunk) =>
369 chunk.trim().length === 0
370 ? Effect.void
371 : // Length only: pi's stderr is unbounded remote output and can carry
372 // credentials or prompt text, so it never enters a log annotation.
373 Effect.logDebug("pi stderr", { stderrLength: chunk.length }),
374 ),
375 Effect.ignore,
376 Effect.forkIn(scope),
377 );
378​
379 // Writer starts after the reader so an already-closed stdout can mark
380 // diagnosis before a broken-pipe stdin claims the transport.
381 yield* Stream.fromQueue(outgoing).pipe(
382 Stream.run(child.stdin),
383 Effect.catchCause((cause) =>
384 diagnosingStdoutClose
385 ? Effect.void
386 : failTransport(new PiRpcError({ operation: "write", cause })),
387 ),
388 Effect.forkIn(scope),
389 );
390​
391 const send =
392 /* Protocol records and writes include streaming deltas; avoid a span per record. */
393 Effect.fnUntraced(function* (record: PiRpcRecord): Effect.fn.Return<void, PiRpcError> {
394 const accepted = yield* Queue.offer(
395 outgoing,
396 new TextEncoder().encode(`${encodeJsonLine(record)}\n`),
397 );
398 if (!accepted) {
399 return yield* Deferred.await(transportDown);
400 }
401 });
402​
403 const request = Effect.fn("PiRpc.request")(function* (
404 record: PiRpcRecord,
405 timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
406 ): Effect.fn.Return<unknown, PiRpcError | PiRpcTimeoutError> {
407 const id = `t3-${nextRequestId++}`;
408 const deferred = yield* Deferred.make<unknown, PiRpcError>();
409 pendingRequests.set(id, { deferred });
410 yield* send({ ...record, id }).pipe(
411 Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),
412 );
413 return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(
414 Effect.timeoutOrElse({
415 duration: Duration.millis(timeoutMs),
416 orElse: () =>
417 Effect.fail(
418 new PiRpcTimeoutError({
419 operation: String(record["type"] ?? "request"),
420 timeoutMs,
421 }),
422 ),
423 }),
424 Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),
425 Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),
426 );
427 });
428​
429 return {
430 send,
431 request,
432 events,
433 exited: Deferred.await(exitDeferred),
434 terminate: failTransport(
435 new PiRpcError({ operation: "terminate", detail: "pi process was stopped" }),
436 ).pipe(Effect.andThen(terminateProcess), Effect.ignore, Effect.uninterruptible),
437 } satisfies PiRpcConnection;
438});