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

rpc.ts

480 lines16.8 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 { windowsSystem32Path } from "@t3tools/shared/windowsSystem";
16import { resolveSpawnCommand } from "@t3tools/shared/shell";
17import {
18 MAX_TOOL_OUTPUT_IMAGES,
19 MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH,
20} from "@t3tools/shared/toolOutput";
21​
22import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
23​
24export class PiRpcError extends Schema.TaggedError<PiRpcError>()("PiRpcError", {
25 operation: Schema.String,
26 detail: Schema.optional(Schema.String),
27 cause: Schema.optional(Schema.Defect()),
28}) {
29 override get message(): string {
30 return `Pi RPC ${this.operation} failed${this.detail === undefined ? "" : `: ${this.detail}`}.`;
31 }
33​
34export class PiRpcTimeoutError extends Schema.TaggedError<PiRpcTimeoutError>()(
35 "PiRpcTimeoutError",
36 {
37 operation: Schema.String,
38 timeoutMs: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER })),
39 },
40) {
41 override get message(): string {
42 return `Pi RPC ${this.operation} failed: timed out after ${this.timeoutMs}ms.`;
43 }
45​
46export type PiRpcRecord = Record<string, unknown>;
47​
48export function piRecordField(input: unknown, key: string): unknown {
49 return Predicate.isObject(input) ? input[key] : undefined;
51​
52export function piRecordString(input: unknown, key: string): string | undefined {
53 const value = piRecordField(input, key);
54 return Predicate.isString(value) ? value : undefined;
56​
57export function piRecordNumber(input: unknown, key: string): number | undefined {
58 const value = piRecordField(input, key);
59 return Predicate.isNumber(value) && Number.isFinite(value) ? value : undefined;
61​
62// Pi provider names and model ids may both contain "/", so a slug only splits
63// reliably through the `{provider, id}` pairs `get_available_models` reported.
64export function findReportedPiModel(
65 slug: string,
66 reportedModels: unknown,
67): { provider: string; modelId: string } | undefined {
68 if (!Array.isArray(reportedModels)) return undefined;
69 for (const model of reportedModels) {
70 const provider = piRecordString(model, "provider");
71 const modelId = piRecordString(model, "id");
72 if (provider !== undefined && modelId !== undefined && `${provider}/${modelId}` === slug)
73 return { provider, modelId };
74 }
75 return undefined;
77​
78export function resolvePiModelSlug(
79 slug: string,
80 reportedModels: unknown,
81): { provider: string; modelId: string } | null {
82 const reported = findReportedPiModel(slug, reportedModels);
83 if (reported !== undefined) return reported;
84 const separator = slug.indexOf("/");
85 if (separator <= 0 || separator === slug.length - 1) return null;
86 return { provider: slug.slice(0, separator), modelId: slug.slice(separator + 1) };
88​
89export interface PiRpcSpawnOptions {
90 readonly command: string;
91 readonly args: ReadonlyArray<string>;
92 readonly cwd: string | undefined;
93 readonly env: NodeJS.ProcessEnv;
95​
96export interface PiRpcConnection {
97 readonly send: (record: PiRpcRecord) => Effect.Effect<void, PiRpcError>;
98 readonly request: (
99 record: PiRpcRecord,
100 timeoutMs?: number,
101 ) => Effect.Effect<unknown, PiRpcError | PiRpcTimeoutError>;
102 readonly events: Queue.Queue<PiRpcRecord, PiRpcError>;
103 readonly exited: Effect.Effect<number, PiRpcError>;
104 readonly terminate: Effect.Effect<void>;
106​
107const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
108const TERMINATION_GRACE = Duration.seconds(1);
109const TERMINATION_POLL_INTERVAL = Duration.millis(20);
110​
111interface PendingPiRequest {
112 readonly deferred: Deferred.Deferred<unknown, PiRpcError>;
114​
115// MCP duplicates images in model content and CallToolResult; budget both plus bounded overhead.
116const MAX_PI_RECORD_CHARS =
117 2 * MAX_TOOL_OUTPUT_IMAGES * MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH + 8 * 1024 * 1024;
118​
119function makeJsonlFramer() {
120 let buffer = "";
121 let dropping = false;
122 return (chunk: string) => {
123 const lines: string[] = [];
124 const droppedLengths: number[] = [];
125 let start = 0;
126 while (start < chunk.length) {
127 const newline = chunk.indexOf("\n", start);
128 const end = newline < 0 ? chunk.length : newline;
129 if (!dropping) {
130 if (buffer.length + end - start > MAX_PI_RECORD_CHARS) {
131 droppedLengths.push(buffer.length + end - start);
132 buffer = "";
133 dropping = true;
134 } else {
135 buffer += chunk.slice(start, end);
136 }
137 }
138 if (newline < 0) break;
139 if (!dropping && buffer.length > 0) {
140 lines.push(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
141 }
142 buffer = "";
143 dropping = false;
144 start = newline + 1;
145 }
146 return { lines, droppedLengths };
147 };
149​
150// Report the observed length before LF arrives; an unterminated response can time out first.
151const logDroppedPiRecords = (droppedLengths: ReadonlyArray<number>) =>
152 Effect.forEach(
153 droppedLengths,
154 (recordLength) =>
155 Effect.logWarning("Dropping oversized pi stdout record.", {
156 recordLength,
157 maxRecordLength: MAX_PI_RECORD_CHARS,
158 }),
159 { discard: true },
160 );
161​
162const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
163const decodeJsonLine = Schema.decodeSync(UnknownFromJsonString);
164const encodeJsonLine = Schema.encodeSync(UnknownFromJsonString);
165​
166const PI_ERROR_DETAIL_MAX_CHARS = 200;
167​
168function summarizePiError(error: unknown): string {
169 const text = typeof error === "string" ? error : JSON.stringify(error);
170 if (text === undefined) return "unknown error";
171 return text.length > PI_ERROR_DETAIL_MAX_CHARS
172 ? `${text.slice(0, PI_ERROR_DETAIL_MAX_CHARS)}…`
173 : text;
175​
176// Pi 0.84+ may exit 1 during import without any protocol output.
177function describePiStdoutClosure(exitCode: number | undefined): string {
178 if (exitCode === undefined || !Number.isFinite(exitCode)) {
179 return "pi process closed stdout";
180 }
181 return `pi process exited with code ${exitCode}`;
183​
184function parsePiRecord(line: string): PiRpcRecord | undefined {
185 try {
186 const parsed: unknown = decodeJsonLine(line);
187 return Predicate.isObject(parsed) ? parsed : undefined;
188 } catch {
189 return undefined;
190 }
192​
193/**
194 * `hasExited` is consulted before each signal. Once the original child is
195 * gone its pid/pgid can be recycled by the OS, so escalating blindly could
196 * deliver SIGKILL to an unrelated process.
197 */
198const terminatePiProcess = Effect.fn("PiRpc.terminatePiProcess")(function* (
199 kill: (signal: NodeJS.Signals) => boolean,
200 hasExited: () => boolean,
201 groupGone: () => boolean,
202) {
203 if (hasExited()) return;
204 if (!kill("SIGTERM")) return;
205 yield* Effect.sleep(TERMINATION_POLL_INTERVAL).pipe(
206 Effect.repeat({ until: groupGone }),
207 Effect.timeoutOption(TERMINATION_GRACE),
208 );
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* HostProcess.Platform;
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 // On stdin EOF Pi quits without its SIGTERM handler, so the later SIGTERM kills it mid-cleanup.
230 stdin: { stream: "pipe", endOnDone: false },
231 }),
232 )
233 .pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
234​
235 let childExited = false;
236 let diagnosingStdoutClose = false;
237​
238 const killProcessGroup = (signal: NodeJS.Signals): boolean => {
239 try {
240 if (platform === "win32") {
241 process.kill(Number(child.pid), signal);
242 } else {
243 signalProcessGroup(Number(child.pid), signal);
244 }
245 return true;
246 } catch {
247 return false;
248 }
249 };
250​
251 const hasExited = (): boolean => {
252 if (childExited) return true;
253 try {
254 if (platform === "win32") process.kill(Number(child.pid), 0);
255 else signalProcessGroup(Number(child.pid), 0);
256 return false;
257 } catch {
258 return true;
259 }
260 };
261​
262 // EPERM means a group member is still alive, so only ESRCH ends the SIGTERM grace early.
263 const processGroupGone = (): boolean => {
264 try {
265 signalProcessGroup(Number(child.pid), 0);
266 return false;
267 } catch (cause) {
268 return (cause as NodeJS.ErrnoException | undefined)?.code === "ESRCH";
269 }
270 };
271​
272 // Windows process.kill leaves extension children and pipes alive; taskkill /T reaps the tree.
273 const terminateWindowsTree = Effect.gen(function* () {
274 if (hasExited()) return;
275 const taskkill = yield* spawner.spawn(
276 ChildProcess.make(windowsSystem32Path(yield* HostProcess.Environment, "taskkill.exe"), [
277 "/PID",
278 String(child.pid),
279 "/T",
280 "/F",
281 ]),
282 );
283 yield* taskkill.exitCode;
284 }).pipe(Effect.scoped, Effect.ignore);
285​
286 const terminateProcess =
287 platform === "win32"
288 ? terminateWindowsTree
289 : terminatePiProcess(killProcessGroup, hasExited, processGroupGone);
290​
291 // Register teardown immediately after spawn so interrupted setup cannot leak a detached process.
292 yield* Scope.addFinalizer(scope, terminateProcess.pipe(Effect.ignore, Effect.uninterruptible));
293​
294 const pendingRequests = new Map<string, PendingPiRequest>();
295 const events = yield* Queue.unbounded<PiRpcRecord, PiRpcError>();
296 const outgoing = yield* Queue.unbounded<Uint8Array, PiRpcError>();
297 const transportDown = yield* Deferred.make<never, PiRpcError>();
298 const exitDeferred = yield* Deferred.make<number, PiRpcError>();
299 let nextRequestId = 0;
300​
301 const failTransport = Effect.fn("PiRpc.failTransport")(function* (error: PiRpcError) {
302 const claimed = yield* Deferred.fail(transportDown, error);
303 if (!claimed) return;
304 for (const [key, pending] of pendingRequests) {
305 pendingRequests.delete(key);
306 yield* Deferred.fail(pending.deferred, error);
307 }
308 yield* Queue.fail(outgoing, error);
309 yield* Queue.fail(events, error);
310 });
311​
312 const routeRecord =
313 /* Protocol records and writes include streaming deltas; avoid a span per record. */
314 Effect.fnUntraced(function* (record: PiRpcRecord) {
315 if (record["type"] === "response" && typeof record["id"] === "string") {
316 const pending = pendingRequests.get(record["id"]);
317 if (pending !== undefined) {
318 pendingRequests.delete(record["id"]);
319 if (record["success"] === true) {
320 yield* Deferred.succeed(pending.deferred, record["data"]);
321 } else {
322 yield* Deferred.fail(
323 pending.deferred,
324 new PiRpcError({
325 operation: String(record["command"] ?? "request"),
326 detail: summarizePiError(record["error"]),
327 ...(record["error"] === undefined ? {} : { cause: record["error"] }),
328 }),
329 );
330 }
331 return;
332 }
333 }
334 yield* Queue.offer(events, record);
335 });
336​
337 // Watch exit before reading stdout so immediate crashes populate exitDeferred for diagnosis.
338 yield* child.exitCode.pipe(
339 Effect.matchEffect({
340 onFailure: (cause) =>
341 Deferred.fail(exitDeferred, new PiRpcError({ operation: "exit", cause })),
342 onSuccess: (code) =>
343 Effect.suspend(() => {
344 childExited = true;
345 return Deferred.succeed(exitDeferred, Number(code));
346 }),
347 }),
348 Effect.forkIn(scope),
349 );
350​
351 yield* Effect.gen(function* () {
352 const frame = makeJsonlFramer();
353 yield* child.stdout.pipe(
354 Stream.decodeText(),
355 Stream.runForEach((chunk) =>
356 Effect.gen(function* () {
357 const { lines, droppedLengths } = frame(chunk);
358 yield* logDroppedPiRecords(droppedLengths);
359 for (const line of lines) {
360 const record = parsePiRecord(line);
361 if (record === undefined) {
362 yield* Effect.logDebug("Dropping non-JSON pi stdout line.", {
363 lineLength: line.length,
364 });
365 continue;
366 }
367 yield* routeRecord(record);
368 }
369 }),
370 ),
371 );
372 const flushed = frame("\n");
373 yield* logDroppedPiRecords(flushed.droppedLengths);
374 for (const line of flushed.lines) {
375 const trailing = parsePiRecord(line);
376 if (trailing !== undefined) yield* routeRecord(trailing);
377 }
378 }).pipe(
379 Effect.matchCauseEffect({
380 onFailure: (cause) => failTransport(new PiRpcError({ operation: "read", cause })),
381 // The enclosing operation owns the span for this inline handler.
382 onSuccess: Effect.fnUntraced(function* () {
383 // Claim stdout-close diagnosis before waiting so broken stdin cannot replace the exit error.
384 diagnosingStdoutClose = true;
385 const polled = yield* Deferred.poll(exitDeferred);
386 const maybeExitCode = Option.isSome(polled)
387 ? yield* polled.value.pipe(
388 Effect.asSome,
389 Effect.orElseSucceed(() => Option.none<number>()),
390 )
391 : yield* Deferred.await(exitDeferred).pipe(
392 Effect.timeoutOption(Duration.millis(250)),
393 // Stdout-close waits need wall time; TestClock would strand Stop-with-restart without an exit.
394 Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),
395 Effect.orElseSucceed(() => Option.none<number>()),
396 );
397 return yield* failTransport(
398 new PiRpcError({
399 operation: "read",
400 detail: describePiStdoutClosure(
401 Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined,
402 ),
403 }),
404 );
405 }),
406 }),
407 Effect.forkIn(scope),
408 );
409​
410 yield* child.stderr.pipe(
411 Stream.decodeText(),
412 Stream.runForEach((chunk) =>
413 chunk.trim().length === 0
414 ? Effect.void
415 : // Log stderr length only; unbounded text may contain credentials or prompts.
416 Effect.logDebug("pi stderr", { stderrLength: chunk.length }),
417 ),
418 Effect.ignore,
419 Effect.forkIn(scope),
420 );
421​
422 // Start the reader first so stdout-close diagnosis can win over broken-pipe stdin.
423 yield* Stream.fromQueue(outgoing).pipe(
424 Stream.run(child.stdin),
425 Effect.catchCause((cause) =>
426 diagnosingStdoutClose
427 ? Effect.void
428 : failTransport(new PiRpcError({ operation: "write", cause })),
429 ),
430 Effect.forkIn(scope),
431 );
432​
433 const send =
434 /* Protocol records and writes include streaming deltas; avoid a span per record. */
435 Effect.fnUntraced(function* (record: PiRpcRecord): Effect.fn.Return<void, PiRpcError> {
436 const accepted = yield* Queue.offer(
437 outgoing,
438 new TextEncoder().encode(`${encodeJsonLine(record)}\n`),
439 );
440 if (!accepted) {
441 return yield* Deferred.await(transportDown);
442 }
443 });
444​
445 const request = Effect.fn("PiRpc.request")(function* (
446 record: PiRpcRecord,
447 timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
448 ): Effect.fn.Return<unknown, PiRpcError | PiRpcTimeoutError> {
449 const id = `t3-${nextRequestId++}`;
450 const deferred = yield* Deferred.make<unknown, PiRpcError>();
451 pendingRequests.set(id, { deferred });
452 yield* send({ ...record, id }).pipe(
453 Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),
454 );
455 return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(
456 Effect.timeoutOrElse({
457 duration: Duration.millis(timeoutMs),
458 orElse: () =>
459 Effect.fail(
460 new PiRpcTimeoutError({
461 operation: String(record["type"] ?? "request"),
462 timeoutMs,
463 }),
464 ),
465 }),
466 Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),
467 Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),
468 );
469 });
470​
471 return {
472 send,
473 request,
474 events,
475 exited: Deferred.await(exitDeferred),
476 terminate: failTransport(
477 new PiRpcError({ operation: "terminate", detail: "pi process was stopped" }),
478 ).pipe(Effect.andThen(terminateProcess), Effect.ignore, Effect.uninterruptible),
479 } satisfies PiRpcConnection;
480});