Open History to see the last commit
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 }
35}
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 }
47}
48
49export type PiRpcRecord = Record<string, unknown>;
50
51export function piRecordField(input: unknown, key: string): unknown {
52 return Predicate.isObject(input) ? input[key] : undefined;
53}
54
55export function piRecordString(input: unknown, key: string): string | undefined {
56 const value = piRecordField(input, key);
57 return Predicate.isString(value) ? value : undefined;
58}
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;
63}
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) };
69}
70
71export interface PiRpcSpawnOptions {
72 readonly command: string;
73 readonly args: ReadonlyArray<string>;
74 readonly cwd: string | undefined;
75 readonly env: NodeJS.ProcessEnv;
76}
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>;
87}
88
89const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
90const TERMINATION_GRACE = Duration.seconds(1);
91
92interface PendingPiRequest {
93 readonly deferred: Deferred.Deferred<unknown, PiRpcError>;
94}
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 };
129}
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;
143}
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}`;
154}
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 }
163}
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 = (kill: (signal: NodeJS.Signals) => boolean, hasExited: () => boolean) =>
171 Effect.gen(function* () {
172 if (hasExited()) return;
173 if (!kill("SIGTERM")) return;
174 yield* Effect.sleep(TERMINATION_GRACE);
175 if (hasExited()) return;
176 kill("SIGKILL");
177 });
178
179export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSpawnOptions) {
180 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
181 const platform = yield* HostProcess.Platform;
182 const scope = yield* Effect.scope;
183
184 const spawnCommand = yield* resolveSpawnCommand(options.command, [...options.args], {
185 env: options.env,
186 }).pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
187 const child = yield* spawner
188 .spawn(
189 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
190 ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
191 env: options.env,
192 extendEnv: false,
193 shell: spawnCommand.shell,
194 detached: platform !== "win32",
195 }),
196 )
197 .pipe(Effect.mapError((cause) => new PiRpcError({ operation: "spawn", cause })));
198
199 let childExited = false;
200 let diagnosingStdoutClose = false;
201
202 const killProcessGroup = (signal: NodeJS.Signals): boolean => {
203 try {
204 if (platform === "win32") {
205 process.kill(Number(child.pid), signal);
206 } else {
207 signalProcessGroup(Number(child.pid), signal);
208 }
209 return true;
210 } catch {
211 return false;
212 }
213 };
214
215 const hasExited = (): boolean => {
216 if (childExited) return true;
217 try {
218 if (platform === "win32") process.kill(Number(child.pid), 0);
219 else signalProcessGroup(Number(child.pid), 0);
220 return false;
221 } catch {
222 return true;
223 }
224 };
225
226 /**
227 * Windows has no process groups, so `process.kill` reaches only pi itself
228 * and leaves extension subprocesses running with inherited stdio handles.
229 * `taskkill /T` reaps the whole tree.
230 */
231 const terminateWindowsTree = Effect.gen(function* () {
232 if (hasExited()) return;
233 const taskkill = yield* spawner.spawn(
234 ChildProcess.make("taskkill", ["/PID", String(child.pid), "/T", "/F"]),
235 );
236 yield* taskkill.exitCode;
237 }).pipe(Effect.scoped, Effect.ignore);
238
239 const terminateProcess =
240 platform === "win32" ? terminateWindowsTree : terminatePiProcess(killProcessGroup, hasExited);
241
242 // Registered before any further setup: an interrupt or failure between the
243 // spawn and the rest of this constructor would otherwise leak a detached
244 // pi process with no finalizer to reap it.
245 yield* Scope.addFinalizer(scope, terminateProcess.pipe(Effect.ignore, Effect.uninterruptible));
246
247 const pendingRequests = new Map<string, PendingPiRequest>();
248 const events = yield* Queue.unbounded<PiRpcRecord, PiRpcError>();
249 const outgoing = yield* Queue.unbounded<Uint8Array, PiRpcError>();
250 const transportDown = yield* Deferred.make<never, PiRpcError>();
251 const exitDeferred = yield* Deferred.make<number, PiRpcError>();
252 let nextRequestId = 0;
253
254 const failTransport = (error: PiRpcError) =>
255 Effect.gen(function* () {
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 = (record: PiRpcRecord) =>
267 Effect.gen(function* () {
268 if (record["type"] === "response" && typeof record["id"] === "string") {
269 const pending = pendingRequests.get(record["id"]);
270 if (pending !== undefined) {
271 pendingRequests.delete(record["id"]);
272 if (record["success"] === true) {
273 yield* Deferred.succeed(pending.deferred, record["data"]);
274 } else {
275 yield* Deferred.fail(
276 pending.deferred,
277 new PiRpcError({
278 operation: String(record["command"] ?? "request"),
279 detail: summarizePiError(record["error"]),
280 ...(record["error"] === undefined ? {} : { cause: record["error"] }),
281 }),
282 );
283 }
284 return;
285 }
286 }
287 yield* Queue.offer(events, record);
288 });
289
290 // Watch exit before the reader so an immediate crash can populate
291 // `exitDeferred` before stdout-close diagnosis runs.
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 = frame(chunk);
312 for (const line of lines) {
313 const record = parsePiRecord(line);
314 if (record === undefined) {
315 yield* Effect.logDebug("Dropping non-JSON pi stdout line.", {
316 lineLength: line.length,
317 });
318 continue;
319 }
320 yield* routeRecord(record);
321 }
322 }),
323 ),
324 );
325 for (const line of frame("\n")) {
326 const trailing = parsePiRecord(line);
327 if (trailing !== undefined) yield* routeRecord(trailing);
328 }
329 }).pipe(
330 Effect.matchCauseEffect({
331 onFailure: (cause) => failTransport(new PiRpcError({ operation: "read", cause })),
332 onSuccess: () =>
333 Effect.gen(function* () {
334 // Claim the stdout-close path before waiting so a broken stdin
335 // writer cannot replace the exit diagnosis with a write error.
336 diagnosingStdoutClose = true;
337 const polled = yield* Deferred.poll(exitDeferred);
338 const maybeExitCode = Option.isSome(polled)
339 ? yield* polled.value.pipe(
340 Effect.map(Option.some),
341 Effect.orElseSucceed(() => Option.none<number>()),
342 )
343 : yield* Deferred.await(exitDeferred).pipe(
344 Effect.timeoutOption(Duration.millis(250)),
345 // Adapter tests run under TestClock. A planned stdout close
346 // without an exit, for example Stop-with-restart, must not wait
347 // on that clock or the transport never fails.
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 : // Length only: pi's stderr is unbounded remote output and can carry
370 // credentials or prompt text, so it never enters a log annotation.
371 Effect.logDebug("pi stderr", { stderrLength: chunk.length }),
372 ),
373 Effect.ignore,
374 Effect.forkIn(scope),
375 );
376
377 // Writer starts after the reader so an already-closed stdout can mark
378 // diagnosis before a broken-pipe stdin claims the transport.
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 = (record: PiRpcRecord): Effect.Effect<void, PiRpcError> =>
390 Effect.gen(function* () {
391 const accepted = yield* Queue.offer(
392 outgoing,
393 new TextEncoder().encode(`${encodeJsonLine(record)}\n`),
394 );
395 if (!accepted) {
396 return yield* Deferred.await(transportDown);
397 }
398 });
399
400 const request = (
401 record: PiRpcRecord,
402 timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
403 ): Effect.Effect<unknown, PiRpcError | PiRpcTimeoutError> =>
404 Effect.gen(function* () {
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});