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

rpc.ts

417 lines14.5 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): ReadonlyArray<string> => {
100 const lines: string[] = [];
101 let start = 0;
102 while (start < chunk.length) {
103 const newline = chunk.indexOf("\n", start);
104 const end = newline < 0 ? chunk.length : newline;
105 if (!dropping) {
106 if (buffer.length + end - start > MAX_PI_RECORD_CHARS) {
107 buffer = "";
108 dropping = true;
109 } else {
110 buffer += chunk.slice(start, end);
111 }
112 }
113 if (newline < 0) break;
114 if (!dropping && buffer.length > 0) {
115 lines.push(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
116 }
117 buffer = "";
118 dropping = false;
119 start = newline + 1;
120 }
121 return lines;
122 };
124​
125const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
126const decodeJsonLine = Schema.decodeSync(UnknownFromJsonString);
127const encodeJsonLine = Schema.encodeSync(UnknownFromJsonString);
128​
129const PI_ERROR_DETAIL_MAX_CHARS = 200;
130​
131function summarizePiError(error: unknown): string {
132 const text = typeof error === "string" ? error : JSON.stringify(error);
133 if (text === undefined) return "unknown error";
134 return text.length > PI_ERROR_DETAIL_MAX_CHARS
135 ? `${text.slice(0, PI_ERROR_DETAIL_MAX_CHARS)}…`
136 : text;
138​
139// Pi 0.84+ may exit 1 during import without any protocol output.
140function describePiStdoutClosure(exitCode: number | undefined): string {
141 if (exitCode === undefined || !Number.isFinite(exitCode)) {
142 return "pi process closed stdout";
143 }
144 return `pi process exited with code ${exitCode}`;
146​
147function parsePiRecord(line: string): PiRpcRecord | undefined {
148 try {
149 const parsed: unknown = decodeJsonLine(line);
150 return Predicate.isObject(parsed) ? parsed : undefined;
151 } catch {
152 return undefined;
153 }
155​
156/**
157 * `hasExited` is consulted before each signal. Once the original child is
158 * gone its pid/pgid can be recycled by the OS, so escalating blindly could
159 * deliver SIGKILL to an unrelated process.
160 */
161const terminatePiProcess = Effect.fn("PiRpc.terminatePiProcess")(function* (
162 kill: (signal: NodeJS.Signals) => boolean,
163 hasExited: () => boolean,
164) {
165 if (hasExited()) return;
166 if (!kill("SIGTERM")) return;
167 yield* Effect.sleep(TERMINATION_GRACE);
168 if (hasExited()) return;
169 kill("SIGKILL");
170});
171​
172export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpawnOptions) {
173 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
174 const platform = yield* HostProcess.Platform;
175 const scope = yield* Effect.scope;
176​
177 const spawnCommand = yield* resolveSpawnCommand(options.command, [...options.args], {
178 env: options.env,
179 }).pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
180 const child = yield* spawner
181 .spawn(
182 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
183 ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
184 env: options.env,
185 extendEnv: false,
186 shell: spawnCommand.shell,
187 detached: platform !== "win32",
188 }),
189 )
190 .pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
191​
192 let childExited = false;
193 let diagnosingStdoutClose = false;
194​
195 const killProcessGroup = (signal: NodeJS.Signals): boolean => {
196 try {
197 if (platform === "win32") {
198 process.kill(Number(child.pid), signal);
199 } else {
200 signalProcessGroup(Number(child.pid), signal);
201 }
202 return true;
203 } catch {
204 return false;
205 }
206 };
207​
208 const hasExited = (): boolean => {
209 if (childExited) return true;
210 try {
211 if (platform === "win32") process.kill(Number(child.pid), 0);
212 else signalProcessGroup(Number(child.pid), 0);
213 return false;
214 } catch {
215 return true;
216 }
217 };
218​
219 // Windows process.kill leaves extension children and pipes alive; taskkill /T reaps the tree.
220 const terminateWindowsTree = Effect.gen(function* () {
221 if (hasExited()) return;
222 const taskkill = yield* spawner.spawn(
223 ChildProcess.make("taskkill", ["/PID", String(child.pid), "/T", "/F"]),
224 );
225 yield* taskkill.exitCode;
226 }).pipe(Effect.scoped, Effect.ignore);
227​
228 const terminateProcess =
229 platform === "win32" ? terminateWindowsTree : terminatePiProcess(killProcessGroup, hasExited);
230​
231 // Register teardown immediately after spawn so interrupted setup cannot leak a detached process.
232 yield* Scope.addFinalizer(scope, terminateProcess.pipe(Effect.ignore, Effect.uninterruptible));
233​
234 const pendingRequests = new Map<string, PendingPiRequest>();
235 const events = yield* Queue.unbounded<PiRpcRecord, PiRpcError>();
236 const outgoing = yield* Queue.unbounded<Uint8Array, PiRpcError>();
237 const transportDown = yield* Deferred.make<never, PiRpcError>();
238 const exitDeferred = yield* Deferred.make<number, PiRpcError>();
239 let nextRequestId = 0;
240​
241 const failTransport = Effect.fn("PiRpc.failTransport")(function* (error: PiRpcError) {
242 const claimed = yield* Deferred.fail(transportDown, error);
243 if (!claimed) return;
244 for (const [key, pending] of pendingRequests) {
245 pendingRequests.delete(key);
246 yield* Deferred.fail(pending.deferred, error);
247 }
248 yield* Queue.fail(outgoing, error);
249 yield* Queue.fail(events, error);
250 });
251​
252 const routeRecord =
253 /* Protocol records and writes include streaming deltas; avoid a span per record. */
254 Effect.fnUntraced(function* (record: PiRpcRecord) {
255 if (record["type"] === "response" && typeof record["id"] === "string") {
256 const pending = pendingRequests.get(record["id"]);
257 if (pending !== undefined) {
258 pendingRequests.delete(record["id"]);
259 if (record["success"] === true) {
260 yield* Deferred.succeed(pending.deferred, record["data"]);
261 } else {
262 yield* Deferred.fail(
263 pending.deferred,
264 new PiRpcError({
265 operation: String(record["command"] ?? "request"),
266 detail: summarizePiError(record["error"]),
267 ...(record["error"] === undefined ? {} : { cause: record["error"] }),
268 }),
269 );
270 }
271 return;
272 }
273 }
274 yield* Queue.offer(events, record);
275 });
276​
277 // Watch exit before reading stdout so immediate crashes populate exitDeferred for diagnosis.
278 yield* child.exitCode.pipe(
279 Effect.matchEffect({
280 onFailure: (cause) =>
281 Deferred.fail(exitDeferred, new PiRpcError({ operation: "exit", cause })),
282 onSuccess: (code) =>
283 Effect.suspend(() => {
284 childExited = true;
285 return Deferred.succeed(exitDeferred, Number(code));
286 }),
287 }),
288 Effect.forkIn(scope),
289 );
290​
291 yield* Effect.gen(function* () {
292 const frame = makeJsonlFramer();
293 yield* child.stdout.pipe(
294 Stream.decodeText(),
295 Stream.runForEach((chunk) =>
296 Effect.gen(function* () {
297 const lines = frame(chunk);
298 for (const line of lines) {
299 const record = parsePiRecord(line);
300 if (record === undefined) {
301 yield* Effect.logDebug("Dropping non-JSON pi stdout line.", {
302 lineLength: line.length,
303 });
304 continue;
305 }
306 yield* routeRecord(record);
307 }
308 }),
309 ),
310 );
311 for (const line of frame("\n")) {
312 const trailing = parsePiRecord(line);
313 if (trailing !== undefined) yield* routeRecord(trailing);
314 }
315 }).pipe(
316 Effect.matchCauseEffect({
317 onFailure: (cause) => failTransport(new PiRpcError({ operation: "read", cause })),
318 // The enclosing operation owns the span for this inline handler.
319 onSuccess: Effect.fnUntraced(function* () {
320 // Claim stdout-close diagnosis before waiting so broken stdin cannot replace the exit error.
321 diagnosingStdoutClose = true;
322 const polled = yield* Deferred.poll(exitDeferred);
323 const maybeExitCode = Option.isSome(polled)
324 ? yield* polled.value.pipe(
325 Effect.asSome,
326 Effect.orElseSucceed(() => Option.none<number>()),
327 )
328 : yield* Deferred.await(exitDeferred).pipe(
329 Effect.timeoutOption(Duration.millis(250)),
330 // Stdout-close waits need wall time; TestClock would strand Stop-with-restart without an exit.
331 Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),
332 Effect.orElseSucceed(() => Option.none<number>()),
333 );
334 return yield* failTransport(
335 new PiRpcError({
336 operation: "read",
337 detail: describePiStdoutClosure(
338 Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined,
339 ),
340 }),
341 );
342 }),
343 }),
344 Effect.forkIn(scope),
345 );
346​
347 yield* child.stderr.pipe(
348 Stream.decodeText(),
349 Stream.runForEach((chunk) =>
350 chunk.trim().length === 0
351 ? Effect.void
352 : // Log stderr length only; unbounded text may contain credentials or prompts.
353 Effect.logDebug("pi stderr", { stderrLength: chunk.length }),
354 ),
355 Effect.ignore,
356 Effect.forkIn(scope),
357 );
358​
359 // Start the reader first so stdout-close diagnosis can win over broken-pipe stdin.
360 yield* Stream.fromQueue(outgoing).pipe(
361 Stream.run(child.stdin),
362 Effect.catchCause((cause) =>
363 diagnosingStdoutClose
364 ? Effect.void
365 : failTransport(new PiRpcError({ operation: "write", cause })),
366 ),
367 Effect.forkIn(scope),
368 );
369​
370 const send =
371 /* Protocol records and writes include streaming deltas; avoid a span per record. */
372 Effect.fnUntraced(function* (record: PiRpcRecord): Effect.fn.Return<void, PiRpcError> {
373 const accepted = yield* Queue.offer(
374 outgoing,
375 new TextEncoder().encode(`${encodeJsonLine(record)}\n`),
376 );
377 if (!accepted) {
378 return yield* Deferred.await(transportDown);
379 }
380 });
381​
382 const request = Effect.fn("PiRpc.request")(function* (
383 record: PiRpcRecord,
384 timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
385 ): Effect.fn.Return<unknown, PiRpcError | PiRpcTimeoutError> {
386 const id = `t3-${nextRequestId++}`;
387 const deferred = yield* Deferred.make<unknown, PiRpcError>();
388 pendingRequests.set(id, { deferred });
389 yield* send({ ...record, id }).pipe(
390 Effect.tapError(() => Effect.sync(() => pendingRequests.delete(id))),
391 );
392 return yield* Effect.raceFirst(Deferred.await(deferred), Deferred.await(transportDown)).pipe(
393 Effect.timeoutOrElse({
394 duration: Duration.millis(timeoutMs),
395 orElse: () =>
396 Effect.fail(
397 new PiRpcTimeoutError({
398 operation: String(record["type"] ?? "request"),
399 timeoutMs,
400 }),
401 ),
402 }),
403 Effect.onInterrupt(() => Effect.sync(() => pendingRequests.delete(id))),
404 Effect.onError(() => Effect.sync(() => pendingRequests.delete(id))),
405 );
406 });
407​
408 return {
409 send,
410 request,
411 events,
412 exited: Deferred.await(exitDeferred),
413 terminate: failTransport(
414 new PiRpcError({ operation: "terminate", detail: "pi process was stopped" }),
415 ).pipe(Effect.andThen(terminateProcess), Effect.ignore, Effect.uninterruptible),
416 } satisfies PiRpcConnection;
417});