Open History to see the last commit
1/** Typed JSONL transport + pure parsing helpers for `pi --mode rpc`. */
2import type {
3 AgentSessionEvent,
4 ModelInfo,
5 RpcCommand,
6 RpcExtensionUIRequest,
7 RpcExtensionUIResponse,
8 RpcResponse,
9} from "@earendil-works/pi-coding-agent";
10import type { ModelSelection, ServerProviderModel } from "@t3tools/contracts";
11import type { ModelCapabilities } from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Stream from "effect/Stream";
18import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
19
20import { buildSelectOptionDescriptor } from "../providerSnapshot.ts";
21import { createModelCapabilities, getModelSelectionStringOptionValue } from "@t3tools/shared/model";
22
23export type PiStdoutMessage =
24 | { readonly _tag: "response"; readonly id: string | undefined; readonly response: RpcResponse }
25 | { readonly _tag: "extension-ui"; readonly request: RpcExtensionUIRequest }
26 | { readonly _tag: "event"; readonly event: AgentSessionEvent };
27
28export function tryParsePiJsonObject(text: string): Record<string, unknown> | null {
29 const trimmed = text.trim();
30 if (!trimmed || (trimmed[0] !== "{" && trimmed[0] !== "[")) {
31 return null;
32 }
33 try {
34 const value = JSON.parse(trimmed) as unknown; // @effect-diagnostics-ignore preferSchemaOverJson
35 return value !== null && typeof value === "object" && !Array.isArray(value)
36 ? (value as Record<string, unknown>)
37 : null;
38 } catch {
39 return null;
40 }
41}
42
43export function classifyPiStdoutMessage(msg: Record<string, unknown>): PiStdoutMessage | null {
44 const type = msg["type"];
45 if (type === "response") {
46 return {
47 _tag: "response",
48 id: typeof msg["id"] === "string" ? (msg["id"] as string) : undefined,
49 response: msg as unknown as RpcResponse,
50 };
51 }
52 if (type === "extension_ui_request") {
53 return { _tag: "extension-ui", request: msg as unknown as RpcExtensionUIRequest };
54 }
55 if (typeof type === "string" && type.length > 0) {
56 return { _tag: "event", event: msg as unknown as AgentSessionEvent };
57 }
58 return null;
59}
60
61export function parsePiStdoutLine(line: string): PiStdoutMessage | null {
62 const msg = tryParsePiJsonObject(line);
63 return msg ? classifyPiStdoutMessage(msg) : null;
64}
65
66// only text_delta is user-visible; thinking/toolcall deltas leak raw json
67export function extractAssistantTextDelta(event: AgentSessionEvent): string | null {
68 if (event.type !== "message_update") return null;
69 const assistantEvent = event.assistantMessageEvent;
70 if (!assistantEvent || assistantEvent.type !== "text_delta") return null;
71 return typeof assistantEvent.delta === "string" ? assistantEvent.delta : null;
72}
73
74export function extractReasoningTextDelta(event: AgentSessionEvent): string | null {
75 if (event.type !== "message_update") return null;
76 const assistantEvent = event.assistantMessageEvent;
77 if (!assistantEvent || assistantEvent.type !== "thinking_delta") return null;
78 const delta = (assistantEvent as { delta?: unknown }).delta;
79 return typeof delta === "string" ? delta : null;
80}
81
82// slugs are provider/id; keep any extra "/" in the id
83export function splitPiModelSlug(slug: string): { provider: string; id: string } | null {
84 const trimmed = slug.trim();
85 const idx = trimmed.indexOf("/");
86 if (idx <= 0 || idx >= trimmed.length - 1) return null;
87 return { provider: trimmed.slice(0, idx), id: trimmed.slice(idx + 1) };
88}
89
90export function piModelSlug(model: Pick<ModelInfo, "provider" | "id">): string {
91 return `${model.provider}/${model.id}`;
92}
93
94// derived from RpcCommand so it tracks the installed package
95export type PiImageContent = NonNullable<Extract<RpcCommand, { type: "prompt" }>["images"]>[number];
96
97export type PiTurnCommand = Extract<RpcCommand, { type: "prompt" } | { type: "steer" }>;
98
99// raw base64, not a data URL
100export function piImageContentFromBytes(input: {
101 readonly mimeType: string;
102 readonly bytes: Uint8Array;
103}): PiImageContent {
104 return {
105 type: "image",
106 data: Buffer.from(input.bytes).toString("base64"),
107 mimeType: input.mimeType,
108 };
109}
110
111// mid-turn must "steer": a bare prompt is rejected while streaming and, being
112// fire-and-forget, would be silently dropped
113export function buildPiTurnCommand(args: {
114 readonly isMidTurn: boolean;
115 readonly message: string;
116 readonly images?: ReadonlyArray<PiImageContent>;
117}): PiTurnCommand {
118 const hasImages = args.images !== undefined && args.images.length > 0;
119 const images = hasImages ? [...(args.images as ReadonlyArray<PiImageContent>)] : undefined;
120 return args.isMidTurn
121 ? { type: "steer", message: args.message, ...(images ? { images } : {}) }
122 : { type: "prompt", message: args.message, ...(images ? { images } : {}) };
123}
124
125const PI_THINKING_LEVELS = [
126 { value: "off", label: "Off" },
127 { value: "minimal", label: "Minimal" },
128 { value: "low", label: "Low" },
129 { value: "medium", label: "Medium", isDefault: true },
130 { value: "high", label: "High" },
131 { value: "xhigh", label: "Extra High" },
132] as const;
133
134export type PiThinkingLevel = Extract<RpcCommand, { type: "set_thinking_level" }>["level"];
135
136export const PI_THINKING_OPTION_ID = "thinking";
137
138export const PI_THINKING_LEVEL_VALUES = PI_THINKING_LEVELS.map(
139 (level) => level.value,
140) as ReadonlyArray<PiThinkingLevel>;
141
142const PI_THINKING_LEVEL_SET: ReadonlySet<string> = new Set(PI_THINKING_LEVEL_VALUES);
143
144export function asPiThinkingLevel(value: string | undefined): PiThinkingLevel | undefined {
145 return value !== undefined && PI_THINKING_LEVEL_SET.has(value)
146 ? (value as PiThinkingLevel)
147 : undefined;
148}
149
150export function resolvePiThinkingLevel(
151 modelSelection: ModelSelection | null | undefined,
152): PiThinkingLevel | undefined {
153 return asPiThinkingLevel(
154 getModelSelectionStringOptionValue(modelSelection, PI_THINKING_OPTION_ID),
155 );
156}
157
158export type PiModelSwitchPlan =
159 | { readonly kind: "noop" }
160 | { readonly kind: "invalid"; readonly slug: string }
161 | {
162 readonly kind: "switch";
163 readonly provider: string;
164 readonly modelId: string;
165 readonly slug: string;
166 };
167
168export function planPiModelSwitch(
169 currentModel: string | undefined,
170 requestedModel: string | undefined,
171): PiModelSwitchPlan {
172 if (requestedModel === undefined || requestedModel === currentModel) return { kind: "noop" };
173 const parts = splitPiModelSlug(requestedModel);
174 if (!parts) return { kind: "invalid", slug: requestedModel };
175 return { kind: "switch", provider: parts.provider, modelId: parts.id, slug: requestedModel };
176}
177
178export function piModelCapabilities(reasoning: boolean): ModelCapabilities {
179 return createModelCapabilities({
180 optionDescriptors: reasoning
181 ? [
182 buildSelectOptionDescriptor({
183 id: "thinking",
184 label: "Thinking",
185 options: PI_THINKING_LEVELS.map((level) => ({ ...level })),
186 }),
187 ]
188 : [],
189 });
190}
191
192export function piModelInfoToServerModel(model: ModelInfo): ServerProviderModel {
193 const slug = piModelSlug(model);
194 const rawName = (model as unknown as { name?: unknown }).name;
195 const name = typeof rawName === "string" && rawName.trim().length > 0 ? rawName.trim() : model.id;
196 return {
197 slug,
198 name,
199 isCustom: false,
200 capabilities: piModelCapabilities(Boolean(model.reasoning)),
201 };
202}
203
204export function piResponseData(response: RpcResponse | undefined): Record<string, unknown> | null {
205 if (!response || response.type !== "response" || response.success !== true) return null;
206 const data = (response as { data?: unknown }).data;
207 return data !== null && typeof data === "object" ? (data as Record<string, unknown>) : null;
208}
209
210export function extractSessionFile(response: RpcResponse | undefined): string | undefined {
211 const sessionFile = piResponseData(response)?.["sessionFile"];
212 return typeof sessionFile === "string" && sessionFile.trim().length > 0
213 ? sessionFile.trim()
214 : undefined;
215}
216
217export function extractAvailableModels(
218 response: RpcResponse | undefined,
219): ReadonlyArray<ModelInfo> {
220 const models = piResponseData(response)?.["models"];
221 return Array.isArray(models) ? (models as ReadonlyArray<ModelInfo>) : [];
222}
223
224// approval-gate handshake: the sentinel command's presence confirms the gate loaded
225export function piResponseHasCommand(
226 response: RpcResponse | undefined,
227 commandName: string,
228): boolean {
229 const commands = piResponseData(response)?.["commands"];
230 if (!Array.isArray(commands)) return false;
231 return commands.some(
232 (entry) =>
233 typeof entry === "object" &&
234 entry !== null &&
235 (entry as Record<string, unknown>)["name"] === commandName,
236 );
237}
238
239export function extractLastAssistantText(response: RpcResponse | undefined): string | null {
240 const text = piResponseData(response)?.["text"];
241 return typeof text === "string" ? text : null;
242}
243
244// fail-closed: a timeout (undefined) or mismatched command counts as failure
245export function piResponseSucceeded(response: RpcResponse | undefined, command: string): boolean {
246 return (
247 response !== undefined &&
248 response.type === "response" &&
249 response.success === true &&
250 (response as { command?: unknown }).command === command
251 );
252}
253
254// branch-scoped user messages (each with entryId) — the only valid fork targets
255export function extractForkMessages(
256 response: RpcResponse | undefined,
257): ReadonlyArray<{ readonly entryId: string; readonly text: string }> | undefined {
258 if (!piResponseSucceeded(response, "get_fork_messages")) return undefined;
259 const messages = piResponseData(response)?.["messages"];
260 if (!Array.isArray(messages)) return undefined;
261 return messages.flatMap((entry) => {
262 if (!entry || typeof entry !== "object") return [];
263 const record = entry as Record<string, unknown>;
264 const entryId = record["entryId"];
265 if (typeof entryId !== "string" || entryId.length === 0) return [];
266 const text = typeof record["text"] === "string" ? (record["text"] as string) : "";
267 return [{ entryId, text }];
268 });
269}
270
271// fail-closed; both fork/new_session return { cancelled } on success
272export function piForkSucceeded(response: RpcResponse | undefined): boolean {
273 if (!response || response.type !== "response" || response.success !== true) return false;
274 return piResponseData(response)?.["cancelled"] !== true;
275}
276
277// linear 1-user-message-per-turn mapping; mid-turn steers can under-drop (deferred)
278export function resolveForkTargetEntryId(
279 userMessages: ReadonlyArray<{ readonly entryId: string }>,
280 numTurns: number,
281): { readonly kind: "fork"; readonly entryId: string } | { readonly kind: "reset" } | null {
282 if (numTurns <= 0 || userMessages.length === 0) return null;
283 const targetIndex = userMessages.length - numTurns;
284 if (targetIndex <= 0) return { kind: "reset" };
285 return { kind: "fork", entryId: userMessages[targetIndex]!.entryId };
286}
287
288// ---------------------------------------------------------------------------
289// Transport
290// ---------------------------------------------------------------------------
291
292export interface PiRpcTransport {
293 readonly writeCommand: (command: RpcCommand) => Effect.Effect<void>;
294 readonly writeExtensionResponse: (response: RpcExtensionUIResponse) => Effect.Effect<void>;
295 // sends a command and awaits its correlated response; times out to `undefined`
296 readonly request: (
297 command: RpcCommand,
298 id: string,
299 timeoutMs: number,
300 ) => Effect.Effect<RpcResponse | undefined>;
301 readonly messages: Queue.Dequeue<PiStdoutMessage, Cause.Done<void>>;
302 readonly isClosed: Effect.Effect<boolean>;
303 readonly kill: Effect.Effect<void>;
304}
305
306export interface MakePiRpcTransportOptions {
307 readonly binaryPath: string;
308 readonly args: ReadonlyArray<string>;
309 readonly cwd: string;
310 readonly env: NodeJS.ProcessEnv;
311 readonly onExit: Effect.Effect<void>;
312}
313
314export const makePiRpcTransport = (options: MakePiRpcTransportOptions) =>
315 Effect.gen(function* () {
316 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
317
318 const child = yield* spawner.spawn(
319 ChildProcess.make(options.binaryPath || "pi", [...options.args], {
320 cwd: options.cwd,
321 env: options.env,
322 shell: false,
323 forceKillAfter: 5000,
324 }),
325 );
326
327 const outgoing = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
328 const messages = yield* Queue.unbounded<PiStdoutMessage, Cause.Done<void>>();
329 const pendingRequests = new Map<string, Deferred.Deferred<RpcResponse>>();
330 // resolved on process exit to unblock in-flight requests (fail fast, not full timeout)
331 const closed = yield* Deferred.make<void>();
332
333 const offerLine = (obj: RpcCommand | RpcExtensionUIResponse): Effect.Effect<boolean> =>
334 Queue.offer(outgoing, Buffer.from(`${JSON.stringify(obj)}\n`));
335
336 const writeLine = (obj: RpcCommand | RpcExtensionUIResponse): Effect.Effect<void> =>
337 offerLine(obj).pipe(
338 Effect.flatMap((offered) =>
339 offered
340 ? Effect.void
341 : Effect.die(new Error("Pi RPC process exited before the command could be delivered.")),
342 ),
343 );
344
345 const handleLine = (line: string): Effect.Effect<void> =>
346 Effect.gen(function* () {
347 const message = parsePiStdoutLine(line);
348 if (!message) return;
349 if (message._tag === "response") {
350 if (message.id !== undefined) {
351 const deferred = pendingRequests.get(message.id);
352 if (deferred) {
353 pendingRequests.delete(message.id);
354 yield* Deferred.succeed(deferred, message.response);
355 }
356 }
357 return;
358 }
359 yield* Queue.offer(messages, message);
360 });
361
362 const onProcessExit = Effect.gen(function* () {
363 yield* Deferred.succeed(closed, undefined);
364 yield* Queue.end(outgoing);
365 yield* Queue.end(messages);
366 pendingRequests.clear();
367 yield* options.onExit;
368 });
369
370 yield* Stream.fromQueue(outgoing).pipe(
371 Stream.run(child.stdin),
372 Effect.ignore,
373 Effect.forkScoped,
374 );
375
376 // stderr drain (prevents the pipe from blocking)
377 yield* child.stderr.pipe(Stream.runDrain, Effect.ignore, Effect.forkScoped);
378
379 yield* child.stdout.pipe(
380 Stream.decodeText(),
381 Stream.splitLines,
382 Stream.runForEach(handleLine),
383 Effect.ignore,
384 Effect.ensuring(onProcessExit),
385 Effect.forkScoped,
386 );
387
388 const request = (
389 command: RpcCommand,
390 id: string,
391 timeoutMs: number,
392 ): Effect.Effect<RpcResponse | undefined> =>
393 Effect.gen(function* () {
394 const deferred = yield* Deferred.make<RpcResponse>();
395 pendingRequests.set(id, deferred);
396 const offered = yield* offerLine({ ...command, id });
397 if (!offered) {
398 pendingRequests.delete(id);
399 return undefined;
400 }
401 // resolve on response, process exit, or timeout — whichever comes first
402 const outcome = yield* Deferred.await(deferred).pipe(
403 Effect.map((response) => Option.some(response)),
404 Effect.race(Deferred.await(closed).pipe(Effect.as(Option.none<RpcResponse>()))),
405 Effect.timeoutOption(timeoutMs),
406 );
407 pendingRequests.delete(id);
408 return outcome._tag === "None" ? undefined : Option.getOrUndefined(outcome.value);
409 });
410
411 const kill = child.kill().pipe(Effect.ignore);
412
413 return {
414 writeCommand: (command) => writeLine(command),
415 writeExtensionResponse: (response) => writeLine(response),
416 request,
417 messages,
418 isClosed: Deferred.isDone(closed),
419 kill,
420 } satisfies PiRpcTransport;
421 });
422
423export type {
424 AgentSessionEvent,
425 ModelInfo,
426 RpcCommand,
427 RpcExtensionUIRequest,
428 RpcExtensionUIResponse,
429 RpcResponse,
430};