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

rpc.ts

436 lines15.3 KB

1// Pi frames are LF-delimited with trailing CR stripped; readline also splits U+2028/U+2029 and corrupts them.
2import * as Clock from "effect/Clock";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Option from "effect/Option";
7import * as Predicate from "effect/Predicate";
8import * as Queue from "effect/Queue";
9import * as Scope from "effect/Scope";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import * as ChildProcess from "effect/process/ChildProcess";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import { resolveSpawnCommand } from "@t3tools/shared/shell";
16import {
17 MAX_TOOL_OUTPUT_IMAGES,
18 MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH,
19} from "@t3tools/shared/toolOutput";
20​
21import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
22​
23export class PiRpcError extends Schema.TaggedError<PiRpcError>()("PiRpcError", {
24 operation: Schema.String,
25 detail: Schema.optional(Schema.String),
26 cause: Schema.optional(Schema.Defect()),
27}) {
28 override get message(): string {
29 return `Pi RPC ${this.operation} failed${this.detail === undefined ? "" : `: ${this.detail}`}.`;
30 }
32​
33export class PiRpcTimeoutError extends Schema.TaggedError<PiRpcTimeoutError>()(
34 "PiRpcTimeoutError",
35 {
36 operation: Schema.String,
37 timeoutMs: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER })),
38 },
39) {
40 override get message(): string {
41 return `Pi RPC ${this.operation} failed: timed out after ${this.timeoutMs}ms.`;
42 }
44​
45export type PiRpcRecord = Record<string, unknown>;
46​
47export function piRecordField(input: unknown, key: string): unknown {
48 return Predicate.isObject(input) ? input[key] : undefined;
50​
51export function piRecordString(input: unknown, key: string): string | undefined {
52 const value = piRecordField(input, key);
53 return Predicate.isString(value) ? value : undefined;
55​
56export function piRecordNumber(input: unknown, key: string): number | undefined {
57 const value = piRecordField(input, key);
58 return Predicate.isNumber(value) && Number.isFinite(value) ? value : undefined;
60​
61export function parsePiModelSlug(slug: string): { provider: string; modelId: string } | null {
62 const separator = slug.indexOf("/");
63 if (separator <= 0 || separator === slug.length - 1) return null;
64 return { provider: slug.slice(0, separator), modelId: slug.slice(separator + 1) };
66​
67export interface PiRpcSpawnOptions {
68 readonly command: string;
69 readonly args: ReadonlyArray<string>;
70 readonly cwd: string | undefined;
71 readonly env: NodeJS.ProcessEnv;
73​
74export interface PiRpcConnection {
75 readonly send: (record: PiRpcRecord) => Effect.Effect<void, PiRpcError>;
76 readonly request: (
77 record: PiRpcRecord,
78 timeoutMs?: number,
79 ) => Effect.Effect<unknown, PiRpcError | PiRpcTimeoutError>;
80 readonly events: Queue.Queue<PiRpcRecord, PiRpcError>;
81 readonly exited: Effect.Effect<number, PiRpcError>;
82 readonly terminate: Effect.Effect<void>;
84​
85const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
86const TERMINATION_GRACE = Duration.seconds(1);
87​
88interface PendingPiRequest {
89 readonly deferred: Deferred.Deferred<unknown, PiRpcError>;
91​
92// MCP duplicates images in model content and CallToolResult; budget both plus bounded overhead.
93const MAX_PI_RECORD_CHARS =
94 2 * MAX_TOOL_OUTPUT_IMAGES * MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH + 8 * 1024 * 1024;
95​
96function makeJsonlFramer() {
97 let buffer = "";
98 let dropping = false;
99 return (chunk: string) => {
100 const lines: string[] = [];
101 const droppedLengths: number[] = [];
102 let start = 0;
103 while (start < chunk.length) {
104 const newline = chunk.indexOf("\n", start);
105 const end = newline < 0 ? chunk.length : newline;
106 if (!dropping) {
107 if (buffer.length + end - start > MAX_PI_RECORD_CHARS) {
108 droppedLengths.push(buffer.length + end - start);
109 buffer = "";
110 dropping = true;
111 } else {
112 buffer += chunk.slice(start, end);
113 }
114 }
115 if (newline < 0) break;
116 if (!dropping && buffer.length > 0) {
117 lines.push(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
118 }
119 buffer = "";
120 dropping = false;
121 start = newline + 1;
122 }
123 return { lines, droppedLengths };
124 };
126​
127// Report the observed length before LF arrives; an unterminated response can time out first.
128const logDroppedPiRecords = (droppedLengths: ReadonlyArray<number>) =>
129 Effect.forEach(
130 droppedLengths,
131 (recordLength) =>
132 Effect.logWarning("Dropping oversized pi stdout record.", {
133 recordLength,
134 maxRecordLength: MAX_PI_RECORD_CHARS,
135 }),
136 { discard: true },
137 );
138​
139const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
140const decodeJsonLine = Schema.decodeSync(UnknownFromJsonString);
141const encodeJsonLine = Schema.encodeSync(UnknownFromJsonString);
142​
143const PI_ERROR_DETAIL_MAX_CHARS = 200;
144​
145function summarizePiError(error: unknown): string {
146 const text = typeof error === "string" ? error : JSON.stringify(error);
147 if (text === undefined) return "unknown error";
148 return text.length > PI_ERROR_DETAIL_MAX_CHARS
149 ? `${text.slice(0, PI_ERROR_DETAIL_MAX_CHARS)}…`
150 : text;
152​
153// Pi 0.84+ may exit 1 during import without any protocol output.
154function describePiStdoutClosure(exitCode: number | undefined): string {
155 if (exitCode === undefined || !Number.isFinite(exitCode)) {
156 return "pi process closed stdout";
157 }
158 return `pi process exited with code ${exitCode}`;
160​
161function parsePiRecord(line: string): PiRpcRecord | undefined {
162 try {
163 const parsed: unknown = decodeJsonLine(line);
164 return Predicate.isObject(parsed) ? parsed : undefined;
165 } catch {
166 return undefined;
167 }
169​
170/**
171 * `hasExited` is consulted before each signal. Once the original child is
172 * gone its pid/pgid can be recycled by the OS, so escalating blindly could
173 * deliver SIGKILL to an unrelated process.
174 */
175const terminatePiProcess = Effect.fn("PiRpc.terminatePiProcess")(function* (
176 kill: (signal: NodeJS.Signals) => boolean,
177 hasExited: () => boolean,
178) {
179 if (hasExited()) return;
180 if (!kill("SIGTERM")) return;
181 yield* Effect.sleep(TERMINATION_GRACE);
182 if (hasExited()) return;
183 kill("SIGKILL");
184});
185​
186export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpawnOptions) {
187 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
188 const platform = yield* HostProcess.Platform;
189 const scope = yield* Effect.scope;
190​
191 const spawnCommand = yield* resolveSpawnCommand(options.command, [...options.args], {
192 env: options.env,
193 }).pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
194 const child = yield* spawner
195 .spawn(
196 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
197 ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
198 env: options.env,
199 extendEnv: false,
200 shell: spawnCommand.shell,
201 detached: platform !== "win32",
202 // On stdin EOF Pi quits without its SIGTERM handler, so the later SIGTERM kills it mid-cleanup.
203 stdin: { stream: "pipe", endOnDone: false },
204 }),
205 )
206 .pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
207​
208 let childExited = false;
209 let diagnosingStdoutClose = false;
210​
211 const killProcessGroup = (signal: NodeJS.Signals): boolean => {
212 try {
213 if (platform === "win32") {
214 process.kill(Number(child.pid), signal);
215 } else {
216 signalProcessGroup(Number(child.pid), signal);
217 }
218 return true;
219 } catch {
220 return false;
221 }
222 };
223​
224 const hasExited = (): boolean => {
225 if (childExited) return true;
226 try {
227 if (platform === "win32") process.kill(Number(child.pid), 0);
228 else signalProcessGroup(Number(child.pid), 0);
229 return false;
230 } catch {
231 return true;
232 }
233 };
234​
235 // Windows process.kill leaves extension children and pipes alive; taskkill /T reaps the tree.
236 const terminateWindowsTree = Effect.gen(function* () {
237 if (hasExited()) return;
238 const taskkill = yield* spawner.spawn(
239 ChildProcess.make("taskkill", ["/PID", String(child.pid), "/T", "/F"]),
240 );
241 yield* taskkill.exitCode;
242 }).pipe(Effect.scoped, Effect.ignore);
243​
244 const terminateProcess =
245 platform === "win32" ? terminateWindowsTree : terminatePiProcess(killProcessGroup, hasExited);
246​
247 // Register teardown immediately after spawn so interrupted setup cannot leak a detached process.
248 yield* Scope.addFinalizer(scope, terminateProcess.pipe(Effect.ignore, Effect.uninterruptible));
249​
250 const pendingRequests = new Map<string, PendingPiRequest>();
251 const events = yield* Queue.unbounded<PiRpcRecord, PiRpcError>();
252 const outgoing = yield* Queue.unbounded<Uint8Array, PiRpcError>();
253 const transportDown = yield* Deferred.make<never, PiRpcError>();
254 const exitDeferred = yield* Deferred.make<number, PiRpcError>();
255 let nextRequestId = 0;
256​
257 const failTransport = Effect.fn("PiRpc.failTransport")(function* (error: PiRpcError) {
258 const claimed = yield* Deferred.fail(transportDown, error);
259 if (!claimed) return;
260 for (const [key, pending] of pendingRequests) {
261 pendingRequests.delete(key);
262 yield* Deferred.fail(pending.deferred, error);
263 }
264 yield* Queue.fail(outgoing, error);
265 yield* Queue.fail(events, error);
266 });
267​
268 const routeRecord =
269 /* Protocol records and writes include streaming deltas; avoid a span per record. */
270 Effect.fnUntraced(function* (record: PiRpcRecord) {
271 if (record["type"] === "response" && typeof record["id"] === "string") {
272 const pending = pendingRequests.get(record["id"]);
273 if (pending !== undefined) {
274 pendingRequests.delete(record["id"]);
275 if (record["success"] === true) {
276 yield* Deferred.succeed(pending.deferred, record["data"]);
277 } else {
278 yield* Deferred.fail(
279 pending.deferred,
280 new PiRpcError({
281 operation: String(record["command"] ?? "request"),
282 detail: summarizePiError(record["error"]),
283 ...(record["error"] === undefined ? {} : { cause: record["error"] }),
284 }),
285 );
286 }
287 return;
288 }
289 }
290 yield* Queue.offer(events, record);
291 });
292​
293 // Watch exit before reading stdout so immediate crashes populate exitDeferred for diagnosis.
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, droppedLengths } = frame(chunk);
314 yield* logDroppedPiRecords(droppedLengths);
315 for (const line of lines) {
316 const record = parsePiRecord(line);
317 if (record === undefined) {
318 yield* Effect.logDebug("Dropping non-JSON pi stdout line.", {
319 lineLength: line.length,
320 });
321 continue;
322 }
323 yield* routeRecord(record);
324 }
325 }),
326 ),
327 );
328 const flushed = frame("\n");
329 yield* logDroppedPiRecords(flushed.droppedLengths);
330 for (const line of flushed.lines) {
331 const trailing = parsePiRecord(line);
332 if (trailing !== undefined) yield* routeRecord(trailing);
333 }
334 }).pipe(
335 Effect.matchCauseEffect({
336 onFailure: (cause) => failTransport(new PiRpcError({ operation: "read", cause })),
337 // The enclosing operation owns the span for this inline handler.
338 onSuccess: Effect.fnUntraced(function* () {
339 // Claim stdout-close diagnosis before waiting so broken stdin cannot replace the exit error.
340 diagnosingStdoutClose = true;
341 const polled = yield* Deferred.poll(exitDeferred);
342 const maybeExitCode = Option.isSome(polled)
343 ? yield* polled.value.pipe(
344 Effect.asSome,
345 Effect.orElseSucceed(() => Option.none<number>()),
346 )
347 : yield* Deferred.await(exitDeferred).pipe(
348 Effect.timeoutOption(Duration.millis(250)),
349 // Stdout-close waits need wall time; TestClock would strand Stop-with-restart without an exit.
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 : // Log stderr length only; unbounded text may contain credentials or prompts.
372 Effect.logDebug("pi stderr", { stderrLength: chunk.length }),
373 ),
374 Effect.ignore,
375 Effect.forkIn(scope),
376 );
377​
378 // Start the reader first so stdout-close diagnosis can win over broken-pipe stdin.
379 yield* Stream.fromQueue(outgoing).pipe(
380 Stream.run(child.stdin),
381 Effect.catchCause((cause) =>
382 diagnosingStdoutClose
383 ? Effect.void
384 : failTransport(new PiRpcError({ operation: "write", cause })),
385 ),
386 Effect.forkIn(scope),
387 );
388​
389 const send =
390 /* Protocol records and writes include streaming deltas; avoid a span per record. */
391 Effect.fnUntraced(function* (record: PiRpcRecord): Effect.fn.Return<void, PiRpcError> {
392 const accepted = yield* Queue.offer(
393 outgoing,
394 new TextEncoder().encode(`${encodeJsonLine(record)}\n`),
395 );
396 if (!accepted) {
397 return yield* Deferred.await(transportDown);
398 }
399 });
400​
401 const request = Effect.fn("PiRpc.request")(function* (
402 record: PiRpcRecord,
403 timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
404 ): Effect.fn.Return<unknown, PiRpcError | PiRpcTimeoutError> {
405 const id = `t3-${nextRequestId++}`;
406 const deferred = yield* Deferred.make<unknown, PiRpcError>();
407 pendingRequests.set(id, { deferred });
408 yield* send({ ...record, id }).pipe(
409 Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),
410 );
411 return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(
412 Effect.timeoutOrElse({
413 duration: Duration.millis(timeoutMs),
414 orElse: () =>
415 Effect.fail(
416 new PiRpcTimeoutError({
417 operation: String(record["type"] ?? "request"),
418 timeoutMs,
419 }),
420 ),
421 }),
422 Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),
423 Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),
424 );
425 });
426​
427 return {
428 send,
429 request,
430 events,
431 exited: Deferred.await(exitDeferred),
432 terminate: failTransport(
433 new PiRpcError({ operation: "terminate", detail: "pi process was stopped" }),
434 ).pipe(Effect.andThen(terminateProcess), Effect.ignore, Effect.uninterruptible),
435 } satisfies PiRpcConnection;
436});