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

ProviderSessionManager.ts

1,309 lines49.5 KB

1import {
2 ModelSelection,
3 OrchestrationV2DomainEvent,
4 OrchestrationV2ProviderSession,
5 OrchestrationV2RuntimeRequest,
6 ProviderInstanceId,
7 ProviderSessionId,
8 ThreadId,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import * as Clock from "effect/Clock";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Queue from "effect/Queue";
21import * as Ref from "effect/Ref";
22import * as Schema from "effect/Schema";
23import * as Scope from "effect/Scope";
24import * as Stream from "effect/Stream";
25​
26import * as McpProviderSession from "../mcp/McpProviderSession.ts";
27import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
28import { EventSinkV2 } from "./EventSink.ts";
29import { IdAllocatorV2 } from "./IdAllocator.ts";
30import { makeKeyedSerialExecutor } from "./KeyedSerialExecutor.ts";
31import {
32 ProviderAdapterEventStreamError,
33 ProviderAdapterV2RuntimePolicy,
34 type ProviderAdapterV2Error,
35 type ProviderAdapterV2Event,
36 type ProviderAdapterV2EventSubscription,
37 type ProviderAdapterV2SessionRuntime,
38} from "./ProviderAdapter.ts";
39import { ProviderAdapterRegistryV2 } from "./ProviderAdapterRegistry.ts";
40import { ProjectionStoreV2 } from "./ProjectionStore.ts";
41​
42const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
43​
44export const ProviderSessionReleaseReason = Schema.Literals([
45 "idle_timeout",
46 "runtime_error",
47 "manual_shutdown",
48 "server_shutdown",
49]);
50export type ProviderSessionReleaseReason = typeof ProviderSessionReleaseReason.Type;
51​
52/**
53 * ProviderSessionManager owns live session residency: open sessions, idle release,
54 * explicit shutdown, and release-on-runtime-failure.
55 *
56 * It intentionally does not resurrect persisted sessions. Process-loss recovery
57 * terminalizes provider-bound work and retires non-replayable effects; a later
58 * user command or durable replay-safe operation opens a session lazily.
59 */
60export class ProviderSessionOpenError extends Schema.TaggedErrorClass<ProviderSessionOpenError>()(
61 "ProviderSessionOpenError",
62 {
63 instanceId: ProviderInstanceId,
64 providerSessionId: ProviderSessionId,
65 cause: Schema.optional(Schema.Defect()),
66 },
67) {
68 override get message(): string {
69 return `Failed to open provider instance ${this.instanceId} session ${this.providerSessionId}.`;
70 }
72​
73export class ProviderSessionLookupError extends Schema.TaggedErrorClass<ProviderSessionLookupError>()(
74 "ProviderSessionLookupError",
75 {
76 providerSessionId: ProviderSessionId,
77 cause: Schema.optional(Schema.Defect()),
78 },
79) {
80 override get message(): string {
81 return `Failed to look up provider session ${this.providerSessionId}.`;
82 }
84​
85export class ProviderSessionCloseError extends Schema.TaggedErrorClass<ProviderSessionCloseError>()(
86 "ProviderSessionCloseError",
87 {
88 providerSessionId: ProviderSessionId,
89 cause: Schema.optional(Schema.Defect()),
90 },
91) {
92 override get message(): string {
93 return `Failed to close provider session ${this.providerSessionId}.`;
94 }
96​
97export class ProviderSessionReleaseError extends Schema.TaggedErrorClass<ProviderSessionReleaseError>()(
98 "ProviderSessionReleaseError",
99 {
100 providerSessionId: ProviderSessionId,
101 reason: ProviderSessionReleaseReason,
102 cause: Schema.optional(Schema.Defect()),
103 },
104) {
105 override get message(): string {
106 return `Failed to release provider session ${this.providerSessionId}.`;
107 }
109​
110export class ProviderSessionActivityError extends Schema.TaggedErrorClass<ProviderSessionActivityError>()(
111 "ProviderSessionActivityError",
112 {
113 providerSessionId: ProviderSessionId,
114 cause: Schema.optional(Schema.Defect()),
115 },
116) {
117 override get message(): string {
118 return `Failed to update provider session activity for ${this.providerSessionId}.`;
119 }
121​
122export const ProviderSessionManagerV2Error = Schema.Union([
123 ProviderSessionOpenError,
124 ProviderSessionLookupError,
125 ProviderSessionCloseError,
126 ProviderSessionReleaseError,
127 ProviderSessionActivityError,
128]);
129export type ProviderSessionManagerV2Error = typeof ProviderSessionManagerV2Error.Type;
130​
131export interface ProviderSessionManagerV2Shape {
132 readonly shutdown: Effect.Effect<void>;
133 readonly open: (input: {
134 readonly threadId: ThreadId;
135 readonly providerSessionId: ProviderSessionId;
136 readonly modelSelection: ModelSelection;
137 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
138 readonly resumeFromSession?: OrchestrationV2ProviderSession;
139 }) => Effect.Effect<ProviderAdapterV2SessionRuntime, ProviderSessionManagerV2Error>;
140 readonly get: (
141 providerSessionId: ProviderSessionId,
142 ) => Effect.Effect<Option.Option<ProviderAdapterV2SessionRuntime>, ProviderSessionManagerV2Error>;
143 readonly close: (
144 providerSessionId: ProviderSessionId,
145 ) => Effect.Effect<void, ProviderSessionManagerV2Error>;
146 readonly release: (input: {
147 readonly providerSessionId: ProviderSessionId;
148 readonly reason: ProviderSessionReleaseReason;
149 readonly detail?: string;
150 }) => Effect.Effect<void, ProviderSessionManagerV2Error>;
151 readonly detach: (input: {
152 readonly providerSessionId: ProviderSessionId;
153 readonly threadId: ThreadId;
154 readonly detail?: string;
155 }) => Effect.Effect<void, ProviderSessionManagerV2Error>;
157​
158export class ProviderSessionManagerV2 extends Context.Service<
159 ProviderSessionManagerV2,
160 ProviderSessionManagerV2Shape
161>()("t3/orchestration-v2/ProviderSessionManager/ProviderSessionManagerV2") {}
162​
163interface LiveSessionEntry {
164 readonly attachedThreadIds: ReadonlySet<ThreadId>;
165 readonly loadedProviderThreadKeyByThread: ReadonlyMap<ThreadId, string>;
166 readonly supportsMultipleProviderThreads: boolean;
167 readonly runtime: ProviderAdapterV2SessionRuntime;
168 readonly exposedRuntime: ProviderAdapterV2SessionRuntime;
169 readonly eventSubscribers: Ref.Ref<
170 ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
171 >;
172 readonly scope: Scope.Closeable;
173 readonly idleGeneration: number;
174 readonly busyCount: number;
175 readonly lastActivityAtMs: number;
176 readonly idleFiber: Fiber.Fiber<void, never> | null;
178​
179type ProviderSessionEventSignal =
180 | { readonly type: "event"; readonly event: ProviderAdapterV2Event }
181 | {
182 readonly type: "failure";
183 readonly cause: Cause.Cause<ProviderAdapterV2Error>;
184 };
185​
186export interface ProviderSessionManagerV2LayerOptions {
187 readonly idleTimeoutMs?: number;
188 /** Test replay harnesses can omit T3's MCP server from provider protocol fixtures. */
189 readonly configureMcp?: boolean;
191​
192function releaseStatusFor(
193 reason: ProviderSessionReleaseReason,
194): OrchestrationV2ProviderSession["status"] {
195 return reason === "runtime_error" ? "error" : "stopped";
197​
198function releasedRuntimeRequestStatusFor(
199 reason: ProviderSessionReleaseReason,
200): OrchestrationV2RuntimeRequest["status"] {
201 return reason === "manual_shutdown" || reason === "server_shutdown" ? "cancelled" : "expired";
203​
204function sessionKey(providerSessionId: ProviderSessionId): string {
205 return String(providerSessionId);
207​
208function providerThreadRuntimeKey(
209 providerThread: Parameters<ProviderAdapterV2SessionRuntime["resumeThread"]>[0]["providerThread"],
210): string {
211 const nativeThreadRef = providerThread.nativeThreadRef;
212 return nativeThreadRef === null
213 ? String(providerThread.id)
214 : `${nativeThreadRef.driver}:${nativeThreadRef.nativeId}`;
216​
217function providerThreadLoadKey(input: {
218 readonly providerThread: Parameters<
219 ProviderAdapterV2SessionRuntime["resumeThread"]
220 >[0]["providerThread"];
221 readonly modelSelection?: ModelSelection;
222 readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy;
223}): string {
224 return JSON.stringify({
225 providerThread: providerThreadRuntimeKey(input.providerThread),
226 modelSelection: input.modelSelection ?? null,
227 runtimePolicy: input.runtimePolicy ?? null,
228 });
230​
231export const layerWithOptions = (
232 options: ProviderSessionManagerV2LayerOptions = {},
233): Layer.Layer<
234 ProviderSessionManagerV2,
235 never,
236 | EventSinkV2
237 | IdAllocatorV2
238 | McpSessionRegistry.McpSessionRegistry
239 | ProjectionStoreV2
240 | ProviderAdapterRegistryV2
241> =>
242 Layer.effect(
243 ProviderSessionManagerV2,
244 Effect.gen(function* () {
245 const registry = yield* ProviderAdapterRegistryV2;
246 const mcpSessionRegistry = yield* McpSessionRegistry.McpSessionRegistry;
247 const eventSink = yield* EventSinkV2;
248 const idAllocator = yield* IdAllocatorV2;
249 const projectionStore = yield* ProjectionStoreV2;
250 const layerScope = yield* Effect.scope;
251 const sessions = yield* Ref.make(new Map<string, LiveSessionEntry>());
252 const nextSubscriberId = yield* Ref.make(0);
253 const sessionOpen = yield* makeKeyedSerialExecutor<ProviderSessionId>();
254 const idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS);
255 const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
256 options.configureMcp === false
257 ? Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))
258 : mcpSessionRegistry.revokeThread(threadId).pipe(
259 Effect.andThen(mcpSessionRegistry.issue({ threadId, providerInstanceId })),
260 Effect.tap((credential) =>
261 Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config)),
262 ),
263 );
264 const clearMcpSession = (threadId: ThreadId) =>
265 mcpSessionRegistry
266 .revokeThread(threadId)
267 .pipe(
268 Effect.tap(() =>
269 Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId)),
270 ),
271 );
272​
273 const publishToSubscribers = (
274 subscribers: Ref.Ref<
275 ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
276 >,
277 signal: ProviderSessionEventSignal,
278 ) =>
279 Ref.get(subscribers).pipe(
280 Effect.flatMap((current) =>
281 Effect.forEach(current.values(), (queue) => Queue.offer(queue, signal), {
282 discard: true,
283 }),
284 ),
285 );
286​
287 const failSubscribers = (entry: LiveSessionEntry, detail: string) =>
288 Effect.gen(function* () {
289 const error = new ProviderAdapterEventStreamError({
290 driver: entry.runtime.driver,
291 providerSessionId: entry.runtime.providerSessionId,
292 cause: detail,
293 });
294 const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
295 yield* Effect.forEach(
296 subscribers.values(),
297 (queue) =>
298 Queue.offer(queue, {
299 type: "failure",
300 cause: Cause.fail(error),
301 }),
302 { discard: true },
303 );
304 });
305​
306 const closeSubscribers = (entry: LiveSessionEntry) =>
307 Effect.gen(function* () {
308 const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
309 yield* Effect.forEach(
310 subscribers.values(),
311 (queue) => Queue.clear(queue).pipe(Effect.andThen(Queue.end(queue))),
312 { discard: true },
313 );
314 });
315​
316 const cancelIdleFiber = (fiber: Fiber.Fiber<void, never> | null) =>
317 fiber === null ? Effect.void : Fiber.interrupt(fiber).pipe(Effect.ignore);
318​
319 const writeProviderSessionEvents = (input: {
320 readonly runtime: ProviderAdapterV2SessionRuntime;
321 readonly threadIds: Iterable<ThreadId>;
322 readonly type: "provider-session.attached" | "provider-session.updated";
323 readonly payload: OrchestrationV2ProviderSession;
324 }) =>
325 Effect.gen(function* () {
326 const now = yield* DateTime.now;
327 const events = yield* Effect.forEach(input.threadIds, (threadId) =>
328 Effect.gen(function* () {
329 return {
330 id: yield* idAllocator.allocate.event({
331 threadId,
332 providerSessionId: input.runtime.providerSessionId,
333 }),
334 type: input.type,
335 threadId,
336 driver: input.runtime.driver,
337 providerInstanceId: input.runtime.instanceId,
338 occurredAt: now,
339 payload: input.payload,
340 } satisfies OrchestrationV2DomainEvent;
341 }),
342 );
343 if (events.length > 0) {
344 yield* eventSink.write({ events });
345 }
346 });
347​
348 const writeReleasedSessionEvents = (input: {
349 readonly entry: LiveSessionEntry;
350 readonly reason: ProviderSessionReleaseReason;
351 readonly detail?: string;
352 }) =>
353 Effect.gen(function* () {
354 const now = yield* DateTime.now;
355 const payload: OrchestrationV2ProviderSession = {
356 ...input.entry.runtime.providerSession,
357 status: releaseStatusFor(input.reason),
358 updatedAt: now,
359 lastError:
360 input.reason === "runtime_error"
361 ? (input.detail ?? "Provider runtime failed.")
362 : null,
363 };
364 yield* writeProviderSessionEvents({
365 runtime: input.entry.runtime,
366 threadIds: input.entry.attachedThreadIds,
367 type: "provider-session.updated",
368 payload,
369 });
370 });
371​
372 const writeReleasedRuntimeRequestEvents = (input: {
373 readonly entry: LiveSessionEntry;
374 readonly reason: ProviderSessionReleaseReason;
375 }) =>
376 Effect.gen(function* () {
377 const providerSessionId = input.entry.runtime.providerSessionId;
378 const now = yield* DateTime.now;
379 const status = releasedRuntimeRequestStatusFor(input.reason);
380 const reason =
381 input.reason === "runtime_error"
382 ? "Provider session failed before this runtime request was resolved."
383 : "Provider session was closed before this runtime request was resolved.";
384​
385 const events: Array<OrchestrationV2DomainEvent> = [];
386 for (const threadId of input.entry.attachedThreadIds) {
387 const projection = yield* projectionStore.getThreadProjection(threadId);
388 const releasedRequests = projection.runtimeRequests.filter(
389 (request) =>
390 request.status === "pending" &&
391 request.responseCapability.type === "live" &&
392 request.responseCapability.providerSessionId === providerSessionId,
393 );
394​
395 for (const request of releasedRequests) {
396 events.push({
397 id: yield* idAllocator.allocate.event({
398 threadId,
399 providerSessionId,
400 }),
401 type: "runtime-request.updated",
402 threadId,
403 nodeId: request.nodeId,
404 driver: input.entry.runtime.driver,
405 occurredAt: now,
406 payload: {
407 ...request,
408 status,
409 responseCapability: {
410 type: "not_resumable",
411 reason,
412 },
413 resolvedAt: now,
414 },
415 });
416​
417 const requestNode = projection.nodes.find((node) => node.id === request.nodeId);
418 if (requestNode !== undefined) {
419 events.push({
420 id: yield* idAllocator.allocate.event({
421 threadId,
422 providerSessionId,
423 }),
424 type: "node.updated",
425 threadId,
426 ...(requestNode.runId === null ? {} : { runId: requestNode.runId }),
427 nodeId: requestNode.id,
428 driver: input.entry.runtime.driver,
429 occurredAt: now,
430 payload: {
431 ...requestNode,
432 status: input.reason === "runtime_error" ? "failed" : "cancelled",
433 completedAt: now,
434 },
435 });
436 }
437​
438 const turnItem = projection.turnItems.find(
439 (item) => item.type === "approval_request" && item.requestId === request.id,
440 );
441 if (turnItem !== undefined) {
442 events.push({
443 id: yield* idAllocator.allocate.event({
444 threadId,
445 providerSessionId,
446 }),
447 type: "turn-item.updated",
448 threadId,
449 ...(turnItem.runId === null ? {} : { runId: turnItem.runId }),
450 ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
451 driver: input.entry.runtime.driver,
452 occurredAt: now,
453 payload: {
454 ...turnItem,
455 status: input.reason === "runtime_error" ? "failed" : "cancelled",
456 completedAt: now,
457 updatedAt: now,
458 },
459 });
460 }
461 }
462 }
463​
464 if (events.length > 0) {
465 yield* eventSink.write({ events });
466 }
467 });
468​
469 const releaseEntry = (input: {
470 readonly providerSessionId: ProviderSessionId;
471 readonly reason: ProviderSessionReleaseReason;
472 readonly detail?: string;
473 readonly cancelIdleFiber?: boolean;
474 }) =>
475 Effect.acquireUseRelease(
476 Ref.modify(sessions, (current) => {
477 const key = sessionKey(input.providerSessionId);
478 const existing = current.get(key);
479 if (existing === undefined) {
480 return [Option.none<LiveSessionEntry>(), current] as const;
481 }
482 const updated = new Map(current);
483 updated.delete(key);
484 return [Option.some(existing), updated] as const;
485 }),
486 (entry) =>
487 Option.match(entry, {
488 onNone: () => Effect.void,
489 onSome: (entry) =>
490 Effect.gen(function* () {
491 if (input.cancelIdleFiber !== false) {
492 yield* cancelIdleFiber(entry.idleFiber);
493 }
494 if (input.reason === "server_shutdown") {
495 yield* closeSubscribers(entry);
496 } else {
497 yield* failSubscribers(
498 entry,
499 input.detail ?? `Provider session released: ${input.reason}.`,
500 );
501 }
502 const closeExit = yield* Effect.exit(Scope.close(entry.scope, Exit.void));
503 yield* writeReleasedSessionEvents({
504 entry,
505 reason: input.reason,
506 ...(input.detail === undefined ? {} : { detail: input.detail }),
507 });
508 yield* writeReleasedRuntimeRequestEvents({
509 entry,
510 reason: input.reason,
511 });
512 if (Exit.isFailure(closeExit)) {
513 return yield* Effect.failCause(closeExit.cause);
514 }
515 }),
516 }),
517 (entry) =>
518 Option.match(entry, {
519 onNone: () => Effect.void,
520 onSome: (entry) =>
521 Effect.forEach(entry.attachedThreadIds, clearMcpSession, { discard: true }),
522 }),
523 ).pipe(
524 Effect.catchCause((cause) =>
525 Effect.fail(
526 new ProviderSessionReleaseError({
527 providerSessionId: input.providerSessionId,
528 reason: input.reason,
529 cause,
530 }),
531 ),
532 ),
533 );
534​
535 const releaseIfStillIdle = (input: {
536 readonly providerSessionId: ProviderSessionId;
537 readonly generation: number;
538 }) =>
539 Effect.gen(function* () {
540 const current = yield* Ref.get(sessions);
541 const entry = current.get(sessionKey(input.providerSessionId));
542 if (
543 entry === undefined ||
544 entry.busyCount > 0 ||
545 entry.idleGeneration !== input.generation
546 ) {
547 return;
548 }
549 yield* releaseEntry({
550 providerSessionId: input.providerSessionId,
551 reason: "idle_timeout",
552 cancelIdleFiber: false,
553 }).pipe(
554 Effect.catchCause((cause) =>
555 Effect.logWarning("orchestration-v2.driver-session.idle-release-failed", {
556 providerSessionId: input.providerSessionId,
557 cause,
558 }),
559 ),
560 );
561 });
562​
563 const withActivityError = <A, E, R>(
564 providerSessionId: ProviderSessionId,
565 effect: Effect.Effect<A, E, R>,
566 ): Effect.Effect<A, ProviderSessionActivityError, R> =>
567 effect.pipe(
568 Effect.catchCause((cause) =>
569 Effect.fail(
570 new ProviderSessionActivityError({
571 providerSessionId,
572 cause,
573 }),
574 ),
575 ),
576 );
577​
578 const scheduleIdleReleaseInternal = (providerSessionId: ProviderSessionId) =>
579 Effect.gen(function* () {
580 const key = sessionKey(providerSessionId);
581 const current = yield* Ref.get(sessions);
582 const entry = current.get(key);
583 if (entry === undefined || entry.busyCount > 0) {
584 return;
585 }
586​
587 yield* cancelIdleFiber(entry.idleFiber);
588 const generation = entry.idleGeneration + 1;
589 const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe(
590 Effect.andThen(releaseIfStillIdle({ providerSessionId, generation })),
591 Effect.forkIn(layerScope),
592 );
593 const lastActivityAtMs = yield* Clock.currentTimeMillis;
594 yield* Ref.update(sessions, (latest) => {
595 const latestEntry = latest.get(key);
596 if (latestEntry === undefined || latestEntry.busyCount > 0) {
597 return latest;
598 }
599 const updated = new Map(latest);
600 updated.set(key, {
601 ...latestEntry,
602 idleGeneration: generation,
603 idleFiber,
604 lastActivityAtMs,
605 });
606 return updated;
607 });
608 });
609​
610 const scheduleIdleRelease = (providerSessionId: ProviderSessionId) =>
611 withActivityError(providerSessionId, scheduleIdleReleaseInternal(providerSessionId));
612​
613 const touchActivity = (providerSessionId: ProviderSessionId) =>
614 withActivityError(
615 providerSessionId,
616 Effect.gen(function* () {
617 const lastActivityAtMs = yield* Clock.currentTimeMillis;
618 yield* Ref.update(sessions, (current) => {
619 const entry = current.get(sessionKey(providerSessionId));
620 if (entry === undefined) {
621 return current;
622 }
623 const updated = new Map(current);
624 updated.set(sessionKey(providerSessionId), {
625 ...entry,
626 lastActivityAtMs,
627 });
628 return updated;
629 });
630 yield* scheduleIdleReleaseInternal(providerSessionId);
631 }),
632 );
633​
634 const attachThread = (input: {
635 readonly providerSessionId: ProviderSessionId;
636 readonly threadId: ThreadId;
637 }) =>
638 withActivityError(
639 input.providerSessionId,
640 Ref.modify(sessions, (current) => {
641 const entry = current.get(sessionKey(input.providerSessionId));
642 if (entry === undefined || entry.attachedThreadIds.has(input.threadId)) {
643 return [false, current] as const;
644 }
645 const updated = new Map(current);
646 updated.set(sessionKey(input.providerSessionId), {
647 ...entry,
648 attachedThreadIds: new Set([...entry.attachedThreadIds, input.threadId]),
649 });
650 return [true, updated] as const;
651 }),
652 );
653​
654 const removeThreadAttachment = (input: {
655 readonly providerSessionId: ProviderSessionId;
656 readonly threadId: ThreadId;
657 }) =>
658 Ref.update(sessions, (current) => {
659 const key = sessionKey(input.providerSessionId);
660 const entry = current.get(key);
661 if (entry === undefined || !entry.attachedThreadIds.has(input.threadId)) {
662 return current;
663 }
664 const attachedThreadIds = new Set(entry.attachedThreadIds);
665 attachedThreadIds.delete(input.threadId);
666 const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread);
667 loadedProviderThreadKeyByThread.delete(input.threadId);
668 const updated = new Map(current);
669 updated.set(key, {
670 ...entry,
671 attachedThreadIds,
672 loadedProviderThreadKeyByThread,
673 });
674 return updated;
675 });
676​
677 const isProviderThreadLoaded = (input: {
678 readonly providerSessionId: ProviderSessionId;
679 readonly threadId: ThreadId;
680 readonly providerThreadKey: string;
681 }) =>
682 Ref.get(sessions).pipe(
683 Effect.map(
684 (current) =>
685 current
686 .get(sessionKey(input.providerSessionId))
687 ?.loadedProviderThreadKeyByThread.get(input.threadId) === input.providerThreadKey,
688 ),
689 );
690​
691 const markProviderThreadLoaded = (input: {
692 readonly providerSessionId: ProviderSessionId;
693 readonly threadId: ThreadId;
694 readonly providerThreadKey: string;
695 }) =>
696 Ref.update(sessions, (current) => {
697 const key = sessionKey(input.providerSessionId);
698 const entry = current.get(key);
699 if (entry === undefined) {
700 return current;
701 }
702 const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread);
703 loadedProviderThreadKeyByThread.set(input.threadId, input.providerThreadKey);
704 const updated = new Map(current);
705 updated.set(key, { ...entry, loadedProviderThreadKeyByThread });
706 return updated;
707 });
708​
709 const ensureThreadAttached = (input: {
710 readonly providerSessionId: ProviderSessionId;
711 readonly threadId: ThreadId;
712 readonly providerInstanceId: ProviderInstanceId;
713 }) =>
714 Effect.gen(function* () {
715 const attached = yield* attachThread(input);
716 if (attached) {
717 yield* prepareMcpSession(input.threadId, input.providerInstanceId);
718 const entry = (yield* Ref.get(sessions)).get(sessionKey(input.providerSessionId));
719 if (entry !== undefined) {
720 yield* withActivityError(
721 input.providerSessionId,
722 writeProviderSessionEvents({
723 runtime: entry.runtime,
724 threadIds: [input.threadId],
725 type: "provider-session.attached",
726 payload: entry.runtime.providerSession,
727 }),
728 );
729 }
730 }
731 }).pipe(
732 Effect.tapError(() =>
733 removeThreadAttachment(input).pipe(Effect.andThen(clearMcpSession(input.threadId))),
734 ),
735 );
736​
737 const markBusy = (providerSessionId: ProviderSessionId) =>
738 withActivityError(
739 providerSessionId,
740 Effect.gen(function* () {
741 const key = sessionKey(providerSessionId);
742 const now = yield* Clock.currentTimeMillis;
743 const idleFiber = yield* Ref.modify(sessions, (current) => {
744 const entry = current.get(key);
745 if (entry === undefined) {
746 return [null, current] as const;
747 }
748 const updated = new Map(current);
749 updated.set(key, {
750 ...entry,
751 busyCount: entry.busyCount + 1,
752 idleFiber: null,
753 lastActivityAtMs: now,
754 });
755 return [entry.idleFiber, updated] as const;
756 });
757 yield* cancelIdleFiber(idleFiber);
758 }),
759 );
760​
761 const markIdle = (providerSessionId: ProviderSessionId) =>
762 withActivityError(
763 providerSessionId,
764 Effect.gen(function* () {
765 const key = sessionKey(providerSessionId);
766 const now = yield* Clock.currentTimeMillis;
767 yield* Ref.update(sessions, (current) => {
768 const entry = current.get(key);
769 if (entry === undefined) {
770 return current;
771 }
772 const updated = new Map(current);
773 updated.set(key, {
774 ...entry,
775 busyCount: Math.max(0, entry.busyCount - 1),
776 lastActivityAtMs: now,
777 });
778 return updated;
779 });
780 yield* scheduleIdleReleaseInternal(providerSessionId);
781 }),
782 );
783​
784 const observeActivity = (
785 providerSessionId: ProviderSessionId,
786 activity: Effect.Effect<void, ProviderSessionActivityError>,
787 ) =>
788 activity.pipe(
789 Effect.catchCause((cause) =>
790 Effect.logWarning("orchestration-v2.driver-session.activity-failed", {
791 providerSessionId,
792 cause,
793 }),
794 ),
795 );
796​
797 const makeEventSubscription = (
798 subscribers: Ref.Ref<
799 ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
800 >,
801 ): Effect.Effect<ProviderAdapterV2EventSubscription> =>
802 Effect.gen(function* () {
803 const queue = yield* Queue.unbounded<ProviderSessionEventSignal, Cause.Done>();
804 const subscriberId = yield* Ref.getAndUpdate(nextSubscriberId, (value) => value + 1);
805 yield* Ref.update(subscribers, (current) => {
806 const updated = new Map(current);
807 updated.set(subscriberId, queue);
808 return updated;
809 });
810 const close = Ref.modify(subscribers, (current) => {
811 if (!current.has(subscriberId)) {
812 return [false, current] as const;
813 }
814 const updated = new Map(current);
815 updated.delete(subscriberId);
816 return [true, updated] as const;
817 }).pipe(
818 Effect.flatMap((removed) =>
819 removed
820 ? Queue.clear(queue).pipe(Effect.andThen(Queue.end(queue)), Effect.asVoid)
821 : Effect.void,
822 ),
823 );
824 const events = Stream.fromQueue(queue).pipe(
825 Stream.mapEffect((signal) =>
826 signal.type === "event"
827 ? Effect.succeed(signal.event)
828 : Effect.failCause(signal.cause),
829 ),
830 Stream.ensuring(close),
831 );
832 return { events, close } satisfies ProviderAdapterV2EventSubscription;
833 });
834​
835 const decorateRuntime = (
836 runtime: ProviderAdapterV2SessionRuntime,
837 eventSubscribers: Ref.Ref<
838 ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
839 >,
840 ): ProviderAdapterV2SessionRuntime => {
841 const providerSessionId = runtime.providerSessionId;
842 const subscribeEvents = makeEventSubscription(eventSubscribers);
843 return {
844 ...runtime,
845 subscribeEvents,
846 events: Stream.unwrap(
847 subscribeEvents.pipe(Effect.map((subscription) => subscription.events)),
848 ),
849 ensureThread: (input) =>
850 observeActivity(
851 providerSessionId,
852 ensureThreadAttached({
853 providerSessionId,
854 threadId: input.threadId,
855 providerInstanceId: runtime.instanceId,
856 }),
857 ).pipe(
858 Effect.andThen(runtime.ensureThread(input)),
859 Effect.tap((providerThread) =>
860 markProviderThreadLoaded({
861 providerSessionId,
862 threadId: input.threadId,
863 providerThreadKey: providerThreadLoadKey({
864 providerThread,
865 modelSelection: input.modelSelection,
866 runtimePolicy: input.runtimePolicy,
867 }),
868 }),
869 ),
870 ),
871 resumeThread: (input) => {
872 const threadId = input.threadId ?? input.providerThread.appThreadId;
873 if (threadId === null || threadId === undefined) {
874 return runtime.resumeThread(input);
875 }
876 const providerThreadKey = providerThreadLoadKey({
877 providerThread: input.providerThread,
878 ...(input.modelSelection === undefined
879 ? {}
880 : { modelSelection: input.modelSelection }),
881 ...(input.runtimePolicy === undefined ? {} : { runtimePolicy: input.runtimePolicy }),
882 });
883 return observeActivity(
884 providerSessionId,
885 ensureThreadAttached({
886 providerSessionId,
887 threadId,
888 providerInstanceId: runtime.instanceId,
889 }),
890 ).pipe(
891 Effect.andThen(
892 isProviderThreadLoaded({ providerSessionId, threadId, providerThreadKey }),
893 ),
894 Effect.flatMap((loaded) =>
895 loaded ? Effect.succeed(input.providerThread) : runtime.resumeThread(input),
896 ),
897 Effect.tap((providerThread) =>
898 markProviderThreadLoaded({
899 providerSessionId,
900 threadId,
901 providerThreadKey: providerThreadLoadKey({
902 providerThread,
903 ...(input.modelSelection === undefined
904 ? {}
905 : { modelSelection: input.modelSelection }),
906 ...(input.runtimePolicy === undefined
907 ? {}
908 : { runtimePolicy: input.runtimePolicy }),
909 }),
910 }),
911 ),
912 );
913 },
914 forkThread: (input) =>
915 observeActivity(
916 providerSessionId,
917 ensureThreadAttached({
918 providerSessionId,
919 threadId: input.targetThreadId,
920 providerInstanceId: runtime.instanceId,
921 }),
922 ).pipe(
923 Effect.andThen(runtime.forkThread(input)),
924 Effect.tap((providerThread) =>
925 markProviderThreadLoaded({
926 providerSessionId,
927 threadId: input.targetThreadId,
928 providerThreadKey: providerThreadLoadKey({
929 providerThread,
930 ...(input.modelSelection === undefined
931 ? {}
932 : { modelSelection: input.modelSelection }),
933 ...(input.runtimePolicy === undefined
934 ? {}
935 : { runtimePolicy: input.runtimePolicy }),
936 }),
937 }),
938 ),
939 ),
940 startTurn: (input) =>
941 observeActivity(
942 providerSessionId,
943 ensureThreadAttached({
944 providerSessionId,
945 threadId: input.threadId,
946 providerInstanceId: runtime.instanceId,
947 }),
948 ).pipe(
949 Effect.andThen(observeActivity(providerSessionId, markBusy(providerSessionId))),
950 Effect.andThen(runtime.startTurn(input)),
951 Effect.catch((error) =>
952 observeActivity(providerSessionId, markIdle(providerSessionId)).pipe(
953 Effect.andThen(Effect.fail(error)),
954 ),
955 ),
956 ),
957 steerTurn: (input) =>
958 observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe(
959 Effect.andThen(runtime.steerTurn(input)),
960 ),
961 interruptTurn: (input) =>
962 observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe(
963 Effect.andThen(runtime.interruptTurn(input)),
964 ),
965 respondToRuntimeRequest: (input) =>
966 observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe(
967 Effect.andThen(runtime.respondToRuntimeRequest(input)),
968 ),
969 };
970 };
971​
972 const persistProviderSessionUpdate = (
973 entry: LiveSessionEntry,
974 event: Extract<ProviderAdapterV2Event, { readonly type: "provider_session.updated" }>,
975 ) =>
976 Effect.gen(function* () {
977 const current = (yield* Ref.get(sessions)).get(
978 sessionKey(entry.runtime.providerSessionId),
979 );
980 if (current?.runtime !== entry.runtime) {
981 return;
982 }
983 yield* writeProviderSessionEvents({
984 runtime: entry.runtime,
985 threadIds: current.attachedThreadIds,
986 type: "provider-session.updated",
987 payload: event.providerSession,
988 });
989 }).pipe(
990 Effect.catchCause((cause) =>
991 Effect.logWarning("orchestration-v2.driver-session.status-persist-failed", {
992 providerSessionId: entry.runtime.providerSessionId,
993 cause,
994 }),
995 ),
996 );
997​
998 const startEventPump = (entry: LiveSessionEntry) =>
999 entry.runtime.events.pipe(
1000 Stream.runForEach((event) =>
1001 observeActivity(
1002 entry.runtime.providerSessionId,
1003 event.type === "turn.terminal"
1004 ? markIdle(entry.runtime.providerSessionId)
1005 : touchActivity(entry.runtime.providerSessionId),
1006 ).pipe(
1007 Effect.andThen(
1008 event.type === "provider_session.updated"
1009 ? persistProviderSessionUpdate(entry, event)
1010 : Effect.void,
1011 ),
1012 Effect.andThen(
1013 publishToSubscribers(entry.eventSubscribers, { type: "event", event }),
1014 ),
1015 ),
1016 ),
1017 Effect.exit,
1018 Effect.flatMap((exit) =>
1019 Effect.gen(function* () {
1020 const current = (yield* Ref.get(sessions)).get(
1021 sessionKey(entry.runtime.providerSessionId),
1022 );
1023 if (current?.runtime !== entry.runtime) {
1024 return;
1026 const cause = Exit.isFailure(exit)
1027 ? exit.cause
1028 : Cause.fail(
1029 new ProviderAdapterEventStreamError({
1030 driver: entry.runtime.driver,
1031 providerSessionId: entry.runtime.providerSessionId,
1032 cause: "Provider event stream ended unexpectedly.",
1033 }),
1034 );
1035 yield* publishToSubscribers(entry.eventSubscribers, {
1036 type: "failure",
1037 cause,
1038 });
1039 yield* Ref.set(entry.eventSubscribers, new Map());
1040 yield* releaseEntry({
1041 providerSessionId: entry.runtime.providerSessionId,
1042 reason: "runtime_error",
1043 detail: Cause.pretty(cause),
1044 }).pipe(Effect.ignore);
1045 }),
1046 ),
1047 Effect.forkIn(layerScope),
1048 );
1049​
1050 const shutdown = Effect.gen(function* () {
1051 const activeSessions = [...(yield* Ref.get(sessions)).values()];
1052 yield* Effect.forEach(
1053 activeSessions,
1054 (entry) =>
1055 releaseEntry({
1056 providerSessionId: entry.runtime.providerSessionId,
1057 reason: "server_shutdown",
1058 }).pipe(
1059 Effect.catchCause((cause) =>
1060 Effect.logWarning("orchestration-v2.driver-session.shutdown-release-failed", {
1061 providerSessionId: entry.runtime.providerSessionId,
1062 cause,
1063 }),
1064 ),
1065 ),
1066 { discard: true },
1067 );
1068 });
1069 yield* Effect.addFinalizer(() => shutdown);
1070​
1071 return ProviderSessionManagerV2.of({
1072 shutdown,
1073 open: (input) =>
1074 sessionOpen.withLock(
1075 input.providerSessionId,
1076 Effect.gen(function* () {
1077 const key = sessionKey(input.providerSessionId);
1078 const existing = (yield* Ref.get(sessions)).get(key);
1079 if (existing !== undefined) {
1080 if (
1081 !existing.attachedThreadIds.has(input.threadId) &&
1082 !existing.supportsMultipleProviderThreads
1083 ) {
1084 return yield* new ProviderSessionOpenError({
1085 instanceId: input.modelSelection.instanceId,
1086 providerSessionId: input.providerSessionId,
1087 cause: `Provider ${existing.runtime.driver} does not support attaching multiple app threads to one session.`,
1088 });
1090 yield* ensureThreadAttached({
1091 providerSessionId: input.providerSessionId,
1092 threadId: input.threadId,
1093 providerInstanceId: existing.runtime.instanceId,
1094 });
1095 yield* touchActivity(input.providerSessionId);
1096 return existing.exposedRuntime;
1098​
1099 const adapter = yield* registry.get(input.modelSelection.instanceId).pipe(
1100 Effect.mapError(
1101 (cause) =>
1102 new ProviderSessionOpenError({
1103 instanceId: input.modelSelection.instanceId,
1104 providerSessionId: input.providerSessionId,
1105 cause,
1106 }),
1107 ),
1108 );
1109 yield* prepareMcpSession(input.threadId, input.modelSelection.instanceId);
1110 const sessionScope = yield* Scope.make();
1111 const runtime = yield* adapter
1112 .openSession({
1113 threadId: input.threadId,
1114 providerSessionId: input.providerSessionId,
1115 modelSelection: input.modelSelection,
1116 runtimePolicy: input.runtimePolicy,
1117 ...(input.resumeFromSession === undefined
1118 ? {}
1119 : { resumeFromSession: input.resumeFromSession }),
1120 })
1121 .pipe(
1122 Effect.provideService(Scope.Scope, sessionScope),
1123 Effect.tapError(() =>
1124 Scope.close(sessionScope, Exit.void).pipe(
1125 Effect.ignore,
1126 Effect.andThen(clearMcpSession(input.threadId)),
1127 ),
1128 ),
1129 Effect.mapError(
1130 (cause) =>
1131 new ProviderSessionOpenError({
1132 instanceId: input.modelSelection.instanceId,
1133 providerSessionId: input.providerSessionId,
1134 cause,
1135 }),
1136 ),
1137 );
1138 const eventSubscribers = yield* Ref.make<
1139 ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
1140 >(new Map());
1141 const exposedRuntime = decorateRuntime(runtime, eventSubscribers);
1142 const now = yield* Clock.currentTimeMillis;
1143 const entry: LiveSessionEntry = {
1144 attachedThreadIds: new Set([input.threadId]),
1145 loadedProviderThreadKeyByThread: new Map(),
1146 supportsMultipleProviderThreads:
1147 runtime.providerSession.capabilities.sessions
1148 .supportsMultipleProviderThreadsPerSession,
1149 runtime,
1150 exposedRuntime,
1151 eventSubscribers,
1152 scope: sessionScope,
1153 idleGeneration: 0,
1154 busyCount: 0,
1155 lastActivityAtMs: now,
1156 idleFiber: null,
1157 };
1158 yield* Ref.update(sessions, (current) => {
1159 const updated = new Map(current);
1160 updated.set(key, entry);
1161 return updated;
1162 });
1163 yield* withActivityError(
1164 input.providerSessionId,
1165 writeProviderSessionEvents({
1166 runtime,
1167 threadIds: [input.threadId],
1168 type: "provider-session.attached",
1169 payload: runtime.providerSession,
1170 }),
1171 ).pipe(
1172 Effect.tapError(() =>
1173 releaseEntry({
1174 providerSessionId: input.providerSessionId,
1175 reason: "runtime_error",
1176 detail: "Failed to persist the provider-session attachment.",
1177 }).pipe(Effect.ignore),
1178 ),
1179 );
1180 yield* startEventPump(entry);
1181 yield* scheduleIdleRelease(input.providerSessionId);
1182 return exposedRuntime;
1183 }),
1184 ),
1185 get: (providerSessionId) =>
1186 Effect.gen(function* () {
1187 const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId));
1188 if (entry === undefined) {
1189 return Option.none<ProviderAdapterV2SessionRuntime>();
1191 yield* touchActivity(providerSessionId);
1192 return Option.some(entry.exposedRuntime);
1193 }).pipe(
1194 Effect.mapError(
1195 (cause) =>
1196 new ProviderSessionLookupError({
1197 providerSessionId,
1198 cause,
1199 }),
1200 ),
1201 ),
1202 close: (providerSessionId) =>
1203 releaseEntry({ providerSessionId, reason: "manual_shutdown" }).pipe(
1204 Effect.mapError(
1205 (cause) =>
1206 new ProviderSessionCloseError({
1207 providerSessionId,
1208 cause,
1209 }),
1210 ),
1211 ),
1212 release: releaseEntry,
1213 detach: (input) =>
1214 Effect.gen(function* () {
1215 const key = sessionKey(input.providerSessionId);
1216 const currentEntry = (yield* Ref.get(sessions)).get(key);
1217 if (currentEntry?.supportsMultipleProviderThreads === true) {
1218 const projection = yield* Effect.option(
1219 projectionStore.getThreadProjection(input.threadId),
1220 );
1221 if (Option.isSome(projection)) {
1222 const providerThreads = new Map(
1223 projection.value.providerThreads
1224 .filter((thread) => thread.providerSessionId === input.providerSessionId)
1225 .map((thread) => [thread.id, thread] as const),
1226 );
1227 const activeTurns = projection.value.providerTurns.filter(
1228 (turn) => turn.status === "running" && providerThreads.has(turn.providerThreadId),
1229 );
1230 yield* Effect.forEach(
1231 activeTurns,
1232 (turn) =>
1233 currentEntry.exposedRuntime
1234 .interruptTurn({
1235 providerThread: providerThreads.get(turn.providerThreadId)!,
1236 providerTurnId: turn.id,
1237 })
1238 .pipe(
1239 Effect.catchCause((cause) =>
1240 Effect.logWarning(
1241 "orchestration-v2.driver-session.detach-interrupt-failed",
1243 providerSessionId: input.providerSessionId,
1244 threadId: input.threadId,
1245 providerTurnId: turn.id,
1246 cause,
1247 },
1248 ),
1249 ),
1250 ),
1251 { concurrency: 1, discard: true },
1252 );
1255 const detached = yield* Ref.modify(sessions, (current) => {
1256 const entry = current.get(key);
1257 if (entry === undefined || !entry.attachedThreadIds.has(input.threadId)) {
1258 return [Option.none<LiveSessionEntry>(), current] as const;
1260 const attachedThreadIds = new Set(entry.attachedThreadIds);
1261 attachedThreadIds.delete(input.threadId);
1262 const loadedProviderThreadKeyByThread = new Map(
1263 entry.loadedProviderThreadKeyByThread,
1264 );
1265 loadedProviderThreadKeyByThread.delete(input.threadId);
1266 const updatedEntry = {
1267 ...entry,
1268 attachedThreadIds,
1269 loadedProviderThreadKeyByThread,
1270 };
1271 const updated = new Map(current);
1272 updated.set(key, updatedEntry);
1273 return [Option.some(updatedEntry), updated] as const;
1274 });
1275 if (Option.isNone(detached)) {
1276 return;
1278 // Detach effects are retried. Once the old entry is gone, its
1279 // retry must not revoke credentials issued by a replacement
1280 // session for the same app thread.
1281 yield* clearMcpSession(input.threadId);
1282 if (
1283 detached.value.attachedThreadIds.size === 0 &&
1284 !detached.value.supportsMultipleProviderThreads
1285 ) {
1286 yield* releaseEntry({
1287 providerSessionId: input.providerSessionId,
1288 reason: "manual_shutdown",
1289 ...(input.detail === undefined ? {} : { detail: input.detail }),
1290 });
1291 return;
1293 yield* scheduleIdleRelease(input.providerSessionId);
1294 }).pipe(
1295 Effect.catchCause((cause) =>
1296 Effect.fail(
1297 new ProviderSessionReleaseError({
1298 providerSessionId: input.providerSessionId,
1299 reason: "manual_shutdown",
1300 cause,
1301 }),
1302 ),
1303 ),
1304 ),
1305 } satisfies ProviderSessionManagerV2Shape);
1306 }),
1307 );
1308​
1309export const layer = layerWithOptions();