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

PiAdapter.ts

1,077 lines34.8 KB

1import { type AgentSessionEvent, type RpcCommand } from "@earendil-works/pi-coding-agent";
2import {
3 ApprovalRequestId,
4 type CanonicalItemType,
5 EventId,
6 type PiSettings,
7 type ProviderApprovalDecision,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 type ProviderRuntimeEvent,
11 type ProviderRuntimeTurnStatus,
12 type ProviderSendTurnInput,
13 type ProviderSession,
14 type ProviderUserInputAnswers,
15 RuntimeItemId,
16 RuntimeRequestId,
17 ThreadId,
18 TurnId,
19 type UserInputQuestion,
20} from "@t3tools/contracts";
21import * as DateTime from "effect/DateTime";
22import * as Deferred from "effect/Deferred";
23import * as Effect from "effect/Effect";
24import * as Exit from "effect/Exit";
25import * as Fiber from "effect/Fiber";
26import * as Queue from "effect/Queue";
27import * as Random from "effect/Random";
28import * as Scope from "effect/Scope";
29import * as Stream from "effect/Stream";
30import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
31​
32import { ServerConfig } from "../../config.ts";
33import { makePiEnvironment } from "../Drivers/PiHome.ts";
34import {
35 ProviderAdapterProcessError,
36 ProviderAdapterSessionClosedError,
37 ProviderAdapterSessionNotFoundError,
38 ProviderAdapterValidationError,
39 type ProviderAdapterError,
40} from "../Errors.ts";
41import type { PiAdapterShape } from "../Services/PiAdapter.ts";
42​
43// RpcExtensionUIRequest / RpcExtensionUIResponse are defined in the pi package's
44// internal rpc-types module but not re-exported from the public index, so we
45// mirror the relevant subset here.
46type RpcExtensionUIRequest =
47 | { type: "extension_ui_request"; id: string; method: "select"; title: string; options: string[]; timeout?: number }
48 | { type: "extension_ui_request"; id: string; method: "confirm"; title: string; message: string; timeout?: number }
49 | { type: "extension_ui_request"; id: string; method: "input"; title: string; placeholder?: string; timeout?: number }
50 | { type: "extension_ui_request"; id: string; method: "editor"; title: string; prefill?: string }
51 | { type: "extension_ui_request"; id: string; method: "notify"; message: string; notifyType?: "info" | "warning" | "error" }
52 | { type: "extension_ui_request"; id: string; method: "setStatus"; statusKey: string; statusText: string | undefined }
53 | { type: "extension_ui_request"; id: string; method: "setWidget"; widgetKey: string; widgetLines: string[] | undefined; widgetPlacement?: "aboveEditor" | "belowEditor" }
54 | { type: "extension_ui_request"; id: string; method: "setTitle"; title: string }
55 | { type: "extension_ui_request"; id: string; method: "set_editor_text"; text: string };
56​
57type RpcExtensionUIResponse =
58 | { type: "extension_ui_response"; id: string; value: string }
59 | { type: "extension_ui_response"; id: string; confirmed: boolean }
60 | { type: "extension_ui_response"; id: string; cancelled: true };
61​
62const PROVIDER = ProviderDriverKind.make("piAgent");
63​
64interface PiToolItem {
65 readonly id: RuntimeItemId;
66 readonly type: CanonicalItemType;
67 readonly toolName: string;
68 readonly args: unknown;
70​
71interface PiTurnState {
72 readonly turnId: TurnId;
73 readonly startedAt: string;
74 readonly items: Array<PiToolItem>;
76​
77interface PendingExtensionUI {
78 readonly piId: string;
79 readonly questionId: string;
80 readonly deferred: Deferred.Deferred<ProviderUserInputAnswers, never>;
81 readonly method: "select" | "confirm" | "input" | "editor";
82 // Populated for `input` requests that were parsed as numbered lists.
83 // Used to map selected labels back to 1-based indices for Pi's multi-select protocol.
84 readonly numberedOptions?: ReadonlyArray<string>;
86​
87interface PiSessionContext {
88 session: ProviderSession;
89 readonly sessionScope: Scope.Closeable;
90 writeCommand: (cmd: RpcCommand) => Effect.Effect<void>;
91 writeExtensionResponse: (resp: RpcExtensionUIResponse) => Effect.Effect<void>;
92 stdoutFiber: Fiber.Fiber<void, never> | undefined;
93 readonly pendingRequests: Map<string, Deferred.Deferred<unknown, never>>;
94 readonly pendingExtensionUIs: Map<ApprovalRequestId, PendingExtensionUI>;
95 readonly startedAt: string;
96 turnState: PiTurnState | undefined;
97 readonly turns: Array<{ id: TurnId; items: Array<PiToolItem> }>;
98 stopped: boolean;
100​
101function toMessage(cause: unknown, fallback: string): string {
102 if (cause instanceof Error && cause.message.length > 0) {
103 return cause.message;
104 }
105 return fallback;
107​
108function readPiResumeState(resumeCursor: unknown): { sessionFile: string } | undefined {
109 if (!resumeCursor || typeof resumeCursor !== "object") return undefined;
110 const cursor = resumeCursor as Record<string, unknown>;
111 return typeof cursor.sessionFile === "string" && cursor.sessionFile.trim().length > 0
112 ? { sessionFile: cursor.sessionFile }
113 : undefined;
115​
116function classifyToolItemType(toolName: string): CanonicalItemType {
117 const normalized = toolName.toLowerCase();
118 if (
119 normalized.includes("agent") ||
120 normalized.includes("subagent") ||
121 normalized.includes("sub-agent") ||
122 normalized === "task" ||
123 normalized === "skill"
124 ) {
125 return "collab_agent_tool_call";
126 }
127 if (
128 normalized.includes("bash") ||
129 normalized.includes("shell") ||
130 normalized.includes("command") ||
131 normalized.includes("terminal") ||
132 normalized.includes("exec")
133 ) {
134 return "command_execution";
135 }
136 if (
137 normalized.includes("edit") ||
138 normalized.includes("write") ||
139 normalized.includes("file") ||
140 normalized.includes("patch") ||
141 normalized.includes("apply") ||
142 normalized.includes("replace") ||
143 normalized.includes("create") ||
144 normalized.includes("delete")
145 ) {
146 return "file_change";
147 }
148 if (normalized.includes("mcp")) {
149 return "mcp_tool_call";
150 }
151 if (normalized.includes("websearch") || normalized.includes("web search")) {
152 return "web_search";
153 }
154 if (normalized.includes("image")) {
155 return "image_view";
156 }
157 return "dynamic_tool_call";
159​
160// Pi's RPC multi-select fallback encodes options as a numbered list in the title:
161// "Which colors?\n1. Red\n2. Blue\n3. Green"
162// Returns the question title and extracted option strings, or null if no list found.
163function parseNumberedList(text: string): { title: string; items: ReadonlyArray<string> } | null {
164 const lines = text.split("\n");
165 const items: string[] = [];
166 for (const line of lines.slice(1)) {
167 const m = /^\d+\.\s+(.+)$/.exec(line.trim());
168 if (m?.[1]) items.push(m[1]);
169 }
170 return items.length >= 2 ? { title: lines[0] ?? text, items } : null;
172​
173function tryParseJsonObject(text: string): Record<string, unknown> | null {
174 try {
175 // eslint-disable-next-line no-restricted-syntax -- non-Effect context, no schema needed
176 const v = JSON.parse(text) as unknown; // @effect-diagnostics-ignore preferSchemaOverJson
177 return v !== null && typeof v === "object" ? (v as Record<string, unknown>) : null;
178 } catch {
179 return null;
180 }
182​
183function summarizePiToolArgs(args: unknown): string | undefined {
184 if (!args || typeof args !== "object") return undefined;
185 const input = args as Record<string, unknown>;
186​
187 const commandValue = input.command ?? input.cmd;
188 if (typeof commandValue === "string" && commandValue.trim().length > 0) {
189 return commandValue.trim().slice(0, 400);
190 }
191​
192 const skillValue = input.skill ?? input.skillName;
193 if (typeof skillValue === "string" && skillValue.trim().length > 0) {
194 const skillArgs = typeof input.args === "string" ? input.args.trim() : undefined;
195 return skillArgs ? `${skillValue.trim()} ${skillArgs}`.slice(0, 400) : skillValue.trim();
196 }
197​
198 const descValue = input.description ?? input.prompt;
199 if (typeof descValue === "string" && descValue.trim().length > 0) {
200 return descValue.trim().slice(0, 400);
201 }
202​
203 const pathValue = input.file_path ?? input.path ?? input.filePath;
204 if (typeof pathValue === "string" && pathValue.trim().length > 0) {
205 return pathValue.trim().slice(0, 400);
206 }
207​
208 const patternValue = input.pattern ?? input.query;
209 if (typeof patternValue === "string" && patternValue.trim().length > 0) {
210 return patternValue.trim().slice(0, 400);
211 }
212​
213 try {
214 const serialized = JSON.stringify(input);
215 if (serialized.length <= 400) return serialized;
216 return `${serialized.slice(0, 397)}...`;
217 } catch {
218 return undefined;
219 }
221​
222export interface PiAdapterLiveOptions {
223 readonly instanceId?: ProviderInstanceId;
224 readonly environment?: NodeJS.ProcessEnv;
226​
227export const makePiAdapter = Effect.fn("makePiAdapter")(function* (
228 piSettings: PiSettings,
229 options?: PiAdapterLiveOptions,
230) {
231 const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("piAgent");
232 const serverConfig = yield* ServerConfig;
233 const piEnvironment = yield* makePiEnvironment(piSettings, options?.environment);
234 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
235​
236 const sessions = new Map<ThreadId, PiSessionContext>();
237 const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
238​
239 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
240 const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
241 const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
242​
243 const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
244 Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
245​
246 const completeTurn = Effect.fn("completeTurn")(function* (
247 context: PiSessionContext,
248 state: ProviderRuntimeTurnStatus,
249 message?: string,
250 ) {
251 const turnState = context.turnState;
252 if (!turnState) return;
253​
254 context.turnState = undefined;
255 context.turns.push({
256 id: turnState.turnId,
257 items: [...turnState.items],
258 });
259​
260 const updatedAt = yield* nowIso;
261 context.session = {
262 ...context.session,
263 status: "ready",
264 activeTurnId: undefined,
265 updatedAt,
266 };
267​
268 const stamp = yield* makeEventStamp();
269 yield* offerRuntimeEvent({
270 type: "turn.completed",
271 eventId: stamp.eventId,
272 provider: PROVIDER,
273 createdAt: stamp.createdAt,
274 threadId: context.session.threadId,
275 turnId: turnState.turnId,
276 payload: {
277 state,
278 ...(message ? { message } : {}),
279 },
280 providerRefs: {},
281 });
282 });
283​
284 const handlePiEvent = Effect.fn("handlePiEvent")(function* (
285 context: PiSessionContext,
286 event: AgentSessionEvent,
287 ) {
288 const stamp = yield* makeEventStamp();
289 const base = {
290 eventId: stamp.eventId,
291 provider: PROVIDER,
292 createdAt: stamp.createdAt,
293 threadId: context.session.threadId,
294 ...(context.turnState ? { turnId: context.turnState.turnId } : {}),
295 providerRefs: {},
296 raw: {
297 source: "pi.sdk.event" as const,
298 method: event.type,
299 payload: event,
300 },
301 };
302​
303 switch (event.type) {
304 case "agent_start":
305 yield* offerRuntimeEvent({
306 ...base,
307 type: "session.state.changed",
308 payload: { state: "running" },
309 });
310 return;
311​
312 case "turn_start": {
313 if (!context.turnState) {
314 const turnId = TurnId.make(yield* Random.nextUUIDv4);
315 const startedAt = yield* nowIso;
316 context.turnState = { turnId, startedAt, items: [] };
317 const updatedAt = yield* nowIso;
318 context.session = {
319 ...context.session,
320 status: "running",
321 activeTurnId: turnId,
322 updatedAt,
323 };
324 yield* offerRuntimeEvent({
325 ...base,
326 turnId,
327 type: "turn.started",
328 payload: {},
329 });
330 }
331 return;
332 }
333​
334 case "message_update": {
335 if (!context.turnState) return;
336 const assistantEvent = event.assistantMessageEvent;
337 if (!assistantEvent) return;
338 if (assistantEvent.type === "text_delta") {
339 yield* offerRuntimeEvent({
340 ...base,
341 turnId: context.turnState.turnId,
342 type: "content.delta",
343 payload: {
344 streamKind: "assistant_text",
345 delta: assistantEvent.delta,
346 },
347 });
348 } else if (assistantEvent.type === "thinking_delta") {
349 yield* offerRuntimeEvent({
350 ...base,
351 turnId: context.turnState.turnId,
352 type: "content.delta",
353 payload: {
354 streamKind: "reasoning_text",
355 delta: assistantEvent.delta,
356 },
357 });
358 }
359 return;
360 }
361​
362 case "tool_execution_start": {
363 if (!context.turnState) return;
364 const itemId = RuntimeItemId.make(event.toolCallId);
365 const itemType = classifyToolItemType(event.toolName);
366 const detail = summarizePiToolArgs(event.args);
367 const argsObj =
368 event.args && typeof event.args === "object"
369 ? (event.args as Record<string, unknown>)
370 : undefined;
371 context.turnState.items.push({
372 id: itemId,
373 type: itemType,
374 toolName: event.toolName,
375 args: event.args,
376 });
377 yield* offerRuntimeEvent({
378 ...base,
379 turnId: context.turnState.turnId,
380 itemId,
381 type: "item.started",
382 payload: {
383 itemType,
384 title: event.toolName,
385 ...(detail ? { detail } : {}),
386 ...(argsObj ? { data: { toolName: event.toolName, input: argsObj } } : {}),
387 },
388 });
389 return;
390 }
391​
392 case "tool_execution_update": {
393 if (!context.turnState) return;
394 const itemId = RuntimeItemId.make(event.toolCallId);
395 const itemType = classifyToolItemType(event.toolName);
396 if (event.partialResult !== undefined) {
397 const partial =
398 typeof event.partialResult === "string"
399 ? event.partialResult
400 : String(event.partialResult);
401 yield* offerRuntimeEvent({
402 ...base,
403 turnId: context.turnState.turnId,
404 itemId,
405 type: "content.delta",
406 payload: {
407 streamKind:
408 itemType === "command_execution" ? "command_output" : "file_change_output",
409 delta: partial,
410 },
411 });
412 }
413 return;
414 }
415​
416 case "tool_execution_end": {
417 if (!context.turnState) return;
418 const itemId = RuntimeItemId.make(event.toolCallId);
419 const itemType = classifyToolItemType(event.toolName);
420 const storedItem = context.turnState.items.find((item) => item.id === itemId);
421 const args = storedItem?.args;
422 const detail = summarizePiToolArgs(args);
423 const argsObj =
424 args && typeof args === "object" ? (args as Record<string, unknown>) : undefined;
425 yield* offerRuntimeEvent({
426 ...base,
427 turnId: context.turnState.turnId,
428 itemId,
429 type: "item.completed",
430 payload: {
431 itemType,
432 title: event.toolName,
433 status: event.isError ? "failed" : "completed",
434 ...(detail ? { detail } : {}),
435 ...(argsObj ? { data: { toolName: event.toolName, input: argsObj } } : {}),
436 },
437 });
438 return;
439 }
440​
441 case "turn_end": {
442 // Pi fires turn_end after each internal LLM call, but agent_end fires
443 // after the full agent run. Completing here would fragment the Pi run
444 // into multiple t3code turns, causing tool activities to disappear and
445 // the timer to reset on every sub-turn. Let agent_end drive completion.
446 return;
447 }
448​
449 case "agent_end": {
450 if (context.turnState) {
451 const willRetry = "willRetry" in event ? Boolean(event.willRetry) : false;
452 yield* completeTurn(context, willRetry ? "interrupted" : "completed");
453 }
454 return;
455 }
456​
457 case "compaction_start": {
458 yield* offerRuntimeEvent({
459 ...base,
460 type: "session.state.changed",
461 payload: {
462 state: "waiting",
463 reason: `compaction:${"reason" in event ? String(event.reason) : "unknown"}`,
464 },
465 });
466 return;
467 }
468​
469 case "compaction_end": {
470 yield* offerRuntimeEvent({
471 ...base,
472 type: "thread.state.changed",
473 payload: { state: "compacted" },
474 });
475 return;
476 }
477​
478 default:
479 return;
480 }
481 });
482​
483 const handleExtensionUIRequest = Effect.fn("handleExtensionUIRequest")(function* (
484 context: PiSessionContext,
485 event: RpcExtensionUIRequest,
486 ) {
487 // Fire-and-forget side-effects: Pi does not wait for a response.
488 if (
489 event.method === "notify" ||
490 event.method === "setStatus" ||
491 event.method === "setWidget" ||
492 event.method === "setTitle" ||
493 event.method === "set_editor_text"
494 ) {
495 return;
496 }
497​
498 // editor: surface as freeform text input (same protocol shape as input).
499 // Falls through to the input branch below.
500​
501 // select / confirm / input: surface as user-input.requested
502 const ourRequestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
503 const questionId = String(ourRequestId);
504 const deferred = yield* Deferred.make<ProviderUserInputAnswers, never>();
505​
506 let question: UserInputQuestion;
507 let numberedOptions: ReadonlyArray<string> | undefined;
508​
509 if (event.method === "select") {
510 question = {
511 id: questionId,
512 header: event.title.slice(0, 12),
513 question: event.title,
514 options: event.options.map((label: string) => ({ label, description: label })),
515 multiSelect: false,
516 };
517 } else if (event.method === "confirm") {
518 const body = event.message.length > 0 ? `${event.title}\n${event.message}` : event.title;
519 question = {
520 id: questionId,
521 header: "Confirm",
522 question: body,
523 options: [
524 { label: "Yes", description: "Confirm" },
525 { label: "No", description: "Cancel" },
526 ],
527 multiSelect: false,
528 };
529 } else {
530 // input / editor — both expect { value: "..." } back.
531 // input: Pi uses this for multi-select (numbered list in title) and freeform.
532 // If the title contains a numbered list, parse it into real options with multiSelect.
533 // Otherwise surface with empty options; T3's auto-added "Other" field handles free text.
534 // editor: multi-line freeform, no options — same freeform path.
535 const title = "title" in event ? event.title : "";
536 const parsed = event.method === "input" ? parseNumberedList(title) : null;
537 if (parsed) {
538 numberedOptions = parsed.items;
539 question = {
540 id: questionId,
541 header: parsed.title.slice(0, 12),
542 question: parsed.title,
543 options: parsed.items.map((item) => ({ label: item, description: item })),
544 multiSelect: true,
545 };
546 } else {
547 question = {
548 id: questionId,
549 header: title.slice(0, 12),
550 question: title,
551 options: [],
552 multiSelect: false,
553 };
554 }
555 }
556​
557 context.pendingExtensionUIs.set(ourRequestId, {
558 piId: event.id,
559 questionId,
560 deferred,
561 method: event.method,
562 ...(numberedOptions ? { numberedOptions } : {}),
563 });
564​
565 const stamp = yield* makeEventStamp();
566 yield* offerRuntimeEvent({
567 type: "user-input.requested",
568 eventId: stamp.eventId,
569 provider: PROVIDER,
570 createdAt: stamp.createdAt,
571 threadId: context.session.threadId,
572 ...(context.turnState ? { turnId: context.turnState.turnId } : {}),
573 requestId: RuntimeRequestId.make(ourRequestId),
574 payload: { questions: [question] },
575 providerRefs: {},
576 raw: {
577 source: "pi.sdk.event" as const,
578 method: "extension_ui_request",
579 payload: event,
580 },
581 });
582 });
583​
584 const handleStdoutLine = Effect.fn("handleStdoutLine")(function* (
585 context: PiSessionContext,
586 line: string,
587 ) {
588 const trimmed = line.trim();
589 if (!trimmed) return;
590​
591 const msg = tryParseJsonObject(trimmed);
592 if (!msg) return;
593​
594 if (msg["type"] === "response") {
595 if (typeof msg["id"] === "string") {
596 const deferred = context.pendingRequests.get(msg["id"]);
597 if (deferred) {
598 context.pendingRequests.delete(msg["id"]);
599 yield* Deferred.succeed(deferred, msg);
600 }
601 }
602 return;
603 }
604​
605 if (msg["type"] === "extension_ui_request") {
606 yield* handleExtensionUIRequest(context, msg as RpcExtensionUIRequest);
607 return;
608 }
609​
610 yield* handlePiEvent(context, msg as AgentSessionEvent);
611 });
612​
613 const stopSessionInternal = Effect.fn("stopSessionInternal")(function* (
614 context: PiSessionContext,
615 options?: { readonly emitExitEvent?: boolean },
616 ) {
617 if (context.stopped) return;
618 context.stopped = true;
619​
620 if (context.turnState) {
621 yield* completeTurn(context, "interrupted", "Session stopped.");
622 }
623​
624 // Cancel any pending extension UI requests so Pi doesn't hang
625 for (const [, pending] of context.pendingExtensionUIs) {
626 yield* Effect.ignore(
627 context.writeExtensionResponse({ type: "extension_ui_response", id: pending.piId, cancelled: true }),
628 );
629 yield* Effect.ignore(Deferred.interrupt(pending.deferred));
630 }
631 context.pendingExtensionUIs.clear();
632​
633 if (context.stdoutFiber) {
634 yield* Fiber.interrupt(context.stdoutFiber);
635 context.stdoutFiber = undefined;
636 }
637​
638 yield* Effect.ignore(Scope.close(context.sessionScope, Exit.void));
639​
640 const updatedAt = yield* nowIso;
641 context.session = {
642 ...context.session,
643 status: "closed",
644 activeTurnId: undefined,
645 updatedAt,
646 };
647​
648 if (options?.emitExitEvent !== false) {
649 const stamp = yield* makeEventStamp();
650 yield* offerRuntimeEvent({
651 type: "session.exited",
652 eventId: stamp.eventId,
653 provider: PROVIDER,
654 createdAt: stamp.createdAt,
655 threadId: context.session.threadId,
656 payload: {
657 reason: "Session stopped",
658 exitKind: "graceful",
659 },
660 providerRefs: {},
661 });
662 }
663​
664 sessions.delete(context.session.threadId);
665 });
666​
667 const requireSession = (
668 threadId: ThreadId,
669 ): Effect.Effect<PiSessionContext, ProviderAdapterError> => {
670 const context = sessions.get(threadId);
671 if (!context) {
672 return Effect.fail(
673 new ProviderAdapterSessionNotFoundError({
674 provider: PROVIDER,
675 threadId,
676 }),
677 );
678 }
679 if (context.stopped || context.session.status === "closed") {
680 return Effect.fail(
681 new ProviderAdapterSessionClosedError({
682 provider: PROVIDER,
683 threadId,
684 }),
685 );
686 }
687 return Effect.succeed(context);
688 };
689​
690 const startSession: PiAdapterShape["startSession"] = Effect.fn("startSession")(function* (input) {
691 if (input.provider !== undefined && input.provider !== PROVIDER) {
692 return yield* new ProviderAdapterValidationError({
693 provider: PROVIDER,
694 operation: "startSession",
695 issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
696 });
697 }
698​
699 const existingContext = sessions.get(input.threadId);
700 if (existingContext) {
701 yield* stopSessionInternal(existingContext, { emitExitEvent: false }).pipe(
702 Effect.catchCause((cause) =>
703 Effect.logWarning("pi.session.replace.stop-failed", {
704 threadId: input.threadId,
705 cause,
706 }),
707 ),
708 );
709 }
710​
711 const startedAt = yield* nowIso;
712 const threadId = input.threadId;
713 const modelSelection =
714 input.modelSelection !== undefined && input.modelSelection.instanceId === boundInstanceId
715 ? input.modelSelection
716 : undefined;
717​
718 const piResumeState = readPiResumeState(input.resumeCursor);
719 const baseCwd = input.cwd ?? serverConfig.cwd;
720​
721 const spawnArgs: string[] = ["--mode", "rpc"];
722 if (piResumeState) {
723 spawnArgs.push("--session", piResumeState.sessionFile);
724 }
725 if (modelSelection?.model) {
726 spawnArgs.push("--model", modelSelection.model);
727 }
728​
729 const sessionScope = yield* Scope.make();
730​
731 const child = yield* spawner
732 .spawn(
733 ChildProcess.make(piSettings.binaryPath || "pi", spawnArgs, {
734 env: piEnvironment,
735 cwd: baseCwd,
736 shell: false,
737 }),
738 )
739 .pipe(
740 Effect.provideService(Scope.Scope, sessionScope),
741 Effect.mapError(
742 (cause) =>
743 new ProviderAdapterProcessError({
744 provider: PROVIDER,
745 threadId,
746 detail: toMessage(cause, "Failed to start Pi Agent RPC process."),
747 cause,
748 }),
749 ),
750 Effect.onError(() => Effect.ignore(Scope.close(sessionScope, Exit.void))),
751 );
752​
753 const outgoingQueue = yield* Queue.unbounded<Uint8Array>();
754​
755 const writeLine = (obj: RpcCommand | RpcExtensionUIResponse): Effect.Effect<void> =>
756 Queue.offer(outgoingQueue, Buffer.from(JSON.stringify(obj) + "\n")).pipe(Effect.asVoid);
757​
758 const writeCommand = (cmd: RpcCommand): Effect.Effect<void> => writeLine(cmd);
759 const writeExtensionResponse = (resp: RpcExtensionUIResponse): Effect.Effect<void> =>
760 writeLine(resp);
761​
762 const pendingRequests = new Map<string, Deferred.Deferred<unknown, never>>();
763 const pendingExtensionUIs = new Map<ApprovalRequestId, PendingExtensionUI>();
764​
765 const session: ProviderSession = {
766 threadId,
767 provider: PROVIDER,
768 providerInstanceId: boundInstanceId,
769 status: "ready",
770 runtimeMode: input.runtimeMode,
771 ...(input.cwd ? { cwd: input.cwd } : {}),
772 ...(modelSelection?.model ? { model: modelSelection.model } : {}),
773 createdAt: startedAt,
774 updatedAt: startedAt,
775 };
776​
777 const context: PiSessionContext = {
778 session,
779 sessionScope,
780 writeCommand,
781 writeExtensionResponse,
782 stdoutFiber: undefined,
783 pendingRequests,
784 pendingExtensionUIs,
785 startedAt,
786 turnState: undefined,
787 turns: [],
788 stopped: false,
789 };
790 sessions.set(threadId, context);
791​
792 const runtimeContext = yield* Effect.context<never>();
793 const runFork = Effect.runForkWith(runtimeContext);
794​
795 // Fork stdin writer — continuously drains the outgoing queue to the process stdin
796 runFork(
797 Stream.fromQueue(outgoingQueue).pipe(
798 Stream.run(child.stdin),
799 Effect.ignore,
800 ),
801 );
802​
803 // Fork stdout reader — parses JSONL events and routes them
804 const stdoutFiber = runFork(
805 child.stdout.pipe(
806 Stream.decodeText(),
807 Stream.splitLines,
808 Stream.mapEffect((line) => handleStdoutLine(context, line)),
809 Stream.runDrain,
810 Effect.ignore,
811 // Emit session exit if the process dies while the session is still active
812 Effect.ensuring(
813 Effect.suspend(() => {
814 if (!context.stopped && context.session.status !== "closed") {
815 return stopSessionInternal(context, { emitExitEvent: true });
816 }
817 return Effect.void;
818 }),
819 ),
820 ),
821 );
822 context.stdoutFiber = stdoutFiber;
823​
824 // Drain stderr to avoid blocking the process
825 runFork(
826 child.stderr.pipe(
827 Stream.runDrain,
828 Effect.ignore,
829 ),
830 );
831​
832 // Fetch the session file path via get_state for resume cursor
833 const stateReqId = yield* Random.nextUUIDv4;
834 const stateDeferred = yield* Deferred.make<unknown, never>();
835 pendingRequests.set(stateReqId, stateDeferred);
836 yield* writeCommand({ type: "get_state", id: stateReqId });
837​
838 const stateResponse = yield* Deferred.await(stateDeferred).pipe(
839 Effect.timeoutOption(5000),
840 );
841​
842 const sessionFile: string | undefined = (() => {
843 if (stateResponse._tag === "None") return undefined;
844 const resp = stateResponse.value as Record<string, unknown>;
845 if (resp["success"] !== true) return undefined;
846 const data = resp["data"];
847 if (!data || typeof data !== "object") return undefined;
848 const sf = (data as Record<string, unknown>)["sessionFile"];
849 return typeof sf === "string" && sf.trim().length > 0 ? sf.trim() : undefined;
850 })();
851​
852 if (sessionFile !== undefined) {
853 context.session = {
854 ...context.session,
855 resumeCursor: { sessionFile },
856 };
857 }
858​
859 const sessionStartedStamp = yield* makeEventStamp();
860 yield* offerRuntimeEvent({
861 type: "session.started",
862 eventId: sessionStartedStamp.eventId,
863 provider: PROVIDER,
864 createdAt: sessionStartedStamp.createdAt,
865 threadId,
866 payload: {},
867 providerRefs: {},
868 });
869​
870 const configuredStamp = yield* makeEventStamp();
871 yield* offerRuntimeEvent({
872 type: "session.configured",
873 eventId: configuredStamp.eventId,
874 provider: PROVIDER,
875 createdAt: configuredStamp.createdAt,
876 threadId,
877 payload: {
878 config: {
879 ...(modelSelection?.model ? { model: modelSelection.model } : {}),
880 ...(input.cwd ? { cwd: input.cwd } : {}),
881 },
882 },
883 providerRefs: {},
884 });
885​
886 const readyStamp = yield* makeEventStamp();
887 yield* offerRuntimeEvent({
888 type: "session.state.changed",
889 eventId: readyStamp.eventId,
890 provider: PROVIDER,
891 createdAt: readyStamp.createdAt,
892 threadId,
893 payload: { state: "ready" },
894 providerRefs: {},
895 });
896​
897 return { ...context.session };
898 });
899​
900 const sendTurn: PiAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
901 const context = yield* requireSession(input.threadId);
902​
903 if (context.turnState) {
904 yield* completeTurn(context, "completed");
905 }
906​
907 const turnId = TurnId.make(yield* Random.nextUUIDv4);
908 const turnStartedAt = yield* nowIso;
909 context.turnState = { turnId, startedAt: turnStartedAt, items: [] };
910 context.session = {
911 ...context.session,
912 status: "running",
913 activeTurnId: turnId,
914 updatedAt: turnStartedAt,
915 };
916​
917 const turnStartedStamp = yield* makeEventStamp();
918 yield* offerRuntimeEvent({
919 type: "turn.started",
920 eventId: turnStartedStamp.eventId,
921 provider: PROVIDER,
922 createdAt: turnStartedStamp.createdAt,
923 threadId: context.session.threadId,
924 turnId,
925 payload: {},
926 providerRefs: {},
927 });
928​
929 const promptText = typeof input.input === "string" ? input.input : "";
930​
931 yield* context.writeCommand({ type: "prompt", message: promptText }).pipe(
932 Effect.catchDefect(() => completeTurn(context, "failed", "Failed to send prompt.")),
933 );
934​
935 return {
936 threadId: context.session.threadId,
937 turnId,
938 };
939 });
940​
941 const interruptTurn: PiAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
942 function* (threadId, _turnId) {
943 const context = yield* requireSession(threadId);
944 yield* Effect.ignore(context.writeCommand({ type: "abort" }));
945 },
946 );
947​
948 const readThread: PiAdapterShape["readThread"] = Effect.fn("readThread")(function* (threadId) {
949 const context = yield* requireSession(threadId);
950 return {
951 threadId,
952 turns: context.turns.map((turn) => ({
953 id: turn.id,
954 items: [...turn.items],
955 })),
956 };
957 });
958​
959 const rollbackThread: PiAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(
960 function* (threadId, numTurns) {
961 const context = yield* requireSession(threadId);
962 const nextLength = Math.max(0, context.turns.length - numTurns);
963 context.turns.splice(nextLength);
964 return {
965 threadId,
966 turns: context.turns.map((turn) => ({
967 id: turn.id,
968 items: [...turn.items],
969 })),
970 };
971 },
972 );
973​
974 const respondToRequest: PiAdapterShape["respondToRequest"] = (_threadId, _requestId, _decision) =>
975 Effect.void;
976​
977 const respondToUserInput: PiAdapterShape["respondToUserInput"] = Effect.fn("respondToUserInput")(
978 function* (threadId, requestId, answers) {
979 const context = yield* requireSession(threadId);
980 const pending = context.pendingExtensionUIs.get(requestId);
981 if (!pending) return;
982 context.pendingExtensionUIs.delete(requestId);
983​
984 // Build the response Pi expects based on the original method
985 let piResponse: RpcExtensionUIResponse;
986 if (pending.method === "confirm") {
987 const answer = answers[pending.questionId];
988 piResponse = { type: "extension_ui_response", id: pending.piId, confirmed: answer === "Yes" };
989 } else if (pending.method === "input" && pending.numberedOptions) {
990 // Multi-select numbered list: map selected labels back to 1-based indices
991 const raw = answers[pending.questionId];
992 const selected: string[] = Array.isArray(raw)
993 ? raw.map(String)
994 : typeof raw === "string" && raw.length > 0
995 ? [raw]
996 : [];
997 const indices = selected
998 .map((label) => {
999 const idx = pending.numberedOptions!.indexOf(label);
1000 return idx >= 0 ? String(idx + 1) : null;
1001 })
1002 .filter((i): i is string => i !== null);
1003 piResponse = { type: "extension_ui_response", id: pending.piId, value: indices.join(",") };
1004 } else {
1005 // select or freeform input: answer is a string value
1006 const answer = answers[pending.questionId];
1007 const value = typeof answer === "string" ? answer : "";
1008 piResponse = { type: "extension_ui_response", id: pending.piId, value };
1010​
1011 yield* context.writeExtensionResponse(piResponse);
1012 yield* Deferred.succeed(pending.deferred, answers);
1013​
1014 const stamp = yield* makeEventStamp();
1015 yield* offerRuntimeEvent({
1016 type: "user-input.resolved",
1017 eventId: stamp.eventId,
1018 provider: PROVIDER,
1019 createdAt: stamp.createdAt,
1020 threadId: context.session.threadId,
1021 requestId: RuntimeRequestId.make(requestId),
1022 payload: { answers },
1023 providerRefs: {},
1024 });
1025 },
1026 );
1027​
1028 const stopSession: PiAdapterShape["stopSession"] = Effect.fn("stopSession")(function* (threadId) {
1029 const context = yield* requireSession(threadId);
1030 yield* stopSessionInternal(context, { emitExitEvent: true });
1031 });
1032​
1033 const listSessions: PiAdapterShape["listSessions"] = () =>
1034 Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session })));
1035​
1036 const hasSession: PiAdapterShape["hasSession"] = (threadId) =>
1037 Effect.sync(() => {
1038 const context = sessions.get(threadId);
1039 return context !== undefined && !context.stopped;
1040 });
1041​
1042 const stopAll: PiAdapterShape["stopAll"] = () =>
1043 Effect.forEach(
1044 sessions,
1045 ([, context]) => stopSessionInternal(context, { emitExitEvent: true }),
1046 { discard: true },
1047 );
1048​
1049 yield* Effect.addFinalizer(() =>
1050 Effect.forEach(
1051 sessions,
1052 ([, context]) => stopSessionInternal(context, { emitExitEvent: false }),
1053 { discard: true },
1054 ).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))),
1055 );
1056​
1057 return {
1058 provider: PROVIDER,
1059 capabilities: {
1060 sessionModelSwitch: "unsupported" as const,
1061 },
1062 startSession,
1063 sendTurn,
1064 interruptTurn,
1065 readThread,
1066 rollbackThread,
1067 respondToRequest,
1068 respondToUserInput,
1069 stopSession,
1070 listSessions,
1071 hasSession,
1072 stopAll,
1073 get streamEvents() {
1074 return Stream.fromQueue(runtimeEventQueue);
1075 },
1076 } satisfies PiAdapterShape;
1077});