Repository navigation
Expand file tree
/
Copy pathadapter.ts
More file actions
3310 lines (3226 loc) · 136 KB
/
Copy pathadapter.ts
File metadata and controls
3310 lines (3226 loc) · 136 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* PiAdapterV2 — orchestrator-v2 adapter for the Pi coding agent
* (https://pi.dev), driving `pi --mode rpc` over stdio JSONL via `PiRpc.ts`.
*
* Design intent: honor the user's Pi customizations. The process is spawned
* with no `--no-*` flags, so the user's extensions, skills, prompt templates,
* AGENTS.md / SYSTEM.md context, settings.json, custom models, and auth all
* load exactly as they do in the `pi` TUI. Sessions are stored by Pi itself
* (default `~/.pi/agent/sessions/`), and the session file path is the durable
* `nativeThreadRef`, so a thread started in T3 can be resumed from the TUI
* and vice versa.
*
* Turn lifecycle: `agent_settled` is the only terminal signal. `agent_end`
* merely closes one low-level run — compaction retries, auto-retries, and
* queued continuations may still follow it, so the turn stays open until Pi
* reports the session settled. An extension can start detached compaction as
* that signal unwinds, so the adapter confirms Pi is idle before terminalizing.
*
* Extension UI: Pi extensions raise dialogs through `extension_ui_request`.
* Dialog methods become v2 runtime requests (`confirm` → approval_request,
* `select`/`input`/`editor` → user_input_request); answers travel back as
* `extension_ui_response`. `notify` becomes a completed activity item.
* Terminal-only decoration such as status, widget, title, and editor-text
* updates has no matching T3 surface and is ignored.
*/
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import {
defaultInstanceIdForDriver,
ProviderDriverKind,
type ChatAttachment,
type ModelSelection,
type OrchestrationV2ExecutionNode,
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderFailure,
type OrchestrationV2ProviderRef,
type OrchestrationV2ProviderRetry,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
type OrchestrationV2ProviderTurn,
type OrchestrationV2RuntimeRequest,
type OrchestrationV2TurnItem,
type OrchestrationV2UserInputQuestion,
type ProviderApprovalDecision,
type ProviderInstanceId,
type OrchestrationV2ProviderTurnTokenUsage,
} from "@t3tools/contracts";
import { PiSettings } from "../settings.ts";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Option from "effect/Option";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/process";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import { parsePiCompactCommand, type PiCompactCommand } from "./commands.ts";
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/continuationRequests";
import {
ProviderAdapterDriverCreateError,
type ProviderAdapterDriver,
type ProviderAdapterDriverCreateInput,
} from "@t3tools/provider-core/server/adapterDriver";
import {
makeProviderFailure,
makeProviderRetryTurnItem,
} from "@t3tools/provider-core/server/failure";
import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
import {
makePiRpcConnection,
parsePiModelSlug,
piRecordField as recordField,
piRecordNumber as recordNumber,
piRecordString as recordString,
type PiRpcConnection,
type PiRpcRecord,
} from "./rpc.ts";
import {
buildPiRpcLaunch,
materializePiT3McpExtension,
resolvePiLaunchArgs,
} from "./mcpInjection.ts";
import { PI_FILE_CHANGE_TOOLS } from "./mcpExtensionSource.ts";
export const PI_PROVIDER = ProviderDriverKind.make("pi");
const PI_DRIVER_KIND = PI_PROVIDER;
const PI_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(PI_DRIVER_KIND);
const DEFAULT_PI_SETTINGS = Schema.decodeSync(PiSettings)({});
/**
* Sentinel model slug meaning "do not call set_model": Pi resolves the model
* from the user's own settings.json (`defaultProvider`/`defaultModel`).
*/
const PI_INHERIT_MODEL_SLUG = "default";
const STREAM_FLUSH_MS = 50;
const PI_REQUEST_TIMEOUT_MS = 15_000;
// Session lifecycle hooks reload extensions, MCP servers and language servers.
const PI_SESSION_TIMEOUT_MS = 60_000;
const PI_UNSOLICITED_ACTIVITY_ERROR =
"Pi started agent work outside an active T3 turn. The session was stopped to prevent invisible tool execution.";
const SETTLE_PROBE_MAX_ATTEMPTS = 3;
const SETTLE_PROBE_RETRY_DELAY = Duration.millis(100);
const PiProviderCapabilitiesV2 = {
runtimePolicy: { enforcement: "client-boundary" },
sessions: {
supportsMultipleProviderThreadsPerSession: false,
supportsModelSwitchInSession: true,
supportsProviderSwitchingViaHandoff: true,
// Mode changes restart this process so the injected permission hook gets
// one immutable policy for its whole lifetime.
supportsRuntimeModeSwitchInSession: false,
pendingRequestsSurviveRestart: false,
},
threads: {
canCreateEmptyThread: true,
canReadThreadSnapshot: true,
canRollbackThread: true,
canForkThread: true,
canForkFromTurn: true,
canForkFromSubagentThread: false,
exposesNativeThreadId: true,
},
turns: {
exposesNativeTurnId: false,
emitsTurnStarted: true,
emitsTurnCompleted: true,
supportsInterrupt: true,
supportsActiveSteering: true,
supportsSteeringByInterruptRestart: false,
supportsQueuedMessages: true,
terminalStatusQuality: "strong",
},
streaming: {
streamsAssistantText: true,
streamsReasoning: true,
streamsToolOutput: true,
streamsPlanText: false,
emitsMessageCompleted: true,
},
tools: {
exposesToolItemIds: true,
emitsToolStarted: true,
emitsToolCompleted: true,
emitsToolOutput: true,
supportsMcpTools: true,
supportsDynamicToolCallbacks: false,
},
approvals: {
// Pi exposes a blocking tool_call extension hook. The T3 bridge uses it
// for supervised and auto-accept modes and forwards its confirmations
// through the same extension UI protocol as user-installed extensions.
supportsCommandApproval: true,
supportsFileReadApproval: false,
supportsFileChangeApproval: true,
supportsApplyPatchApproval: false,
approvalsHaveNativeRequestIds: true,
approvalCallbacksAreLiveOnly: true,
approvalsCanOriginateFromSubagents: false,
},
planning: {
emitsPlanUpdated: false,
emitsTodoList: false,
emitsProposedPlan: false,
supportsStructuredQuestions: true,
planDeltasHaveItemIds: false,
},
subagents: {
// T3 delegation uses the shared MCP `delegate_task` path. Installed Pi
// subagent extensions are observed best-effort, but their official tool
// runs children with --no-session and exposes no resumable child id.
supportsSubagents: true,
exposesSubagentThreadIds: false,
emitsSubagentLifecycle: true,
canWaitForSubagents: false,
canCloseSubagents: false,
canForkSubagentThread: false,
},
context: {
acceptsSystemContext: false,
acceptsDeveloperContext: false,
acceptsSyntheticUserContext: true,
canGenerateSummaries: false,
canConsumeHandoffSummaries: true,
// T3 delivers both full and delta handoffs through Pi's normal user-message
// input, so neither strategy depends on a Pi-specific context hook.
supportsDeltaHandoff: true,
supportsFullThreadHandoff: true,
maxRecommendedHandoffChars: null,
},
checkpointing: {
appCanCheckpointFilesystem: true,
supportsNestedCheckpointScopes: false,
providerCanRollbackConversation: true,
// CommandPolicy.ensureRollback requires the snapshot whenever provider
// rollback is enabled; rollbackThread returns the updated provider thread.
providerRollbackReturnsSnapshot: true,
providerCanReadConversationSnapshot: true,
},
identity: {
nativeThreadIds: "strong",
nativeTurnIds: "weak",
nativeItemIds: "strong",
nativeRequestIds: "strong",
},
} satisfies OrchestrationV2ProviderCapabilities;
export interface PiAdapterV2Options {
readonly instanceId: ProviderInstanceId;
readonly settings: PiSettings;
readonly environment: NodeJS.ProcessEnv;
/**
* Where to offer a wake turn for provider-initiated work. Without one, such
* work has no owner and the adapter stops it.
*/
readonly continuationRequests?: {
readonly offer: (
request: ProviderContinuationRequests.ProviderContinuationRequest,
) => Effect.Effect<void>;
};
}
/** Concatenate the `text` fields of a Pi content-block array. */
function contentText(content: unknown): string {
if (!Array.isArray(content)) {
return typeof content === "string" ? content : "";
}
return content
.map((block) => {
if (recordField(block, "type") === "text") return recordString(block, "text") ?? "";
return "";
})
.join("");
}
function providerRef(
nativeId: string,
strength: "strong" | "weak" = "strong",
): OrchestrationV2ProviderRef {
return { driver: PI_PROVIDER, nativeId, strength };
}
const PI_THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
// ── per-session state ─────────────────────────────────────────
interface PiStreamItemState {
readonly nativeItemId: string;
readonly kind: "assistant_message" | "reasoning";
text: string;
completed: boolean;
flushScheduled: boolean;
readonly startedAt: DateTime.Utc;
}
type PiCompactionStatus = "running" | "completed" | "failed" | "cancelled";
interface PiCompactionState {
readonly nativeItemId: string;
readonly startedAt: DateTime.Utc;
}
interface PiProviderRetryState {
readonly retry: OrchestrationV2ProviderRetry;
readonly failure: OrchestrationV2ProviderFailure;
readonly startedAt: DateTime.Utc;
readonly itemOrdinal: number;
}
function compactionTitle(status: PiCompactionStatus): string {
switch (status) {
case "running":
return "Compacting context...";
case "completed":
return "Context compacted";
case "failed":
return "Context compaction failed";
case "cancelled":
return "Context compaction stopped";
}
}
interface ActivePiTurn {
readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput;
readonly providerTurn: OrchestrationV2ProviderTurn;
readonly startedAt: DateTime.Utc;
readonly itemOrdinals: Map<string, number>;
nextItemOrdinal: number;
/** Increments on assistant `message_start` so content indexes stay unique. */
messageOrdinal: number;
readonly streamItems: Map<string, PiStreamItemState>;
readonly toolArgs: Map<string, unknown>;
/**
* First-seen time per `toolCallId`. Later update/end events reuse it so a
* tool keeps one start timestamp and reports a real duration.
*/
readonly toolStartedAt: Map<string, DateTime.Utc>;
interrupted: boolean;
/**
* Whether any agent run activity was observed. Command-only prompts (pure
* extension slash commands) never start an agent run and never emit
* `agent_settled`; their deferred prompt ack plus an idle probe settles
* the turn instead.
*/
sawAgentActivity: boolean;
/** A user prompt joined provider-native work whose settlement may already be queued. */
adoptedWake: boolean;
/** Only slash-command prompts can complete without starting an agent run. */
readonly promptMayBeCommandOnly: boolean;
/** Pi reports context as unknown immediately after compaction; keep its estimate for the meter. */
latestCompactionAfterTokens: number | null;
/** Last streamed usage total already emitted on the running turn. */
lastLiveUsedTokens: number | null;
/** Invalidates idle snapshots when new work starts after a settle probe. */
settleProbeGeneration: number;
/** An extension may start compaction immediately after Pi emits agent_settled. */
settleWhenIdle: boolean;
sawCompaction: boolean;
/** RPC compact is in flight; Pi abort does not cancel it. */
manualCompactInFlight: boolean;
activeCompaction: PiCompactionState | null;
activeProviderRetry: PiProviderRetryState | null;
failure: ReturnType<typeof makeProviderFailure> | null;
/** Native retry can recover its work without accepting a rejected joining prompt. */
rejectedPromptFailure: ReturnType<typeof makeProviderFailure> | null;
/** Session-tree refs read just before Stop terminates Pi, when no read is possible later. */
stopTreeRefs?: PiTurnTreeRefs | null;
}
interface PiTurnTreeRefs {
/** Omitted keeps the synthetic ref; null means the turn left nothing on the active branch. */
readonly nativeTurnRef: OrchestrationV2ProviderRef | null | undefined;
readonly leafId: string | null;
/** Set after a native rewind: every user entry still on the active branch. */
readonly retainedNativeTurnIds: ReadonlyArray<string> | undefined;
}
interface PendingPiPrompt {
readonly nativeRequestId: string;
readonly method: "select" | "confirm" | "input" | "editor";
readonly questionId: string;
readonly approvalKey: string;
runtimeRequest: OrchestrationV2RuntimeRequest;
readonly node: OrchestrationV2ExecutionNode;
readonly turnItem: OrchestrationV2TurnItem;
}
/**
* The T3 bridge confirms tool calls as `Allow <tool>?`. Edits surface as
* file-change approvals so clients render them like other providers' edits;
* every other confirmation, including ones from user extensions, is a command.
*/
function piApprovalRequestKind(title: string): "command" | "file-change" {
const toolName = /^Allow (\S+)\?$/.exec(title)?.[1];
return toolName !== undefined &&
(PI_FILE_CHANGE_TOOLS as ReadonlyArray<string>).includes(toolName)
? "file-change"
: "command";
}
interface PiThreadState {
providerThread: OrchestrationV2ProviderThread;
activeTurn: ActivePiTurn | null;
}
interface PiWake {
readonly state: PiThreadState;
readonly events: Array<PiRpcRecord>;
}
// ── adapter ───────────────────────────────────────────────────
export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
options: PiAdapterV2Options,
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const host = yield* ProviderHost.ProviderHost;
const { continuationRequests } = options;
const protocolError = (detail: string, payload?: unknown) =>
new ProviderAdapter.ProviderAdapterProtocolError({
driver: PI_PROVIDER,
detail,
...(payload === undefined ? {} : { payload }),
});
return ProviderAdapter.ProviderAdapterV2.of({
instanceId: options.instanceId,
driver: PI_PROVIDER,
getCapabilities: () => Effect.succeed(PiProviderCapabilitiesV2),
planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
openSession: Effect.fn("PiAdapterV2.openSession")(function* (
input: ProviderAdapter.ProviderAdapterV2OpenSessionInput,
) {
const scope = yield* Effect.scope;
const cwd = input.runtimePolicy.cwd ?? host.paths.cwd;
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
const provideCacheFs = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem>) =>
effect.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterOpenSessionError({
driver: PI_PROVIDER,
providerSessionId: input.providerSessionId,
cause,
}),
),
);
// The extension owns both the optional MCP bridge and Pi's permission
// hook. Materialize it even when this session has no MCP credential so
// Supervised never silently degrades to unrestricted tool execution.
const extensionPath = yield* provideCacheFs(
materializePiT3McpExtension(host.paths.providerStatusCacheDir),
);
const resolvedLaunchArgs = resolvePiLaunchArgs(options.settings.launchArgs);
if (!resolvedLaunchArgs.ok) {
return yield* protocolError(resolvedLaunchArgs.message);
}
const launch = buildPiRpcLaunch({
launchArgs: resolvedLaunchArgs.args,
environment: options.environment,
mcpSession,
extensionPath,
runtimeMode: input.runtimePolicy.runtimeMode,
});
const connection: PiRpcConnection = yield* makePiRpcConnection({
command: options.settings.binaryPath || "pi",
args: launch.args,
cwd,
env: launch.env,
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterOpenSessionError({
driver: PI_PROVIDER,
providerSessionId: input.providerSessionId,
cause,
}),
),
);
const now = yield* DateTime.now;
let sessionEntity: OrchestrationV2ProviderSession = {
id: input.providerSessionId,
driver: PI_PROVIDER,
providerInstanceId: options.instanceId,
status: "ready",
cwd,
model: input.modelSelection.model,
capabilities: PiProviderCapabilitiesV2,
createdAt: now,
updatedAt: now,
lastError: null,
};
const events = yield* Queue.unbounded<
ProviderAdapter.ProviderAdapterV2Event,
ProviderAdapter.ProviderAdapterV2Error | Cause.Done
>();
const pendingPrompts = new Map<string, PendingPiPrompt>();
const sessionApprovals = new Set<string>();
// Answering a dialog and terminalizing a turn both publish lifecycle
// events. Pi can settle immediately after `extension_ui_response`, so
// serialize the two paths to stop `turn.terminal` from overtaking the
// dialog's own resolution updates.
const sessionEventPermit = yield* Semaphore.make(1);
let threadState: PiThreadState | null = null;
let registrationAttempted = false;
let lastNativeThreadId: string | null = null;
// User Stop intentionally tears down this RPC process after aborting.
// Keep that intent beyond turn finalization so the later stdout close is
// not mistaken for an unexpected transport failure.
let stopRequested = false;
// Native work is held until an orchestrator-owned continuation or user
// turn attaches. The guard remains for sessions with no routable owner.
let unsolicitedActivityDetected = false;
let pendingWake: PiWake | null = null;
let rollbackBarrier: Deferred.Deferred<
void,
ProviderAdapter.ProviderAdapterProtocolError
> | null = null;
let closed = false;
yield* Effect.addFinalizer(() =>
Effect.gen(function* () {
closed = true;
pendingWake = null;
if (rollbackBarrier !== null)
yield* Deferred.fail(
rollbackBarrier,
protocolError("Pi session closed during rollback"),
);
}),
);
let appliedModel: string | null = null;
let appliedThinking: string | null = null;
/** Last thread title synced into pi's session name (`/resume` listing). */
let appliedSessionName: string | null = null;
/** Extension failures raised during startup are attached to the next turn. */
const outOfTurnExtensionErrors: Array<PiRpcRecord> = [];
/**
* Leaf entry id of the pi session tree as of the last turn boundary.
* Turn-start user entries are located relative to it, giving each
* provider turn a durable native ref for session-tree rollback.
*/
let lastKnownLeaf: string | null = null;
/**
* Set when a `get_entries` capture failed. Pi may have advanced past
* `lastKnownLeaf` since, so the cursor no longer bounds a single turn
* and the next capture re-syncs it instead of trusting it.
*/
let leafCursorStale = false;
// Pi's own configured defaults, captured from the first `get_state` so
// that selecting the displayed "Pi default" again can restore them. Pi
// has no "unset" commands, so the baselines have to be replayed
// explicitly.
let baselineModel: { provider: string; modelId: string } | null = null;
let baselineThinking: string | null = null;
/** Context window of the model Pi currently runs, from get_state and set_model. */
let contextWindow: number | null = null;
const modelContextWindows = new Map<string, number>();
let modelsDiscovered = false;
// Prompt responses carry no id. Keep their session-wide send order and
// owner so a late ack from a settled turn cannot affect the next turn.
const pendingPromptResponses: Array<{
readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
readonly kind: "turn_start" | "steer";
}> = [];
const pendingCompactResponses: Array<{
readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
readonly kind: "turn_start" | "steer";
}> = [];
const compactRpcRecord = (command: PiCompactCommand): PiRpcRecord =>
command.customInstructions === undefined
? { type: "compact" }
: { type: "compact", customInstructions: command.customInstructions };
const emit = (event: ProviderAdapter.ProviderAdapterV2Event) =>
Queue.offer(events, event).pipe(Effect.asVoid);
const updateProviderSession = (
status: OrchestrationV2ProviderSession["status"],
lastError: string | null = sessionEntity.lastError,
) =>
Effect.gen(function* () {
const updatedAt = yield* DateTime.now;
sessionEntity = { ...sessionEntity, status, lastError, updatedAt };
yield* emit({
type: "provider_session.updated",
driver: PI_PROVIDER,
providerSession: sessionEntity,
});
});
const updateProviderThread = (
state: PiThreadState,
patch: Partial<OrchestrationV2ProviderThread>,
retainedNativeTurnIds?: ReadonlyArray<string>,
) =>
Effect.gen(function* () {
const updatedAt = yield* DateTime.now;
state.providerThread = { ...state.providerThread, ...patch, updatedAt };
yield* emit({
type: "provider_thread.updated",
driver: PI_PROVIDER,
providerThread: state.providerThread,
...(retainedNativeTurnIds === undefined ? {} : { retainedNativeTurnIds }),
});
});
const itemOrdinal = (turn: ActivePiTurn, nativeItemId: string): number => {
const existing = turn.itemOrdinals.get(nativeItemId);
if (existing !== undefined) return existing;
const ordinal = turn.nextItemOrdinal++;
turn.itemOrdinals.set(nativeItemId, ordinal);
return ordinal;
};
const request = (record: PiRpcRecord, timeoutMs = PI_REQUEST_TIMEOUT_MS) =>
connection.request(record, timeoutMs);
const nonNegativeInteger = (input: unknown, key: string): number | undefined => {
const value = recordNumber(input, key);
return value === undefined ? undefined : Math.max(0, Math.trunc(value));
};
const rememberModelContextWindow = (model: unknown): number | null => {
const provider = recordString(model, "provider");
const id = recordString(model, "id");
const capacity = nonNegativeInteger(model, "contextWindow");
if (provider !== undefined && id !== undefined && capacity !== undefined && capacity > 0) {
modelContextWindows.set(`${provider}/${id}`, capacity);
return capacity;
}
return null;
};
const lifecycleRequest = (record: PiRpcRecord) =>
request(record, PI_SESSION_TIMEOUT_MS).pipe(
// A local timeout does not cancel Pi's lifecycle hook. Retire the
// process before fallback can race its eventual switch/new-session.
Effect.tapError((error) =>
Effect.logWarning("Pi session lifecycle request failed", {
providerSessionId: input.providerSessionId,
operation: record["type"],
errorTag: error._tag,
}),
),
Effect.catchTags({
PiRpcTimeoutError: (error) =>
connection.terminate.pipe(Effect.andThen(Effect.fail(error))),
}),
Effect.onInterrupt(() => connection.terminate),
);
const tokenUsageFromStats = (
stats: unknown,
fallbackUsedTokens: number | null,
updatedAt: DateTime.Utc,
): OrchestrationV2ProviderTurnTokenUsage | undefined => {
const contextUsage = recordField(stats, "contextUsage");
const maxTokens = nonNegativeInteger(contextUsage, "contextWindow");
const usedTokens =
nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined;
if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0)
return undefined;
const totals = recordField(stats, "tokens");
const inputTokens = nonNegativeInteger(totals, "input");
const cachedInputTokens = nonNegativeInteger(totals, "cacheRead");
const outputTokens = nonNegativeInteger(totals, "output");
return {
usedTokens,
maxTokens,
...(inputTokens === undefined ? {} : { inputTokens }),
...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),
...(outputTokens === undefined ? {} : { outputTokens }),
updatedAt: DateTime.formatIso(updatedAt),
};
};
/**
* Pi only reports context usage through `get_session_stats`, so the
* settled turn carries it on the base's per-turn `tokenUsage` (#8144).
* Usage is secondary telemetry: the request is bounded and a provider
* version without stats simply leaves the turn without a report, which
* keeps the meter on the last turn that had one.
*/
const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) =>
request({ type: "get_session_stats" }, 2_000).pipe(
Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)),
Effect.orElseSucceed(() => undefined),
);
/**
* Pi attaches the current message's cumulative usage to every streaming
* update (0.84.2+). Emit it on the running turn only when the total
* changes, so the meter moves live without a burst of no-op updates.
*/
const reportLiveUsage = (turn: ActivePiTurn, usage: unknown) =>
Effect.gen(function* () {
const usedTokens = nonNegativeInteger(usage, "totalTokens");
if (
usedTokens === undefined ||
usedTokens === 0 ||
usedTokens === turn.lastLiveUsedTokens ||
contextWindow === null ||
contextWindow === 0
) {
return;
}
turn.lastLiveUsedTokens = usedTokens;
const inputTokens = nonNegativeInteger(usage, "input");
const cachedInputTokens = nonNegativeInteger(usage, "cacheRead");
const outputTokens = nonNegativeInteger(usage, "output");
const updatedAt = yield* DateTime.now;
yield* emit({
type: "provider_turn.updated",
driver: PI_PROVIDER,
threadId: turn.turnInput.threadId,
providerTurn: {
...turn.providerTurn,
tokenUsage: {
usedTokens,
maxTokens: contextWindow,
...(inputTokens === undefined ? {} : { inputTokens }),
...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),
...(outputTokens === undefined ? {} : { outputTokens }),
updatedAt: DateTime.formatIso(updatedAt),
},
},
});
});
const baseItemFields = (
turn: ActivePiTurn,
nativeItemId: string,
startedAt: DateTime.Utc,
updatedAt: DateTime.Utc,
) => ({
id: idAllocator.derive.turnItemFromProviderItem({
driver: PI_PROVIDER,
nativeItemId,
}),
threadId: turn.turnInput.threadId,
runId: turn.turnInput.runId,
nodeId: idAllocator.derive.nodeFromProviderItem({
driver: PI_PROVIDER,
nativeItemId,
}),
providerThreadId: turn.turnInput.providerThread.id,
providerTurnId: turn.providerTurn.id,
nativeItemRef: providerRef(nativeItemId),
parentItemId: null,
ordinal: itemOrdinal(turn, nativeItemId),
startedAt,
updatedAt,
});
const emitItemNode = (
turn: ActivePiTurn,
nativeItemId: string,
kind: OrchestrationV2ExecutionNode["kind"],
status: OrchestrationV2ExecutionNode["status"],
startedAt: DateTime.Utc,
completedAt: DateTime.Utc | null,
) =>
emit({
type: "node.updated",
driver: PI_PROVIDER,
node: {
id: idAllocator.derive.nodeFromProviderItem({
driver: PI_PROVIDER,
nativeItemId,
}),
threadId: turn.turnInput.threadId,
runId: turn.turnInput.runId,
parentNodeId: turn.turnInput.rootNodeId,
rootNodeId: turn.turnInput.rootNodeId,
kind,
status,
countsForRun: false,
providerThreadId: turn.turnInput.providerThread.id,
providerTurnId: turn.providerTurn.id,
nativeItemRef: providerRef(nativeItemId),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt,
completedAt,
},
});
const emitProviderRetry = Effect.fnUntraced(function* (
turn: ActivePiTurn,
providerRetry: PiProviderRetryState,
status: "running" | "completed" | "failed" | "interrupted" | "cancelled",
updatedAt: DateTime.Utc,
) {
yield* emit({
type: "turn_item.updated",
driver: PI_PROVIDER,
turnItem: makeProviderRetryTurnItem({
idAllocator,
driver: PI_PROVIDER,
threadId: turn.turnInput.threadId,
runId: turn.turnInput.runId,
nodeId: turn.turnInput.rootNodeId,
providerThreadId: turn.turnInput.providerThread.id,
providerTurnId: turn.providerTurn.id,
itemOrdinal: providerRetry.itemOrdinal,
failure: providerRetry.failure,
retry: providerRetry.retry,
status,
startedAt: providerRetry.startedAt,
updatedAt,
}),
});
});
const compactionNativeItemId = (turn: ActivePiTurn): string =>
`compaction:${turn.providerTurn.id}:${turn.nextItemOrdinal}`;
const emitCompaction = Effect.fnUntraced(function* (
turn: ActivePiTurn,
compaction: PiCompactionState,
status: PiCompactionStatus,
details: {
readonly summary?: string;
readonly beforeTokenCount?: number;
readonly afterTokenCount?: number;
} = {},
) {
const emittedAt = yield* DateTime.now;
const completedAt = status === "running" ? null : emittedAt;
yield* emitItemNode(
turn,
compaction.nativeItemId,
"system",
status,
compaction.startedAt,
completedAt,
);
yield* emit({
type: "turn_item.updated",
driver: PI_PROVIDER,
turnItem: {
...baseItemFields(turn, compaction.nativeItemId, compaction.startedAt, emittedAt),
status,
title: compactionTitle(status),
completedAt,
type: "compaction",
driver: PI_PROVIDER,
...details,
},
});
});
// ── streaming text / reasoning ────────────────────────
const emitStreamItem = (turn: ActivePiTurn, item: PiStreamItemState, streaming: boolean) =>
Effect.gen(function* () {
const emittedAt = yield* DateTime.now;
const base = baseItemFields(turn, item.nativeItemId, item.startedAt, emittedAt);
yield* emitItemNode(
turn,
item.nativeItemId,
item.kind,
streaming ? "running" : "completed",
item.startedAt,
streaming ? null : emittedAt,
);
if (item.kind === "assistant_message") {
const messageId = idAllocator.derive.messageFromProviderItem({
driver: PI_PROVIDER,
nativeItemId: item.nativeItemId,
});
yield* emit({
type: "turn_item.updated",
driver: PI_PROVIDER,
turnItem: {
...base,
status: streaming ? "running" : "completed",
title: null,
completedAt: streaming ? null : emittedAt,
type: "assistant_message",
messageId,
text: item.text,
streaming,
},
});
yield* emit({
type: "message.updated",
driver: PI_PROVIDER,
message: {
id: messageId,
threadId: turn.turnInput.threadId,
runId: turn.turnInput.runId,
nodeId: idAllocator.derive.nodeFromProviderItem({
driver: PI_PROVIDER,
nativeItemId: item.nativeItemId,
}),
role: "assistant",
text: item.text,
attachments: [],
streaming,
createdBy: "agent",
creationSource: "provider",
createdAt: item.startedAt,
updatedAt: emittedAt,
},
});
return;
}
yield* emit({
type: "turn_item.updated",
driver: PI_PROVIDER,
turnItem: {
...base,
status: streaming ? "running" : "completed",
title: null,
completedAt: streaming ? null : emittedAt,
type: "reasoning",
text: item.text,
streaming,
},
});
});
const scheduleStreamFlush = (turn: ActivePiTurn, item: PiStreamItemState) =>
Effect.gen(function* () {
if (item.flushScheduled || item.completed) return;
item.flushScheduled = true;
yield* Effect.sleep(Duration.millis(STREAM_FLUSH_MS)).pipe(
Effect.andThen(
Effect.suspend(() => {
item.flushScheduled = false;
return item.completed ? Effect.void : emitStreamItem(turn, item, true);
}),
),
Effect.forkIn(scope),
);
});
const streamItemFor = Effect.fnUntraced(function* (
turn: ActivePiTurn,
kind: PiStreamItemState["kind"],
contentIndex: number,
) {
const nativeItemId = `${turn.providerTurn.id}:m${turn.messageOrdinal}:c${contentIndex}`;
const existing = turn.streamItems.get(nativeItemId);
if (existing !== undefined) return existing;
const startedAt = yield* DateTime.now;
const item: PiStreamItemState = {
nativeItemId,
kind,
text: "",
completed: false,
flushScheduled: false,
startedAt,
};
turn.streamItems.set(nativeItemId, item);
// Ordinal reserved on first delta so items appear in stream order.
itemOrdinal(turn, nativeItemId);
return item;
});
const completeStreamItem = (turn: ActivePiTurn, item: PiStreamItemState, text?: string) =>
Effect.suspend(() => {
if (item.completed) return Effect.void;
item.completed = true;
if (text !== undefined && text.length > 0) item.text = text;
return item.text.length === 0 ? Effect.void : emitStreamItem(turn, item, false);
});
const completeOpenStreamItems = (turn: ActivePiTurn) =>
Effect.forEach(
Array.from(turn.streamItems.values()).filter((item) => !item.completed),
(item) => completeStreamItem(turn, item),
{ discard: true },
);
// ── tools ─────────────────────────────────────────────
const emitToolItem = Effect.fnUntraced(function* (
turn: ActivePiTurn,
event: PiRpcRecord,
phase: "start" | "update" | "end",
) {
const toolCallId = recordString(event, "toolCallId");
const toolName = recordString(event, "toolName") ?? "tool";
if (toolCallId === undefined) return;
if (phase === "start") {
turn.toolArgs.set(toolCallId, event["args"]);
}
const args = event["args"] ?? turn.toolArgs.get(toolCallId);
const emittedAt = yield* DateTime.now;
const startedAt = turn.toolStartedAt.get(toolCallId) ?? emittedAt;
turn.toolStartedAt.set(toolCallId, startedAt);
const completed = phase === "end";
const isError = event["isError"] === true;
const resultRecord = completed ? event["result"] : event["partialResult"];
const outputText = contentText(recordField(resultRecord, "content"));
// A Stop aborts in-flight tools, and pi reports those as error ends.
// Present them as interrupted (matching the run) rather than failed.
const status = completed
? isError
? turn.interrupted
? "interrupted"
: "failed"
: "completed"
: "running";
const base = baseItemFields(turn, toolCallId, startedAt, emittedAt);
yield* emitItemNode(
turn,
toolCallId,
"tool_call",
status,
startedAt,
completed ? emittedAt : null,
);
const shared = {
...base,
status,
completedAt: completed ? emittedAt : null,
} as const;