@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 4,540 lines 184 KB
Raw
1 import * as HostProcess from "@t3tools/shared/HostProcess";
2 import * as NodeUtil from "node:util";
3 import { AgentScope } from "@t3tools/shared/AgentScope";
4 import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
5 import { readToolOutputImage } from "@t3tools/shared/toolOutput";
6 import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
7 import * as Predicate from "effect/Predicate";
8 import {
9 ProviderDriverKind,
10 type ChatAttachment,
11 type ModelSelection,
12 type OrchestrationV2ExecutionNode,
13 type OrchestrationV2ProviderCapabilities,
14 type OrchestrationV2ProviderFailure,
15 type OrchestrationV2ProviderRef,
16 type OrchestrationV2ProviderRetry,
17 type OrchestrationV2ProviderSession,
18 type OrchestrationV2ProviderThread,
19 type OrchestrationV2ProviderTurn,
20 type OrchestrationV2RuntimeRequest,
21 type OrchestrationV2Subagent,
22 type OrchestrationV2TurnItem,
23 type OrchestrationV2UserInputQuestion,
24 type ProviderApprovalDecision,
25 type ProviderInstanceId,
26 type MessageId,
27 type OrchestrationV2ProviderTurnTokenUsage,
28 } from "@t3tools/contracts";
29 import { PiSettings } from "../settings.ts";
30 import * as Cause from "effect/Cause";
31 import * as DateTime from "effect/DateTime";
32 import * as Deferred from "effect/Deferred";
33 import * as Option from "effect/Option";
34 import * as Path from "effect/Path";
35 import * as Duration from "effect/Duration";
36 import * as Effect from "effect/Effect";
37 import * as FileSystem from "effect/FileSystem";
38 import * as Exit from "effect/Exit";
39 import * as Scope from "effect/Scope";
40 import * as Fiber from "effect/Fiber";
41 import * as Queue from "effect/Queue";
42 import * as Schema from "effect/Schema";
43 import * as Semaphore from "effect/Semaphore";
44 import * as Stream from "effect/Stream";
45 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
46
47 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
48 import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt";
49 import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation";
50 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
51 import { parsePiCompactCommand, type PiCompactCommand } from "./commands.ts";
52 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
53 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
54 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
55 import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
56 import {
57 ProviderAdapterDriverCreateError,
58 type ProviderAdapterDriver,
59 type ProviderAdapterDriverCreateInput,
60 } from "@t3tools/provider-core/server/adapterDriver";
61 import {
62 makeProviderFailure,
63 makeProviderRetryTurnItem,
64 } from "@t3tools/provider-core/server/failure";
65 import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
66 import {
67 findReportedPiModel,
68 makePiRpcConnection,
69 resolvePiModelSlug,
70 piRecordField as recordField,
71 piRecordNumber as recordNumber,
72 piRecordString as recordString,
73 type PiRpcConnection,
74 type PiRpcError,
75 type PiRpcRecord,
76 } from "./rpc.ts";
77 import {
78 buildPiRpcLaunch,
79 materializePiT3McpExtension,
80 resolvePiLaunchArgs,
81 } from "./mcpInjection.ts";
82 import { PI_FILE_CHANGE_TOOLS, PI_T3_SERVICE_TIER_COMMAND } from "./mcpExtensionSource.ts";
83 import { PI_STANDARD_SERVICE_TIER } from "./modelCapabilities.ts";
84
85 export const PI_PROVIDER = ProviderDriverKind.make("pi");
86 const PI_DRIVER_KIND = PI_PROVIDER;
87 const DEFAULT_PI_SETTINGS = Schema.decodeSync(PiSettings)({});
88
89 // Inherit Pi's configured defaultProvider/defaultModel without calling set_model.
90 const PI_INHERIT_MODEL_SLUG = "default";
91
92 const STREAM_FLUSH_MS = 50;
93 const PI_REQUEST_TIMEOUT_MS = 15_000;
94 const PI_SUBAGENT_ASYNC_PREFIX = "PI_SUBAGENT_ASYNC_JSON:";
95 const decodePiJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
96 const PI_SESSION_TIMEOUT_MS = 60_000;
97 const MAX_EXTENSION_STATUSES = 32;
98 const MAX_EXTENSION_STATUS_KEY_LENGTH = 256;
99 const MAX_EXTENSION_STATUS_TEXT_LENGTH = 4096;
100 const PI_UNSOLICITED_ACTIVITY_ERROR =
101 "Pi started agent work outside an active T3 turn. The session was stopped to prevent invisible tool execution.";
102 const SETTLE_PROBE_MAX_ATTEMPTS = 3;
103 const SETTLE_PROBE_RETRY_DELAY = Duration.millis(100);
104
105 const PiProviderCapabilitiesV2 = {
106 runtimePolicy: { enforcement: "client-boundary" },
107 sessions: {
108 supportsMultipleProviderThreadsPerSession: false,
109 supportsModelSwitchInSession: true,
110 supportsProviderSwitchingViaHandoff: true,
111 // Restart on mode changes so the permission hook retains one immutable lifetime policy.
112 supportsRuntimeModeSwitchInSession: false,
113 pendingRequestsSurviveRestart: false,
114 },
115 threads: {
116 canCreateEmptyThread: true,
117 canReadThreadSnapshot: true,
118 canRollbackThread: true,
119 canForkThread: true,
120 canForkFromTurn: true,
121 canForkFromSubagentThread: false,
122 exposesNativeThreadId: true,
123 },
124 turns: {
125 exposesNativeTurnId: false,
126 emitsTurnStarted: true,
127 emitsTurnCompleted: true,
128 supportsInterrupt: true,
129 supportsNativeResume: false,
130 supportsActiveSteering: true,
131 supportsSteeringByInterruptRestart: false,
132 supportsQueuedMessages: true,
133 terminalStatusQuality: "strong",
134 },
135 streaming: {
136 streamsAssistantText: true,
137 streamsReasoning: true,
138 streamsToolOutput: true,
139 streamsPlanText: false,
140 emitsMessageCompleted: true,
141 },
142 tools: {
143 exposesToolItemIds: true,
144 emitsToolStarted: true,
145 emitsToolCompleted: true,
146 emitsToolOutput: true,
147 supportsMcpTools: true,
148 supportsDynamicToolCallbacks: false,
149 },
150 approvals: {
151 supportsCommandApproval: true,
152 supportsFileReadApproval: false,
153 supportsFileChangeApproval: true,
154 supportsApplyPatchApproval: false,
155 approvalsHaveNativeRequestIds: true,
156 approvalCallbacksAreLiveOnly: true,
157 approvalsCanOriginateFromSubagents: false,
158 },
159 planning: {
160 emitsPlanUpdated: false,
161 emitsTodoList: false,
162 emitsProposedPlan: false,
163 supportsStructuredQuestions: true,
164 planDeltasHaveItemIds: false,
165 },
166 subagents: {
167 supportsSubagents: true,
168 exposesSubagentThreadIds: false,
169 emitsSubagentLifecycle: true,
170 canWaitForSubagents: false,
171 canCloseSubagents: false,
172 canForkSubagentThread: false,
173 },
174 context: {
175 acceptsSystemContext: false,
176 acceptsDeveloperContext: false,
177 acceptsSyntheticUserContext: true,
178 canGenerateSummaries: false,
179 canConsumeHandoffSummaries: true,
180 supportsDeltaHandoff: true,
181 supportsFullThreadHandoff: true,
182 maxRecommendedHandoffChars: null,
183 },
184 checkpointing: {
185 appCanCheckpointFilesystem: true,
186 supportsNestedCheckpointScopes: false,
187 providerCanRollbackConversation: true,
188 // CommandPolicy requires a snapshot for rollback; rollbackThread returns the updated provider thread.
189 providerRollbackReturnsSnapshot: true,
190 providerCanReadConversationSnapshot: true,
191 },
192 identity: {
193 nativeThreadIds: "strong",
194 nativeTurnIds: "weak",
195 nativeItemIds: "strong",
196 nativeRequestIds: "strong",
197 },
198 } satisfies OrchestrationV2ProviderCapabilities;
199
200 export interface PiAdapterV2Options {
201 readonly instanceId: ProviderInstanceId;
202 readonly settings: PiSettings;
203 readonly environment: NodeJS.ProcessEnv;
204 readonly continuationRequests?: {
205 readonly offer: (
206 request: ProviderContinuationRequests.ProviderContinuationRequest,
207 ) => Effect.Effect<void>;
208 };
209 }
210
211 function contentText(content: unknown): string {
212 if (!Array.isArray(content)) {
213 return typeof content === "string" ? content : "";
214 }
215 return content
216 .map((block) => {
217 if (recordField(block, "type") === "text") return recordString(block, "text") ?? "";
218 return "";
219 })
220 .join("");
221 }
222
223 const MAX_STRUCTURED_TOOL_OUTPUT_BYTES = 64 * 1024;
224
225 function isBoundedStructuredToolValue(value: unknown): boolean {
226 let bytes = MAX_STRUCTURED_TOOL_OUTPUT_BYTES;
227 let nodes = 4_096;
228 const visit = (entry: unknown, depth: number): boolean => {
229 if (depth > 32 || --nodes < 0 || bytes < 0) return false;
230 if (Array.isArray(entry)) {
231 bytes -= 2 + entry.length;
232 return entry.every((item) => visit(item, depth + 1));
233 }
234 if (Predicate.isObject(entry)) {
235 bytes -= 2;
236 for (const key in entry) {
237 if (!Object.hasOwn(entry, key)) continue;
238 if (key.length > bytes) return false;
239 bytes -= Buffer.byteLength(JSON.stringify(key), "utf8") + 2;
240 if (!visit(entry[key], depth + 1)) return false;
241 }
242 return bytes >= 0;
243 }
244 if (typeof entry === "string" && entry.length > bytes) return false;
245 bytes -= Buffer.byteLength(JSON.stringify(entry) ?? "null", "utf8");
246 return bytes >= 0;
247 };
248 return visit(value, 0);
249 }
250
251 function piToolOutput(result: unknown, toolName: string): unknown {
252 const rawContent = recordField(result, "content");
253 const content = Array.isArray(rawContent)
254 ? rawContent
255 : typeof rawContent === "string"
256 ? [{ type: "text", text: rawContent }]
257 : [];
258 let structured = recordField(result, "structuredContent");
259 const details = recordField(result, "details");
260 const isMcpResult =
261 toolName.startsWith("mcp__") &&
262 recordString(details, "server") !== undefined &&
263 recordString(details, "tool") !== undefined &&
264 Array.isArray(recordField(structured, "content"));
265 if (isMcpResult) {
266 structured = recordField(structured, "structuredContent");
267 }
268 if (typeof structured === "string" && structured === contentText(content)) {
269 structured = undefined;
270 }
271 // Native read mirrors image/note in structured output; drop only that mirror, retaining extension metadata.
272 if (toolName === "read" && Predicate.isObject(structured)) {
273 const image = readToolOutputImage(structured);
274 const note =
275 recordString(
276 content.find((block) => recordField(block, "type") === "text"),
277 "text",
278 ) ?? "";
279 if (
280 image !== null &&
281 Object.keys(structured).every((key) => ["type", "data", "mimeType", "note"].includes(key)) &&
282 recordString(structured, "note") === note &&
283 content.some((block) => {
284 const match = readToolOutputImage(block);
285 return match !== null && match.mimeType === image.mimeType && match.data === image.data;
286 })
287 ) {
288 structured = undefined;
289 }
290 }
291 if (structured !== undefined && !isBoundedStructuredToolValue(structured)) {
292 return {
293 content: [
294 ...content,
295 {
296 type: "text",
297 text: "Structured output omitted because it exceeds the stored result limit.",
298 },
299 ],
300 };
301 }
302 if (
303 !isMcpResult &&
304 structured === undefined &&
305 content.every((block) => recordField(block, "type") === "text")
306 ) {
307 const text = contentText(content);
308 return text.length > 0 ? text : undefined;
309 }
310 return {
311 content,
312 ...(structured === undefined ? {} : { structuredContent: structured }),
313 };
314 }
315
316 function providerRef(
317 nativeId: string,
318 strength: "strong" | "weak" = "strong",
319 ): OrchestrationV2ProviderRef {
320 return { driver: PI_PROVIDER, nativeId, strength };
321 }
322
323 const PI_THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
324
325 interface PiStreamItemState {
326 readonly nativeItemId: string;
327 readonly kind: "assistant_message" | "reasoning";
328 text: string;
329 completed: boolean;
330 flushScheduled: boolean;
331 published: boolean;
332 readonly startedAt: DateTime.Utc;
333 }
334
335 type PiCompactionStatus = "running" | "completed" | "failed" | "cancelled";
336
337 interface PiCompactionState {
338 readonly nativeItemId: string;
339 readonly startedAt: DateTime.Utc;
340 }
341
342 interface PiProviderRetryState {
343 readonly retry: OrchestrationV2ProviderRetry;
344 readonly failure: OrchestrationV2ProviderFailure;
345 readonly startedAt: DateTime.Utc;
346 readonly itemOrdinal: number;
347 }
348
349 function compactionTitle(status: PiCompactionStatus): string {
350 switch (status) {
351 case "running":
352 return "Compacting context...";
353 case "completed":
354 return "Context compacted";
355 case "failed":
356 return "Context compaction failed";
357 case "cancelled":
358 return "Context compaction stopped";
359 }
360 }
361
362 interface ActivePiTurn {
363 readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput;
364 readonly providerTurn: OrchestrationV2ProviderTurn;
365 readonly startedAt: DateTime.Utc;
366 readonly itemOrdinals: Map<string, number>;
367 nextItemOrdinal: number;
368 messageOrdinal: number;
369 readonly streamItems: Map<string, PiStreamItemState>;
370 readonly toolArgs: Map<string, unknown>;
371 readonly toolStartedAt: Map<string, DateTime.Utc>;
372 readonly commandOutputBytes: Map<string, number>;
373 interrupted: boolean;
374 nativeAborted: boolean;
375 sawAgentActivity: boolean;
376 adoptedWake: boolean;
377 promptMayBeCommandOnly: boolean;
378 latestCompactionAfterTokens: number | null;
379 lastLiveUsedTokens: number | null;
380 settleProbeGeneration: number;
381 /** An extension may start compaction immediately after Pi emits agent_settled. */
382 settleWhenIdle: boolean;
383 /** Pi fails a cancelled compact's response too; that is a stop, not a turn failure. */
384 compactionCancelled: boolean;
385 manualCompactInFlight: boolean;
386 activeCompaction: PiCompactionState | null;
387 activeProviderRetry: PiProviderRetryState | null;
388 failure: ReturnType<typeof makeProviderFailure> | null;
389 rejectedPromptFailure: ReturnType<typeof makeProviderFailure> | null;
390 /** Steers Pi queued in send order; it reads them at a step boundary, after running tools return. */
391 readonly unreadSteers: Array<MessageId>;
392 stopTreeRefs?: PiTurnTreeRefs | null;
393 /** The provider/model Pi reported on its latest assistant message. */
394 reportedModel?: string;
395 }
396
397 interface PiTurnTreeRefs {
398 /** Omitted keeps the synthetic ref; null means the turn left nothing on the active branch. */
399 readonly nativeTurnRef: OrchestrationV2ProviderRef | null | undefined;
400 readonly leafId: string | null;
401 readonly retainedNativeTurnIds: ReadonlyArray<string> | undefined;
402 }
403
404 interface PendingPiPrompt {
405 readonly nativeRequestId: string;
406 readonly method: "select" | "confirm" | "input" | "editor";
407 readonly questionId: string;
408 readonly approvalKey: string;
409 readonly expiresAt: number | null;
410 expirationFiber: Fiber.Fiber<void> | null;
411 runtimeRequest: OrchestrationV2RuntimeRequest;
412 readonly node: OrchestrationV2ExecutionNode;
413 readonly turnItem: OrchestrationV2TurnItem;
414 readonly customAnswerRoute: PiCustomAnswerRoute | undefined;
415 }
416
417 /**
418 * The ask_user_question extension misreads typed text sent as a select value, so a custom answer
419 * picks the select's last "Type something." line and answers the input dialog that follows.
420 */
421 interface PiCustomAnswerRoute {
422 readonly lines: ReadonlyArray<unknown>;
423 readonly sentinel: string;
424 readonly followUpTitlePrefix: string;
425 }
426
427 function piApprovalRequestKind(title: string): "command" | "file-change" {
428 const toolName = /^Allow (\S+)\?$/.exec(title)?.[1];
429 return toolName !== undefined &&
430 (PI_FILE_CHANGE_TOOLS as ReadonlyArray<string>).includes(toolName)
431 ? "file-change"
432 : "command";
433 }
434
435 /** Pi 1.4.0 rejects prompts with this when they race a compaction it already started. */
436 const PI_COMPACTING_PROMPT_REJECTION = "Cannot submit a prompt while compaction is in progress";
437
438 interface PiPromptSend {
439 readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
440 readonly kind: "turn_start" | "steer";
441 readonly record: PiRpcRecord;
442 readonly messageId?: MessageId;
443 }
444
445 interface PiThreadState {
446 providerThread: OrchestrationV2ProviderThread;
447 activeTurn: ActivePiTurn | null;
448 /** Files an extension moved this thread off (ctx.newSession); queued turns may still name them. */
449 readonly supersededSessionFiles: Set<string>;
450 }
451
452 const isLiveSessionOf = (state: PiThreadState, nativeId: string | null | undefined) =>
453 nativeId === state.providerThread.nativeThreadRef?.nativeId ||
454 (nativeId != null && state.supersededSessionFiles.has(nativeId));
455
456 interface PiWake {
457 readonly state: PiThreadState;
458 readonly events: Array<PiRpcRecord>;
459 }
460
461 export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
462 options: PiAdapterV2Options,
463 ) {
464 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
465 const agentScope = yield* AgentScope;
466 const fileSystem = yield* FileSystem.FileSystem;
467 const path = yield* Path.Path;
468 const idAllocator = yield* IdAllocator.IdAllocatorV2;
469 const host = yield* ProviderHost.ProviderHost;
470 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
471 const { continuationRequests } = options;
472
473 const protocolError = (detail: string, payload?: unknown) =>
474 new ProviderAdapter.ProviderAdapterProtocolError({
475 driver: PI_PROVIDER,
476 detail,
477 ...(payload === undefined ? {} : { payload }),
478 });
479
480 return ProviderAdapter.ProviderAdapterV2.of({
481 instanceId: options.instanceId,
482 driver: PI_PROVIDER,
483 getCapabilities: Effect.fn("PiAdapter.getCapabilities")(function () {
484 return Effect.succeed(PiProviderCapabilitiesV2);
485 }),
486 planSelectionTransition: Effect.fn("PiAdapter.planSelectionTransition")(function () {
487 return Effect.succeed(turnScopedSelectionTransition());
488 }),
489 openSession: Effect.fn("PiAdapterV2.openSession")(function* (
490 input: ProviderAdapter.ProviderAdapterV2OpenSessionInput,
491 ) {
492 const scope = yield* Effect.scope;
493 const cwd = input.runtimePolicy.cwd ?? host.paths.cwd;
494 const mcpSession = yield* mcpSessions.read(input.threadId);
495 const provideCacheFs = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem>) =>
496 effect.pipe(
497 Effect.provideService(FileSystem.FileSystem, fileSystem),
498 Effect.mapError(
499 (cause) =>
500 new ProviderAdapter.ProviderAdapterOpenSessionError({
501 driver: PI_PROVIDER,
502 providerSessionId: input.providerSessionId,
503 cause,
504 }),
505 ),
506 );
507 // Always inject the permission hook even without MCP credentials; otherwise Supervised becomes unrestricted.
508 const extensionPath = yield* provideCacheFs(
509 materializePiT3McpExtension(host.paths.providerStatusCacheDir),
510 );
511 const resolvedLaunchArgs = resolvePiLaunchArgs(options.settings.launchArgs);
512 if (!resolvedLaunchArgs.ok) {
513 return yield* protocolError(resolvedLaunchArgs.message);
514 }
515 // A workspace handoff restarts Pi in a new cwd, but the session header still names the old one.
516 const sessionHeaderNamesCwd = Effect.fnUntraced(function* (sessionFile: string) {
517 const header = yield* fileSystem.stream(sessionFile).pipe(
518 Stream.decodeText(),
519 Stream.splitLines,
520 Stream.runHead,
521 Effect.map(Option.getOrUndefined),
522 Effect.orElseSucceed(() => undefined),
523 );
524 if (header === undefined) return true;
525 const sessionCwd = recordString(Option.getOrUndefined(decodeSessionLine(header)), "cwd");
526 if (sessionCwd === undefined || sessionCwd === cwd) return true;
527 const realCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd));
528 return sessionCwd === realCwd;
529 });
530 // Spawning on a session from another cwd would skip the handoff fork in registerThread.
531 const initialSessionPath =
532 input.initialNativeThreadId !== undefined &&
533 (yield* sessionHeaderNamesCwd(input.initialNativeThreadId))
534 ? input.initialNativeThreadId
535 : undefined;
536 const startConnection = Effect.fnUntraced(function* (sessionPath?: string) {
537 const connectionScope = yield* Scope.fork(scope, "sequential");
538 return yield* Effect.gen(function* () {
539 const launch = buildPiRpcLaunch({
540 launchArgs: resolvedLaunchArgs.args,
541 // PortScanner.AGENT_THREAD_ENV, as a literal because this package cannot reach apps/server.
542 environment: { ...options.environment, T3CODE_THREAD_ID: input.threadId },
543 mcpSession,
544 extensionPath,
545 sessionPath,
546 runtimeMode: input.runtimePolicy.runtimeMode,
547 });
548 const scopedLaunch = yield* agentScope.wrap({
549 command: options.settings.binaryPath || "pi",
550 args: launch.args,
551 name: "pi",
552 threadId: input.threadId,
553 env: launch.env,
554 });
555 // Finalizers run in reverse order: reap detached work after terminating Pi.
556 const scopeUnit = scopedLaunch.unit;
557 const stopScope =
558 scopeUnit === undefined
559 ? Effect.void
560 : yield* Effect.cached(agentScope.stop(scopeUnit));
561 yield* Effect.addFinalizer(() => stopScope);
562 const connection = yield* makePiRpcConnection({
563 command: scopedLaunch.command,
564 args: scopedLaunch.args,
565 cwd,
566 env: launch.env,
567 });
568 // Its tools carry T3CODE_THREAD_ID, so port discovery must scan while Pi runs.
569 const trackAgent = host.trackAgent;
570 if (trackAgent !== undefined) {
571 yield* Effect.acquireRelease(Effect.sync(trackAgent), (release) =>
572 Effect.sync(release),
573 );
574 }
575 // Detached children can keep stdout open after Pi exits.
576 if (scopeUnit !== undefined) {
577 yield* connection.exited.pipe(
578 Effect.matchEffect({ onFailure: () => stopScope, onSuccess: () => stopScope }),
579 Effect.forkIn(connectionScope),
580 );
581 }
582 return { connection, scope: connectionScope };
583 }).pipe(
584 Effect.provideService(Scope.Scope, connectionScope),
585 Effect.onExit((exit) =>
586 Exit.isFailure(exit) ? Scope.close(connectionScope, exit) : Effect.void,
587 ),
588 );
589 });
590 let started = yield* startConnection(initialSessionPath).pipe(
591 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
592 Effect.mapError(
593 (cause) =>
594 new ProviderAdapter.ProviderAdapterOpenSessionError({
595 driver: PI_PROVIDER,
596 providerSessionId: input.providerSessionId,
597 cause,
598 }),
599 ),
600 );
601 let connection: PiRpcConnection = started.connection;
602 const initialActivationDone = yield* Deferred.make<void>();
603 let initialActivationPending = initialSessionPath !== undefined;
604 let initialRequestStarted = false;
605 const now = yield* DateTime.now;
606 let sessionEntity: OrchestrationV2ProviderSession = {
607 id: input.providerSessionId,
608 driver: PI_PROVIDER,
609 providerInstanceId: options.instanceId,
610 status: "ready",
611 cwd,
612 model: input.modelSelection.model,
613 capabilities: PiProviderCapabilitiesV2,
614 extensionStatuses: [],
615 createdAt: now,
616 updatedAt: now,
617 lastError: null,
618 };
619 const events = yield* Queue.unbounded<
620 ProviderAdapter.ProviderAdapterV2Event,
621 ProviderAdapter.ProviderAdapterV2Error | Cause.Done
622 >();
623 const pendingPrompts = new Map<string, PendingPiPrompt>();
624 // Custom answers waiting for their ask_user_question follow-up input, keyed by title prefix.
625 // FIFO per prefix: the extension asks each follow-up right after its own select is answered.
626 const customAnswerFollowUps = new Map<string, string[]>();
627 const sessionApprovals = new Set<string>();
628 // Async pi-subagents runs launched in this session, by async id, until they settle.
629 const piAsyncRuns = new Map<
630 string,
631 {
632 readonly turn: ActivePiTurn;
633 readonly toolCallId: string;
634 readonly emitted: Map<string, string>;
635 }
636 >();
637 // The launch snapshot arrives before the tool result that names its run.
638 let latestAsyncSnapshotRuns: ReadonlyArray<unknown> = [];
639 // Pi can settle immediately after dialog response; serialize so terminal cannot overtake request resolution.
640 const sessionEventPermit = yield* Semaphore.make(1);
641 let threadState: PiThreadState | null = null;
642 let registrationAttempted = initialSessionPath !== undefined;
643 let registrationInProgress = false;
644 let lastNativeThreadId: string | null = initialSessionPath ?? null;
645 let stopRequested = false;
646 let unsolicitedActivityDetected = false;
647 // Turn failures can leave Pi alive; pump termination retires the runtime.
648 let runtimeRetired = false;
649 let pendingWake: PiWake | null = null;
650 let extensionStatusReset: {
651 previous: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]>;
652 readonly touched: Set<string>;
653 readonly ready: Deferred.Deferred<void, ProviderAdapter.ProviderAdapterProtocolError>;
654 } | null = null;
655 let rollbackBarrier: Deferred.Deferred<
656 void,
657 ProviderAdapter.ProviderAdapterProtocolError
658 > | null = null;
659 let pendingPromptResponsesDrained: Deferred.Deferred<
660 void,
661 ProviderAdapter.ProviderAdapterProtocolError
662 > | null = null;
663 let closed = false;
664 yield* Effect.addFinalizer(() =>
665 Effect.gen(function* () {
666 closed = true;
667 sessionEntity = { ...sessionEntity, extensionStatuses: [] };
668 pendingWake = null;
669 if (pendingPromptResponsesDrained !== null)
670 yield* Deferred.fail(
671 pendingPromptResponsesDrained,
672 protocolError("Pi session closed while awaiting prompt acknowledgment"),
673 );
674 if (extensionStatusReset !== null)
675 yield* Deferred.fail(
676 extensionStatusReset.ready,
677 protocolError("Pi session closed during status reset"),
678 );
679 if (rollbackBarrier !== null)
680 yield* Deferred.fail(
681 rollbackBarrier,
682 protocolError("Pi session closed during rollback"),
683 );
684 }),
685 );
686 let appliedModel: string | null = null;
687 let appliedThinking: string | null = null;
688 // Pi reloads extensions (resetting the tier) on paths the adapter cannot see, so a chosen tier
689 // is resent every turn; Standard sends a clear only when an earlier tier may still be set.
690 let serviceTierMayBeSet = false;
691 let appliedSessionName: string | null = null;
692 const outOfTurnExtensionErrors: Array<PiRpcRecord> = [];
693 let lastKnownLeaf: string | null = null;
694 // Failed get_entries leaves an untrustworthy turn boundary; re-sync the cursor on next capture.
695 let leafCursorStale = false;
696 // Pi has no unset commands; capture initial defaults so Pi default can replay them.
697 let baselineModel: { provider: string; modelId: string } | null = null;
698 let baselineThinking: string | null = null;
699 let contextWindow: number | null = null;
700 const modelContextWindows = new Map<string, number>();
701 let discoveredModels: ReadonlyArray<unknown> | null = null;
702 let nextPromptId = 0;
703 const pendingPromptResponses: Array<PiPromptSend & { readonly id: string }> = [];
704 const pendingCompactResponses: Array<{
705 readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
706 readonly kind: "turn_start" | "steer";
707 }> = [];
708 // Pi rejects every prompt while it compacts, including compaction an
709 // extension starts after the turn settled. Hold prompts until it ends.
710 let nativeCompacting = false;
711 const heldPrompts: Array<PiPromptSend> = [];
712 // Prompts sent before the pump observed compaction_start are rejected
713 // after it; they precede every prompt held since.
714 let rejectedHeldCount = 0;
715
716 const sendPrompt = Effect.fnUntraced(function* (prompt: PiPromptSend) {
717 if (nativeCompacting) {
718 heldPrompts.push(prompt);
719 return;
720 }
721 const id = `t3-prompt-${nextPromptId++}`;
722 yield* connection.send({ ...prompt.record, id });
723 pendingPromptResponsesDrained ??= yield* Deferred.make<
724 void,
725 ProviderAdapter.ProviderAdapterProtocolError
726 >();
727 pendingPromptResponses.push({ ...prompt, id });
728 });
729 // A just-released prompt has not started its run yet, so a settle probe
730 // racing it would see Pi idle. Its ack re-arms the probe instead.
731 let releasedPromptTurnId: OrchestrationV2ProviderTurn["id"] | null = null;
732
733 const compactRpcRecord = (command: PiCompactCommand): PiRpcRecord =>
734 command.customInstructions === undefined
735 ? { type: "compact" }
736 : { type: "compact", customInstructions: command.customInstructions };
737
738 const emit = (event: ProviderAdapter.ProviderAdapterV2Event) =>
739 Queue.offer(events, event).pipe(Effect.asVoid);
740
741 const emitSteerStatus = (
742 turn: ActivePiTurn,
743 messageId: MessageId,
744 status: "pending" | "completed" | "cancelled",
745 ) =>
746 emit({
747 type: "steer.updated",
748 driver: PI_PROVIDER,
749 threadId: turn.turnInput.threadId,
750 runId: turn.turnInput.runId,
751 messageId,
752 status,
753 });
754
755 const updateProviderSession =
756 /* Provider events include streaming deltas; avoid a span for each update. */
757 Effect.fnUntraced(function* (
758 status: OrchestrationV2ProviderSession["status"],
759 lastError: string | null = sessionEntity.lastError,
760 ) {
761 const updatedAt = yield* DateTime.now;
762 sessionEntity = {
763 ...sessionEntity,
764 status,
765 lastError,
766 updatedAt,
767 ...(status === "stopped" || runtimeRetired || unsolicitedActivityDetected
768 ? { extensionStatuses: [] }
769 : {}),
770 };
771 yield* emit({
772 type: "provider_session.updated",
773 driver: PI_PROVIDER,
774 providerSession: sessionEntity,
775 });
776 });
777
778 // Frequent notifications share the event pump's tracing boundary and outlive individual turns.
779 const updateExtensionStatus = Effect.fnUntraced(function* (event: PiRpcRecord) {
780 if (
781 closed ||
782 stopRequested ||
783 runtimeRetired ||
784 unsolicitedActivityDetected ||
785 sessionEntity.status === "stopped"
786 )
787 return;
788 const key = recordString(event, "statusKey");
789 const rawText = recordField(event, "statusText");
790 if (
791 key === undefined ||
792 key.trim().length === 0 ||
793 key.length > MAX_EXTENSION_STATUS_KEY_LENGTH ||
794 (rawText !== undefined && typeof rawText !== "string")
795 )
796 return;
797 const text =
798 typeof rawText === "string"
799 ? NodeUtil.stripVTControlCharacters(
800 rawText.slice(0, MAX_EXTENSION_STATUS_TEXT_LENGTH * 4),
801 )
802 .replaceAll(/\p{Cc}/gu, " ")
803 .trim()
804 .slice(0, MAX_EXTENSION_STATUS_TEXT_LENGTH)
805 : "";
806 const statuses = sessionEntity.extensionStatuses ?? [];
807 if (extensionStatusReset?.previous.some((status) => status.key === key)) {
808 extensionStatusReset.touched.add(key);
809 }
810 const index = statuses.findIndex((status) => status.key === key);
811 if (
812 index < 0
813 ? text.length === 0 || statuses.length >= MAX_EXTENSION_STATUSES
814 : statuses[index]?.text === text
815 )
816 return;
817 sessionEntity = {
818 ...sessionEntity,
819 extensionStatuses:
820 text.length === 0
821 ? statuses.filter((status) => status.key !== key)
822 : index < 0
823 ? [...statuses, { key, text }]
824 : statuses.map((status) => (status.key === key ? { key, text } : status)),
825 };
826 yield* updateProviderSession(sessionEntity.status);
827 });
828
829 const clearExtensionStatuses = Effect.fn("PiAdapter.clearExtensionStatuses")(function* () {
830 if (sessionEntity.extensionStatuses?.length === 0) return;
831 sessionEntity = { ...sessionEntity, extensionStatuses: [] };
832 yield* updateProviderSession(sessionEntity.status);
833 });
834
835 const updateProviderThread =
836 /* Provider events include streaming deltas; avoid a span for each update. */
837 Effect.fnUntraced(function* (
838 state: PiThreadState,
839 patch: Partial<OrchestrationV2ProviderThread>,
840 retainedNativeTurnIds?: ReadonlyArray<string>,
841 ) {
842 const updatedAt = yield* DateTime.now;
843 state.providerThread = { ...state.providerThread, ...patch, updatedAt };
844 yield* emit({
845 type: "provider_thread.updated",
846 driver: PI_PROVIDER,
847 providerThread: state.providerThread,
848 ...(retainedNativeTurnIds === undefined ? {} : { retainedNativeTurnIds }),
849 });
850 });
851
852 const itemOrdinal = (turn: ActivePiTurn, nativeItemId: string): number => {
853 const existing = turn.itemOrdinals.get(nativeItemId);
854 if (existing !== undefined) return existing;
855 const ordinal = turn.nextItemOrdinal++;
856 turn.itemOrdinals.set(nativeItemId, ordinal);
857 return ordinal;
858 };
859
860 const request = Effect.fnUntraced(function* (
861 record: PiRpcRecord,
862 timeoutMs = PI_REQUEST_TIMEOUT_MS,
863 ) {
864 if (!initialActivationPending || initialRequestStarted)
865 return yield* connection.request(record, timeoutMs);
866 initialRequestStarted = true;
867 return yield* connection.request(record, timeoutMs).pipe(
868 Effect.catchTags({
869 PiRpcError: Effect.fn("PiAdapter.recoverSpawnSession")(function* (error: PiRpcError) {
870 if (
871 closed ||
872 stopRequested ||
873 unsolicitedActivityDetected ||
874 (error.operation !== "read" && error.operation !== "write")
875 )
876 return yield* error;
877 // Pi can exit on an unusable --session before RPC starts.
878 // Finish failing its queue before retiring the readers.
879 yield* Queue.fail(connection.events, error);
880 yield* Scope.close(started.scope, Exit.void);
881 yield* sessionEventPermit.withPermits(1)(cancelPendingPrompts(yield* DateTime.now));
882 started = yield* startConnection().pipe(
883 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
884 );
885 connection = started.connection;
886 if (closed || stopRequested) {
887 yield* connection.terminate;
888 return yield* error;
889 }
890 return yield* connection.request(record, timeoutMs);
891 }),
892 }),
893 Effect.ensuring(
894 Effect.gen(function* () {
895 initialActivationPending = false;
896 yield* Deferred.succeed(initialActivationDone, undefined);
897 }),
898 ),
899 );
900 });
901
902 const nonNegativeInteger = (input: unknown, key: string): number | undefined => {
903 const value = recordNumber(input, key);
904 return value === undefined ? undefined : Math.max(0, Math.trunc(value));
905 };
906
907 const rememberModelContextWindow = (model: unknown): number | null => {
908 const provider = recordString(model, "provider");
909 const id = recordString(model, "id");
910 const capacity = nonNegativeInteger(model, "contextWindow");
911 if (provider !== undefined && id !== undefined && capacity !== undefined && capacity > 0) {
912 modelContextWindows.set(`${provider}/${id}`, capacity);
913 return capacity;
914 }
915 return null;
916 };
917
918 const lifecycleRequest = Effect.fn("PiAdapter.lifecycleRequest")(
919 function* (record: PiRpcRecord) {
920 if (extensionStatusReset !== null)
921 return yield* protocolError("A Pi session lifecycle request is already pending");
922 const reset = {
923 previous: sessionEntity.extensionStatuses ?? [],
924 touched: new Set<string>(),
925 ready: yield* Deferred.make<void, ProviderAdapter.ProviderAdapterProtocolError>(),
926 };
927 extensionStatusReset = reset;
928 return yield* Effect.gen(function* () {
929 // RPC responses bypass the pump. Reset after all earlier native notifications.
930 if (
931 !(yield* Queue.offer(connection.events, { type: "t3.extension_status_reset", reset }))
932 )
933 return yield* protocolError("Pi transport closed during status reset");
934 yield* Deferred.await(reset.ready);
935 const result = yield* request(record, PI_SESSION_TIMEOUT_MS);
936 if (recordField(result, "cancelled") === true) {
937 yield* sessionEventPermit.withPermits(1)(
938 Effect.gen(function* () {
939 if (closed || stopRequested) return;
940 const current = sessionEntity.extensionStatuses ?? [];
941 // A veto keeps the old session. Preserve updates and clears from its lifecycle hooks.
942 const restored = reset.previous.flatMap((status) => {
943 if (!reset.touched.has(status.key)) return [status];
944 const updated = current.find((candidate) => candidate.key === status.key);
945 return updated === undefined ? [] : [updated];
946 });
947 restored.push(
948 ...current.filter(
949 (status) => !reset.previous.some((previous) => previous.key === status.key),
950 ),
951 );
952 const statuses = restored.slice(0, MAX_EXTENSION_STATUSES);
953 if (
954 statuses.length === current.length &&
955 statuses.every(
956 (status, index) =>
957 status.key === current[index]?.key && status.text === current[index]?.text,
958 )
959 )
960 return;
961 sessionEntity = { ...sessionEntity, extensionStatuses: statuses };
962 yield* updateProviderSession(sessionEntity.status);
963 }),
964 );
965 }
966 return result;
967 }).pipe(
968 Effect.ensuring(
969 Effect.sync(() => {
970 if (extensionStatusReset === reset) extensionStatusReset = null;
971 }),
972 ),
973 );
974 },
975 (effect, record) =>
976 effect.pipe(
977 Effect.tapError((error) =>
978 Effect.logWarning("Pi session lifecycle request failed", {
979 providerSessionId: input.providerSessionId,
980 operation: record["type"],
981 errorTag: error._tag,
982 }),
983 ),
984 // A failed lifecycle RPC can leave Pi's previous native session disposed.
985 Effect.tapError((error) =>
986 error._tag === "PiRpcError" || error._tag === "PiRpcTimeoutError"
987 ? connection.terminate
988 : Effect.void,
989 ),
990 Effect.onInterrupt(() => connection.terminate),
991 ),
992 );
993
994 const tokenUsageFromStats = (
995 stats: unknown,
996 fallbackUsedTokens: number | null,
997 updatedAt: DateTime.Utc,
998 ): OrchestrationV2ProviderTurnTokenUsage | undefined => {
999 const contextUsage = recordField(stats, "contextUsage");
1000 const maxTokens = nonNegativeInteger(contextUsage, "contextWindow");
1001 const usedTokens =
1002 nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined;
1003 if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0)
1004 return undefined;
1005
1006 const totals = recordField(stats, "tokens");
1007 const inputTokens = nonNegativeInteger(totals, "input");
1008 const cachedInputTokens = nonNegativeInteger(totals, "cacheRead");
1009 const outputTokens = nonNegativeInteger(totals, "output");
1010 return {
1011 usedTokens,
1012 maxTokens,
1013 ...(inputTokens === undefined ? {} : { inputTokens }),
1014 ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),
1015 ...(outputTokens === undefined ? {} : { outputTokens }),
1016 updatedAt: DateTime.formatIso(updatedAt),
1017 };
1018 };
1019
1020 const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) =>
1021 request({ type: "get_session_stats" }, 2_000).pipe(
1022 Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)),
1023 Effect.orElseSucceed(() => undefined),
1024 );
1025
1026 /**
1027 * Pi attaches the current message's cumulative usage to every streaming update (0.84.2+).
1028 */
1029 const reportLiveUsage =
1030 /* Provider events include streaming deltas; avoid a span for each update. */
1031 Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) {
1032 const usedTokens = nonNegativeInteger(usage, "totalTokens");
1033 if (
1034 usedTokens === undefined ||
1035 usedTokens === 0 ||
1036 usedTokens === turn.lastLiveUsedTokens ||
1037 contextWindow === null ||
1038 contextWindow === 0
1039 ) {
1040 return;
1041 }
1042 turn.lastLiveUsedTokens = usedTokens;
1043 const inputTokens = nonNegativeInteger(usage, "input");
1044 const cachedInputTokens = nonNegativeInteger(usage, "cacheRead");
1045 const outputTokens = nonNegativeInteger(usage, "output");
1046 const updatedAt = yield* DateTime.now;
1047 yield* emit({
1048 type: "provider_turn.updated",
1049 driver: PI_PROVIDER,
1050 threadId: turn.turnInput.threadId,
1051 providerTurn: {
1052 ...turn.providerTurn,
1053 tokenUsage: {
1054 usedTokens,
1055 maxTokens: contextWindow,
1056 ...(inputTokens === undefined ? {} : { inputTokens }),
1057 ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),
1058 ...(outputTokens === undefined ? {} : { outputTokens }),
1059 updatedAt: DateTime.formatIso(updatedAt),
1060 },
1061 },
1062 });
1063 });
1064
1065 const baseItemFields = (
1066 turn: ActivePiTurn,
1067 nativeItemId: string,
1068 startedAt: DateTime.Utc,
1069 updatedAt: DateTime.Utc,
1070 parentNativeItemId?: string,
1071 ) => ({
1072 id: idAllocator.derive.turnItemFromProviderItem({
1073 driver: PI_PROVIDER,
1074 nativeItemId,
1075 }),
1076 threadId: turn.turnInput.threadId,
1077 runId: turn.turnInput.runId,
1078 nodeId: idAllocator.derive.nodeFromProviderItem({
1079 driver: PI_PROVIDER,
1080 nativeItemId,
1081 }),
1082 providerThreadId: turn.turnInput.providerThread.id,
1083 providerTurnId: turn.providerTurn.id,
1084 nativeItemRef: providerRef(nativeItemId),
1085 parentItemId:
1086 parentNativeItemId === undefined
1087 ? null
1088 : idAllocator.derive.turnItemFromProviderItem({
1089 driver: PI_PROVIDER,
1090 nativeItemId: parentNativeItemId,
1091 }),
1092 ordinal: itemOrdinal(turn, nativeItemId),
1093 startedAt,
1094 updatedAt,
1095 });
1096
1097 const emitItemNode = (
1098 turn: ActivePiTurn,
1099 nativeItemId: string,
1100 kind: OrchestrationV2ExecutionNode["kind"],
1101 status: OrchestrationV2ExecutionNode["status"],
1102 startedAt: DateTime.Utc,
1103 completedAt: DateTime.Utc | null,
1104 parentNativeItemId?: string,
1105 ) =>
1106 emit({
1107 type: "node.updated",
1108 driver: PI_PROVIDER,
1109 node: {
1110 id: idAllocator.derive.nodeFromProviderItem({
1111 driver: PI_PROVIDER,
1112 nativeItemId,
1113 }),
1114 threadId: turn.turnInput.threadId,
1115 runId: turn.turnInput.runId,
1116 parentNodeId:
1117 parentNativeItemId === undefined
1118 ? turn.turnInput.rootNodeId
1119 : idAllocator.derive.nodeFromProviderItem({
1120 driver: PI_PROVIDER,
1121 nativeItemId: parentNativeItemId,
1122 }),
1123 rootNodeId: turn.turnInput.rootNodeId,
1124 kind,
1125 status,
1126 countsForRun: false,
1127 providerThreadId: turn.turnInput.providerThread.id,
1128 providerTurnId: turn.providerTurn.id,
1129 nativeItemRef: providerRef(nativeItemId),
1130 runtimeRequestId: null,
1131 checkpointScopeId: null,
1132 startedAt,
1133 completedAt,
1134 },
1135 });
1136
1137 const emitProviderRetry = Effect.fnUntraced(function* (
1138 turn: ActivePiTurn,
1139 providerRetry: PiProviderRetryState,
1140 status: "running" | "completed" | "failed" | "interrupted" | "cancelled",
1141 updatedAt: DateTime.Utc,
1142 ) {
1143 yield* emit({
1144 type: "turn_item.updated",
1145 driver: PI_PROVIDER,
1146 turnItem: makeProviderRetryTurnItem({
1147 driver: PI_PROVIDER,
1148 threadId: turn.turnInput.threadId,
1149 runId: turn.turnInput.runId,
1150 nodeId: turn.turnInput.rootNodeId,
1151 providerThreadId: turn.turnInput.providerThread.id,
1152 providerTurnId: turn.providerTurn.id,
1153 itemOrdinal: providerRetry.itemOrdinal,
1154 failure: providerRetry.failure,
1155 retry: providerRetry.retry,
1156 status,
1157 startedAt: providerRetry.startedAt,
1158 updatedAt,
1159 }),
1160 });
1161 });
1162
1163 const compactionNativeItemId = (turn: ActivePiTurn): string =>
1164 `compaction:${turn.providerTurn.id}:${turn.nextItemOrdinal}`;
1165
1166 const emitCompaction = Effect.fnUntraced(function* (
1167 turn: ActivePiTurn,
1168 compaction: PiCompactionState,
1169 status: PiCompactionStatus,
1170 details: {
1171 readonly summary?: string;
1172 readonly beforeTokenCount?: number;
1173 readonly afterTokenCount?: number;
1174 } = {},
1175 ) {
1176 const emittedAt = yield* DateTime.now;
1177 const completedAt = status === "running" ? null : emittedAt;
1178 yield* emitItemNode(
1179 turn,
1180 compaction.nativeItemId,
1181 "system",
1182 status,
1183 compaction.startedAt,
1184 completedAt,
1185 );
1186 yield* emit({
1187 type: "turn_item.updated",
1188 driver: PI_PROVIDER,
1189 turnItem: {
1190 ...baseItemFields(turn, compaction.nativeItemId, compaction.startedAt, emittedAt),
1191 status,
1192 title: compactionTitle(status),
1193 completedAt,
1194 type: "compaction",
1195 driver: PI_PROVIDER,
1196 ...details,
1197 },
1198 });
1199 });
1200
1201 const emitStreamItem =
1202 /* Provider events include streaming deltas; avoid a span for each update. */
1203 Effect.fnUntraced(function* (
1204 turn: ActivePiTurn,
1205 item: PiStreamItemState,
1206 streaming: boolean,
1207 ) {
1208 item.published = true;
1209 const emittedAt = yield* DateTime.now;
1210 const base = baseItemFields(turn, item.nativeItemId, item.startedAt, emittedAt);
1211 yield* emitItemNode(
1212 turn,
1213 item.nativeItemId,
1214 item.kind,
1215 streaming ? "running" : "completed",
1216 item.startedAt,
1217 streaming ? null : emittedAt,
1218 );
1219 if (item.kind === "assistant_message") {
1220 const messageId = idAllocator.derive.messageFromProviderItem({
1221 driver: PI_PROVIDER,
1222 nativeItemId: item.nativeItemId,
1223 });
1224 yield* emit({
1225 type: "turn_item.updated",
1226 driver: PI_PROVIDER,
1227 turnItem: {
1228 ...base,
1229 status: streaming ? "running" : "completed",
1230 title: null,
1231 completedAt: streaming ? null : emittedAt,
1232 type: "assistant_message",
1233 messageId,
1234 text: item.text,
1235 streaming,
1236 },
1237 });
1238 yield* emit({
1239 type: "message.updated",
1240 driver: PI_PROVIDER,
1241 message: {
1242 id: messageId,
1243 threadId: turn.turnInput.threadId,
1244 runId: turn.turnInput.runId,
1245 nodeId: idAllocator.derive.nodeFromProviderItem({
1246 driver: PI_PROVIDER,
1247 nativeItemId: item.nativeItemId,
1248 }),
1249 role: "assistant",
1250 text: item.text,
1251 attachments: [],
1252 streaming,
1253 createdBy: "agent",
1254 creationSource: "provider",
1255 createdAt: item.startedAt,
1256 updatedAt: emittedAt,
1257 },
1258 });
1259 return;
1260 }
1261 yield* emit({
1262 type: "turn_item.updated",
1263 driver: PI_PROVIDER,
1264 turnItem: {
1265 ...base,
1266 status: streaming ? "running" : "completed",
1267 title: null,
1268 completedAt: streaming ? null : emittedAt,
1269 type: "reasoning",
1270 text: item.text,
1271 streaming,
1272 },
1273 });
1274 });
1275
1276 const scheduleStreamFlush =
1277 /* Provider events include streaming deltas; avoid a span for each update. */
1278 Effect.fnUntraced(function* (turn: ActivePiTurn, item: PiStreamItemState) {
1279 if (item.flushScheduled || item.completed) return;
1280 item.flushScheduled = true;
1281 yield* Effect.sleep(Duration.millis(STREAM_FLUSH_MS)).pipe(
1282 Effect.andThen(
1283 Effect.suspend(() => {
1284 item.flushScheduled = false;
1285 return item.completed ? Effect.void : emitStreamItem(turn, item, true);
1286 }),
1287 ),
1288 Effect.forkIn(scope),
1289 );
1290 });
1291
1292 const streamItemId = (turn: ActivePiTurn, contentIndex: number) =>
1293 `${turn.providerTurn.id}:m${turn.messageOrdinal}:c${contentIndex}`;
1294
1295 const streamItemFor = Effect.fnUntraced(function* (
1296 turn: ActivePiTurn,
1297 kind: PiStreamItemState["kind"],
1298 contentIndex: number,
1299 ) {
1300 const nativeItemId = streamItemId(turn, contentIndex);
1301 const existing = turn.streamItems.get(nativeItemId);
1302 if (existing !== undefined) return existing;
1303 const startedAt = yield* DateTime.now;
1304 const item: PiStreamItemState = {
1305 nativeItemId,
1306 kind,
1307 text: "",
1308 completed: false,
1309 flushScheduled: false,
1310 published: false,
1311 startedAt,
1312 };
1313 turn.streamItems.set(nativeItemId, item);
1314 itemOrdinal(turn, nativeItemId);
1315 return item;
1316 });
1317
1318 const completeStreamItem = (turn: ActivePiTurn, item: PiStreamItemState, text?: string) =>
1319 Effect.suspend(() => {
1320 if (item.completed) return Effect.void;
1321 item.completed = true;
1322 if (text !== undefined && text.length > 0) item.text = text;
1323 // A block that was shown and then started again empty still replaces what it showed.
1324 return item.text.length === 0 && !item.published
1325 ? Effect.void
1326 : emitStreamItem(turn, item, false);
1327 });
1328
1329 const completeOpenStreamItems = (turn: ActivePiTurn) =>
1330 Effect.forEach(
1331 Array.from(turn.streamItems.values()).filter((item) => !item.completed),
1332 (item) => completeStreamItem(turn, item),
1333 { discard: true },
1334 );
1335
1336 // Pi resends the whole output tail on every update; stored snapshots grow quadratically.
1337 const emitCommandOutputDelta = (turn: ActivePiTurn, toolCallId: string, result: unknown) =>
1338 Effect.suspend(() => {
1339 const text = contentText(recordField(result, "content"));
1340 const tail = Buffer.from(text, "utf8");
1341 const totalBytes =
1342 recordNumber(recordField(recordField(result, "details"), "truncation"), "totalBytes") ??
1343 tail.length;
1344 const previousBytes = turn.commandOutputBytes.get(toolCallId) ?? 0;
1345 turn.commandOutputBytes.set(toolCallId, totalBytes);
1346 if (totalBytes <= previousBytes) return Effect.void;
1347 let start = Math.max(0, tail.length - (totalBytes - previousBytes));
1348 while (start < tail.length && (tail[start]! & 0xc0) === 0x80) start++;
1349 const chunk = tail.subarray(start).toString("utf8");
1350 if (chunk.length === 0) return Effect.void;
1351 return emit({
1352 type: "command_output.delta",
1353 driver: PI_PROVIDER,
1354 threadId: turn.turnInput.threadId,
1355 itemId: idAllocator.derive.turnItemFromProviderItem({
1356 driver: PI_PROVIDER,
1357 nativeItemId: toolCallId,
1358 }),
1359 chunk,
1360 });
1361 });
1362
1363 const emitToolItem = Effect.fnUntraced(function* (
1364 turn: ActivePiTurn,
1365 event: PiRpcRecord,
1366 phase: "start" | "update" | "end",
1367 ) {
1368 const toolCallId = recordString(event, "toolCallId");
1369 const toolName = recordString(event, "toolName") ?? "tool";
1370 // Pi tags every phase of a call made through ctx.executeTool, such as from a codemode script.
1371 const parentToolCallId = recordString(event, "parentToolCallId");
1372 if (toolCallId === undefined) return;
1373 if (phase === "update" && (toolName === "bash" || toolName === "powershell")) {
1374 yield* emitCommandOutputDelta(turn, toolCallId, event["partialResult"]);
1375 return;
1376 }
1377 if (phase === "start") {
1378 turn.toolArgs.set(toolCallId, event["args"]);
1379 }
1380 const args = event["args"] ?? turn.toolArgs.get(toolCallId);
1381 const emittedAt = yield* DateTime.now;
1382 const startedAt = turn.toolStartedAt.get(toolCallId) ?? emittedAt;
1383 turn.toolStartedAt.set(toolCallId, startedAt);
1384 const completed = phase === "end";
1385 const isError = event["isError"] === true;
1386 const resultRecord = completed ? event["result"] : event["partialResult"];
1387 const outputText = contentText(recordField(resultRecord, "content"));
1388 const status = completed
1389 ? isError
1390 ? turn.interrupted
1391 ? "interrupted"
1392 : "failed"
1393 : "completed"
1394 : "running";
1395 const base = baseItemFields(turn, toolCallId, startedAt, emittedAt, parentToolCallId);
1396 yield* emitItemNode(
1397 turn,
1398 toolCallId,
1399 "tool_call",
1400 status,
1401 startedAt,
1402 completed ? emittedAt : null,
1403 parentToolCallId,
1404 );
1405 const shared = {
1406 ...base,
1407 status,
1408 completedAt: completed ? emittedAt : null,
1409 } as const;
1410 if (toolName === "bash" || toolName === "powershell") {
1411 const exitCode =
1412 recordNumber(recordField(resultRecord, "structuredContent"), "exit_code") ??
1413 recordNumber(recordField(resultRecord, "details"), "exitCode");
1414 yield* emit({
1415 type: "turn_item.updated",
1416 driver: PI_PROVIDER,
1417 turnItem: {
1418 ...shared,
1419 title: toolName,
1420 type: "command_execution",
1421 input: recordString(args, "command") ?? "",
1422 ...(outputText.length > 0 ? { output: outputText } : {}),
1423 ...(exitCode === undefined ? {} : { exitCode }),
1424 },
1425 });
1426 return;
1427 }
1428 if (toolName === "edit" || toolName === "write") {
1429 const fileName = recordString(args, "path") ?? recordString(args, "file_path");
1430 if (fileName !== undefined) {
1431 const diffStr =
1432 recordString(recordField(resultRecord, "details"), "patch") ??
1433 (isError && outputText.trim().length > 0 ? outputText : undefined);
1434 const newStr = toolName === "write" ? recordString(args, "content") : undefined;
1435 yield* emit({
1436 type: "turn_item.updated",
1437 driver: PI_PROVIDER,
1438 turnItem: {
1439 ...shared,
1440 title: toolName,
1441 type: "file_change",
1442 fileName,
1443 ...(diffStr === undefined ? {} : { diffStr }),
1444 ...(newStr === undefined ? {} : { newStr }),
1445 },
1446 });
1447 return;
1448 }
1449 }
1450 const output = piToolOutput(resultRecord, toolName);
1451 const readPath =
1452 toolName === "read"
1453 ? (recordString(args, "path") ?? recordString(args, "file_path"))?.trim()
1454 : undefined;
1455 const viewedImagePath =
1456 readPath &&
1457 readPath.length <= 4096 &&
1458 !/[\r\n]/.test(readPath) &&
1459 isWorkspaceImagePreviewPath(readPath)
1460 ? readPath
1461 : undefined;
1462 yield* emit({
1463 type: "turn_item.updated",
1464 driver: PI_PROVIDER,
1465 turnItem: {
1466 ...shared,
1467 title: toolName,
1468 type: "dynamic_tool",
1469 ...mcpToolPresentation({ toolName }),
1470 toolName,
1471 input: args ?? {},
1472 ...(output === undefined ? {} : { output }),
1473 ...(viewedImagePath === undefined ? {} : { viewedImagePath }),
1474 },
1475 });
1476 if (toolName === "subagent") {
1477 yield* emitSubagentTasks(turn, toolCallId, resultRecord, completed);
1478 }
1479 });
1480
1481 const emitSubagentTasks = Effect.fnUntraced(function* (
1482 turn: ActivePiTurn,
1483 toolCallId: string,
1484 resultRecord: unknown,
1485 completed: boolean,
1486 ) {
1487 const details = recordField(resultRecord, "details");
1488 const results = recordField(details, "results");
1489 if (!Array.isArray(results)) return;
1490 let emitted = false;
1491 for (const [index, result] of results.entries()) {
1492 const agent = recordString(result, "agent");
1493 const task = recordString(result, "task");
1494 if (agent === undefined || task === undefined) continue;
1495 emitted = true;
1496 const finished = completed || recordField(result, "finished") === true;
1497 const stopReason = recordString(result, "stopReason");
1498 const interrupted = finished && stopReason === "aborted";
1499 const failed =
1500 finished &&
1501 !interrupted &&
1502 ((recordNumber(result, "exitCode") ?? 0) !== 0 || stopReason === "error");
1503 const outputText = piSubagentOutput(result);
1504 yield* emitSubagent(turn, toolCallId, `${recordNumber(result, "step") ?? index}`, {
1505 agent,
1506 task,
1507 model: recordString(result, "model") ?? null,
1508 status: interrupted
1509 ? "interrupted"
1510 : failed
1511 ? "failed"
1512 : finished
1513 ? "completed"
1514 : "running",
1515 progress: !finished && outputText.length > 0 ? outputText.slice(0, 200) : undefined,
1516 result: finished && outputText.length > 0 ? outputText.slice(0, 10_000) : null,
1517 });
1518 }
1519 // Async launches return no results; their members arrive in the subagent-async widget.
1520 const asyncId = recordString(details, "asyncId");
1521 if (!emitted && asyncId !== undefined && !piAsyncRuns.has(asyncId)) {
1522 const tracked = { turn, toolCallId, emitted: new Map<string, string>() };
1523 piAsyncRuns.set(asyncId, tracked);
1524 // Keeps the run ingesting after the coordinator's turn ends, until the run settles.
1525 yield* emit({
1526 type: "background_work.updated",
1527 driver: PI_PROVIDER,
1528 providerTurnId: turn.providerTurn.id,
1529 pending: true,
1530 });
1531 const run = latestAsyncSnapshotRuns.find((run) => recordString(run, "id") === asyncId);
1532 if (run !== undefined) yield* updateAsyncRun(asyncId, tracked, run);
1533 }
1534 });
1535
1536 const emitSubagent = Effect.fnUntraced(function* (
1537 turn: ActivePiTurn,
1538 toolCallId: string,
1539 taskKey: string,
1540 task: {
1541 readonly agent: string;
1542 readonly task: string;
1543 readonly model: string | null;
1544 readonly status: OrchestrationV2Subagent["status"];
1545 readonly progress?: string | undefined;
1546 readonly result: string | null;
1547 },
1548 ) {
1549 const emittedAt = yield* DateTime.now;
1550 const parentNodeId = idAllocator.derive.nodeFromProviderItem({
1551 driver: PI_PROVIDER,
1552 nativeItemId: toolCallId,
1553 });
1554 const nativeTaskId = `${toolCallId}:subagent:${taskKey}`;
1555 const subagentId = idAllocator.derive.nodeFromProviderItem({
1556 driver: PI_PROVIDER,
1557 nativeItemId: nativeTaskId,
1558 });
1559 const startedAt = turn.toolStartedAt.get(nativeTaskId) ?? emittedAt;
1560 turn.toolStartedAt.set(nativeTaskId, startedAt);
1561 const finished =
1562 task.status !== "running" && task.status !== "pending" && task.status !== "waiting";
1563 const progress = task.progress === undefined ? {} : { progress: task.progress };
1564 yield* emit({
1565 type: "subagent.updated",
1566 driver: PI_PROVIDER,
1567 subagent: {
1568 id: subagentId,
1569 threadId: turn.turnInput.threadId,
1570 runId: turn.turnInput.runId,
1571 parentNodeId,
1572 origin: "provider_native",
1573 createdBy: "agent",
1574 driver: PI_PROVIDER,
1575 providerInstanceId: options.instanceId,
1576 providerThreadId: turn.turnInput.providerThread.id,
1577 childThreadId: null,
1578 nativeTaskRef: providerRef(nativeTaskId),
1579 prompt: task.task,
1580 title: task.agent,
1581 model: task.model,
1582 status: task.status,
1583 ...progress,
1584 result: task.result,
1585 startedAt,
1586 completedAt: finished ? emittedAt : null,
1587 updatedAt: emittedAt,
1588 },
1589 });
1590 yield* emit({
1591 type: "turn_item.updated",
1592 driver: PI_PROVIDER,
1593 turnItem: {
1594 ...baseItemFields(turn, nativeTaskId, startedAt, emittedAt),
1595 status: task.status,
1596 title: task.agent,
1597 completedAt: finished ? emittedAt : null,
1598 type: "subagent",
1599 subagentId,
1600 origin: "provider_native",
1601 driver: PI_PROVIDER,
1602 providerInstanceId: options.instanceId,
1603 childThreadId: null,
1604 prompt: task.task,
1605 ...progress,
1606 result: task.result,
1607 },
1608 });
1609 });
1610
1611 const updateAsyncRun = Effect.fnUntraced(function* (
1612 runId: string,
1613 tracked: {
1614 readonly turn: ActivePiTurn;
1615 readonly toolCallId: string;
1616 readonly emitted: Map<string, string>;
1617 },
1618 run: unknown,
1619 ) {
1620 const children = recordField(run, "children");
1621 let childrenSettled = true;
1622 for (const child of Array.isArray(children) ? children : []) {
1623 const id = recordString(child, "id");
1624 const agent = recordString(child, "agent");
1625 const status = piAsyncSubagentStatus(recordString(child, "state"));
1626 if (recordString(child, "kind") !== "step" || id === undefined) continue;
1627 if (agent === undefined || status === undefined) continue;
1628 if (status === "running" || status === "pending") childrenSettled = false;
1629 const model = recordString(child, "model") ?? null;
1630 const key = `${status}:${model}`;
1631 if (tracked.emitted.get(id) === key) continue;
1632 tracked.emitted.set(id, key);
1633 yield* emitSubagent(tracked.turn, tracked.toolCallId, id, {
1634 agent,
1635 task: "",
1636 model,
1637 status,
1638 result: null,
1639 });
1640 }
1641 const runStatus = piAsyncSubagentStatus(recordString(run, "state"));
1642 if (runStatus === undefined || runStatus === "running" || runStatus === "pending") return;
1643 // pi-subagents can settle the run one snapshot before its last step.
1644 if (!childrenSettled) return;
1645 piAsyncRuns.delete(runId);
1646 const providerTurnId = tracked.turn.providerTurn.id;
1647 for (const other of piAsyncRuns.values()) {
1648 if (other.turn.providerTurn.id === providerTurnId) return;
1649 }
1650 yield* emit({
1651 type: "background_work.updated",
1652 driver: PI_PROVIDER,
1653 providerTurnId,
1654 pending: false,
1655 });
1656 });
1657
1658 const updateAsyncSubagents = Effect.fnUntraced(function* (event: PiRpcRecord) {
1659 const lines = recordField(event, "widgetLines");
1660 if (!Array.isArray(lines)) return;
1661 for (const line of lines) {
1662 if (typeof line !== "string" || !line.startsWith(PI_SUBAGENT_ASYNC_PREFIX)) continue;
1663 const snapshot = Option.getOrUndefined(
1664 decodePiJson(line.slice(PI_SUBAGENT_ASYNC_PREFIX.length)),
1665 );
1666 const runs = recordField(snapshot, "runs");
1667 if (!Array.isArray(runs)) continue;
1668 latestAsyncSnapshotRuns = runs;
1669 for (const run of runs) {
1670 const runId = recordString(run, "id");
1671 const tracked = runId === undefined ? undefined : piAsyncRuns.get(runId);
1672 if (runId === undefined || tracked === undefined) continue;
1673 yield* updateAsyncRun(runId, tracked, run);
1674 }
1675 }
1676 });
1677
1678 const cancelPrompt = Effect.fn("PiAdapter.cancelPrompt")(function* (
1679 pending: PendingPiPrompt,
1680 resolvedAt: DateTime.Utc,
1681 ) {
1682 if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber);
1683 yield* connection
1684 .send({
1685 type: "extension_ui_response",
1686 id: pending.nativeRequestId,
1687 cancelled: true,
1688 })
1689 .pipe(Effect.ignore);
1690 pending.runtimeRequest = {
1691 ...pending.runtimeRequest,
1692 status: "cancelled",
1693 resolvedAt,
1694 };
1695 yield* emit({
1696 type: "runtime_request.updated",
1697 driver: PI_PROVIDER,
1698 threadId: pending.node.threadId,
1699 runtimeRequest: pending.runtimeRequest,
1700 });
1701 yield* emit({
1702 type: "node.updated",
1703 driver: PI_PROVIDER,
1704 node: { ...pending.node, status: "cancelled", completedAt: resolvedAt },
1705 });
1706 yield* emit({
1707 type: "turn_item.updated",
1708 driver: PI_PROVIDER,
1709 turnItem: {
1710 ...pending.turnItem,
1711 status: "cancelled",
1712 completedAt: resolvedAt,
1713 updatedAt: resolvedAt,
1714 },
1715 });
1716 });
1717
1718 const cancelPendingPrompts = Effect.fn("PiAdapter.cancelPendingPrompts")(function* (
1719 resolvedAt: DateTime.Utc,
1720 ) {
1721 const pending = Array.from(pendingPrompts.values());
1722 pendingPrompts.clear();
1723 customAnswerFollowUps.clear();
1724 yield* Effect.forEach(pending, (prompt) => cancelPrompt(prompt, resolvedAt), {
1725 discard: true,
1726 });
1727 });
1728
1729 const emitSystemNotice = Effect.fnUntraced(function* (
1730 turn: ActivePiTurn,
1731 nativeItemId: string,
1732 message: string,
1733 level?: "info" | "warning" | "error",
1734 ) {
1735 const emittedAt = yield* DateTime.now;
1736 yield* emitItemNode(turn, nativeItemId, "system", "completed", emittedAt, emittedAt);
1737 yield* emit({
1738 type: "turn_item.updated",
1739 driver: PI_PROVIDER,
1740 turnItem: {
1741 ...baseItemFields(turn, nativeItemId, emittedAt, emittedAt),
1742 status: "completed",
1743 completedAt: emittedAt,
1744 title: message,
1745 type: "system_notice",
1746 message,
1747 ...(level === undefined ? {} : { level }),
1748 },
1749 });
1750 });
1751
1752 // Abort leaves queued steers and follow-ups for Pi's next prompt, and Pi before 0.86 starts them
1753 // as soon as abort lands, so Stop clears them first. Pi before 0.84.4 rejects clear_queue.
1754 const clearNativeQueue = Effect.fnUntraced(function* (turn: ActivePiTurn) {
1755 const cleared = yield* request({ type: "clear_queue" }, 2_000).pipe(
1756 Effect.map((data) =>
1757 ["steering", "followUp"].flatMap((key) => {
1758 const texts = recordField(data, key);
1759 return Array.isArray(texts)
1760 ? texts.filter((text): text is string => typeof text === "string")
1761 : [];
1762 }),
1763 ),
1764 Effect.orElseSucceed((): ReadonlyArray<string> => []),
1765 );
1766 if (cleared.length === 0) return;
1767 yield* sessionEventPermit.withPermits(1)(
1768 threadState?.activeTurn === turn
1769 ? emitSystemNotice(
1770 turn,
1771 `queue-cleared:${turn.providerTurn.id}`,
1772 [
1773 `Stop cleared ${cleared.length} queued ${cleared.length === 1 ? "message" : "messages"} Pi had not read:`,
1774 // Image-only messages come back as empty text.
1775 ...cleared.filter((text) => text.length > 0),
1776 ]
1777 .join("\n\n")
1778 .slice(0, 2_000),
1779 )
1780 : Effect.void,
1781 );
1782 });
1783
1784 const handleExtensionUiRequest = Effect.fnUntraced(function* (event: PiRpcRecord) {
1785 const method = recordString(event, "method");
1786 const nativeRequestId = recordString(event, "id");
1787 if (method === undefined) return;
1788 if (method === "notify") {
1789 const state = threadState;
1790 const turn = state?.activeTurn ?? null;
1791 const message = recordString(event, "message") ?? "";
1792 if (turn === null || message.length === 0) return;
1793 const notifyType = recordString(event, "notifyType");
1794 yield* emitSystemNotice(
1795 turn,
1796 `notify:${turn.providerTurn.id}:${turn.nextItemOrdinal}`,
1797 message,
1798 notifyType === "warning" || notifyType === "error" ? notifyType : "info",
1799 );
1800 return;
1801 }
1802 if (method === "setWidget" && recordString(event, "widgetKey") === "subagent-async") {
1803 yield* updateAsyncSubagents(event);
1804 return;
1805 }
1806 if (
1807 method !== "select" &&
1808 method !== "confirm" &&
1809 method !== "input" &&
1810 method !== "editor"
1811 ) {
1812 yield* Effect.logDebug("Ignoring pi extension UI update.", { method });
1813 return;
1814 }
1815 if (nativeRequestId === undefined) return;
1816 // The extension's follow-up input has an empty placeholder; its multi-select input does not.
1817 const inputTitle =
1818 method === "input" && event["placeholder"] === ""
1819 ? (recordString(event, "title") ?? "")
1820 : "";
1821 const followUpPrefix = Array.from(customAnswerFollowUps.keys())
1822 .filter((prefix) => inputTitle.startsWith(prefix))
1823 .reduce<string | undefined>(
1824 (longest, prefix) => (prefix.length > (longest?.length ?? -1) ? prefix : longest),
1825 undefined,
1826 );
1827 if (followUpPrefix !== undefined) {
1828 const queued = customAnswerFollowUps.get(followUpPrefix) ?? [];
1829 const value = queued.shift() ?? "";
1830 if (queued.length === 0) customAnswerFollowUps.delete(followUpPrefix);
1831 yield* connection.send({ type: "extension_ui_response", id: nativeRequestId, value });
1832 return;
1833 }
1834 const approvalTitle = recordString(event, "title") ?? "";
1835 const approvalKey = `${approvalTitle.length}:${approvalTitle}${recordString(event, "message") ?? ""}`;
1836 if (method === "confirm" && sessionApprovals.has(approvalKey)) {
1837 yield* connection.send({
1838 type: "extension_ui_response",
1839 id: nativeRequestId,
1840 confirmed: true,
1841 });
1842 return;
1843 }
1844 const state = threadState;
1845 const turn = state?.activeTurn ?? null;
1846 const createdAt = yield* DateTime.now;
1847 const timeout = recordNumber(event, "timeout");
1848 // Pi treats zero as no timeout and negative durations as immediate expiry.
1849 const expiresAt =
1850 timeout === undefined || timeout === 0
1851 ? null
1852 : DateTime.toEpochMillis(createdAt) + Math.max(0, timeout);
1853 const requestId = yield* idAllocator.allocate.runtimeRequest({
1854 driver: PI_PROVIDER,
1855 ...(turn === null ? {} : { providerTurnId: turn.providerTurn.id }),
1856 nativeRequestId,
1857 });
1858 const nodeId = idAllocator.derive.approvalNode({ requestId });
1859 const title = recordString(event, "title") ?? method;
1860 const threadId =
1861 turn?.turnInput.threadId ?? state?.providerThread.appThreadId ?? input.threadId;
1862 const providerThreadId = state?.providerThread.id ?? null;
1863 const providerTurnId = turn?.providerTurn.id ?? null;
1864 const runtimeRequest: OrchestrationV2RuntimeRequest = {
1865 id: requestId,
1866 nodeId,
1867 providerTurnId,
1868 nativeRequestRef: providerRef(nativeRequestId),
1869 kind: method === "confirm" ? "command" : "user_input",
1870 status: "pending",
1871 responseCapability: { type: "live", providerSessionId: input.providerSessionId },
1872 createdAt,
1873 resolvedAt: null,
1874 };
1875 const node: OrchestrationV2ExecutionNode = {
1876 id: nodeId,
1877 threadId,
1878 runId: turn?.turnInput.runId ?? null,
1879 parentNodeId: turn?.turnInput.rootNodeId ?? null,
1880 rootNodeId: turn?.turnInput.rootNodeId ?? nodeId,
1881 kind: method === "confirm" ? "approval_request" : "user_input_request",
1882 status: "waiting",
1883 countsForRun: false,
1884 providerThreadId,
1885 providerTurnId,
1886 nativeItemRef: providerRef(nativeRequestId),
1887 runtimeRequestId: requestId,
1888 checkpointScopeId: null,
1889 startedAt: createdAt,
1890 completedAt: null,
1891 };
1892 const itemBase = {
1893 id: idAllocator.derive.approvalTurnItem({ requestId }),
1894 threadId,
1895 runId: turn?.turnInput.runId ?? null,
1896 nodeId,
1897 providerThreadId,
1898 providerTurnId,
1899 nativeItemRef: providerRef(nativeRequestId),
1900 parentItemId: null,
1901 ordinal: turn === null ? 0 : itemOrdinal(turn, nativeRequestId),
1902 status: "waiting" as const,
1903 title,
1904 startedAt: createdAt,
1905 completedAt: null,
1906 updatedAt: createdAt,
1907 };
1908 const askUser =
1909 method === "select" && turn !== null
1910 ? piAskUserSingleSelectQuestion(nativeRequestId, title, event, turn.toolArgs)
1911 : undefined;
1912 const turnItem: OrchestrationV2TurnItem =
1913 method === "confirm"
1914 ? {
1915 ...itemBase,
1916 type: "approval_request",
1917 requestId,
1918 requestKind: piApprovalRequestKind(title),
1919 prompt: recordString(event, "message") ?? title,
1920 }
1921 : {
1922 ...itemBase,
1923 type: "user_input_request",
1924 requestId,
1925 questions: [askUser?.question ?? piQuestion(nativeRequestId, method, title, event)],
1926 };
1927 const pending: PendingPiPrompt = {
1928 nativeRequestId,
1929 method,
1930 questionId: nativeRequestId,
1931 approvalKey,
1932 expiresAt,
1933 expirationFiber: null,
1934 runtimeRequest,
1935 node,
1936 turnItem,
1937 customAnswerRoute: askUser?.customAnswerRoute,
1938 };
1939 pendingPrompts.set(String(requestId), pending);
1940 yield* emit({
1941 type: "runtime_request.updated",
1942 driver: PI_PROVIDER,
1943 threadId,
1944 runtimeRequest,
1945 });
1946 yield* emit({ type: "node.updated", driver: PI_PROVIDER, node });
1947 yield* emit({ type: "turn_item.updated", driver: PI_PROVIDER, turnItem });
1948 if (expiresAt !== null) {
1949 const now = yield* DateTime.now;
1950 pending.expirationFiber = yield* Effect.sleep(
1951 Duration.millis(Math.max(0, expiresAt - DateTime.toEpochMillis(now))),
1952 ).pipe(
1953 Effect.andThen(
1954 Queue.offer(connection.events, {
1955 type: "t3.ui_request_expired",
1956 requestId: String(requestId),
1957 pending,
1958 }),
1959 ),
1960 Effect.asVoid,
1961 Effect.forkIn(scope),
1962 );
1963 }
1964 });
1965
1966 const emitExtensionError = Effect.fnUntraced(function* (event: PiRpcRecord) {
1967 const state = threadState;
1968 const turn = state?.activeTurn ?? null;
1969 if (turn === null) {
1970 outOfTurnExtensionErrors.push(event);
1971 return;
1972 }
1973 const emittedAt = yield* DateTime.now;
1974 const nativeItemId = `extension-error:${turn.providerTurn.id}:${turn.nextItemOrdinal}`;
1975 const extensionName = piExtensionDisplayName(recordString(event, "extensionPath"));
1976 const extensionEvent = recordString(event, "event");
1977 const detail = recordString(event, "error")?.trim();
1978 const message = [
1979 `${extensionName} failed${extensionEvent === undefined ? "" : ` during ${extensionEvent}`}.`,
1980 detail === undefined || detail.length === 0 ? undefined : detail.slice(0, 2_000),
1981 ]
1982 .filter((part): part is string => part !== undefined)
1983 .join("\n\n");
1984 const failure = makeProviderFailure({
1985 message,
1986 class: "provider_error",
1987 retryable: false,
1988 });
1989 yield* emitItemNode(turn, nativeItemId, "system", "failed", emittedAt, emittedAt);
1990 yield* emit({
1991 type: "turn_item.updated",
1992 driver: PI_PROVIDER,
1993 turnItem: {
1994 ...baseItemFields(turn, nativeItemId, emittedAt, emittedAt),
1995 status: "failed",
1996 title: extensionName,
1997 completedAt: emittedAt,
1998 type: "error",
1999 failure,
2000 },
2001 });
2002 });
2003
2004 const listSessionEntries = (since: string | null, timeoutMs: number) =>
2005 request({ type: "get_entries", ...(since === null ? {} : { since }) }, timeoutMs).pipe(
2006 Effect.map(piSessionListing),
2007 Effect.orElseSucceed(() => null),
2008 );
2009
2010 // get_entries includes abandoned branches in append order; follow leaf parentId ancestry instead.
2011 const captureTurnTreeRefs = Effect.fnUntraced(function* (
2012 timeoutMs = PI_REQUEST_TIMEOUT_MS,
2013 ): Effect.fn.Return<PiTurnTreeRefs | null> {
2014 const cursorWasStale = leafCursorStale;
2015 const previousLeaf = lastKnownLeaf;
2016 const fullListing = cursorWasStale || previousLeaf === null;
2017 const listing = yield* listSessionEntries(fullListing ? null : previousLeaf, timeoutMs);
2018 const turnWalk =
2019 listing === null ? null : walkPiBranch(listing.entries, listing.leafId, previousLeaf);
2020 const rewound = turnWalk !== null && previousLeaf !== null && !turnWalk.reachedStop;
2021 // since ends at the previous leaf; rewound ancestry requires the whole tree.
2022 const tree = rewound && !fullListing ? yield* listSessionEntries(null, timeoutMs) : listing;
2023 if (listing === null || turnWalk === null || tree === null) {
2024 leafCursorStale = true;
2025 return null;
2026 }
2027 lastKnownLeaf = listing.leafId;
2028 leafCursorStale = false;
2029 const turnStartEntryId = turnWalk.userEntryIds.at(-1);
2030 // Only a complete acyclic root walk proves all survivors.
2031 // The old leaf must remain in this tree to prove rewind rather than session replacement.
2032 const branch =
2033 rewound && previousLeaf !== null && tree.entries.has(previousLeaf)
2034 ? walkPiBranch(tree.entries, listing.leafId, null)
2035 : undefined;
2036 return {
2037 // Stale cursors span earlier turns; keep a synthetic ref to avoid rolling back too far.
2038 nativeTurnRef: cursorWasStale
2039 ? undefined
2040 : turnStartEntryId !== undefined
2041 ? providerRef(turnStartEntryId)
2042 : turnWalk.entryCount === 0
2043 ? null
2044 : undefined,
2045 leafId: listing.leafId,
2046 retainedNativeTurnIds: branch?.reachedStop === true ? branch.userEntryIds : undefined,
2047 };
2048 });
2049
2050 const finalizeTurn = Effect.fnUntraced(function* (state: PiThreadState, readUsage = true) {
2051 const turn = state.activeTurn;
2052 if (turn === null) return;
2053 state.activeTurn = null;
2054 const interrupted = turn.interrupted || turn.nativeAborted;
2055 const completedAt = yield* DateTime.now;
2056 yield* completeOpenStreamItems(turn);
2057 if (turn.activeCompaction !== null) {
2058 const status = interrupted ? "cancelled" : turn.failure === null ? "completed" : "failed";
2059 yield* emitCompaction(turn, turn.activeCompaction, status);
2060 turn.activeCompaction = null;
2061 }
2062 if (turn.activeProviderRetry !== null) {
2063 if (interrupted) {
2064 yield* emitProviderRetry(turn, turn.activeProviderRetry, "interrupted", completedAt);
2065 turn.activeProviderRetry = null;
2066 } else if (turn.failure === null) {
2067 yield* emitProviderRetry(turn, turn.activeProviderRetry, "completed", completedAt);
2068 turn.activeProviderRetry = null;
2069 }
2070 }
2071 yield* cancelPendingPrompts(completedAt);
2072 // Stop clears Pi's queue, so an unread steer was dropped; otherwise Pi read it before settling.
2073 for (const messageId of turn.unreadSteers.splice(0)) {
2074 yield* emitSteerStatus(turn, messageId, interrupted ? "cancelled" : "completed");
2075 }
2076 const treeRefs =
2077 turn.stopTreeRefs !== undefined ? turn.stopTreeRefs : yield* captureTurnTreeRefs();
2078 const tokenUsage = readUsage
2079 ? yield* readTokenUsage(turn.latestCompactionAfterTokens, completedAt)
2080 : undefined;
2081 const failure = interrupted ? null : (turn.rejectedPromptFailure ?? turn.failure);
2082 yield* emit({
2083 type: "provider_turn.updated",
2084 driver: PI_PROVIDER,
2085 threadId: turn.turnInput.threadId,
2086 providerTurn: {
2087 ...turn.providerTurn,
2088 ...(treeRefs === null || treeRefs.nativeTurnRef === undefined
2089 ? {}
2090 : { nativeTurnRef: treeRefs.nativeTurnRef }),
2091 ...(state.providerThread.nativeThreadRef === null
2092 ? {}
2093 : { nativeThreadRef: state.providerThread.nativeThreadRef }),
2094 status: interrupted ? "interrupted" : failure !== null ? "failed" : "completed",
2095 completedAt,
2096 ...(tokenUsage === undefined ? {} : { tokenUsage }),
2097 ...(turn.reportedModel === undefined ? {} : { model: turn.reportedModel }),
2098 },
2099 });
2100 yield* updateProviderThread(
2101 state,
2102 {
2103 status: "idle",
2104 ...(treeRefs === null
2105 ? {}
2106 : {
2107 nativeConversationHeadRef:
2108 treeRefs.leafId === null ? null : providerRef(treeRefs.leafId),
2109 }),
2110 },
2111 treeRefs?.retainedNativeTurnIds,
2112 );
2113 yield* updateProviderSession(
2114 failure !== null ? "error" : "ready",
2115 failure?.message ?? null,
2116 );
2117 if (failure !== null) {
2118 const failureItemId = `terminal-failure:${turn.providerTurn.id}`;
2119 if (turn.activeProviderRetry !== null) {
2120 yield* emitProviderRetry(
2121 turn,
2122 { ...turn.activeProviderRetry, failure },
2123 "failed",
2124 completedAt,
2125 );
2126 } else {
2127 yield* emit({
2128 type: "turn_item.updated",
2129 driver: PI_PROVIDER,
2130 turnItem: {
2131 ...baseItemFields(turn, failureItemId, completedAt, completedAt),
2132 status: "failed",
2133 title: null,
2134 completedAt,
2135 type: "error",
2136 failure,
2137 },
2138 });
2139 }
2140 yield* emit({
2141 type: "turn.terminal",
2142 driver: PI_PROVIDER,
2143 providerThreadId: state.providerThread.id,
2144 providerTurnId: turn.providerTurn.id,
2145 runOrdinal: turn.turnInput.runOrdinal,
2146 failureItemOrdinal: itemOrdinal(turn, failureItemId),
2147 status: "failed",
2148 failure,
2149 ...(turn.activeProviderRetry === null
2150 ? {}
2151 : {
2152 retry: turn.activeProviderRetry.retry,
2153 retryStartedAt: turn.activeProviderRetry.startedAt,
2154 }),
2155 threadDisposition: "reusable",
2156 });
2157 } else {
2158 yield* emit({
2159 type: "turn.terminal",
2160 driver: PI_PROVIDER,
2161 providerThreadId: state.providerThread.id,
2162 providerTurnId: turn.providerTurn.id,
2163 runOrdinal: turn.turnInput.runOrdinal,
2164 status: interrupted ? "interrupted" : "completed",
2165 failure: null,
2166 threadDisposition: "reusable",
2167 });
2168 }
2169 });
2170
2171 // Extensions can move Pi to another session file (ctx.newSession); resume that one.
2172 const adoptLiveSessionFile = (state: PiThreadState, stateData: unknown) => {
2173 const sessionFile = recordString(stateData, "sessionFile");
2174 const previousFile = state.providerThread.nativeThreadRef?.nativeId;
2175 if (sessionFile === undefined || sessionFile === previousFile) return;
2176 if (previousFile != null) state.supersededSessionFiles.add(previousFile);
2177 state.supersededSessionFiles.delete(sessionFile);
2178 state.providerThread = {
2179 ...state.providerThread,
2180 nativeThreadRef: providerRef(sessionFile),
2181 };
2182 lastNativeThreadId = sessionFile;
2183 };
2184
2185 const scheduleSettleProbe = (
2186 turn: ActivePiTurn,
2187 settleAfterAgentActivity = false,
2188 attempt = 1,
2189 ) => {
2190 const providerTurnId = turn.providerTurn.id;
2191 const settleProbeGeneration = turn.settleProbeGeneration;
2192 return request({ type: "get_state" }, 2_000).pipe(
2193 Effect.matchEffect({
2194 onSuccess: (data) =>
2195 Queue.offer(connection.events, {
2196 type: "t3.settle_probe",
2197 providerTurnId,
2198 settleAfterAgentActivity,
2199 settleProbeGeneration,
2200 attempt,
2201 data,
2202 }),
2203 // Failed probes must reach the pump; command-only turns emit no agent events to settle them.
2204 onFailure: () =>
2205 Queue.offer(connection.events, {
2206 type: "t3.settle_probe",
2207 providerTurnId,
2208 settleAfterAgentActivity,
2209 settleProbeGeneration,
2210 attempt,
2211 probeFailed: true,
2212 }),
2213 }),
2214 Effect.ignore,
2215 Effect.forkIn(scope),
2216 );
2217 };
2218
2219 const stopPendingWake = Effect.fnUntraced(function* (wake: PiWake) {
2220 if (pendingWake !== wake || threadState !== wake.state || closed) return;
2221 pendingWake = null;
2222 stopRequested = true;
2223 yield* cancelPendingPrompts(yield* DateTime.now);
2224 yield* connection.terminate;
2225 });
2226
2227 const handleSessionEvent = Effect.fnUntraced(function* (event: PiRpcRecord) {
2228 if (event["type"] === "t3.extension_status_reset") {
2229 const reset = extensionStatusReset;
2230 if (reset !== null && event["reset"] === reset) {
2231 reset.previous = sessionEntity.extensionStatuses ?? [];
2232 reset.touched.clear();
2233 yield* clearExtensionStatuses();
2234 yield* Deferred.succeed(reset.ready, undefined);
2235 }
2236 return;
2237 }
2238 // A native wake may wait for a turn owner; status belongs to the live session immediately.
2239 if (event["type"] === "extension_ui_request" && event["method"] === "setStatus") {
2240 yield* updateExtensionStatus(event);
2241 return;
2242 }
2243 // Model hooks can show dialogs before turn ownership; keep requests session-scoped and buffer output.
2244 const interactiveUiRequest =
2245 event["type"] === "extension_ui_request" &&
2246 ["select", "confirm", "input", "editor"].includes(String(event["method"]));
2247 if (
2248 threadState?.activeTurn === null &&
2249 pendingWake !== null &&
2250 !interactiveUiRequest &&
2251 !String(event["type"]).startsWith("t3.") &&
2252 event["type"] !== "response"
2253 ) {
2254 pendingWake.events.push(event);
2255 if (event["type"] === "agent_start") yield* updateProviderSession("running", null);
2256 if (event["type"] === "agent_settled") yield* updateProviderSession("ready", null);
2257 return;
2258 }
2259 const state = threadState;
2260 const turn = state?.activeTurn ?? null;
2261 switch (event["type"]) {
2262 case "agent_start": {
2263 if (
2264 turn === null &&
2265 state?.providerThread.appThreadId != null &&
2266 continuationRequests !== undefined &&
2267 !closed &&
2268 !stopRequested
2269 ) {
2270 const wake: PiWake = { state, events: [event] };
2271 pendingWake = wake;
2272 if (rollbackBarrier !== null) {
2273 yield* stopPendingWake(wake);
2274 return;
2275 }
2276 yield* updateProviderSession("running", null);
2277 yield* continuationRequests
2278 .offer({
2279 threadId: state.providerThread.appThreadId,
2280 providerThreadId: state.providerThread.id,
2281 driver: PI_PROVIDER,
2282 detail: null,
2283 delivery: "adapter_buffered",
2284 dispatchIfCurrent: (dispatch) =>
2285 sessionEventPermit.withPermits(1)(
2286 Effect.suspend(() =>
2287 pendingWake === wake && threadState === state && !closed
2288 ? dispatch.pipe(
2289 Effect.asSome,
2290 Effect.tapError(() => stopPendingWake(wake)),
2291 )
2292 : Effect.succeedNone,
2293 ),
2294 ),
2295 clearIfCurrent: () => sessionEventPermit.withPermits(1)(stopPendingWake(wake)),
2296 })
2297 .pipe(Effect.tapError(() => stopPendingWake(wake)));
2298 return;
2299 }
2300 if (turn === null) {
2301 unsolicitedActivityDetected = true;
2302 yield* updateProviderSession("error", PI_UNSOLICITED_ACTIVITY_ERROR);
2303 yield* connection.terminate;
2304 return;
2305 }
2306 turn.sawAgentActivity = true;
2307 turn.nativeAborted = false;
2308 turn.settleProbeGeneration += 1;
2309 return;
2310 }
2311 case "message_start": {
2312 const role = recordString(event["message"], "role");
2313 if (turn !== null && role === "assistant") {
2314 turn.sawAgentActivity = true;
2315 turn.messageOrdinal += 1;
2316 }
2317 const readSteer = role === "user" ? turn?.unreadSteers.shift() : undefined;
2318 if (turn !== null && readSteer !== undefined) {
2319 yield* emitSteerStatus(turn, readSteer, "completed");
2320 }
2321 return;
2322 }
2323 case "message_update": {
2324 if (turn === null) return;
2325 turn.sawAgentActivity = true;
2326 // Pi sends auto_retry_end only after the message ends; streamed output is recovery.
2327 if (turn.activeProviderRetry !== null) {
2328 const recoveredAt = yield* DateTime.now;
2329 yield* emitProviderRetry(turn, turn.activeProviderRetry, "completed", recoveredAt);
2330 turn.activeProviderRetry = null;
2331 }
2332 yield* reportLiveUsage(turn, event["usage"]);
2333 const delta = event["assistantMessageEvent"];
2334 const deltaType = recordString(delta, "type");
2335 const contentIndex = recordNumber(delta, "contentIndex") ?? 0;
2336 if (deltaType === "text_start" || deltaType === "thinking_start") {
2337 // A provider that reconnects mid-block starts it again; its earlier text is abandoned.
2338 const restarted = turn.streamItems.get(streamItemId(turn, contentIndex));
2339 if (restarted !== undefined && !restarted.completed) restarted.text = "";
2340 return;
2341 }
2342 if (deltaType === "text_delta" || deltaType === "thinking_delta") {
2343 const item = yield* streamItemFor(
2344 turn,
2345 deltaType === "text_delta" ? "assistant_message" : "reasoning",
2346 contentIndex,
2347 );
2348 item.text += recordString(delta, "delta") ?? "";
2349 yield* scheduleStreamFlush(turn, item);
2350 return;
2351 }
2352 if (deltaType === "text_end" || deltaType === "thinking_end") {
2353 const item = yield* streamItemFor(
2354 turn,
2355 deltaType === "text_end" ? "assistant_message" : "reasoning",
2356 contentIndex,
2357 );
2358 yield* completeStreamItem(
2359 turn,
2360 item,
2361 recordString(delta, "content") ?? recordString(delta, "thinking"),
2362 );
2363 return;
2364 }
2365 return;
2366 }
2367 case "message_end": {
2368 if (turn === null) return;
2369 const message = event["message"];
2370 if (recordString(message, "role") !== "assistant") return;
2371 yield* completeOpenStreamItems(turn);
2372 const reportedProvider = recordString(message, "provider");
2373 const reportedModelId = recordString(message, "model");
2374 if (reportedProvider && reportedModelId) {
2375 turn.reportedModel = `${reportedProvider}/${reportedModelId}`;
2376 }
2377 if (recordString(message, "stopReason") === "error" && turn.failure === null) {
2378 turn.failure = makeProviderFailure({
2379 message: recordString(message, "errorMessage") ?? "Pi reported a model error.",
2380 class: "provider_error",
2381 });
2382 }
2383 return;
2384 }
2385 case "tool_execution_start":
2386 if (turn !== null) {
2387 turn.sawAgentActivity = true;
2388 yield* emitToolItem(turn, event, "start");
2389 }
2390 return;
2391 case "tool_execution_update":
2392 if (turn !== null) yield* emitToolItem(turn, event, "update");
2393 return;
2394 case "tool_execution_end":
2395 if (turn !== null) yield* emitToolItem(turn, event, "end");
2396 return;
2397 case "compaction_start": {
2398 if (turn === null) return;
2399 turn.settleProbeGeneration += 1;
2400 if (turn.activeCompaction !== null) {
2401 yield* emitCompaction(turn, turn.activeCompaction, "cancelled");
2402 }
2403 const startedAt = yield* DateTime.now;
2404 const compaction = {
2405 nativeItemId: compactionNativeItemId(turn),
2406 startedAt,
2407 } satisfies PiCompactionState;
2408 turn.activeCompaction = compaction;
2409 yield* emitCompaction(turn, compaction, "running");
2410 return;
2411 }
2412 case "compaction_end": {
2413 if (turn === null) return;
2414 const observedAt = yield* DateTime.now;
2415 const compaction = turn.activeCompaction ?? {
2416 nativeItemId: compactionNativeItemId(turn),
2417 startedAt: observedAt,
2418 };
2419 turn.activeCompaction = null;
2420 turn.compactionCancelled = event["aborted"] === true;
2421 const result = event["result"];
2422 if (result === null || result === undefined) {
2423 if (event["aborted"] === true) {
2424 yield* emitCompaction(turn, compaction, "cancelled");
2425 if (
2426 (turn.settleWhenIdle || !turn.sawAgentActivity) &&
2427 releasedPromptTurnId !== turn.providerTurn.id
2428 ) {
2429 yield* scheduleSettleProbe(turn, turn.settleWhenIdle);
2430 }
2431 return;
2432 }
2433 const errorMessage =
2434 recordString(event, "errorMessage") ?? "Pi context compaction failed.";
2435 yield* emitCompaction(turn, compaction, "failed", {
2436 summary: errorMessage.slice(0, 1_000),
2437 });
2438 if (
2439 (turn.settleWhenIdle || !turn.sawAgentActivity) &&
2440 releasedPromptTurnId !== turn.providerTurn.id
2441 ) {
2442 yield* scheduleSettleProbe(turn, turn.settleWhenIdle);
2443 }
2444 return;
2445 }
2446 // Clear overflow failures only when compaction will retry; ordinary compaction must retain exhausted retries.
2447 if (event["willRetry"] === true) turn.failure = null;
2448 turn.latestCompactionAfterTokens =
2449 nonNegativeInteger(result, "estimatedTokensAfter") ?? null;
2450 const summary = recordString(result, "summary");
2451 const beforeTokenCount = nonNegativeInteger(result, "tokensBefore");
2452 const afterTokenCount = nonNegativeInteger(result, "estimatedTokensAfter");
2453 yield* emitCompaction(turn, compaction, "completed", {
2454 ...(summary === undefined ? {} : { summary }),
2455 ...(beforeTokenCount === undefined ? {} : { beforeTokenCount }),
2456 ...(afterTokenCount === undefined ? {} : { afterTokenCount }),
2457 });
2458 if (
2459 (turn.settleWhenIdle || !turn.sawAgentActivity) &&
2460 releasedPromptTurnId !== turn.providerTurn.id
2461 ) {
2462 yield* scheduleSettleProbe(turn, turn.settleWhenIdle);
2463 }
2464 return;
2465 }
2466 case "auto_retry_start": {
2467 if (turn === null) return;
2468 const emittedAt = yield* DateTime.now;
2469 const attempt = Math.max(1, Math.trunc(recordNumber(event, "attempt") ?? 1));
2470 const maxAttempts = Math.max(
2471 attempt,
2472 Math.trunc(recordNumber(event, "maxAttempts") ?? attempt),
2473 );
2474 const retryDelayMs = Math.max(0, Math.trunc(recordNumber(event, "delayMs") ?? 0));
2475 const failure = makeProviderFailure({
2476 message: recordString(event, "errorMessage") ?? "Pi provider request failed.",
2477 class: "provider_error",
2478 retryable: true,
2479 });
2480 const current = turn.activeProviderRetry;
2481 const providerRetry = {
2482 retry: { attempt, maxAttempts, retryDelayMs },
2483 failure,
2484 startedAt: current?.startedAt ?? emittedAt,
2485 itemOrdinal:
2486 current?.itemOrdinal ??
2487 itemOrdinal(turn, `terminal-failure:${turn.providerTurn.id}`),
2488 } satisfies PiProviderRetryState;
2489 turn.activeProviderRetry = providerRetry;
2490 yield* emitProviderRetry(turn, providerRetry, "running", emittedAt);
2491 return;
2492 }
2493 case "auto_retry_end": {
2494 if (turn === null) return;
2495 const emittedAt = yield* DateTime.now;
2496 if (event["success"] === true) {
2497 // Successful retries supersede the failure agent_settled would reuse.
2498 if (turn.activeProviderRetry !== null) {
2499 const attempt = Math.max(
2500 1,
2501 Math.trunc(
2502 recordNumber(event, "attempt") ?? turn.activeProviderRetry.retry.attempt,
2503 ),
2504 );
2505 const recoveredRetry = {
2506 ...turn.activeProviderRetry,
2507 retry: { ...turn.activeProviderRetry.retry, attempt },
2508 };
2509 yield* emitProviderRetry(turn, recoveredRetry, "completed", emittedAt);
2510 turn.activeProviderRetry = null;
2511 }
2512 turn.failure = null;
2513 return;
2514 }
2515 const failure = makeProviderFailure({
2516 message: recordString(event, "finalError") ?? "Pi auto-retry failed.",
2517 class: "provider_error",
2518 retryable: false,
2519 });
2520 const attempt = Math.max(1, Math.trunc(recordNumber(event, "attempt") ?? 1));
2521 const current = turn.activeProviderRetry;
2522 const providerRetry = {
2523 retry: {
2524 attempt,
2525 maxAttempts: current?.retry.maxAttempts ?? attempt,
2526 retryDelayMs: current?.retry.retryDelayMs ?? null,
2527 },
2528 failure,
2529 startedAt: current?.startedAt ?? emittedAt,
2530 itemOrdinal:
2531 current?.itemOrdinal ??
2532 itemOrdinal(turn, `terminal-failure:${turn.providerTurn.id}`),
2533 } satisfies PiProviderRetryState;
2534 turn.activeProviderRetry = providerRetry;
2535 turn.failure = failure;
2536 yield* emitProviderRetry(turn, providerRetry, "failed", emittedAt);
2537 return;
2538 }
2539 case "extension_ui_request":
2540 yield* handleExtensionUiRequest(event);
2541 return;
2542 case "extension_error": {
2543 yield* emitExtensionError(event);
2544 return;
2545 }
2546 case "agent_settled": {
2547 if (turn?.interrupted === true) {
2548 if (state === null) return;
2549 const liveState = yield* request({ type: "get_state" }, 2_000).pipe(
2550 Effect.orElseSucceed(() => undefined),
2551 );
2552 adoptLiveSessionFile(state, liveState);
2553 yield* finalizeTurn(state);
2554 return;
2555 }
2556 if (turn !== null) {
2557 turn.nativeAborted = event["aborted"] === true;
2558 turn.settleWhenIdle = true;
2559 turn.settleProbeGeneration += 1;
2560 if (
2561 turn.adoptedWake &&
2562 pendingPromptResponses.some(
2563 (pending) =>
2564 pending.providerTurnId === turn.providerTurn.id &&
2565 pending.kind === "turn_start",
2566 )
2567 )
2568 return;
2569 yield* scheduleSettleProbe(turn, true);
2570 }
2571 return;
2572 }
2573 case "response": {
2574 const command = recordString(event, "command");
2575 if (command === "compact") {
2576 const pendingCompact = pendingCompactResponses.shift();
2577 const compactTurn =
2578 pendingCompact?.providerTurnId === turn?.providerTurn.id ? turn : null;
2579 if (compactTurn !== null) compactTurn.manualCompactInFlight = false;
2580 if (event["success"] === true) {
2581 if (
2582 compactTurn !== null &&
2583 (compactTurn.settleWhenIdle ||
2584 (compactTurn.promptMayBeCommandOnly && !compactTurn.sawAgentActivity))
2585 ) {
2586 yield* scheduleSettleProbe(compactTurn, compactTurn.settleWhenIdle);
2587 }
2588 return;
2589 }
2590 if (event["success"] !== false) return;
2591 if (compactTurn === null) return;
2592 if (compactTurn.activeCompaction !== null) return;
2593 if (pendingCompact?.kind === "steer") {
2594 yield* Effect.logWarning("Pi rejected a compact steer.", {
2595 errorLength: recordString(event, "error")?.length,
2596 });
2597 if (
2598 compactTurn.settleWhenIdle ||
2599 (compactTurn.promptMayBeCommandOnly && !compactTurn.sawAgentActivity)
2600 ) {
2601 yield* scheduleSettleProbe(compactTurn, compactTurn.settleWhenIdle);
2602 }
2603 return;
2604 }
2605 if (!compactTurn.compactionCancelled) {
2606 compactTurn.failure = makeProviderFailure({
2607 message: recordString(event, "error") ?? "Pi compact failed.",
2608 class: "provider_error",
2609 });
2610 if (state !== null) yield* finalizeTurn(state);
2611 return;
2612 }
2613 if (!compactTurn.sawAgentActivity) {
2614 yield* scheduleSettleProbe(compactTurn);
2615 }
2616 return;
2617 }
2618 const responseId = recordString(event, "id");
2619 const promptIndex =
2620 command !== "prompt"
2621 ? -1
2622 : responseId === undefined
2623 ? 0
2624 : pendingPromptResponses.findIndex((pending) => pending.id === responseId);
2625 const pendingPrompt =
2626 promptIndex < 0 ? undefined : pendingPromptResponses.splice(promptIndex, 1)[0];
2627 if (
2628 pendingPrompt !== undefined &&
2629 pendingPromptResponses.length === 0 &&
2630 pendingPromptResponsesDrained !== null
2631 ) {
2632 yield* Deferred.succeed(pendingPromptResponsesDrained, undefined);
2633 pendingPromptResponsesDrained = null;
2634 }
2635 const responseTurn =
2636 pendingPrompt?.providerTurnId === turn?.providerTurn.id ? turn : null;
2637 if (
2638 event["success"] === false &&
2639 nativeCompacting &&
2640 recordString(event, "error")?.startsWith(PI_COMPACTING_PROMPT_REJECTION) === true &&
2641 pendingPrompt !== undefined &&
2642 responseTurn !== null
2643 ) {
2644 heldPrompts.splice(rejectedHeldCount++, 0, pendingPrompt);
2645 return;
2646 }
2647 if (
2648 event["success"] === true &&
2649 pendingPrompt?.kind === "turn_start" &&
2650 responseTurn !== null &&
2651 recordString(event["data"], "disposition") === "handled"
2652 ) {
2653 responseTurn.promptMayBeCommandOnly = true;
2654 }
2655 const consumedInputIsIdleCandidate =
2656 responseTurn !== null &&
2657 (responseTurn.settleWhenIdle ||
2658 (responseTurn.promptMayBeCommandOnly && !responseTurn.sawAgentActivity)) &&
2659 !pendingPromptResponses.some(
2660 (pending) => pending.providerTurnId === responseTurn.providerTurn.id,
2661 );
2662 if (event["success"] === true) {
2663 if (
2664 pendingPrompt?.messageId !== undefined &&
2665 responseTurn !== null &&
2666 recordString(recordField(event, "data"), "disposition") === "queued"
2667 ) {
2668 responseTurn.unreadSteers.push(pendingPrompt.messageId);
2669 yield* emitSteerStatus(responseTurn, pendingPrompt.messageId, "pending");
2670 }
2671 // Consumed input may emit no agent_settled; probe idle behind preceding native events.
2672 if (
2673 responseTurn !== null &&
2674 (consumedInputIsIdleCandidate ||
2675 (pendingPrompt?.kind === "turn_start" &&
2676 responseTurn.adoptedWake &&
2677 (responseTurn.settleWhenIdle || responseTurn.promptMayBeCommandOnly)))
2678 ) {
2679 yield* scheduleSettleProbe(
2680 responseTurn,
2681 responseTurn.adoptedWake || responseTurn.settleWhenIdle,
2682 );
2683 }
2684 return;
2685 }
2686 if (event["success"] !== false) return;
2687 if (command === "steer" || pendingPrompt?.kind === "steer") {
2688 // A rejected steer refuses only that message; its target turn keeps running.
2689 yield* Effect.logWarning("Pi rejected a steer message.", {
2690 errorLength: recordString(event, "error")?.length,
2691 });
2692 if (consumedInputIsIdleCandidate && responseTurn !== null)
2693 yield* scheduleSettleProbe(responseTurn, responseTurn.settleWhenIdle);
2694 return;
2695 }
2696 const failedTurn =
2697 command === "prompt" && pendingPrompt?.kind === "turn_start"
2698 ? responseTurn
2699 : command === "parse"
2700 ? turn
2701 : null;
2702 if (failedTurn !== null) {
2703 const failure = makeProviderFailure({
2704 message: recordString(event, "error") ?? "Pi rejected the prompt.",
2705 class: "provider_error",
2706 });
2707 if (failedTurn.adoptedWake && command === "prompt") {
2708 failedTurn.rejectedPromptFailure = failure;
2709 failedTurn.settleWhenIdle = true;
2710 yield* scheduleSettleProbe(failedTurn, true);
2711 } else {
2712 failedTurn.failure = failure;
2713 if (state !== null) yield* finalizeTurn(state);
2714 }
2715 }
2716 return;
2717 }
2718 case "t3.ui_request_expired": {
2719 const requestId = recordString(event, "requestId");
2720 if (requestId === undefined) return;
2721 const pending = pendingPrompts.get(requestId);
2722 if (pending === undefined || pending !== event["pending"]) return;
2723 pendingPrompts.delete(requestId);
2724 yield* cancelPrompt(pending, yield* DateTime.now);
2725 return;
2726 }
2727 case "t3.flush_extension_errors": {
2728 for (const extensionError of outOfTurnExtensionErrors.splice(0)) {
2729 yield* emitExtensionError(extensionError);
2730 }
2731 return;
2732 }
2733 case "t3.rollback_barrier": {
2734 if (rollbackBarrier !== null && event["barrier"] === rollbackBarrier)
2735 yield* Deferred.succeed(rollbackBarrier, undefined);
2736 return;
2737 }
2738 case "t3.settle_probe": {
2739 const data = event["data"];
2740 const probeFailed = event["probeFailed"] === true;
2741 const settleAfterAgentActivity = event["settleAfterAgentActivity"] === true;
2742 const attempt = Math.max(1, Math.trunc(recordNumber(event, "attempt") ?? 1));
2743 if (
2744 turn === null ||
2745 turn.providerTurn.id !== event["providerTurnId"] ||
2746 turn.settleProbeGeneration !== event["settleProbeGeneration"] ||
2747 (!settleAfterAgentActivity && turn.sawAgentActivity) ||
2748 turn.activeCompaction !== null
2749 ) {
2750 return;
2751 }
2752 if (
2753 turn.manualCompactInFlight ||
2754 pendingCompactResponses.some(
2755 (pending) => pending.providerTurnId === turn.providerTurn.id,
2756 ) ||
2757 pendingPromptResponses.some(
2758 (pending) => pending.providerTurnId === turn.providerTurn.id,
2759 )
2760 ) {
2761 turn.settleWhenIdle = true;
2762 return;
2763 }
2764 if (probeFailed) {
2765 if (!settleAfterAgentActivity) {
2766 if (state !== null) yield* finalizeTurn(state);
2767 return;
2768 }
2769 if (attempt < SETTLE_PROBE_MAX_ATTEMPTS) {
2770 yield* Effect.sleep(SETTLE_PROBE_RETRY_DELAY).pipe(
2771 Effect.andThen(scheduleSettleProbe(turn, true, attempt + 1)),
2772 Effect.forkIn(scope),
2773 );
2774 return;
2775 }
2776 stopRequested = true;
2777 yield* connection.terminate;
2778 return;
2779 }
2780 if (
2781 recordField(data, "isStreaming") !== true &&
2782 recordField(data, "isCompacting") !== true &&
2783 (recordNumber(data, "pendingMessageCount") ?? 0) === 0
2784 ) {
2785 turn.settleWhenIdle = false;
2786 if (state === null) return;
2787 adoptLiveSessionFile(state, data);
2788 yield* finalizeTurn(state);
2789 }
2790 return;
2791 }
2792 default:
2793 return;
2794 }
2795 });
2796
2797 yield* Effect.gen(function* () {
2798 while (true) {
2799 const activeConnection = connection;
2800 const event = yield* Queue.take(activeConnection.events).pipe(
2801 Effect.catchTags({
2802 // Untraced: this runs inside the per-event pump loop.
2803 PiRpcError: Effect.fnUntraced(function* (error: PiRpcError) {
2804 // Let activation replace the failed startup before publishing its transport error.
2805 if (initialActivationPending) yield* Deferred.await(initialActivationDone);
2806 if (activeConnection !== connection) return undefined;
2807 return yield* error;
2808 }),
2809 }),
2810 );
2811 if (event === undefined || activeConnection !== connection) continue;
2812 yield* sessionEventPermit.withPermits(1)(
2813 Effect.gen(function* () {
2814 // Tracked here rather than in handleSessionEvent, which also
2815 // replays buffered wake events after they were observed.
2816 if (event["type"] === "compaction_start") nativeCompacting = true;
2817 if (event["type"] === "compaction_end") {
2818 nativeCompacting = false;
2819 // Send before the handler can probe settlement, so Pi sees the
2820 // prompt first. Prompts whose turn ended or is stopping are dropped.
2821 rejectedHeldCount = 0;
2822 for (const held of heldPrompts.splice(0)) {
2823 const turn = threadState?.activeTurn;
2824 if (
2825 turn?.providerTurn.id !== held.providerTurnId ||
2826 turn.interrupted ||
2827 stopRequested
2828 )
2829 continue;
2830 yield* sendPrompt(held);
2831 releasedPromptTurnId = held.providerTurnId;
2832 }
2833 }
2834 yield* handleSessionEvent(event).pipe(
2835 Effect.ensuring(Effect.sync(() => (releasedPromptTurnId = null))),
2836 );
2837 }),
2838 );
2839 }
2840 }).pipe(
2841 Effect.catchCause((cause) =>
2842 sessionEventPermit.withPermits(1)(
2843 Effect.gen(function* () {
2844 runtimeRetired = true;
2845 const state = threadState;
2846 closed = true;
2847 if (pendingPromptResponsesDrained !== null)
2848 yield* Deferred.fail(
2849 pendingPromptResponsesDrained,
2850 protocolError("Pi transport closed while awaiting prompt acknowledgment"),
2851 );
2852 if (extensionStatusReset !== null)
2853 yield* Deferred.fail(
2854 extensionStatusReset.ready,
2855 protocolError("Pi transport closed during status reset"),
2856 );
2857 if (rollbackBarrier !== null)
2858 yield* Deferred.fail(
2859 rollbackBarrier,
2860 protocolError("Pi transport closed during rollback"),
2861 );
2862 pendingWake = null;
2863 const interrupted = state?.activeTurn?.interrupted === true;
2864 if (state?.activeTurn != null) {
2865 state.activeTurn.failure = interrupted
2866 ? null
2867 : makeProviderFailure({
2868 cause,
2869 message: "Pi process exited unexpectedly.",
2870 class: "transport_error",
2871 });
2872 yield* finalizeTurn(state, false);
2873 } else {
2874 yield* cancelPendingPrompts(yield* DateTime.now);
2875 }
2876 if (unsolicitedActivityDetected) {
2877 yield* updateProviderSession("error", PI_UNSOLICITED_ACTIVITY_ERROR);
2878 yield* Queue.end(events);
2879 } else if (stopRequested) {
2880 yield* updateProviderSession("stopped", null);
2881 yield* Queue.end(events);
2882 } else {
2883 yield* updateProviderSession(
2884 "error",
2885 interrupted ? "Pi process was stopped." : "Pi process exited unexpectedly.",
2886 );
2887 yield* Queue.fail(
2888 events,
2889 new ProviderAdapter.ProviderAdapterEventStreamError({
2890 driver: PI_PROVIDER,
2891 providerSessionId: input.providerSessionId,
2892 cause,
2893 }),
2894 );
2895 }
2896 }),
2897 ),
2898 ),
2899 Effect.forkIn(scope),
2900 );
2901
2902 const discoverModels = Effect.fnUntraced(function* () {
2903 const modelsData = yield* request({ type: "get_available_models" }).pipe(
2904 Effect.orElseSucceed(() => undefined),
2905 );
2906 const models = recordField(modelsData, "models");
2907 if (Array.isArray(models)) {
2908 for (const model of models) rememberModelContextWindow(model);
2909 discoveredModels = models;
2910 }
2911 });
2912
2913 // CLI --fork uses Pi's own session format and sets the destination cwd. RPC
2914 // switch_session/clone alone would retain the source cwd.
2915 const forkSessionIntoCwd = Effect.fnUntraced(function* (
2916 sourceFile: string,
2917 boundary: PiForkBoundary,
2918 providerThreadCreatedAt: DateTime.Utc,
2919 ) {
2920 const forkLaunch = buildPiRpcLaunch({
2921 launchArgs: resolvedLaunchArgs.args,
2922 environment: options.environment,
2923 mcpSession: undefined,
2924 extensionPath: undefined,
2925 shortLived: true,
2926 disableExtensions: true,
2927 disableTools: true,
2928 });
2929 return yield* Effect.scoped(
2930 Effect.gen(function* () {
2931 const forkConnection = yield* makePiRpcConnection({
2932 command: options.settings.binaryPath || "pi",
2933 args: [...forkLaunch.args, "--fork", sourceFile],
2934 cwd,
2935 env: forkLaunch.env,
2936 });
2937 yield* Stream.fromQueue(forkConnection.events).pipe(
2938 Stream.runDrain,
2939 Effect.ignore,
2940 Effect.forkScoped,
2941 );
2942 const beforeEntry =
2943 boundary.type === "nothing"
2944 ? null
2945 : yield* piForkEntry(
2946 boundary,
2947 providerThreadCreatedAt,
2948 forkConnection.request({ type: "get_entries" }),
2949 );
2950 if (beforeEntry !== null) {
2951 const result = yield* forkConnection.request({
2952 type: "fork",
2953 entryId: beforeEntry,
2954 });
2955 if (recordField(result, "cancelled") === true) {
2956 return yield* protocolError("A Pi extension cancelled the session fork");
2957 }
2958 }
2959 const state = yield* forkConnection.request({ type: "get_state" });
2960 const file = recordString(state, "sessionFile");
2961 if (file === undefined || file === sourceFile) {
2962 return yield* protocolError("Pi fork did not create a distinct session file");
2963 }
2964 return file;
2965 }),
2966 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
2967 });
2968
2969 // Old records hold entry IDs without a session file. Recover only when both
2970 // timestamped user entries are on the same branch in a sibling session.
2971 const findHistoricalForkSession = Effect.fnUntraced(function* (
2972 currentFile: string,
2973 boundary: Extract<PiForkBoundary, { type: "entry" }>,
2974 ) {
2975 const targetId = piTurnEntryId(boundary.target);
2976 const startedAt = boundary.target?.startedAt;
2977 const completedAt = boundary.target?.completedAt;
2978 const boundaryEnd = boundary.turn.completedAt;
2979 if (
2980 targetId === undefined ||
2981 startedAt == null ||
2982 completedAt == null ||
2983 boundaryEnd === null
2984 ) {
2985 return undefined;
2986 }
2987 const from = DateTime.toEpochMillis(startedAt);
2988 const between = DateTime.toEpochMillis(completedAt);
2989 const to = DateTime.toEpochMillis(boundaryEnd);
2990 const dir = path.dirname(currentFile);
2991 const siblings = yield* fileSystem
2992 .readDirectoryEntries(dir)
2993 .pipe(Effect.orElseSucceed(() => []));
2994 const files = siblings
2995 .filter((entry) => entry.type === "File" && entry.name.endsWith(".jsonl"))
2996 .map((entry) => path.join(dir, entry.name))
2997 .sort()
2998 .reverse();
2999 for (const file of files) {
3000 if (file === currentFile) continue;
3001 const entries = new Map<string, PiSessionEntry>();
3002 let leafId: string | null = null;
3003 const readable = yield* fileSystem.stream(file).pipe(
3004 Stream.decodeText(),
3005 Stream.splitLines,
3006 Stream.runForEach((line) =>
3007 Effect.sync(() => {
3008 const entry = readPiSessionEntry(Option.getOrUndefined(decodeSessionLine(line)));
3009 if (entry === null) return;
3010 const [id, value] = entry;
3011 entries.set(id, value);
3012 leafId = id;
3013 }),
3014 ),
3015 Effect.as(true),
3016 Effect.orElseSucceed(() => false),
3017 );
3018 if (
3019 readable &&
3020 piUserEntryInWindow(entries.get(targetId), from, between) &&
3021 piUserEntryInWindow(entries.get(boundary.entryId), between, to) &&
3022 walkPiBranch(entries, leafId, boundary.entryId)?.reachedStop === true &&
3023 walkPiBranch(entries, boundary.entryId, targetId)?.reachedStop === true
3024 ) {
3025 return file;
3026 }
3027 }
3028 return undefined;
3029 });
3030
3031 const sessionFileInCwd = Effect.fnUntraced(function* (
3032 sessionFile: string,
3033 providerThreadCreatedAt: DateTime.Utc,
3034 ) {
3035 if (yield* sessionHeaderNamesCwd(sessionFile)) return sessionFile;
3036 return yield* forkSessionIntoCwd(sessionFile, { type: "nothing" }, providerThreadCreatedAt);
3037 });
3038
3039 const registerThread = Effect.fnUntraced(
3040 function* (
3041 threadInput: ProviderAdapter.ProviderAdapterV2EnsureThreadInput,
3042 publish = true,
3043 ) {
3044 if (rollbackBarrier !== null)
3045 return yield* protocolError("Cannot register a Pi thread during rollback");
3046 if (threadState !== null && threadState.activeTurn !== null) {
3047 return yield* protocolError("Cannot register a Pi thread while a turn is active");
3048 }
3049 if (pendingWake !== null) {
3050 const state = threadState;
3051 if (
3052 state !== null &&
3053 state === pendingWake.state &&
3054 state.providerThread.appThreadId === threadInput.threadId &&
3055 (threadInput.existingProviderThread === undefined ||
3056 threadInput.existingProviderThread.nativeThreadRef?.nativeId ===
3057 state.providerThread.nativeThreadRef?.nativeId)
3058 )
3059 return state.providerThread;
3060 return yield* protocolError(
3061 "Cannot switch Pi threads while native work is awaiting a turn",
3062 );
3063 }
3064 const existing = threadInput.existingProviderThread;
3065 const resumeId = existing?.nativeThreadRef?.nativeId;
3066 const needsNewSession = resumeId == null && registrationAttempted;
3067 registrationAttempted = true;
3068 // This probe replaces switch_session as a resume's first request, so it keeps the lifecycle deadline.
3069 // It also recovers a failed spawn session before lifecycleRequest offers to its dead queue.
3070 let stateData =
3071 resumeId != null || initialActivationPending
3072 ? yield* request({ type: "get_state" }, PI_SESSION_TIMEOUT_MS)
3073 : undefined;
3074 const liveSessionFile = recordString(stateData, "sessionFile");
3075 // Switching replaces the session and reloads extensions, so keep an already attached file.
3076 const alreadyOnResumeFile =
3077 resumeId != null &&
3078 liveSessionFile !== undefined &&
3079 path.resolve(cwd, liveSessionFile) === path.resolve(cwd, resumeId);
3080 if (!alreadyOnResumeFile && (resumeId != null || needsNewSession)) {
3081 if (pendingWake !== null) {
3082 return yield* protocolError(
3083 "Cannot switch Pi threads while native work is awaiting a turn",
3084 );
3085 }
3086 lastNativeThreadId = resumeId ?? lastNativeThreadId;
3087 // Failed lifecycle operations can still change native sessions; invalidate bindings and defaults.
3088 threadState = null;
3089 appliedModel = null;
3090 appliedThinking = null;
3091 appliedSessionName = null;
3092 baselineModel = null;
3093 baselineThinking = null;
3094 contextWindow = null;
3095 const result = yield* lifecycleRequest(
3096 resumeId != null && existing !== undefined
3097 ? {
3098 type: "switch_session",
3099 sessionPath: yield* sessionFileInCwd(resumeId, existing.createdAt),
3100 }
3101 : { type: "new_session" },
3102 );
3103 if (recordField(result, "cancelled") === true) {
3104 return yield* protocolError("A Pi extension cancelled the session switch");
3105 }
3106 stateData = undefined;
3107 }
3108 stateData ??= yield* request({ type: "get_state" });
3109 if (discoveredModels === null) yield* discoverModels();
3110 contextWindow = rememberModelContextWindow(recordField(stateData, "model"));
3111 // Capture each baseline before applying selections so our own choices cannot become Pi defaults.
3112 if (baselineModel === null && appliedModel === null) {
3113 const stateModel = recordField(stateData, "model");
3114 const provider = recordString(stateModel, "provider");
3115 const modelId = recordString(stateModel, "id");
3116 if (provider !== undefined && modelId !== undefined) {
3117 baselineModel = { provider, modelId };
3118 }
3119 }
3120 if (baselineThinking === null && appliedThinking === null) {
3121 baselineThinking = recordString(stateData, "thinkingLevel") ?? null;
3122 appliedThinking = baselineThinking;
3123 }
3124 // switch_session accepts a file path, not Pi's display session UUID.
3125 const nativeId = recordString(stateData, "sessionFile");
3126 if (nativeId === undefined) {
3127 return yield* protocolError("get_state returned no persisted sessionFile", stateData);
3128 }
3129 if (needsNewSession && nativeId === lastNativeThreadId) {
3130 return yield* protocolError("Pi did not create a distinct session file");
3131 }
3132 lastNativeThreadId = nativeId;
3133 const createdAt = yield* DateTime.now;
3134 const providerThread: OrchestrationV2ProviderThread =
3135 existing !== undefined
3136 ? {
3137 ...existing,
3138 providerSessionId: input.providerSessionId,
3139 nativeThreadRef: providerRef(nativeId),
3140 ...(needsNewSession
3141 ? { nativeConversationHeadRef: null, contextUsage: null }
3142 : {}),
3143 status: "idle",
3144 updatedAt: createdAt,
3145 }
3146 : {
3147 id: idAllocator.derive.providerThread({
3148 driver: PI_PROVIDER,
3149 nativeThreadId: nativeId,
3150 }),
3151 driver: PI_PROVIDER,
3152 providerInstanceId: options.instanceId,
3153 providerSessionId: input.providerSessionId,
3154 appThreadId: threadInput.threadId,
3155 ownerNodeId: null,
3156 nativeThreadRef: providerRef(nativeId),
3157 nativeConversationHeadRef: null,
3158 status: "idle",
3159 firstRunOrdinal: null,
3160 lastRunOrdinal: null,
3161 handoffIds: [],
3162 forkedFrom: null,
3163 pendingBackgroundTasks: [],
3164 createdAt,
3165 updatedAt: createdAt,
3166 };
3167 if (
3168 threadState !== null &&
3169 threadState.providerThread.id === providerThread.id &&
3170 threadState.providerThread.appThreadId === threadInput.threadId &&
3171 threadState.providerThread.nativeThreadRef?.nativeId === resumeId
3172 ) {
3173 // A wake arriving during the reads still owns this same-session binding.
3174 threadState.providerThread = providerThread;
3175 } else {
3176 if (pendingWake !== null) {
3177 return yield* protocolError(
3178 "Cannot switch Pi threads while native work is awaiting a turn",
3179 );
3180 }
3181 threadState = { providerThread, activeTurn: null, supersededSessionFiles: new Set() };
3182 }
3183 const baselineEntries = yield* request({ type: "get_entries" }).pipe(
3184 Effect.orElseSucceed(() => undefined),
3185 );
3186 lastKnownLeaf = recordString(baselineEntries, "leafId") ?? null;
3187 leafCursorStale = baselineEntries === undefined;
3188 if (publish)
3189 yield* emit({
3190 type: "provider_thread.updated",
3191 driver: PI_PROVIDER,
3192 providerThread,
3193 });
3194 return providerThread;
3195 },
3196 (effect) =>
3197 Effect.acquireUseRelease(
3198 Effect.suspend(() => {
3199 if (registrationInProgress)
3200 return protocolError("Cannot register a Pi thread during registration");
3201 registrationInProgress = true;
3202 return Effect.void;
3203 }),
3204 () => effect,
3205 () =>
3206 Effect.sync(() => {
3207 registrationInProgress = false;
3208 }),
3209 ),
3210 );
3211
3212 const applySelection = Effect.fnUntraced(function* (modelSelection: ModelSelection) {
3213 const thinking = getModelSelectionStringOptionValue(modelSelection, "thinking");
3214 // pi.setModel and /preset can change the model without an RPC event.
3215 // Confirm cached selections against Pi before skipping them.
3216 const modelCached =
3217 modelSelection.model !== PI_INHERIT_MODEL_SLUG && modelSelection.model === appliedModel;
3218 let modelDrifted = false;
3219 if (modelCached || (thinking !== undefined && thinking === appliedThinking)) {
3220 const state = yield* request({ type: "get_state" });
3221 const stateModel = recordField(state, "model");
3222 const piModel = `${recordString(stateModel, "provider")}/${recordString(stateModel, "id")}`;
3223 modelDrifted = modelCached && piModel !== appliedModel;
3224 appliedThinking = recordString(state, "thinkingLevel") ?? null;
3225 }
3226 if (modelSelection.model === PI_INHERIT_MODEL_SLUG) {
3227 if (appliedModel !== null && baselineModel !== null) {
3228 const restoredModel = yield* request({ type: "set_model", ...baselineModel });
3229 appliedThinking = null;
3230 contextWindow = rememberModelContextWindow(restoredModel);
3231 appliedModel = null;
3232 const updatedAt = yield* DateTime.now;
3233 sessionEntity = { ...sessionEntity, model: PI_INHERIT_MODEL_SLUG, updatedAt };
3234 yield* emit({
3235 type: "provider_session.updated",
3236 driver: PI_PROVIDER,
3237 providerSession: sessionEntity,
3238 });
3239 }
3240 if (
3241 thinking === undefined &&
3242 baselineThinking !== null &&
3243 appliedThinking !== baselineThinking
3244 ) {
3245 yield* request({ type: "set_thinking_level", level: baselineThinking });
3246 appliedThinking = baselineThinking;
3247 }
3248 } else if (modelDrifted || modelSelection.model !== appliedModel) {
3249 // Extensions and models.json edits can add providers after the first discovery.
3250 if (findReportedPiModel(modelSelection.model, discoveredModels) === undefined) {
3251 yield* discoverModels();
3252 }
3253 const parsed = resolvePiModelSlug(modelSelection.model, discoveredModels);
3254 if (parsed === null) {
3255 return yield* protocolError(
3256 `Pi model '${modelSelection.model}' must use provider/model format`,
3257 );
3258 }
3259 const selectedModel = yield* request({
3260 type: "set_model",
3261 provider: parsed.provider,
3262 modelId: parsed.modelId,
3263 });
3264 // Pi resets thinking to the target model's configured default on set_model.
3265 appliedThinking = null;
3266 contextWindow = rememberModelContextWindow(selectedModel);
3267 appliedModel = modelSelection.model;
3268 const updatedAt = yield* DateTime.now;
3269 sessionEntity = { ...sessionEntity, model: modelSelection.model, updatedAt };
3270 yield* emit({
3271 type: "provider_session.updated",
3272 driver: PI_PROVIDER,
3273 providerSession: sessionEntity,
3274 });
3275 }
3276 if (
3277 thinking !== undefined &&
3278 thinking !== appliedThinking &&
3279 PI_THINKING_LEVELS.has(thinking)
3280 ) {
3281 yield* request({ type: "set_thinking_level", level: thinking });
3282 appliedThinking = thinking;
3283 }
3284 const requestedTier = getModelSelectionStringOptionValue(modelSelection, "serviceTier");
3285 const serviceTier =
3286 requestedTier === undefined || requestedTier === PI_STANDARD_SERVICE_TIER
3287 ? null
3288 : requestedTier;
3289 if (serviceTier !== null || serviceTierMayBeSet) {
3290 serviceTierMayBeSet = true;
3291 const result = yield* request({
3292 type: "prompt",
3293 message: `/${PI_T3_SERVICE_TIER_COMMAND} ${serviceTier ?? ""}`.trimEnd(),
3294 });
3295 // Pi before 0.99 acknowledges a handled extension command without a disposition.
3296 const disposition = recordString(result, "disposition");
3297 if (disposition !== undefined && disposition !== "handled") {
3298 return yield* protocolError("T3 Code's Pi extension did not apply the service tier");
3299 }
3300 serviceTierMayBeSet = serviceTier !== null;
3301 }
3302 });
3303
3304 const resolvePromptPayload = Effect.fnUntraced(function* (
3305 text: string,
3306 attachments: ReadonlyArray<ChatAttachment>,
3307 ) {
3308 const images: Array<{ type: "image"; data: string; mimeType: string }> = [];
3309 const message = yield* providerMessageTextWithAttachmentPaths({
3310 text,
3311 attachments,
3312 resolveAttachmentPath: host.resolveAttachmentPath,
3313 resolveExtractedTextPath: host.resolveExtractedTextPath,
3314 });
3315 for (const attachment of attachments) {
3316 const path = host.resolveAttachmentPath(attachment);
3317 if (path === null) continue;
3318 if (attachment.mimeType.startsWith("image/")) {
3319 const bytes = yield* fileSystem.readFile(path);
3320 images.push({
3321 type: "image",
3322 data: Buffer.from(bytes).toString("base64"),
3323 mimeType: attachment.mimeType,
3324 });
3325 }
3326 }
3327 return { message, images };
3328 });
3329
3330 const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
3331 instanceId: options.instanceId,
3332 driver: PI_PROVIDER,
3333 providerSessionId: input.providerSessionId,
3334 get providerSession() {
3335 return sessionEntity;
3336 },
3337 events: Stream.fromQueue(events),
3338 backgroundTasksEndWithProcess: true,
3339 hasPendingBackgroundWork: Effect.sync(() => pendingWake !== null),
3340 hasPendingBackgroundWorkForThread: (providerThread) =>
3341 Effect.sync(
3342 () => pendingWake !== null && pendingWake.state.providerThread.id === providerThread.id,
3343 ),
3344 getModelContextWindow: (selection) => {
3345 if (selection.instanceId !== options.instanceId) return undefined;
3346 const slug =
3347 selection.model === PI_INHERIT_MODEL_SLUG
3348 ? baselineModel === null
3349 ? undefined
3350 : `${baselineModel.provider}/${baselineModel.modelId}`
3351 : selection.model;
3352 return slug === undefined ? undefined : modelContextWindows.get(slug);
3353 },
3354 ensureThread: (threadInput) =>
3355 registerThread(threadInput).pipe(
3356 Effect.mapError(
3357 (cause) =>
3358 new ProviderAdapter.ProviderAdapterEnsureThreadError({
3359 driver: PI_PROVIDER,
3360 threadId: threadInput.threadId,
3361 cause,
3362 }),
3363 ),
3364 ),
3365 resumeThread: (threadInput) =>
3366 registerThread({
3367 threadId:
3368 threadInput.threadId ?? threadInput.providerThread.appThreadId ?? input.threadId,
3369 modelSelection: threadInput.modelSelection ?? input.modelSelection,
3370 runtimePolicy: threadInput.runtimePolicy ?? input.runtimePolicy,
3371 existingProviderThread: threadInput.providerThread,
3372 }).pipe(
3373 Effect.mapError(
3374 (cause) =>
3375 new ProviderAdapter.ProviderAdapterResumeThreadError({
3376 driver: PI_PROVIDER,
3377 providerSessionId: input.providerSessionId,
3378 providerThreadId: threadInput.providerThread.id,
3379 cause,
3380 }),
3381 ),
3382 ),
3383 compactThread: (turnInput) =>
3384 runtime.startTurn({
3385 ...turnInput,
3386 message: { ...turnInput.message, text: "/compact" },
3387 }),
3388 startTurn: Effect.fn("PiAdapter.startTurn")(
3389 function* (turnInput) {
3390 if (registrationInProgress)
3391 return yield* protocolError("Cannot start a Pi turn during registration");
3392 if (rollbackBarrier !== null)
3393 return yield* protocolError("Cannot start a Pi turn during rollback");
3394 const state = threadState;
3395 if (state === null) {
3396 return yield* protocolError("Pi session has no registered thread");
3397 }
3398 while (true) {
3399 if (state.activeTurn !== null) {
3400 return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3401 driver: PI_PROVIDER,
3402 detail: `Pi provider thread ${turnInput.providerThread.id} already has an active turn`,
3403 reason: "previous_turn_active",
3404 });
3405 }
3406 if (closed || stopRequested)
3407 return yield* protocolError("Cannot start a Pi turn after session closure");
3408 if (pendingPromptResponsesDrained === null) break;
3409 yield* Deferred.await(pendingPromptResponsesDrained);
3410 }
3411 if (!isLiveSessionOf(state, turnInput.providerThread.nativeThreadRef?.nativeId)) {
3412 return yield* protocolError("Pi turn requested for a different native session");
3413 }
3414 // Fork adoption uses the orchestrator-allocated row; preserve that identity in later updates.
3415 const continuation =
3416 turnInput.message.createdBy === "agent" &&
3417 turnInput.message.creationSource === "provider";
3418 if (!continuation) yield* applySelection(turnInput.modelSelection);
3419 if (turnInput.appThread.title !== appliedSessionName) {
3420 yield* request({
3421 type: "set_session_name",
3422 name: turnInput.appThread.title,
3423 }).pipe(
3424 Effect.tap(() =>
3425 Effect.sync(() => (appliedSessionName = turnInput.appThread.title)),
3426 ),
3427 Effect.ignore,
3428 );
3429 }
3430 // Resolve attachments before turn installation so failures cannot strand activeTurn.
3431 // Inject instructions through before_agent_start; wrapping user text breaks slash-command expansion.
3432 const compactCommand = continuation
3433 ? null
3434 : parsePiCompactCommand(turnInput.message.text);
3435 const payload =
3436 !continuation && compactCommand === null
3437 ? yield* resolvePromptPayload(turnInput.message.text, turnInput.message.attachments)
3438 : null;
3439 const startedAt = yield* DateTime.now;
3440 const syntheticNativeTurnId = `${state.providerThread.id}:attempt:${turnInput.attemptId}`;
3441 const providerTurn: OrchestrationV2ProviderTurn = {
3442 id: idAllocator.derive.providerTurn({
3443 driver: PI_PROVIDER,
3444 nativeTurnId: syntheticNativeTurnId,
3445 }),
3446 providerThreadId: turnInput.providerThread.id,
3447 nodeId: turnInput.rootNodeId,
3448 runAttemptId: turnInput.attemptId,
3449 nativeTurnRef: providerRef(syntheticNativeTurnId, "weak"),
3450 ...(state.providerThread.nativeThreadRef === null
3451 ? {}
3452 : { nativeThreadRef: state.providerThread.nativeThreadRef }),
3453 ordinal: turnInput.providerTurnOrdinal,
3454 status: "running",
3455 startedAt,
3456 completedAt: null,
3457 };
3458 const activeTurn: ActivePiTurn = {
3459 turnInput,
3460 providerTurn,
3461 startedAt,
3462 itemOrdinals: new Map(),
3463 nextItemOrdinal: turnInput.providerTurnOrdinal * 100 + 1,
3464 messageOrdinal: 0,
3465 streamItems: new Map(),
3466 toolArgs: new Map(),
3467 toolStartedAt: new Map(),
3468 commandOutputBytes: new Map(),
3469 interrupted: false,
3470 nativeAborted: false,
3471 sawAgentActivity: false,
3472 adoptedWake: false,
3473 promptMayBeCommandOnly:
3474 compactCommand !== null || (payload?.message.trimStart().startsWith("/") ?? false),
3475 latestCompactionAfterTokens: null,
3476 lastLiveUsedTokens: null,
3477 settleProbeGeneration: 0,
3478 settleWhenIdle: false,
3479 compactionCancelled: false,
3480 manualCompactInFlight: compactCommand !== null,
3481 activeCompaction: null,
3482 activeProviderRetry: null,
3483 failure: null,
3484 rejectedPromptFailure: null,
3485 unreadSteers: [],
3486 };
3487 // Lock only install/send/start events; correlated setup must leave the pump free for dialogs.
3488 while (true) {
3489 const pendingAck = yield* Effect.gen(function* () {
3490 if (
3491 threadState !== state ||
3492 registrationInProgress ||
3493 state.activeTurn !== null ||
3494 closed ||
3495 stopRequested ||
3496 rollbackBarrier !== null ||
3497 !isLiveSessionOf(state, turnInput.providerThread.nativeThreadRef?.nativeId)
3498 ) {
3499 return yield* protocolError("Pi turn ownership changed before it could start");
3500 }
3501 if (pendingPromptResponsesDrained !== null) return pendingPromptResponsesDrained;
3502 const wake = pendingWake?.state === state ? pendingWake : null;
3503 if (wake !== null && wake.state.providerThread.appThreadId !== turnInput.threadId) {
3504 return yield* protocolError("Pi native wake belongs to a different app thread");
3505 }
3506 pendingWake = null;
3507 state.providerThread = {
3508 ...turnInput.providerThread,
3509 nativeThreadRef: state.providerThread.nativeThreadRef,
3510 };
3511 state.activeTurn = activeTurn;
3512 activeTurn.adoptedWake = wake !== null && !continuation;
3513 if (compactCommand !== null) {
3514 yield* connection.send(compactRpcRecord(compactCommand));
3515 pendingCompactResponses.push({
3516 providerTurnId: providerTurn.id,
3517 kind: "turn_start",
3518 });
3519 } else if (payload !== null) {
3520 yield* sendPrompt({
3521 providerTurnId: providerTurn.id,
3522 kind: "turn_start",
3523 record: {
3524 type: "prompt",
3525 message: payload.message,
3526 streamingBehavior: "steer",
3527 ...(payload.images.length === 0 ? {} : { images: payload.images }),
3528 },
3529 });
3530 }
3531 yield* emit({
3532 type: "provider_turn.updated",
3533 driver: PI_PROVIDER,
3534 threadId: turnInput.threadId,
3535 providerTurn,
3536 });
3537 yield* updateProviderThread(state, {
3538 status: "active",
3539 firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,
3540 lastRunOrdinal: turnInput.runOrdinal,
3541 });
3542 yield* updateProviderSession("running", null);
3543 if (wake !== null) {
3544 for (const event of wake.events) {
3545 if (!continuation && event["type"] === "agent_settled") {
3546 activeTurn.nativeAborted = event["aborted"] === true;
3547 activeTurn.settleWhenIdle = true;
3548 continue;
3549 }
3550 yield* handleSessionEvent(event);
3551 }
3552 } else if (continuation) {
3553 yield* finalizeTurn(state);
3554 }
3555 if (outOfTurnExtensionErrors.length > 0) {
3556 yield* Queue.offer(connection.events, { type: "t3.flush_extension_errors" });
3557 }
3558 return null;
3559 }).pipe(
3560 sessionEventPermit.withPermits(1),
3561 Effect.tapError(() =>
3562 Effect.sync(() => {
3563 if (state.activeTurn === activeTurn) state.activeTurn = null;
3564 }),
3565 ),
3566 );
3567 if (pendingAck === null) break;
3568 // The native event pump needs the permit to consume the actual ACK.
3569 yield* Deferred.await(pendingAck);
3570 }
3571 // Pi acks `prompt` only after slash-command expansion completes,
3572 // and extension commands may block on user dialogs indefinitely.
3573 // Correlated responses therefore return later through the event pump.
3574 },
3575 (effect, turnInput) =>
3576 effect.pipe(
3577 Effect.mapError(
3578 (cause) =>
3579 new ProviderAdapter.ProviderAdapterTurnStartError({
3580 driver: PI_PROVIDER,
3581 threadId: turnInput.threadId,
3582 providerThreadId: turnInput.providerThread.id,
3583 runId: turnInput.runId,
3584 cause,
3585 }),
3586 ),
3587 ),
3588 ),
3589 steerTurn: Effect.fn("PiAdapter.steerTurn")(
3590 function* (steerInput: ProviderAdapter.ProviderAdapterV2SteerInput) {
3591 const turn = threadState?.activeTurn ?? null;
3592 if (turn === null || turn.providerTurn.id !== steerInput.providerTurnId) {
3593 return yield* protocolError(`Pi turn ${steerInput.providerTurnId} is not active`);
3594 }
3595 const compactCommand = parsePiCompactCommand(steerInput.message.text);
3596 const payload =
3597 compactCommand === null
3598 ? yield* resolvePromptPayload(
3599 steerInput.message.text,
3600 steerInput.message.attachments,
3601 )
3602 : null;
3603 // prompt with steer atomically queues or starts; fire-and-forget under the permit avoids dialog deadlocks.
3604 // /compact uses its RPC, which aborts the agent first.
3605 yield* sessionEventPermit.withPermits(1)(
3606 Effect.gen(function* () {
3607 if (threadState?.activeTurn !== turn) {
3608 return yield* protocolError(`Pi turn ${steerInput.providerTurnId} is not active`);
3609 }
3610 if (compactCommand !== null) {
3611 turn.manualCompactInFlight = true;
3612 yield* connection.send(compactRpcRecord(compactCommand));
3613 pendingCompactResponses.push({
3614 providerTurnId: turn.providerTurn.id,
3615 kind: "steer",
3616 });
3617 } else if (payload !== null) {
3618 yield* sendPrompt({
3619 providerTurnId: turn.providerTurn.id,
3620 kind: "steer",
3621 messageId: steerInput.message.messageId,
3622 record: {
3623 type: "prompt",
3624 message: payload.message,
3625 streamingBehavior: "steer",
3626 ...(payload.images.length === 0 ? {} : { images: payload.images }),
3627 },
3628 });
3629 }
3630 turn.settleProbeGeneration += 1;
3631 }),
3632 );
3633 },
3634 (effect, steerInput) =>
3635 effect.pipe(
3636 Effect.mapError(
3637 (cause) =>
3638 new ProviderAdapter.ProviderAdapterSteerRunError({
3639 driver: PI_PROVIDER,
3640 providerThreadId: steerInput.providerThread.id,
3641 providerTurnId: steerInput.providerTurnId,
3642 cause,
3643 }),
3644 ),
3645 ),
3646 ),
3647 interruptTurn: Effect.fn("PiAdapter.interruptTurn")(
3648 function* (interruptInput) {
3649 const turn = threadState?.activeTurn ?? null;
3650 if (turn === null && interruptInput.requestRuntimeRestart === true) {
3651 if (pendingWake !== null)
3652 yield* sessionEventPermit.withPermits(1)(stopPendingWake(pendingWake));
3653 return;
3654 }
3655 if (turn === null || turn.providerTurn.id !== interruptInput.providerTurnId) {
3656 return yield* protocolError(`Pi turn ${interruptInput.providerTurnId} is not active`);
3657 }
3658 turn.interrupted = true;
3659 if (
3660 interruptInput.requestRuntimeRestart === true ||
3661 turn.settleWhenIdle ||
3662 turn.activeCompaction !== null ||
3663 turn.manualCompactInFlight ||
3664 nativeCompacting
3665 ) {
3666 // Generic abort misses manual compaction; terminate so Stop covers /compact and recovery.
3667 stopRequested = true;
3668 if (interruptInput.requestRuntimeRestart === true && !turn.settleWhenIdle) {
3669 yield* clearNativeQueue(turn);
3670 yield* request({ type: "abort" }, 2_000).pipe(Effect.ignore);
3671 }
3672 // Capture session identity and rollback refs while Pi can still answer; serialize with settlement.
3673 yield* sessionEventPermit.withPermits(1)(
3674 Effect.gen(function* () {
3675 const state = threadState;
3676 if (state?.activeTurn === turn) {
3677 // Probes answered before Stop may carry a session file the extension already left.
3678 turn.settleProbeGeneration += 1;
3679 const liveState = yield* request({ type: "get_state" }, 2_000).pipe(
3680 Effect.orElseSucceed(() => undefined),
3681 );
3682 adoptLiveSessionFile(state, liveState);
3683 if (turn.stopTreeRefs === undefined) {
3684 turn.stopTreeRefs = yield* captureTurnTreeRefs(2_000);
3685 }
3686 }
3687 yield* connection.terminate;
3688 }),
3689 );
3690 return;
3691 }
3692 yield* clearNativeQueue(turn);
3693 yield* request({ type: "abort" }).pipe(
3694 Effect.tapError(() => Effect.sync(() => (turn.interrupted = false))),
3695 );
3696 },
3697 (effect, interruptInput) =>
3698 effect.pipe(
3699 Effect.mapError(
3700 (cause) =>
3701 new ProviderAdapter.ProviderAdapterInterruptError({
3702 driver: PI_PROVIDER,
3703 providerThreadId: interruptInput.providerThread.id,
3704 providerTurnId: interruptInput.providerTurnId,
3705 cause,
3706 }),
3707 ),
3708 ),
3709 ),
3710 respondToRuntimeRequest: Effect.fn("PiAdapter.respondToRuntimeRequest")(
3711 function* (requestInput) {
3712 const pending = pendingPrompts.get(String(requestInput.requestId));
3713 if (pending === undefined) {
3714 return yield* protocolError(
3715 `No pending Pi extension request ${requestInput.requestId}`,
3716 );
3717 }
3718 const answeredAt = yield* DateTime.now;
3719 if (
3720 pending.expiresAt !== null &&
3721 DateTime.toEpochMillis(answeredAt) >= pending.expiresAt
3722 ) {
3723 pendingPrompts.delete(String(requestInput.requestId));
3724 yield* cancelPrompt(pending, answeredAt);
3725 return yield* protocolError(
3726 `Pi extension request ${requestInput.requestId} has expired`,
3727 );
3728 }
3729 let response = piUiResponse(pending, requestInput.decision, requestInput.answers);
3730 const route = pending.customAnswerRoute;
3731 if (
3732 route !== undefined &&
3733 typeof response["value"] === "string" &&
3734 response["value"].trim().length > 0 &&
3735 !route.lines.includes(response["value"])
3736 ) {
3737 customAnswerFollowUps.set(route.followUpTitlePrefix, [
3738 ...(customAnswerFollowUps.get(route.followUpTitlePrefix) ?? []),
3739 response["value"],
3740 ]);
3741 response = { value: route.sentinel };
3742 }
3743 yield* connection.send({
3744 type: "extension_ui_response",
3745 id: pending.nativeRequestId,
3746 ...response,
3747 });
3748 pendingPrompts.delete(String(requestInput.requestId));
3749 if (pending.expirationFiber !== null) yield* Fiber.interrupt(pending.expirationFiber);
3750 if (pending.method === "confirm" && requestInput.decision === "acceptForSession") {
3751 sessionApprovals.add(pending.approvalKey);
3752 }
3753 const resolvedAt = yield* DateTime.now;
3754 pending.runtimeRequest = {
3755 ...pending.runtimeRequest,
3756 status: "resolved",
3757 resolvedAt,
3758 };
3759 yield* emit({
3760 type: "runtime_request.updated",
3761 driver: PI_PROVIDER,
3762 threadId: pending.node.threadId,
3763 runtimeRequest: pending.runtimeRequest,
3764 });
3765 yield* emit({
3766 type: "node.updated",
3767 driver: PI_PROVIDER,
3768 node: { ...pending.node, status: "completed", completedAt: resolvedAt },
3769 });
3770 yield* emit({
3771 type: "turn_item.updated",
3772 driver: PI_PROVIDER,
3773 turnItem: {
3774 ...pending.turnItem,
3775 status: "completed",
3776 completedAt: resolvedAt,
3777 updatedAt: resolvedAt,
3778 },
3779 });
3780 },
3781 (effect, requestInput) =>
3782 effect.pipe(
3783 sessionEventPermit.withPermits(1),
3784 Effect.mapError(
3785 (cause) =>
3786 new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
3787 driver: PI_PROVIDER,
3788 requestId: requestInput.requestId,
3789 cause,
3790 }),
3791 ),
3792 ),
3793 ),
3794 readThreadSnapshot: Effect.fn("PiAdapter.readThreadSnapshot")(
3795 function* (snapshotInput) {
3796 const state = threadState;
3797 const boundNativeId = state?.providerThread.nativeThreadRef?.nativeId;
3798 const wantedNativeId = snapshotInput.providerThread.nativeThreadRef?.nativeId;
3799 if (state === null || wantedNativeId == null || boundNativeId !== wantedNativeId) {
3800 return yield* protocolError(
3801 "Pi snapshot requested for a thread this session does not host",
3802 );
3803 }
3804 // get_messages contains only the active branch; get_entries would leak abandoned branches into handoffs.
3805 const messagesData = yield* request({ type: "get_messages" });
3806 const activeMessages = recordField(messagesData, "messages");
3807 const threadId = state.providerThread.appThreadId ?? input.threadId;
3808 const messages = (Array.isArray(activeMessages) ? activeMessages : []).flatMap(
3809 (message, index) => {
3810 const role = recordString(message, "role");
3811 if (role !== "user" && role !== "assistant") return [];
3812 const text = contentText(recordField(message, "content"));
3813 if (text.length === 0) return [];
3814 const timestamp = recordNumber(message, "timestamp");
3815 const at = Option.getOrElse(
3816 DateTime.make(timestamp ?? Number.NaN),
3817 () => state.providerThread.createdAt,
3818 );
3819 return [
3820 {
3821 id: idAllocator.derive.messageFromProviderItem({
3822 driver: PI_PROVIDER,
3823 nativeItemId: `${wantedNativeId}:snapshot-message:${index}`,
3824 }),
3825 threadId,
3826 runId: null,
3827 nodeId: null,
3828 role: role as "user" | "assistant",
3829 text,
3830 attachments: [],
3831 streaming: false,
3832 createdBy: role === "user" ? ("user" as const) : ("agent" as const),
3833 creationSource: "provider" as const,
3834 createdAt: at,
3835 updatedAt: at,
3836 },
3837 ];
3838 },
3839 );
3840 return {
3841 providerThread: state.providerThread,
3842 providerTurns: [],
3843 messages,
3844 runtimeRequests: [],
3845 };
3846 },
3847 (effect, snapshotInput) =>
3848 effect.pipe(
3849 Effect.mapError(
3850 (cause) =>
3851 new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
3852 driver: PI_PROVIDER,
3853 providerThreadId: snapshotInput.providerThread.id,
3854 cause,
3855 }),
3856 ),
3857 ),
3858 ),
3859 rollbackThread: Effect.fn("PiAdapter.rollbackThread")(
3860 function* (rollbackInput) {
3861 if (registrationInProgress)
3862 return yield* protocolError("Cannot roll back a Pi thread during registration");
3863 // A fresh runtime (restart or idle release) must load the persisted session before forking.
3864 // Unpublished: the rollback service persists the returned snapshot.
3865 if (
3866 threadState === null &&
3867 rollbackInput.providerThread.nativeThreadRef?.nativeId != null
3868 ) {
3869 yield* registerThread(
3870 {
3871 threadId: rollbackInput.providerThread.appThreadId ?? input.threadId,
3872 modelSelection: input.modelSelection,
3873 runtimePolicy: input.runtimePolicy,
3874 existingProviderThread: rollbackInput.providerThread,
3875 },
3876 false,
3877 );
3878 }
3879 const state = threadState;
3880 if (state === null) {
3881 return yield* protocolError("Pi session has no registered thread");
3882 }
3883 if (state.providerThread.id !== rollbackInput.providerThread.id) {
3884 return yield* protocolError(
3885 "Pi rollback requested for a thread this session does not host",
3886 );
3887 }
3888 if (state.activeTurn !== null) {
3889 return yield* protocolError("Cannot roll back while a Pi turn is active");
3890 }
3891 if (pendingWake !== null) {
3892 return yield* protocolError("Cannot roll back while native Pi work awaits a turn");
3893 }
3894 const boundary = piForkBoundary(rollbackInput);
3895 if (boundary.type === "nothing") {
3896 return piThreadSnapshot(state.providerThread);
3897 }
3898 const forkEntryId = yield* piForkEntry(
3899 boundary,
3900 rollbackInput.providerThread.createdAt,
3901 request({ type: "get_entries" }),
3902 );
3903 return yield* Effect.acquireUseRelease(
3904 sessionEventPermit.withPermits(1)(
3905 Effect.gen(function* () {
3906 if (
3907 rollbackBarrier !== null ||
3908 registrationInProgress ||
3909 threadState !== state ||
3910 state.activeTurn !== null ||
3911 pendingWake !== null ||
3912 closed ||
3913 stopRequested
3914 )
3915 return yield* protocolError(
3916 "Pi rollback ownership changed before its fork could start",
3917 );
3918 const barrier = yield* Deferred.make<
3919 void,
3920 ProviderAdapter.ProviderAdapterProtocolError
3921 >();
3922 rollbackBarrier = barrier;
3923 return barrier;
3924 }),
3925 ),
3926 (barrier) =>
3927 Effect.gen(function* () {
3928 const forkData = yield* lifecycleRequest({ type: "fork", entryId: forkEntryId });
3929 if (recordField(forkData, "cancelled") === true)
3930 return yield* protocolError("A Pi extension cancelled the session fork");
3931 const forkState = yield* request({ type: "get_state" }).pipe(
3932 Effect.onError(() =>
3933 Effect.sync(() => {
3934 threadState = null;
3935 }),
3936 ),
3937 );
3938 const forkSessionFile = recordString(forkState, "sessionFile");
3939 if (forkSessionFile === undefined) {
3940 threadState = null;
3941 return yield* protocolError("Pi fork did not return a persisted session file");
3942 }
3943 const entriesData = yield* request({ type: "get_entries" }).pipe(
3944 Effect.orElseSucceed(() => undefined),
3945 );
3946 const leafId = recordString(entriesData, "leafId") ?? null;
3947 // RPC responses bypass the pump; drain prior native events before replacing their binding.
3948 const queued = yield* Queue.offer(connection.events, {
3949 type: "t3.rollback_barrier",
3950 barrier,
3951 });
3952 if (!queued) return yield* protocolError("Pi transport closed during rollback");
3953 yield* Deferred.await(barrier);
3954 return yield* sessionEventPermit.withPermits(1)(
3955 Effect.gen(function* () {
3956 if (pendingWake !== null) {
3957 yield* stopPendingWake(pendingWake);
3958 return yield* protocolError(
3959 "Native Pi work started while rollback was changing the session",
3960 );
3961 }
3962 if (
3963 threadState !== state ||
3964 state.activeTurn !== null ||
3965 closed ||
3966 stopRequested
3967 )
3968 return yield* protocolError(
3969 "Pi rollback ownership changed during its fork",
3970 );
3971 lastNativeThreadId = forkSessionFile;
3972 appliedModel = null;
3973 appliedThinking = null;
3974 appliedSessionName = null;
3975 lastKnownLeaf = leafId;
3976 leafCursorStale = entriesData === undefined;
3977 yield* updateProviderThread(state, {
3978 nativeThreadRef: providerRef(forkSessionFile),
3979 nativeConversationHeadRef: leafId === null ? null : providerRef(leafId),
3980 });
3981 rollbackBarrier = null;
3982 return piThreadSnapshot(state.providerThread);
3983 }),
3984 );
3985 }).pipe(Effect.onInterrupt(() => connection.terminate)),
3986 (barrier) =>
3987 Effect.sync(() => {
3988 if (rollbackBarrier === barrier) rollbackBarrier = null;
3989 }),
3990 );
3991 },
3992 (effect, rollbackInput) =>
3993 effect.pipe(
3994 Effect.mapError(
3995 (cause) =>
3996 new ProviderAdapter.ProviderAdapterRollbackThreadError({
3997 driver: PI_PROVIDER,
3998 providerThreadId: rollbackInput.providerThread.id,
3999 checkpointId: rollbackInput.target.checkpointId,
4000 cause,
4001 }),
4002 ),
4003 ),
4004 ),
4005 forkThread: Effect.fn("PiAdapter.forkThread")(
4006 function* (forkInput) {
4007 if (threadState?.activeTurn != null) {
4008 return yield* protocolError("Cannot fork while a Pi turn is active");
4009 }
4010 const source = forkInput.sourceProviderThread;
4011 const currentFile = source.nativeThreadRef?.nativeId;
4012 if (currentFile == null)
4013 return yield* protocolError("Pi fork source has no session file");
4014 const sourceTurns = (forkInput.sourceProviderTurns ?? []).filter(
4015 (turn) => turn.providerThreadId === source.id,
4016 );
4017 const target = sourceTurns.find((turn) => turn.id === forkInput.providerTurnId);
4018 if (forkInput.providerTurnId !== undefined && target === undefined) {
4019 return yield* protocolError("Pi fork target turn is missing");
4020 }
4021 const targetFile = target?.nativeThreadRef?.nativeId ?? undefined;
4022 const boundary: PiForkBoundary =
4023 target === undefined
4024 ? { type: "nothing" }
4025 : piForkBoundary({
4026 target: { type: "provider_turn", providerTurn: target },
4027 providerThreadTurns: sourceTurns,
4028 sessionFile: targetFile,
4029 });
4030 const boundaryFile =
4031 boundary.type === "nothing" ? undefined : boundary.turn.nativeThreadRef?.nativeId;
4032 const sourceFile = targetFile ?? boundaryFile ?? currentFile;
4033 const nativeId = yield* forkSessionIntoCwd(sourceFile, boundary, source.createdAt).pipe(
4034 Effect.catchTags({
4035 PiRpcError: (error) => {
4036 if (
4037 boundary.type !== "entry" ||
4038 boundaryFile != null ||
4039 error.operation !== "fork" ||
4040 error.detail !== "Invalid entry ID for forking"
4041 ) {
4042 return Effect.fail(error);
4043 }
4044 return findHistoricalForkSession(currentFile, boundary).pipe(
4045 Effect.flatMap((file) =>
4046 file === undefined
4047 ? Effect.fail(error)
4048 : forkSessionIntoCwd(file, boundary, source.createdAt),
4049 ),
4050 );
4051 },
4052 }),
4053 );
4054 const now = yield* DateTime.now;
4055 return yield* registerThread(
4056 {
4057 threadId: forkInput.targetThreadId,
4058 modelSelection: forkInput.modelSelection ?? input.modelSelection,
4059 runtimePolicy: forkInput.runtimePolicy ?? input.runtimePolicy,
4060 existingProviderThread: {
4061 ...source,
4062 id: idAllocator.derive.providerThread({
4063 driver: PI_PROVIDER,
4064 nativeThreadId: nativeId,
4065 }),
4066 appThreadId: forkInput.targetThreadId,
4067 providerSessionId: input.providerSessionId,
4068 providerInstanceId: options.instanceId,
4069 ownerNodeId: forkInput.ownerNodeId ?? null,
4070 nativeThreadRef: providerRef(nativeId),
4071 nativeConversationHeadRef: null,
4072 firstRunOrdinal: null,
4073 lastRunOrdinal: null,
4074 handoffIds: [],
4075 pendingBackgroundTasks: [],
4076 forkedFrom: {
4077 providerThreadId: source.id,
4078 ...(forkInput.providerTurnId === undefined
4079 ? {}
4080 : { providerTurnId: forkInput.providerTurnId }),
4081 },
4082 createdAt: now,
4083 updatedAt: now,
4084 },
4085 },
4086 false,
4087 );
4088 },
4089 (effect, forkInput) =>
4090 effect.pipe(
4091 Effect.mapError(
4092 (cause) =>
4093 new ProviderAdapter.ProviderAdapterForkThreadError({
4094 driver: PI_PROVIDER,
4095 providerThreadId: forkInput.sourceProviderThread.id,
4096 cause,
4097 }),
4098 ),
4099 ),
4100 ),
4101 };
4102 return runtime;
4103 }),
4104 });
4105 });
4106
4107 const decodeSessionLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
4108
4109 interface PiSessionEntry {
4110 readonly parentId: string | null;
4111 readonly isUserMessage: boolean;
4112 /** Pi's `timestamp` as epoch milliseconds; null when missing or unparsable. */
4113 readonly timestamp: number | null;
4114 }
4115
4116 interface PiSessionListing {
4117 readonly entries: ReadonlyMap<string, PiSessionEntry>;
4118 readonly leafId: string | null;
4119 }
4120
4121 function piSessionListing(data: unknown): PiSessionListing | null {
4122 const leafId = recordField(data, "leafId");
4123 const entries = piSessionEntries(recordField(data, "entries"));
4124 return entries !== null && (typeof leafId === "string" || leafId === null)
4125 ? { entries, leafId }
4126 : null;
4127 }
4128
4129 function piSessionEntries(entries: unknown): ReadonlyMap<string, PiSessionEntry> | null {
4130 if (!Array.isArray(entries)) return null;
4131 const byId = new Map<string, PiSessionEntry>();
4132 for (const raw of entries) {
4133 const entry = readPiSessionEntry(raw);
4134 if (entry === null || byId.has(entry[0])) return null;
4135 byId.set(...entry);
4136 }
4137 return byId;
4138 }
4139
4140 function readPiSessionEntry(entry: unknown): [string, PiSessionEntry] | null {
4141 const id = recordString(entry, "id");
4142 const parentId = recordField(entry, "parentId");
4143 if (id === undefined || (parentId !== null && typeof parentId !== "string")) return null;
4144 const timestamp = recordString(entry, "timestamp");
4145 return [
4146 id,
4147 {
4148 parentId,
4149 isUserMessage:
4150 recordField(entry, "type") === "message" &&
4151 recordString(recordField(entry, "message"), "role") === "user",
4152 timestamp:
4153 timestamp === undefined
4154 ? null
4155 : Option.getOrNull(Option.map(DateTime.make(timestamp), DateTime.toEpochMillis)),
4156 },
4157 ];
4158 }
4159
4160 function piUserEntryInWindow(entry: PiSessionEntry | undefined, from: number, to: number): boolean {
4161 return (
4162 entry?.isUserMessage === true &&
4163 entry.timestamp !== null &&
4164 entry.timestamp >= from &&
4165 entry.timestamp <= to
4166 );
4167 }
4168
4169 function piTurnEntryId(turn: OrchestrationV2ProviderTurn | null | undefined): string | undefined {
4170 const ref = turn?.nativeTurnRef;
4171 return ref?.strength === "strong" ? (ref.nativeId ?? undefined) : undefined;
4172 }
4173
4174 function walkPiBranch(
4175 entries: ReadonlyMap<string, PiSessionEntry>,
4176 leafId: string | null,
4177 stopAt: string | null,
4178 ): {
4179 readonly entryCount: number;
4180 readonly userEntryIds: ReadonlyArray<string>;
4181 readonly reachedStop: boolean;
4182 } | null {
4183 const visited = new Set<string>();
4184 const userEntryIds: Array<string> = [];
4185 let current = leafId;
4186 while (current !== null && current !== stopAt) {
4187 const entry = entries.get(current);
4188 if (entry === undefined) break;
4189 if (visited.has(current)) return null;
4190 visited.add(current);
4191 if (entry.isUserMessage) userEntryIds.push(current);
4192 current = entry.parentId;
4193 }
4194 return { entryCount: visited.size, userEntryIds, reachedStop: current === stopAt };
4195 }
4196
4197 type PiForkBoundary =
4198 | {
4199 readonly type: "entry";
4200 readonly entryId: string;
4201 readonly turn: OrchestrationV2ProviderTurn;
4202 readonly target: OrchestrationV2ProviderTurn | null;
4203 }
4204 | { readonly type: "nothing" }
4205 | {
4206 readonly type: "uncaptured";
4207 readonly turn: OrchestrationV2ProviderTurn;
4208 readonly target: OrchestrationV2ProviderTurn | null;
4209 };
4210
4211 /**
4212 * Turns without a ref left nothing on the active branch, so the boundary is the first discarded
4213 * turn that has one. `uncaptured` is a boundary turn still carrying its synthetic ref (only
4214 * `captureTurnTreeRefs` records strong ones); `piForkEntry` locates it in the session tree.
4215 */
4216 function piForkBoundary(input: {
4217 readonly target:
4218 | { readonly type: "thread_start" }
4219 | { readonly type: "provider_turn"; readonly providerTurn: OrchestrationV2ProviderTurn };
4220 readonly providerThreadTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
4221 /** Only turns recorded in this session can bound a fork from it. */
4222 readonly sessionFile?: string | undefined;
4223 }): PiForkBoundary {
4224 const target = input.target.type === "thread_start" ? null : input.target.providerTurn;
4225 const boundary = input.providerThreadTurns
4226 .filter(
4227 (turn) =>
4228 turn.ordinal > (target?.ordinal ?? 0) &&
4229 turn.nativeTurnRef !== null &&
4230 (input.sessionFile === undefined || turn.nativeThreadRef?.nativeId === input.sessionFile),
4231 )
4232 .sort((a, b) => a.ordinal - b.ordinal)[0];
4233 const ref = boundary?.nativeTurnRef;
4234 if (boundary === undefined || ref == null) return { type: "nothing" };
4235 return ref.strength === "strong" && ref.nativeId !== null
4236 ? { type: "entry", entryId: ref.nativeId, turn: boundary, target }
4237 : { type: "uncaptured", turn: boundary, target };
4238 }
4239
4240 /** Reads the session tree only for an uncaptured boundary. */
4241 function piForkEntry<E>(
4242 boundary: Exclude<PiForkBoundary, { type: "nothing" }>,
4243 providerThreadCreatedAt: DateTime.Utc,
4244 readEntries: Effect.Effect<unknown, E>,
4245 ): Effect.Effect<string, E | ProviderAdapter.ProviderAdapterProtocolError> {
4246 if (boundary.type === "entry") return Effect.succeed(boundary.entryId);
4247 return readEntries.pipe(
4248 Effect.flatMap((data) => {
4249 const listing = piSessionListing(data);
4250 const entryId =
4251 listing === null
4252 ? undefined
4253 : piUncapturedForkEntry(listing, boundary, providerThreadCreatedAt);
4254 return entryId === undefined
4255 ? Effect.fail(
4256 new ProviderAdapter.ProviderAdapterProtocolError({
4257 driver: PI_PROVIDER,
4258 detail: `Pi turn ${boundary.turn.ordinal} has no captured session-tree entry and none was found in the session tree`,
4259 }),
4260 )
4261 : Effect.succeed(entryId);
4262 }),
4263 );
4264 }
4265
4266 /**
4267 * Pi shares the server clock. An adopted wake can precede its T3 turn, so search from the target
4268 * turn's end through the boundary turn's end. A boundary turn still running has no end yet, so
4269 * the window stays open through the tree read. At thread start, use the earlier of thread
4270 * creation and turn start to include adopted wakes while preserving inherited session history.
4271 */
4272 function piUncapturedForkEntry(
4273 listing: PiSessionListing,
4274 boundary: Extract<PiForkBoundary, { type: "uncaptured" }>,
4275 providerThreadCreatedAt: DateTime.Utc,
4276 ): string | undefined {
4277 const { startedAt, completedAt } = boundary.turn;
4278 if (startedAt === null) return undefined;
4279 const from =
4280 boundary.target === null
4281 ? Math.min(DateTime.toEpochMillis(providerThreadCreatedAt), DateTime.toEpochMillis(startedAt))
4282 : DateTime.toEpochMillis(boundary.target.completedAt ?? startedAt);
4283 const to = completedAt === null ? Infinity : DateTime.toEpochMillis(completedAt);
4284 const targetRef = boundary.target?.nativeTurnRef;
4285 const stopAt = targetRef?.strength === "strong" ? targetRef.nativeId : null;
4286 if (stopAt !== null && !listing.entries.has(stopAt)) return undefined;
4287 const walk = walkPiBranch(listing.entries, listing.leafId, stopAt);
4288 if (walk === null || !walk.reachedStop) return undefined;
4289 let earliest: string | undefined;
4290 for (const id of walk.userEntryIds) {
4291 const timestamp = listing.entries.get(id)?.timestamp;
4292 if (timestamp == null) return undefined;
4293 if (timestamp >= from && timestamp <= to) earliest = id;
4294 }
4295 return earliest;
4296 }
4297
4298 function piAsyncSubagentStatus(
4299 state: string | undefined,
4300 ): OrchestrationV2Subagent["status"] | undefined {
4301 switch (state) {
4302 case "queued":
4303 return "pending";
4304 case "running":
4305 return "running";
4306 case "paused":
4307 return "waiting";
4308 case "complete":
4309 case "partial":
4310 return "completed";
4311 case "failed":
4312 case "rejected":
4313 return "failed";
4314 case "stopped":
4315 return "interrupted";
4316 default:
4317 return undefined;
4318 }
4319 }
4320
4321 function piSubagentOutput(result: unknown): string {
4322 const stopReason = recordString(result, "stopReason");
4323 const failed =
4324 (recordNumber(result, "exitCode") ?? 0) !== 0 ||
4325 stopReason === "error" ||
4326 stopReason === "aborted";
4327 if (failed) {
4328 const failure = recordString(result, "errorMessage") || recordString(result, "stderr");
4329 if (failure !== undefined && failure.length > 0) return failure;
4330 }
4331 const messages = recordField(result, "messages");
4332 if (!Array.isArray(messages)) return "";
4333 for (let index = messages.length - 1; index >= 0; index -= 1) {
4334 const message = messages[index];
4335 if (recordString(message, "role") !== "assistant") continue;
4336 const text = contentText(recordField(message, "content"));
4337 if (text.length > 0) return text;
4338 }
4339 return "";
4340 }
4341
4342 function piExtensionDisplayName(extensionPath: string | undefined): string {
4343 if (extensionPath === undefined) return "Pi extension";
4344 const segments = extensionPath.replace(/\\/g, "/").split("/").filter(Boolean);
4345 const fileName = segments.at(-1)?.replace(/\.[^.]+$/, "") ?? "";
4346 // Pi loads a directory extension from its index file; the folder names it.
4347 const name = fileName === "index" ? (segments.at(-2) ?? fileName) : fileName;
4348 return name.length === 0 ? "Pi extension" : name;
4349 }
4350
4351 function piThreadSnapshot(
4352 providerThread: OrchestrationV2ProviderThread,
4353 ): ProviderAdapter.ProviderAdapterV2ThreadSnapshot {
4354 return { providerThread, providerTurns: [], messages: [], runtimeRequests: [] };
4355 }
4356
4357 function piQuestion(
4358 questionId: string,
4359 method: "select" | "input" | "editor",
4360 title: string,
4361 event: PiRpcRecord,
4362 ): OrchestrationV2UserInputQuestion {
4363 const options =
4364 method === "select" && Array.isArray(event["options"])
4365 ? event["options"]
4366 .filter((option): option is string => typeof option === "string")
4367 .map((option) => ({
4368 label: option || "Empty value",
4369 description: option || "Empty value",
4370 value: option,
4371 }))
4372 : method === "editor"
4373 ? []
4374 : [
4375 {
4376 label: "Submit empty value",
4377 description: "Send an empty string to the extension.",
4378 value: "",
4379 },
4380 ];
4381 // Pi's select and editor dialogs carry only a title, so show it once, as the question.
4382 // Extensions may send a blank placeholder, which is not a valid question.
4383 const detail = [recordString(event, "message"), recordString(event, "placeholder")].find(
4384 (text) => text !== undefined && text.trim().length > 0,
4385 );
4386 const questionTitle = title.trim() ? title : "Question";
4387 return {
4388 id: questionId,
4389 header: detail === undefined ? "Question" : questionTitle,
4390 question: detail ?? questionTitle,
4391 ...(method === "editor" ? { initialAnswer: recordString(event, "prefill") ?? "" } : {}),
4392 options,
4393 };
4394 }
4395
4396 /** The extension normalizes line terminators in each question field before building the dialog. */
4397 const rpivField = (input: unknown, key: string) =>
4398 recordString(input, key)?.replace(/\r\n/g, "\n").replace(/\r/g, "");
4399
4400 const rpivOptionLine = (option: unknown, index: number) =>
4401 // oxlint-disable-next-line t3code/no-em-dash-copy -- Matches the extension's option line format.
4402 `${index + 1}. ${rpivField(option, "label")} — ${rpivField(option, "description")}`;
4403
4404 /** The extension folds option previews into the select title, the only place clients show them. */
4405 const rpivPreviewBlock = (options: ReadonlyArray<unknown>) => {
4406 const blocks = options.flatMap((option, index) => {
4407 const preview = rpivField(option, "preview");
4408 return preview
4409 ? [`--- ${index + 1}. ${rpivField(option, "label")} preview ---\n${preview.slice(0, 600)}`]
4410 : [];
4411 });
4412 return blocks.length > 0 ? `\n\n${blocks.join("\n\n")}` : "";
4413 };
4414
4415 /** Mirrors the extension's `prepareQuestionArguments`: some models JSON-encode nested args. */
4416 const rpivDecoded = (value: unknown, isShape: (parsed: unknown) => boolean) => {
4417 if (typeof value !== "string") return value;
4418 try {
4419 const parsed: unknown = JSON.parse(value);
4420 return isShape(parsed) ? parsed : value;
4421 } catch {
4422 return value;
4423 }
4424 };
4425
4426 /**
4427 * @juicesharp/rpiv-ask-user-question asks a single-select question over RPC as a select of
4428 * "N. label — description" lines plus a trailing "Type something." entry. Rebuild the question
4429 * from the tool call's arguments; each option answers with its original line, which the extension
4430 * maps back to that option.
4431 */
4432 function piAskUserSingleSelectQuestion(
4433 questionId: string,
4434 title: string,
4435 event: PiRpcRecord,
4436 toolArgs: ReadonlyMap<string, unknown>,
4437 ):
4438 | { question: OrchestrationV2UserInputQuestion; customAnswerRoute: PiCustomAnswerRoute }
4439 | undefined {
4440 const lines = event["options"];
4441 if (!Array.isArray(lines) || lines.length < 2) return undefined;
4442 const sentinel = lines.at(-1);
4443 if (typeof sentinel !== "string") return undefined;
4444 for (const args of toolArgs.values()) {
4445 const questions = rpivDecoded(recordField(args, "questions"), Array.isArray);
4446 if (!Array.isArray(questions)) continue;
4447 for (const entry of questions) {
4448 const question = rpivDecoded(entry, Predicate.isObject);
4449 const text = rpivField(question, "question");
4450 const header = rpivField(question, "header");
4451 if (recordField(question, "multiSelect") === true || !text?.trim()) continue;
4452 const prefix = header ? `[${header}] ` : "";
4453 if (!title.startsWith(`${prefix}${text}`)) continue;
4454 const encodedOptions = rpivDecoded(recordField(question, "options"), Array.isArray);
4455 if (!Array.isArray(encodedOptions) || encodedOptions.length !== lines.length - 1) continue;
4456 const options = encodedOptions.map((option) => rpivDecoded(option, Predicate.isObject));
4457 const body = `${text}${rpivPreviewBlock(options)}`;
4458 if (title !== `${prefix}${body}`) continue;
4459 if (!options.every((option, index) => lines[index] === rpivOptionLine(option, index))) {
4460 continue;
4461 }
4462 return {
4463 question: {
4464 id: questionId,
4465 header: header?.trim() || "Question",
4466 question: body.trim(),
4467 options: options.map((option, index) => {
4468 const label = rpivField(option, "label")?.trim() || `Option ${index + 1}`;
4469 return {
4470 label,
4471 description: rpivField(option, "description")?.trim() || label,
4472 value: rpivOptionLine(option, index),
4473 };
4474 }),
4475 },
4476 // The follow-up repeats the option lines; only its trailing instruction is localized.
4477 customAnswerRoute: {
4478 lines,
4479 sentinel,
4480 followUpTitlePrefix: `${prefix}${text}\n\n${lines.slice(0, -1).join("\n")}\n\n`,
4481 },
4482 };
4483 }
4484 }
4485 return undefined;
4486 }
4487
4488 function piUiResponse(
4489 pending: PendingPiPrompt,
4490 decision: ProviderApprovalDecision | undefined,
4491 answers: Record<string, unknown> | undefined,
4492 ): PiRpcRecord {
4493 if (pending.method === "confirm") {
4494 if (decision === "accept" || decision === "acceptForSession") return { confirmed: true };
4495 if (decision === "decline") return { confirmed: false };
4496 return { cancelled: true };
4497 }
4498 const answer = answers?.[pending.questionId];
4499 // RPC distinguishes empty dialog values from cancellation (undefined).
4500 if (typeof answer === "string") return { value: answer };
4501 return { cancelled: true };
4502 }
4503
4504 export type PiAdapterV2DriverEnv =
4505 | ChildProcessSpawner.ChildProcessSpawner
4506 | FileSystem.FileSystem
4507 | Path.Path
4508 | IdAllocator.IdAllocatorV2
4509 | McpProviderSessions.McpProviderSessions
4510 | ProviderHost.ProviderHost;
4511
4512 export const PiAdapterV2Driver: ProviderAdapterDriver<PiSettings, PiAdapterV2DriverEnv> = {
4513 driverKind: PI_DRIVER_KIND,
4514 configSchema: PiSettings,
4515 defaultConfig: (): PiSettings => DEFAULT_PI_SETTINGS,
4516 create: Effect.fn("PiAdapterV2Driver.create")(
4517 function* (input: ProviderAdapterDriverCreateInput<PiSettings>) {
4518 const hostEnvironment = yield* HostProcess.Environment;
4519 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
4520 return yield* makePiAdapterV2({
4521 instanceId: input.instanceId,
4522 settings: { ...input.config, enabled: input.enabled },
4523 environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
4524 continuationRequests,
4525 });
4526 },
4527 (effect, input) =>
4528 effect.pipe(
4529 Effect.mapError(
4530 (cause) =>
4531 new ProviderAdapterDriverCreateError({
4532 driver: PI_DRIVER_KIND,
4533 instanceId: input.instanceId,
4534 detail: "Failed to create Pi adapter.",
4535 cause,
4536 }),
4537 ),
4538 ),
4539 ),
4540 };