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

rpc.ts

434 lines15.2 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 }),
203 )
204 .pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
205​
206 let childExited = false;
207 let diagnosingStdoutClose = false;
208​
209 const killProcessGroup = (signal: NodeJS.Signals): boolean => {
210 try {
211 if (platform === "win32") {
212 process.kill(Number(child.pid), signal);
213 } else {
214 signalProcessGroup(Number(child.pid), signal);
215 }
216 return true;
217 } catch {
218 return false;
219 }
220 };
221​
222 const hasExited = (): boolean => {
223 if (childExited) return true;
224 try {
225 if (platform === "win32") process.kill(Number(child.pid), 0);
226 else signalProcessGroup(Number(child.pid), 0);
227 return false;
228 } catch {
229 return true;
230 }
231 };
232​
233 // Windows process.kill leaves extension children and pipes alive; taskkill /T reaps the tree.
234 const terminateWindowsTree = Effect.gen(function* () {
235 if (hasExited()) return;
236 const taskkill = yield* spawner.spawn(
237 ChildProcess.make("taskkill", ["/PID", String(child.pid), "/T", "/F"]),
238 );
239 yield* taskkill.exitCode;
240 }).pipe(Effect.scoped, Effect.ignore);
241​
242 const terminateProcess =
243 platform === "win32" ? terminateWindowsTree : terminatePiProcess(killProcessGroup, hasExited);
244​
245 // Register teardown immediately after spawn so interrupted setup cannot leak a detached process.
246 yield* Scope.addFinalizer(scope, terminateProcess.pipe(Effect.ignore, Effect.uninterruptible));
247​
248 const pendingRequests = new Map<string, PendingPiRequest>();
249 const events = yield* Queue.unbounded<PiRpcRecord, PiRpcError>();
250 const outgoing = yield* Queue.unbounded<Uint8Array, PiRpcError>();
251 const transportDown = yield* Deferred.make<never, PiRpcError>();
252 const exitDeferred = yield* Deferred.make<number, PiRpcError>();
253 let nextRequestId = 0;
254​
255 const failTransport = Effect.fn("PiRpc.failTransport")(function* (error: PiRpcError) {
256 const claimed = yield* Deferred.fail(transportDown, error);
257 if (!claimed) return;
258 for (const [key, pending] of pendingRequests) {
259 pendingRequests.delete(key);
260 yield* Deferred.fail(pending.deferred, error);
261 }
262 yield* Queue.fail(outgoing, error);
263 yield* Queue.fail(events, error);
264 });
265​
266 const routeRecord =
267 /* Protocol records and writes include streaming deltas; avoid a span per record. */
268 Effect.fnUntraced(function* (record: PiRpcRecord) {
269 if (record["type"] === "response" && typeof record["id"] === "string") {
270 const pending = pendingRequests.get(record["id"]);
271 if (pending !== undefined) {
272 pendingRequests.delete(record["id"]);
273 if (record["success"] === true) {
274 yield* Deferred.succeed(pending.deferred, record["data"]);
275 } else {
276 yield* Deferred.fail(
277 pending.deferred,
278 new PiRpcError({
279 operation: String(record["command"] ?? "request"),
280 detail: summarizePiError(record["error"]),
281 ...(record["error"] === undefined ? {} : { cause: record["error"] }),
282 }),
283 );
284 }
285 return;
286 }
287 }
288 yield* Queue.offer(events, record);
289 });
290​
291 // Watch exit before reading stdout so immediate crashes populate exitDeferred for diagnosis.
292 yield* child.exitCode.pipe(
293 Effect.matchEffect({
294 onFailure: (cause) =>
295 Deferred.fail(exitDeferred, new PiRpcError({ operation: "exit", cause })),
296 onSuccess: (code) =>
297 Effect.suspend(() => {
298 childExited = true;
299 return Deferred.succeed(exitDeferred, Number(code));
300 }),
301 }),
302 Effect.forkIn(scope),
303 );
304​
305 yield* Effect.gen(function* () {
306 const frame = makeJsonlFramer();
307 yield* child.stdout.pipe(
308 Stream.decodeText(),
309 Stream.runForEach((chunk) =>
310 Effect.gen(function* () {
311 const { lines, droppedLengths } = frame(chunk);
312 yield* logDroppedPiRecords(droppedLengths);
313 for (const line of lines) {
314 const record = parsePiRecord(line);
315 if (record === undefined) {
316 yield* Effect.logDebug("Dropping non-JSON pi stdout line.", {
317 lineLength: line.length,
318 });
319 continue;
320 }
321 yield* routeRecord(record);
322 }
323 }),
324 ),
325 );
326 const flushed = frame("\n");
327 yield* logDroppedPiRecords(flushed.droppedLengths);
328 for (const line of flushed.lines) {
329 const trailing = parsePiRecord(line);
330 if (trailing !== undefined) yield* routeRecord(trailing);
331 }
332 }).pipe(
333 Effect.matchCauseEffect({
334 onFailure: (cause) => failTransport(new PiRpcError({ operation: "read", cause })),
335 // The enclosing operation owns the span for this inline handler.
336 onSuccess: Effect.fnUntraced(function* () {
337 // Claim stdout-close diagnosis before waiting so broken stdin cannot replace the exit error.
338 diagnosingStdoutClose = true;
339 const polled = yield* Deferred.poll(exitDeferred);
340 const maybeExitCode = Option.isSome(polled)
341 ? yield* polled.value.pipe(
342 Effect.asSome,
343 Effect.orElseSucceed(() => Option.none<number>()),
344 )
345 : yield* Deferred.await(exitDeferred).pipe(
346 Effect.timeoutOption(Duration.millis(250)),
347 // Stdout-close waits need wall time; TestClock would strand Stop-with-restart without an exit.
348 Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),
349 Effect.orElseSucceed(() => Option.none<number>()),
350 );
351 return yield* failTransport(
352 new PiRpcError({
353 operation: "read",
354 detail: describePiStdoutClosure(
355 Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined,
356 ),
357 }),
358 );
359 }),
360 }),
361 Effect.forkIn(scope),
362 );
363​
364 yield* child.stderr.pipe(
365 Stream.decodeText(),
366 Stream.runForEach((chunk) =>
367 chunk.trim().length === 0
368 ? Effect.void
369 : // Log stderr length only; unbounded text may contain credentials or prompts.
370 Effect.logDebug("pi stderr", { stderrLength: chunk.length }),
371 ),
372 Effect.ignore,
373 Effect.forkIn(scope),
374 );
375​
376 // Start the reader first so stdout-close diagnosis can win over broken-pipe stdin.
377 yield* Stream.fromQueue(outgoing).pipe(
378 Stream.run(child.stdin),
379 Effect.catchCause((cause) =>
380 diagnosingStdoutClose
381 ? Effect.void
382 : failTransport(new PiRpcError({ operation: "write", cause })),
383 ),
384 Effect.forkIn(scope),
385 );
386​
387 const send =
388 /* Protocol records and writes include streaming deltas; avoid a span per record. */
389 Effect.fnUntraced(function* (record: PiRpcRecord): Effect.fn.Return<void, PiRpcError> {
390 const accepted = yield* Queue.offer(
391 outgoing,
392 new TextEncoder().encode(`${encodeJsonLine(record)}\n`),
393 );
394 if (!accepted) {
395 return yield* Deferred.await(transportDown);
396 }
397 });
398​
399 const request = Effect.fn("PiRpc.request")(function* (
400 record: PiRpcRecord,
401 timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
402 ): Effect.fn.Return<unknown, PiRpcError | PiRpcTimeoutError> {
403 const id = `t3-${nextRequestId++}`;
404 const deferred = yield* Deferred.make<unknown, PiRpcError>();
405 pendingRequests.set(id, { deferred });
406 yield* send({ ...record, id }).pipe(
407 Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),
408 );
409 return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(
410 Effect.timeoutOrElse({
411 duration: Duration.millis(timeoutMs),
412 orElse: () =>
413 Effect.fail(
414 new PiRpcTimeoutError({
415 operation: String(record["type"] ?? "request"),
416 timeoutMs,
417 }),
418 ),
419 }),
420 Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),
421 Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),
422 );
423 });
424​
425 return {
426 send,
427 request,
428 events,
429 exited: Deferred.await(exitDeferred),
430 terminate: failTransport(
431 new PiRpcError({ operation: "terminate", detail: "pi process was stopped" }),
432 ).pipe(Effect.andThen(terminateProcess), Effect.ignore, Effect.uninterruptible),
433 } satisfies PiRpcConnection;
434});