Repository navigation
Expand file tree
/
Copy pathProviderSessionManager.ts
More file actions
3326 lines (3244 loc) · 142 KB
/
Copy pathProviderSessionManager.ts
File metadata and controls
3326 lines (3244 loc) · 142 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
import { AgentScope } from "@t3tools/shared/AgentScope";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import {
isOrchestrationV2WorkActive,
ModelSelection,
type OrchestrationV2AppThread,
OrchestrationV2DomainEvent,
OrchestrationV2ProviderSession,
type OrchestrationV2PromptSuggestion,
type OrchestrationV2ProviderThread,
type OrchestrationV2Run,
OrchestrationV2RuntimeRequest,
type OrchestrationV2Subagent,
ProviderInstanceId,
ProviderSessionId,
ThreadId,
type OrchestrationV2TurnItem,
type ProviderThreadId,
type ProviderTurnId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FiberSet from "effect/FiberSet";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { normalizeModelMetricLabel } from "../observability/Attributes.ts";
import {
providerSessionsTotal,
providerTurnDuration,
providerTurnsTotal,
withMetrics,
} from "../observability/Metrics.ts";
import { ProviderWorkspaceMissingError } from "../provider/Errors.ts";
import * as ProviderInstallationGate from "../provider/ProviderInstallationGate.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ServerSettings from "../serverSettings.ts";
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
import * as EventSink from "./EventSink.ts";
import * as CommandOutputHub from "./CommandOutputHub.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
const DEFAULT_MAX_IDLE_PIN_MS = 4 * 60 * 60 * 1000;
const RELEASE_SCOPE_CLOSE_TIMEOUT_MS = 30 * 1000;
/** Past adapters' own 10 s stop fallbacks, so they settle first when the provider answers at all. */
export const PROVIDER_INTERRUPT_TIMEOUT_MS = 15 * 1000;
const busyTurnPrefix = (providerThreadId: ProviderThreadId) => `${providerThreadId}#`;
const busyTurnKey = (providerThreadId: ProviderThreadId, runOrdinal: number) =>
`${busyTurnPrefix(providerThreadId)}${runOrdinal}`;
interface OwnBusyTurns {
readonly providerThreadIds: ReadonlyArray<ProviderThreadId>;
readonly throughRunOrdinal: number;
}
const isOwnBusyTurn = (turnKey: string, own: OwnBusyTurns) =>
own.providerThreadIds.some((id) => {
const prefix = busyTurnPrefix(id);
return (
turnKey.startsWith(prefix) && Number(turnKey.slice(prefix.length)) <= own.throughRunOrdinal
);
});
const UNLOAD_THREAD_TIMEOUT_MS = 10 * 1000;
// Providers can announce a retry and never resume. Longer than any adapter's own stall handling.
const PROVIDER_RETRY_STALL_TIMEOUT = Duration.minutes(15);
type ProviderErrorItem = Extract<OrchestrationV2TurnItem, { readonly type: "error" }>;
type ProviderRetryItem = ProviderErrorItem & {
readonly providerTurnId: ProviderTurnId;
readonly providerThreadId: ProviderThreadId;
readonly retry: NonNullable<ProviderErrorItem["retry"]>;
};
/** Suggestions outlive their sessions, so keep only the most recently updated threads. */
const MAX_PROMPT_SUGGESTIONS = 256;
const WORKING_RUN_STATUSES: ReadonlySet<string> = new Set([
"preparing",
"starting",
"running",
"waiting",
]);
/** Matches planDelegatedCompletionDelivery: true while a delegated task's result still wakes the thread. */
export const delegatedTaskWillWake = (records: {
readonly thread: Pick<OrchestrationV2AppThread, "archivedAt" | "deletedAt">;
readonly runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "delegatedCompletion">>;
readonly subagents: ReadonlyArray<
Pick<OrchestrationV2Subagent, "origin" | "status" | "runId" | "completionDelivery">
>;
}): boolean =>
records.thread.archivedAt === null &&
records.thread.deletedAt === null &&
records.subagents.some((task) => {
const run = records.runs.find((candidate) => candidate.id === task.runId);
const delivery = task.completionDelivery?.state;
return (
task.origin === "app_owned" &&
isOrchestrationV2WorkActive(task.status) &&
run !== undefined &&
(run.delegatedCompletion?.disposition ?? "open") === "open" &&
delivery !== "acknowledged" &&
delivery !== "delivered" &&
delivery !== "disposed"
);
});
export const ProviderSessionReleaseReason = Schema.Literals([
"idle_timeout",
"runtime_error",
"manual_shutdown",
"server_shutdown",
]);
export type ProviderSessionReleaseReason = typeof ProviderSessionReleaseReason.Type;
// Tool calls that only a live provider process can end.
const releasedToolCallTypes: ReadonlyArray<OrchestrationV2TurnItem["type"]> = [
"command_execution",
"dynamic_tool",
];
const activeTurnItemStatuses: ReadonlyArray<OrchestrationV2TurnItem["status"]> = [
"pending",
"running",
"waiting",
];
export class ProviderSessionOpenError extends Schema.TaggedError<ProviderSessionOpenError>()(
"ProviderSessionOpenError",
{
instanceId: ProviderInstanceId,
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to open provider instance ${this.instanceId} session ${this.providerSessionId}.`;
}
}
export class ProviderSessionLookupError extends Schema.TaggedError<ProviderSessionLookupError>()(
"ProviderSessionLookupError",
{
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to look up provider session ${this.providerSessionId}.`;
}
}
export class ProviderSessionCloseError extends Schema.TaggedError<ProviderSessionCloseError>()(
"ProviderSessionCloseError",
{
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to close provider session ${this.providerSessionId}.`;
}
}
export class ProviderSessionReleaseError extends Schema.TaggedError<ProviderSessionReleaseError>()(
"ProviderSessionReleaseError",
{
providerSessionId: ProviderSessionId,
reason: ProviderSessionReleaseReason,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to release provider session ${this.providerSessionId}.`;
}
}
export class ProviderSessionActivityError extends Schema.TaggedError<ProviderSessionActivityError>()(
"ProviderSessionActivityError",
{
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to update provider session activity for ${this.providerSessionId}.`;
}
}
export const ProviderSessionManagerV2Error = Schema.Union([
ProviderSessionOpenError,
ProviderWorkspaceMissingError,
ProviderSessionLookupError,
ProviderSessionCloseError,
ProviderSessionReleaseError,
ProviderSessionActivityError,
]);
export type ProviderSessionManagerV2Error = typeof ProviderSessionManagerV2Error.Type;
export interface ProviderSessionManagerV2Shape {
readonly shutdown: Effect.Effect<void>;
readonly open: (input: {
readonly threadId: ThreadId;
readonly providerSessionId: ProviderSessionId;
readonly modelSelection: ModelSelection;
readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
readonly resumeFromSession?: OrchestrationV2ProviderSession;
readonly initialNativeThreadId?: string;
readonly initialProviderItemIdentityVersion?: 2;
}) => Effect.Effect<
ProviderAdapter.ProviderAdapterV2SessionRuntime,
ProviderSessionManagerV2Error
>;
readonly get: (
providerSessionId: ProviderSessionId,
) => Effect.Effect<
Option.Option<ProviderAdapter.ProviderAdapterV2SessionRuntime>,
ProviderSessionManagerV2Error
>;
readonly isLive: (providerSessionId: ProviderSessionId) => Effect.Effect<boolean>;
readonly close: (
providerSessionId: ProviderSessionId,
) => Effect.Effect<void, ProviderSessionManagerV2Error>;
readonly closeInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<void, ProviderSessionManagerV2Error>;
readonly release: (input: {
readonly providerSessionId: ProviderSessionId;
readonly reason: ProviderSessionReleaseReason;
readonly detail?: string;
}) => Effect.Effect<void, ProviderSessionManagerV2Error>;
readonly detach: (input: {
readonly providerSessionId: ProviderSessionId;
readonly threadId: ThreadId;
readonly detail?: string;
readonly revokeMcpCredential?: boolean;
}) => Effect.Effect<void, ProviderSessionManagerV2Error>;
/**
* Releases the session unless, at the moment of removal, a turn is busy on it other than one
* of `ownProviderThreadIds` from a run up to `throughRunOrdinal`. Checked atomically with turn
* starts. Succeeds with whether it was released.
*/
readonly releaseUnlessBusy: (input: {
readonly providerSessionId: ProviderSessionId;
readonly ownProviderThreadIds: ReadonlyArray<ProviderThreadId>;
readonly throughRunOrdinal: number;
/** Keeps the session when it succeeds with true, checked atomically with the removal. */
readonly keepIf?: Effect.Effect<boolean>;
readonly reason: ProviderSessionReleaseReason;
readonly detail?: string;
}) => Effect.Effect<boolean, ProviderSessionManagerV2Error>;
/**
* Other threads with a run or background work on this session's shared process; empty when
* it serves one thread.
*/
readonly otherWorkingThreads: (input: {
readonly providerSessionId: ProviderSessionId;
readonly threadId: ThreadId;
}) => Effect.Effect<ReadonlyArray<ThreadId>>;
/** The thread's latest predicted next prompt, then each replacement. */
readonly subscribePromptSuggestion: (
threadId: ThreadId,
) => Stream.Stream<OrchestrationV2PromptSuggestion>;
}
export class ProviderSessionManagerV2 extends Context.Service<
ProviderSessionManagerV2,
ProviderSessionManagerV2Shape
>()("t3/orchestration-v2/ProviderSessionManager/ProviderSessionManagerV2") {}
interface LiveSessionEntry {
readonly attachedThreadIds: ReadonlySet<ThreadId>;
readonly loadedProviderThreadKeyByThread: ReadonlyMap<ThreadId, string>;
/** null marks an unknown catalog; undefined means MCP refresh is not configured. */
readonly openedWithLinkedEnvironments: boolean | null | undefined;
readonly linkedEnvironmentsByThread: ReadonlyMap<ThreadId, boolean | null>;
/** Scope revocation to recorded credential ids so superseded sessions cannot revoke replacements opened before detach. */
readonly mcpCredentialIdByThread: ReadonlyMap<ThreadId, string>;
readonly supportsMultipleProviderThreads: boolean;
readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime;
readonly exposedRuntime: ProviderAdapter.ProviderAdapterV2SessionRuntime;
readonly eventSubscribers: Ref.Ref<
ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
>;
readonly requestEventPermit: Semaphore.Semaphore;
readonly scope: Scope.Closeable;
readonly idleGeneration: number;
readonly busyTurns: ReadonlySet<string>;
readonly idleFiber: Fiber.Fiber<void, never> | null;
readonly pinnedSinceMs: number | null;
readonly idleThreadUnloads: ReadonlyMap<ThreadId, IdleThreadUnload>;
}
interface IdleThreadUnload {
readonly providerThread: OrchestrationV2ProviderThread;
readonly generation: number;
readonly fiber: Fiber.Fiber<void, never> | null;
}
type ProviderSessionEventSignal =
| { readonly type: "event"; readonly event: ProviderAdapter.ProviderAdapterV2Event }
| {
readonly type: "failure";
readonly cause: Cause.Cause<ProviderAdapter.ProviderAdapterV2Error>;
};
export interface ProviderSessionManagerV2LayerOptions {
readonly idleTimeoutMs?: number;
readonly maxIdlePinMs?: number;
readonly configureMcp?: boolean;
}
function releaseStatusFor(
reason: ProviderSessionReleaseReason,
): OrchestrationV2ProviderSession["status"] {
return reason === "runtime_error" ? "error" : "stopped";
}
function releasedRuntimeRequestStatusFor(
reason: ProviderSessionReleaseReason,
): OrchestrationV2RuntimeRequest["status"] {
return reason === "manual_shutdown" || reason === "server_shutdown" ? "cancelled" : "expired";
}
function sessionKey(providerSessionId: ProviderSessionId): string {
return String(providerSessionId);
}
function sessionScopedArtifactThreadId(
event: ProviderAdapter.ProviderAdapterV2Event,
): ThreadId | undefined {
switch (event.type) {
case "provider_thread.updated":
return event.sessionScoped === true
? (event.providerThread.appThreadId ?? undefined)
: undefined;
case "runtime_request.updated":
return event.runtimeRequest.providerTurnId === null ? event.threadId : undefined;
case "node.updated":
return event.node.runId === null && event.node.runtimeRequestId !== null
? event.node.threadId
: undefined;
case "turn_item.updated":
if (event.turnItem.type === "command_execution")
return event.sessionScoped === true ? event.turnItem.threadId : undefined;
return event.turnItem.runId === null &&
(event.turnItem.type === "approval_request" || event.turnItem.type === "user_input_request")
? event.turnItem.threadId
: undefined;
default:
return undefined;
}
}
function providerThreadRuntimeKey(
providerThread: Parameters<
ProviderAdapter.ProviderAdapterV2SessionRuntime["resumeThread"]
>[0]["providerThread"],
): string {
const nativeThreadRef = providerThread.nativeThreadRef;
return nativeThreadRef === null
? String(providerThread.id)
: `${nativeThreadRef.driver}:${nativeThreadRef.nativeId}`;
}
function providerThreadLoadKey(input: {
readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime;
readonly providerThread: Parameters<
ProviderAdapter.ProviderAdapterV2SessionRuntime["resumeThread"]
>[0]["providerThread"];
readonly modelSelection?: ModelSelection;
readonly runtimePolicy?: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
}): string {
const modelSelection =
input.modelSelection === undefined
? undefined
: (input.runtime.normalizeThreadLoadModelSelection?.(input.modelSelection) ??
input.modelSelection);
return JSON.stringify({
providerThread: providerThreadRuntimeKey(input.providerThread),
modelSelection: modelSelection ?? null,
runtimePolicy: input.runtimePolicy ?? null,
});
}
export const layerWithOptions = (
options: ProviderSessionManagerV2LayerOptions = {},
): Layer.Layer<
ProviderSessionManagerV2,
never,
| CommandOutputHub.CommandOutputHub
| EventSink.EventSinkV2
| FileSystem.FileSystem
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| McpSessionRegistry.McpSessionRegistry
| ProjectionStore.ProjectionStoreV2
| ProviderEventIngestor.ProviderEventIngestorV2
| ProviderAdapterRegistry.ProviderAdapterRegistryV2
| ProviderInstallationGate.ProviderInstallationGate
> =>
Layer.effect(
ProviderSessionManagerV2,
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
const fileSystem = yield* FileSystem.FileSystem;
const mcpSessionRegistry = yield* McpSessionRegistry.McpSessionRegistry;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
/** Unreadable settings must preserve explicit browser-access opt-outs. */
const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
const projectService = yield* Effect.serviceOption(ProjectService.ProjectService);
const eventSink = yield* EventSink.EventSinkV2;
const commandOutput = yield* CommandOutputHub.CommandOutputHub;
const promptSuggestionStore = yield* SubscriptionRef.make<
ReadonlyMap<ThreadId, NonNullable<OrchestrationV2PromptSuggestion>>
>(new Map());
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
const agentScope = yield* AgentScope;
const installationGate = yield* ProviderInstallationGate.ProviderInstallationGate;
// Labs flag, read live: Codex per turn (its shared session outlives a toggle), Claude per query.
// Unreadable settings keep it off.
const promptSuggestionsEnabled = Option.isNone(serverSettings)
? Effect.succeed(false)
: serverSettings.value.getSettings.pipe(
Effect.map((settings) => settings.promptSuggestionsEnabled),
Effect.orElseSucceed(() => false),
);
const agentAccessSettings = Effect.fn("ProviderSessionManagerV2.agentAccessSettings")(
function* (threadId: ThreadId) {
if (Option.isNone(serverSettings)) return { browser: true, device: false };
return yield* Effect.gen(function* () {
const settings = yield* serverSettings.value.getSettings;
const thread = yield* projectionStore.getThread(threadId);
const entries = Object.values(settings.projectSettingsOverrides);
const browserOverridden = entries.some(
(entry) => entry.enableAgentBrowserAccess !== undefined,
);
const deviceOverridden = entries.some(
(entry) => entry.enableAgentDeviceAccess !== undefined,
);
if (browserOverridden || deviceOverridden) {
const project = Option.isSome(projectService)
? yield* projectService.value.getById(thread.projectId)
: Option.none();
if (Option.isNone(project))
return {
browser: browserOverridden ? false : settings.enableAgentBrowserAccess,
device: deviceOverridden ? false : settings.enableAgentDeviceAccess,
};
}
const effective = resolveProjectSettings(settings, thread.projectId).settings;
return {
browser: effective.enableAgentBrowserAccess,
device: effective.enableAgentDeviceAccess,
};
}).pipe(
Effect.catch((cause) =>
Effect.logWarning(
"Could not resolve agent access; withholding browser and device tools.",
{ threadId, cause },
).pipe(Effect.as({ browser: false, device: false })),
),
);
},
);
const readLinkedEnvironments = Effect.gen(function* () {
if (options.configureMcp === false || Option.isNone(serverSettings)) return undefined;
return yield* serverSettings.value.getSettings.pipe(
Effect.map((settings) => settings.linkedEnvironmentsEnabled),
Effect.orElseSucceed(() => null),
);
});
const layerScope = yield* Effect.scope;
// Group signals stop providers before restart capture; drop post-signal events so recovery owns that state.
const shutdownSignal = { received: false };
const onShutdownSignal = () => {
shutdownSignal.received = true;
};
yield* Effect.acquireRelease(
Effect.sync(() => {
process.on("SIGINT", onShutdownSignal);
process.on("SIGTERM", onShutdownSignal);
}),
() =>
Effect.sync(() => {
process.off("SIGINT", onShutdownSignal);
process.off("SIGTERM", onShutdownSignal);
}),
);
const sessions = yield* Ref.make(new Map<string, LiveSessionEntry>());
// Retry per released entry; reusing ids must not lose cleanup for earlier threads.
const releaseRecordRetries = yield* FiberSet.make();
const nextSubscriberId = yield* Ref.make(0);
const sessionOpen = yield* KeyedLock.make<ProviderSessionId>();
const threadAttachment = yield* KeyedLock.make<string>();
const threadAttachmentKey = (input: {
readonly providerSessionId: ProviderSessionId;
readonly threadId: ThreadId;
}) => `${input.providerSessionId}\u0000${input.threadId}`;
const idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS);
const maxIdlePinMs = Math.max(0, options.maxIdlePinMs ?? DEFAULT_MAX_IDLE_PIN_MS);
interface PreparedMcpCredential {
readonly mcpCredentialId: string | undefined;
readonly issued: boolean;
}
/** ACP and OpenCode consume credentials during openSession; reserve them against revocation until publication. */
const mcpCredentialReservations = new Map<string, number>();
const mcpReservationKey = (threadId: ThreadId, mcpCredentialId: string) =>
`${threadId}\0${mcpCredentialId}`;
const reserveMcpCredential = (threadId: ThreadId, mcpCredentialId: string) => {
const key = mcpReservationKey(threadId, mcpCredentialId);
mcpCredentialReservations.set(key, (mcpCredentialReservations.get(key) ?? 0) + 1);
};
const dropMcpCredentialReservation = (threadId: ThreadId, mcpCredentialId: string) => {
const key = mcpReservationKey(threadId, mcpCredentialId);
const count = mcpCredentialReservations.get(key) ?? 0;
if (count <= 1) {
mcpCredentialReservations.delete(key);
} else {
mcpCredentialReservations.set(key, count - 1);
}
};
const isMcpCredentialReserved = (threadId: ThreadId, mcpCredentialId: string) =>
(mcpCredentialReservations.get(mcpReservationKey(threadId, mcpCredentialId)) ?? 0) > 0;
const mcpPrepareLock = yield* KeyedLock.make<ThreadId>();
/** Serialize prepares per thread so concurrent rotations cannot revoke each other's credentials. */
const prepareMcpSession = (
threadId: ThreadId,
providerInstanceId: ProviderInstanceId,
): Effect.Effect<PreparedMcpCredential> =>
options.configureMcp === false
? mcpSessions
.clear(threadId)
.pipe(Effect.as<PreparedMcpCredential>({ mcpCredentialId: undefined, issued: false }))
: mcpPrepareLock.withLock(
threadId,
Effect.gen(function* () {
// Live providers build MCP clients once; reuse credentials across workspace handoffs.
const { browser: browserToolsAvailable, device: deviceToolsAvailable } =
yield* agentAccessSettings(threadId);
const capabilities = new Set<
import("../mcp/McpInvocationContext.ts").McpCapability
>(["orchestration", "worktree", "pull-requests"]);
if (browserToolsAvailable) capabilities.add("preview");
if (deviceToolsAvailable) capabilities.add("device");
const subagent = yield* projectionStore.getThread(threadId).pipe(
Effect.map((thread) => thread.lineage.relationshipToParent === "subagent"),
Effect.orElseSucceed(() => false),
);
const existing = yield* mcpSessions.read(threadId);
if (existing !== undefined) {
// Reserve before async validation so release cannot revoke between validation and reservation.
reserveMcpCredential(threadId, existing.providerSessionId);
const rawToken = existing.authorizationHeader.replace(/^Bearer\s+/, "");
// Interrupted resolution must release the reservation before the caller learns of it.
const resolved = yield* mcpSessionRegistry
.resolve(rawToken)
.pipe(
Effect.onInterrupt(() =>
Effect.sync(() =>
dropMcpCredentialReservation(threadId, existing.providerSessionId),
),
),
);
if (
resolved !== undefined &&
resolved.thread.threadId === threadId &&
resolved.thread.providerInstanceId === providerInstanceId &&
resolved.capabilities.has("preview") === browserToolsAvailable &&
resolved.capabilities.has("device") === deviceToolsAvailable &&
// A credential issued while the lineage read failed is replaced once it works.
(resolved.thread.subagent === true) === subagent
) {
return { mcpCredentialId: existing.providerSessionId, issued: false };
}
dropMcpCredentialReservation(threadId, existing.providerSessionId);
}
yield* mcpSessionRegistry.revokeThread(threadId);
const credential = yield* mcpSessionRegistry.issue({
threadId,
providerInstanceId,
browserToolsAvailable,
capabilities,
subagent,
});
yield* mcpSessions.set({
...credential.config,
hasPendingWake: projectionStore
.getThreadRecords(threadId, ["runs", "subagents"])
.pipe(
Effect.map(delegatedTaskWillWake),
Effect.orElseSucceed(() => false),
),
});
reserveMcpCredential(threadId, credential.config.providerSessionId);
return { mcpCredentialId: credential.config.providerSessionId, issued: true };
}),
);
const clearMcpSession = (threadId: ThreadId, mcpCredentialId?: string) =>
mcpCredentialId === undefined
? mcpSessionRegistry
.revokeThread(threadId)
.pipe(Effect.tap(() => mcpSessions.clear(threadId)))
: mcpSessionRegistry.revokeProviderSession(mcpCredentialId).pipe(
Effect.tap(() =>
Effect.gen(function* () {
if ((yield* mcpSessions.read(threadId))?.providerSessionId === mcpCredentialId) {
yield* mcpSessions.clear(threadId);
}
}),
),
);
const subscriberReleaseCleanup = new WeakMap<
Queue.Queue<ProviderSessionEventSignal, Cause.Done>,
Effect.Effect<void>
>();
const publishToSubscribers = (
subscribers: Ref.Ref<
ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
>,
signal: ProviderSessionEventSignal,
) =>
Ref.get(subscribers).pipe(
Effect.flatMap((current) =>
Effect.forEach(current.values(), (queue) => Queue.offer(queue, signal), {
discard: true,
}),
),
);
const failSubscribers = Effect.fn("ProviderSessionManager.failSubscribers")(function* (
entry: LiveSessionEntry,
detail: string,
afterDrain: Effect.Effect<void>,
cause?: Cause.Cause<ProviderAdapter.ProviderAdapterV2Error>,
detachedThreadId?: ThreadId,
) {
const error = new ProviderAdapter.ProviderAdapterEventStreamError({
driver: entry.runtime.driver,
providerSessionId: entry.runtime.providerSessionId,
...(detachedThreadId === undefined ? {} : { detachedThreadId }),
cause: detail,
});
const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
yield* Effect.forEach(
subscribers.values(),
(queue) => {
subscriberReleaseCleanup.set(queue, afterDrain);
return Queue.offer(queue, {
type: "failure",
cause: cause ?? Cause.fail(error),
});
},
{ discard: true },
);
});
// Server shutdown interrupts subscribers rather than ending them: a
// cleanly ended stream without a terminal fails its run, while an
// interrupted one leaves run settlement to restart recovery.
const interruptSubscribers = Effect.fn("ProviderSessionManager.interruptSubscribers")(
function* (entry: LiveSessionEntry) {
const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
yield* Effect.forEach(
subscribers.values(),
(queue) => Queue.clear(queue).pipe(Effect.andThen(Queue.interrupt(queue))),
{ discard: true },
);
},
);
// Server shutdown intentionally clears them; a provider-announced Stop
// must let consumers drain them before the stream completes.
const endSubscribers = Effect.fn("ProviderSessionManager.endSubscribers")(function* (
entry: LiveSessionEntry,
afterDrain: Effect.Effect<void>,
) {
const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
yield* Effect.forEach(
subscribers.values(),
(queue) => {
subscriberReleaseCleanup.set(queue, afterDrain);
return Queue.end(queue);
},
{ discard: true },
);
});
const cancelIdleFiber = (fiber: Fiber.Fiber<void, never> | null) =>
fiber === null ? Effect.void : Fiber.interrupt(fiber).pipe(Effect.ignore);
const writeProviderSessionEvents = Effect.fn(
"ProviderSessionManager.writeProviderSessionEvents",
)(function* (input: {
readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime;
readonly threadIds: Iterable<ThreadId>;
readonly type: "provider-session.attached" | "provider-session.updated";
readonly payload: OrchestrationV2ProviderSession;
}) {
const now = yield* DateTime.now;
const events = yield* Effect.forEach(input.threadIds, (threadId) =>
Effect.gen(function* () {
return {
id: yield* idAllocator.allocate.event({
threadId,
providerSessionId: input.runtime.providerSessionId,
}),
type: input.type,
threadId,
driver: input.runtime.driver,
providerInstanceId: input.runtime.instanceId,
occurredAt: now,
payload: input.payload,
} satisfies OrchestrationV2DomainEvent;
}),
);
if (events.length > 0) {
yield* eventSink.write({ events });
}
});
const writeReleasedSessionEvents = Effect.fn(
"ProviderSessionManager.writeReleasedSessionEvents",
)(function* (input: {
readonly entry: LiveSessionEntry;
readonly reason: ProviderSessionReleaseReason;
readonly detail?: string;
}) {
const now = yield* DateTime.now;
const payload: OrchestrationV2ProviderSession = {
...input.entry.runtime.providerSession,
status: releaseStatusFor(input.reason),
...(input.entry.runtime.providerSession.extensionStatuses === undefined
? {}
: { extensionStatuses: [] }),
updatedAt: now,
lastError:
input.reason === "runtime_error" ? (input.detail ?? "Provider runtime failed.") : null,
};
yield* writeProviderSessionEvents({
runtime: input.entry.runtime,
threadIds: input.entry.attachedThreadIds,
type: "provider-session.updated",
payload,
});
});
// A detach removes its thread before releasing, but that thread's records still need releasing.
const releasedThreadIds = (input: {
readonly entry: LiveSessionEntry;
readonly detachedThreadId?: ThreadId;
}) => {
const threadIds = new Set(input.entry.attachedThreadIds);
if (input.detachedThreadId !== undefined) threadIds.add(input.detachedThreadId);
return threadIds;
};
const writeReleasedRuntimeRequestEvents = Effect.fn(
"ProviderSessionManager.writeReleasedRuntimeRequestEvents",
)(function* (input: {
readonly entry: LiveSessionEntry;
readonly reason: ProviderSessionReleaseReason;
readonly releasedAt: DateTime.Utc;
readonly detachedThreadId?: ThreadId;
}) {
const providerSessionId = input.entry.runtime.providerSessionId;
const now = yield* DateTime.now;
const status = releasedRuntimeRequestStatusFor(input.reason);
const reason =
input.reason === "runtime_error"
? "Provider session failed before this runtime request was resolved."
: "Provider session was closed before this runtime request was resolved.";
const events: Array<OrchestrationV2DomainEvent> = [];
for (const threadId of releasedThreadIds(input)) {
const projection = yield* projectionStore.getThreadRecords(
threadId,
["runtimeRequests"],
{ runtimeRequestStatuses: ["pending"] },
);
const releasedRequests = projection.runtimeRequests.filter(
(request) =>
request.status === "pending" &&
request.responseCapability.type === "live" &&
request.responseCapability.providerSessionId === providerSessionId &&
DateTime.isLessThanOrEqualTo(request.createdAt, input.releasedAt) &&
// Shutdown reconciliation decides which questions can survive the lost callback.
!(input.reason === "server_shutdown" && request.kind === "user_input"),
);
if (releasedRequests.length === 0) continue;
const records = yield* projectionStore.getThreadRecords(
threadId,
["nodes", "turnItems"],
{
nodeIds: releasedRequests.map((request) => request.nodeId),
turnItemRequestIds: releasedRequests.map((request) => request.id),
turnItemTypes: ["approval_request", "user_input_request"],
},
);
for (const request of releasedRequests) {
events.push({
id: yield* idAllocator.allocate.event({
threadId,
providerSessionId,
}),
type: "runtime-request.updated",
threadId,
nodeId: request.nodeId,
driver: input.entry.runtime.driver,
occurredAt: now,
payload: {
...request,
status,
responseCapability: {
type: "not_resumable",
reason,
},
resolvedAt: now,
},
});
const requestNode = records.nodes.find((node) => node.id === request.nodeId);
if (requestNode !== undefined) {
events.push({
id: yield* idAllocator.allocate.event({
threadId,
providerSessionId,
}),
type: "node.updated",
threadId,
...(requestNode.runId === null ? {} : { runId: requestNode.runId }),
nodeId: requestNode.id,
driver: input.entry.runtime.driver,
occurredAt: now,
payload: {
...requestNode,
status: input.reason === "runtime_error" ? "failed" : "cancelled",
completedAt: now,
},
});
}
const turnItem = records.turnItems.find(
(item) =>
(item.type === "approval_request" || item.type === "user_input_request") &&
item.requestId === request.id,
);
if (turnItem !== undefined) {
events.push({
id: yield* idAllocator.allocate.event({
threadId,
providerSessionId,
}),
type: "turn-item.updated",
threadId,
...(turnItem.runId === null ? {} : { runId: turnItem.runId }),
...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
driver: input.entry.runtime.driver,
occurredAt: now,
payload: {
...turnItem,
status: input.reason === "runtime_error" ? "failed" : "cancelled",
completedAt: now,
updatedAt: now,
},
});
}
}
}
if (events.length > 0) {
yield* eventSink.write({ events });
}
});
// Read the session's provider threads as soon as it leaves the live map, before a
// replacement reports its own tasks. Keep OpenCode's background work: its background
// subagents share a server and can outlive the session.
const readReleasedProviderThreads = Effect.fn(
"ProviderSessionManager.readReleasedProviderThreads",
)(
function* (input: {
readonly entry: LiveSessionEntry;
readonly reason: ProviderSessionReleaseReason;
readonly detachedThreadId?: ThreadId;
}) {
if (
input.reason === "server_shutdown" ||
input.entry.runtime.backgroundTasksEndWithProcess !== true
) {
return [];
}
const providerSessionId = input.entry.runtime.providerSessionId;
const released = [];
for (const threadId of releasedThreadIds(input)) {
const projection = yield* projectionStore.getThreadRecords(threadId, [
"providerThreads",
]);
for (const providerThread of projection.providerThreads) {
if (providerThread.providerSessionId !== providerSessionId) continue;
released.push({
threadId,
providerSessionId,
providerThreadId: providerThread.id,
driver: providerThread.driver,
taskIds: new Set(
(providerThread.pendingBackgroundTasks ?? []).map((task) => task.taskId),
),
});
}
}
return released;
},
(effect, input) =>
effect.pipe(
Effect.catchCause((cause) =>
Effect.logWarning("orchestration-v2.provider-session-release-roster-read-failed", {
providerSessionId: input.entry.runtime.providerSessionId,
cause,
}).pipe(Effect.as([])),
),
),
);
type ReleasedProviderThread = Effect.Success<
ReturnType<typeof readReleasedProviderThreads>
>[number];
// Dead processes cannot report task endings; stale rosters keep threads Waiting.
const writeReleasedRosterEvents = Effect.fn(
"ProviderSessionManager.writeReleasedRosterEvents",
)(function* ({
threadId,
providerSessionId,
providerThreadId,
taskIds,
}: ReleasedProviderThread) {
if (taskIds.size === 0) return;
for (let attempt = 0; attempt < 3; attempt++) {
const projection = yield* projectionStore.getThreadRecords(threadId, ["providerThreads"]);
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === providerThreadId,
);
const tasks = providerThread?.pendingBackgroundTasks ?? [];
const remaining = tasks.filter((task) => !taskIds.has(task.taskId));
if (providerThread === undefined || remaining.length === tasks.length) return;
const now = yield* DateTime.now;
const { committed } = yield* eventSink.writeIfProviderThreadUnchanged({
expected: providerThread,
events: [
{
id: yield* idAllocator.allocate.event({ threadId, providerSessionId }),
type: "provider-thread.updated",
threadId,
driver: providerThread.driver,
providerInstanceId: providerThread.providerInstanceId,
occurredAt: now,
payload: {
...providerThread,
pendingBackgroundTasks: remaining,
updatedAt: now,
},
},
],
});
if (committed) return;
}
yield* Effect.logWarning("orchestration-v2.provider-session-release-roster-conflict", {
providerSessionId,
providerThreadId,
});
});
// Tool calls the dead process started never report an end either, and run finalization
// keeps them open for a late result. Items started after the release belong to a
// replacement session. Subagent rows are left out: run finalization ends run-owned ones.
const writeReleasedToolCallEvents = Effect.fn(
"ProviderSessionManager.writeReleasedToolCallEvents",