Open History to see the last commit
1/**
2 * ProviderServiceLive - Cross-provider orchestration layer.
3 *
4 * Routes validated transport/API calls to provider adapters through
5 * `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a
6 * unified provider event stream for subscribers.
7 *
8 * It does not implement provider protocol details (adapter concern).
9 *
10 * @module ProviderServiceLive
11 */
12import {
13 ModelSelection,
14 NonNegativeInt,
15 ThreadId,
16 ProviderInterruptTurnInput,
17 ProviderRespondToRequestInput,
18 ProviderRespondToUserInputInput,
19 ProviderSendTurnInput,
20 ProviderSessionStartInput,
21 ProviderStopSessionInput,
22 type ProviderInstanceId,
23 type ProviderDriverKind,
24 type ProviderRuntimeEvent,
25 type ProviderSession,
26} from "@t3tools/contracts";
27import { causeErrorTag } from "@t3tools/shared/observability";
28import * as Clock from "effect/Clock";
29import * as DateTime from "effect/DateTime";
30import * as Effect from "effect/Effect";
31import * as Layer from "effect/Layer";
32import * as Option from "effect/Option";
33import * as PubSub from "effect/PubSub";
34import * as Ref from "effect/Ref";
35import * as Schema from "effect/Schema";
36import * as SchemaIssue from "effect/SchemaIssue";
37import * as Stream from "effect/Stream";
38
39import {
40 increment,
41 providerMetricAttributes,
42 providerRuntimeEventsTotal,
43 providerSessionsTotal,
44 providerTurnDuration,
45 providerTurnsTotal,
46 providerTurnMetricAttributes,
47 withMetrics,
48} from "../../observability/Metrics.ts";
49import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts";
50import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
51import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
52import * as ProviderService from "../Services/ProviderService.ts";
53import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts";
54import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
55import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
56import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
57import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
58import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
59const isModelSelection = Schema.is(ModelSelection);
60
61/**
62 * Hook for tests that want to override the canonical event logger pulled
63 * from `ProviderEventLoggers`. Production wiring leaves this undefined and
64 * reads the logger off the tag.
65 */
66export interface ProviderServiceLiveOptions {
67 readonly canonicalEventLogger?: EventNdjsonLogger;
68}
69
70type ProviderServiceMethod<Name extends keyof ProviderService.ProviderService["Service"]> =
71 ProviderService.ProviderService["Service"][Name];
72
73const ProviderRollbackConversationInput = Schema.Struct({
74 threadId: ThreadId,
75 numTurns: NonNegativeInt,
76});
77
78function toValidationError(
79 operation: string,
80 issue: string,
81 cause?: unknown,
82): ProviderValidationError {
83 return new ProviderValidationError({
84 operation,
85 issue,
86 ...(cause !== undefined ? { cause } : {}),
87 });
88}
89
90const decodeInputOrValidationError = <S extends Schema.Top>(input: {
91 readonly operation: string;
92 readonly schema: S;
93 readonly payload: unknown;
94}) => {
95 const decodeProviderRequestInput = Schema.decodeUnknownEffect(input.schema);
96 return decodeProviderRequestInput(input.payload).pipe(
97 Effect.mapError(
98 (schemaError) =>
99 new ProviderValidationError({
100 operation: input.operation,
101 issue: SchemaIssue.makeFormatterDefault()(schemaError.issue),
102 cause: schemaError,
103 }),
104 ),
105 );
106};
107
108function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "stopped" | "error" {
109 switch (session.status) {
110 case "connecting":
111 return "starting";
112 case "error":
113 return "error";
114 case "closed":
115 return "stopped";
116 case "ready":
117 case "running":
118 default:
119 return "running";
120 }
121}
122
123function toRuntimePayloadFromSession(
124 session: ProviderSession,
125 extra?: {
126 readonly modelSelection?: unknown;
127 readonly lastRuntimeEvent?: string;
128 readonly lastRuntimeEventAt?: string;
129 },
130): Record<string, unknown> {
131 return {
132 cwd: session.cwd ?? null,
133 model: session.model ?? null,
134 activeTurnId: session.activeTurnId ?? null,
135 lastError: session.lastError ?? null,
136 ...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),
137 ...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
138 ...(extra?.lastRuntimeEventAt !== undefined
139 ? { lastRuntimeEventAt: extra.lastRuntimeEventAt }
140 : {}),
141 };
142}
143
144function readPersistedModelSelection(
145 runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"],
146): ModelSelection | undefined {
147 if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
148 return undefined;
149 }
150 const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined;
151 return isModelSelection(raw) ? raw : undefined;
152}
153
154function readPersistedCwd(
155 runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"],
156): string | undefined {
157 if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
158 return undefined;
159 }
160 const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined;
161 if (typeof rawCwd !== "string") return undefined;
162 const trimmed = rawCwd.trim();
163 return trimmed.length > 0 ? trimmed : undefined;
164}
165
166const dieOnMissingBindingInstanceId = (
167 operation: string,
168 payload: {
169 readonly providerInstanceId?: ProviderInstanceId | undefined;
170 readonly provider?: ProviderDriverKind | undefined;
171 },
172): ProviderInstanceId => {
173 if (payload.providerInstanceId !== undefined) {
174 return payload.providerInstanceId;
175 }
176 throw new Error(
177 payload.provider
178 ? `${operation}: provider instance id is required for provider '${payload.provider}'.`
179 : `${operation}: provider instance id is required.`,
180 );
181};
182
183export const SESSION_ACTIVITY_EVENT_TYPES: ReadonlySet<ProviderRuntimeEvent["type"]> = new Set([
184 "turn.started",
185 "turn.completed",
186 "turn.aborted",
187 "task.started",
188 "task.progress",
189 "task.updated",
190 "task.completed",
191]);
192
193const SESSION_ACTIVITY_TOUCH_MIN_INTERVAL_MS = 60_000;
194
195const correlateRuntimeEventWithInstance = (
196 source: {
197 readonly instanceId: ProviderInstanceId;
198 readonly provider: ProviderDriverKind;
199 },
200 event: ProviderRuntimeEvent,
201): ProviderRuntimeEvent => {
202 if (event.provider !== source.provider) {
203 throw new Error(
204 `ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`,
205 );
206 }
207 if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) {
208 throw new Error(
209 `ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`,
210 );
211 }
212 return { ...event, providerInstanceId: source.instanceId };
213};
214
215const makeProviderService = Effect.fn("makeProviderService")(function* (
216 options?: ProviderServiceLiveOptions,
217) {
218 const analytics = yield* Effect.service(AnalyticsService.AnalyticsService);
219 const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
220 // Options-provided logger wins (test overrides); otherwise we take whatever
221 // the `ProviderEventLoggers` tag exposes — `undefined` means "no canonical
222 // log writer is attached", which downstream code already handles as a
223 // no-op.
224 const canonicalEventLogger = options?.canonicalEventLogger ?? eventLoggers.canonical;
225
226 const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
227 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
228 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
229 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
230 const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
231 McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(
232 Effect.tap((credential) =>
233 credential
234 ? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config))
235 : Effect.void,
236 ),
237 );
238 const clearMcpSession = (threadId: ThreadId) =>
239 McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(
240 Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))),
241 );
242
243 const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
244 Effect.succeed(event).pipe(
245 Effect.tap((canonicalEvent) =>
246 canonicalEventLogger
247 ? canonicalEventLogger.write(canonicalEvent, canonicalEvent.threadId)
248 : Effect.void,
249 ),
250 Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
251 Effect.asVoid,
252 );
253
254 const requireBindingInstanceId = (
255 operation: string,
256 payload: {
257 readonly providerInstanceId?: ProviderInstanceId | undefined;
258 readonly provider?: ProviderDriverKind | undefined;
259 },
260 ): Effect.Effect<ProviderInstanceId, ProviderValidationError> =>
261 payload.providerInstanceId !== undefined
262 ? Effect.succeed(payload.providerInstanceId)
263 : Effect.fail(
264 toValidationError(
265 operation,
266 payload.provider
267 ? `Provider instance id is required for provider '${payload.provider}'.`
268 : "Provider instance id is required.",
269 ),
270 );
271
272 const upsertSessionBinding = (
273 session: ProviderSession,
274 threadId: ThreadId,
275 extra?: {
276 readonly modelSelection?: unknown;
277 readonly lastRuntimeEvent?: string;
278 readonly lastRuntimeEventAt?: string;
279 },
280 ) =>
281 Effect.gen(function* () {
282 const providerInstanceId = yield* requireBindingInstanceId(
283 "ProviderService.upsertSessionBinding",
284 session,
285 );
286 yield* directory.upsert({
287 threadId,
288 provider: session.provider,
289 providerInstanceId,
290 runtimeMode: session.runtimeMode,
291 status: toRuntimeStatus(session),
292 ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
293 runtimePayload: toRuntimePayloadFromSession(session, extra),
294 });
295 });
296
297 // Turn and background-task lifecycle events prove the provider session is
298 // still doing user-visible work even when no `sendTurn` call delivered it
299 // (queued follow-ups, plan-sourced turns, background tasks that outlive
300 // their foreground turn). Without this, `lastSeenAt` stays at the last
301 // explicit send and the inactivity reaper measures idleness from the last
302 // user message instead of the last completed work.
303 //
304 // Touches are throttled per thread because this runs on the event drain
305 // fiber and task.progress can fire many times per second in multi-agent
306 // sessions; the reaper thresholds are minutes, so minute-level lastSeenAt
307 // granularity is enough. The gate timestamp is set before the write so a
308 // failing database is not retried on every event.
309 const lastTouchAtByThread = new Map<ThreadId, number>();
310
311 const touchSessionActivity = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
312 SESSION_ACTIVITY_EVENT_TYPES.has(event.type)
313 ? Clock.currentTimeMillis.pipe(
314 Effect.flatMap((now) => {
315 const lastTouchAt = lastTouchAtByThread.get(event.threadId);
316 if (
317 lastTouchAt !== undefined &&
318 now - lastTouchAt < SESSION_ACTIVITY_TOUCH_MIN_INTERVAL_MS
319 ) {
320 return Effect.void;
321 }
322 lastTouchAtByThread.set(event.threadId, now);
323 return directory.touch(event.threadId).pipe(
324 Effect.catchCause((cause) =>
325 Effect.logWarning("provider.session.activity-touch-failed", {
326 threadId: event.threadId,
327 eventType: event.type,
328 errorTag: causeErrorTag(cause),
329 }),
330 ),
331 );
332 }),
333 )
334 : Effect.void;
335
336 const processRuntimeEvent = (
337 source: {
338 readonly instanceId: ProviderInstanceId;
339 readonly provider: ProviderDriverKind;
340 },
341 event: ProviderRuntimeEvent,
342 ): Effect.Effect<void> =>
343 Effect.sync(() => correlateRuntimeEventWithInstance(source, event)).pipe(
344 Effect.flatMap((canonicalEvent) =>
345 increment(providerRuntimeEventsTotal, {
346 provider: canonicalEvent.provider,
347 eventType: canonicalEvent.type,
348 }).pipe(
349 Effect.andThen(publishRuntimeEvent(canonicalEvent)),
350 Effect.andThen(touchSessionActivity(canonicalEvent)),
351 ),
352 ),
353 );
354
355 // `subscribedAdapters` is our source-of-truth for "which instance adapters
356 // are currently wired into the runtime event bus". It both tracks the set
357 // of live subscriptions (so `reconcileInstanceSubscriptions` can diff and
358 // fork only the *new* or *rebuilt* ones) and serves as the dynamic adapter
359 // list consumed by `stopStaleSessionsForThread`, `listSessions`, and
360 // `runStopAll` — replacing the pre-Slice-D startup snapshot so hot-added
361 // instances become visible to those call sites as soon as settings edits
362 // land.
363 const subscribedAdapters = yield* Ref.make(
364 new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>(),
365 );
366
367 const getAdapterEntries = Ref.get(subscribedAdapters).pipe(
368 Effect.map((map) => Array.from(map.entries())),
369 );
370
371 // Rebuild the map of id → adapter from the registry and fork a new event
372 // subscription for every instance that is either brand new or whose adapter
373 // identity changed (indicating the underlying `ProviderInstance` was torn
374 // down and rebuilt by `ProviderInstanceRegistry.reconcile`). Orphaned
375 // fibers for removed/replaced instances exit on their own because their
376 // adapter's `streamEvents` source terminates when the old scope closes.
377 const reconcileInstanceSubscriptions = Effect.gen(function* () {
378 const previous = yield* Ref.get(subscribedAdapters);
379 const currentIds = yield* registry.listInstances();
380 const next = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();
381 for (const id of currentIds) {
382 const adapterOption = yield* registry
383 .getByInstance(id)
384 .pipe(Effect.tapError(Effect.logWarning), Effect.option);
385 if (Option.isNone(adapterOption)) continue;
386 const adapter = adapterOption.value;
387 next.set(id, adapter);
388 if (previous.get(id) !== adapter) {
389 yield* Stream.runForEach(adapter.streamEvents, (event) =>
390 processRuntimeEvent(
391 {
392 instanceId: id,
393 provider: adapter.provider,
394 },
395 event,
396 ),
397 ).pipe(Effect.forkScoped);
398 }
399 }
400 yield* Ref.set(subscribedAdapters, next);
401 });
402
403 const instanceChanges = yield* registry.subscribeChanges;
404 yield* reconcileInstanceSubscriptions;
405 yield* Stream.runForEach(
406 Stream.fromSubscription(instanceChanges),
407 () => reconcileInstanceSubscriptions,
408 ).pipe(Effect.forkScoped);
409
410 const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
411 readonly binding: ProviderSessionDirectory.ProviderRuntimeBinding;
412 readonly operation: string;
413 }) {
414 const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding);
415 yield* Effect.annotateCurrentSpan({
416 "provider.operation": "recover-session",
417 "provider.kind": input.binding.provider,
418 "provider.instance_id": bindingInstanceId,
419 "provider.thread_id": input.binding.threadId,
420 });
421 return yield* Effect.gen(function* () {
422 const adapter = yield* registry.getByInstance(bindingInstanceId);
423 const hasResumeCursor =
424 input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
425 const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
426 if (hasActiveSession) {
427 const activeSessions = yield* adapter.listSessions();
428 const existing = activeSessions.find(
429 (session) => session.threadId === input.binding.threadId,
430 );
431 if (existing) {
432 yield* upsertSessionBinding(
433 { ...existing, providerInstanceId: bindingInstanceId },
434 input.binding.threadId,
435 );
436 yield* analytics.record("provider.session.recovered", {
437 provider: existing.provider,
438 strategy: "adopt-existing",
439 hasResumeCursor: existing.resumeCursor !== undefined,
440 });
441 return { adapter, session: existing } as const;
442 }
443 }
444
445 if (!hasResumeCursor) {
446 return yield* toValidationError(
447 input.operation,
448 `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
449 );
450 }
451
452 const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
453 const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
454
455 yield* prepareMcpSession(input.binding.threadId, bindingInstanceId);
456 const resumed = yield* adapter
457 .startSession({
458 threadId: input.binding.threadId,
459 provider: input.binding.provider,
460 providerInstanceId: bindingInstanceId,
461 ...(persistedCwd ? { cwd: persistedCwd } : {}),
462 ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
463 ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
464 runtimeMode: input.binding.runtimeMode ?? "full-access",
465 })
466 .pipe(Effect.onError(() => clearMcpSession(input.binding.threadId)));
467 if (resumed.provider !== adapter.provider) {
468 yield* clearMcpSession(input.binding.threadId);
469 return yield* toValidationError(
470 input.operation,
471 `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
472 );
473 }
474
475 yield* upsertSessionBinding(
476 { ...resumed, providerInstanceId: bindingInstanceId },
477 input.binding.threadId,
478 );
479 yield* analytics.record("provider.session.recovered", {
480 provider: resumed.provider,
481 strategy: "resume-thread",
482 hasResumeCursor: resumed.resumeCursor !== undefined,
483 });
484 return { adapter, session: resumed } as const;
485 }).pipe(
486 withMetrics({
487 counter: providerSessionsTotal,
488 attributes: providerMetricAttributes(input.binding.provider, {
489 operation: "recover",
490 }),
491 }),
492 );
493 });
494
495 const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: {
496 readonly threadId: ThreadId;
497 readonly operation: string;
498 readonly allowRecovery: boolean;
499 }) {
500 const bindingOption = yield* directory.getBinding(input.threadId);
501 const binding = Option.getOrUndefined(bindingOption);
502 if (!binding) {
503 return yield* toValidationError(
504 input.operation,
505 `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
506 );
507 }
508 const instanceId = yield* requireBindingInstanceId(input.operation, binding);
509 const adapter = yield* registry.getByInstance(instanceId);
510
511 const hasRequestedSession = yield* adapter.hasSession(input.threadId);
512 if (hasRequestedSession) {
513 return {
514 adapter,
515 instanceId,
516 threadId: input.threadId,
517 isActive: true,
518 } as const;
519 }
520
521 if (!input.allowRecovery) {
522 return {
523 adapter,
524 instanceId,
525 threadId: input.threadId,
526 isActive: false,
527 } as const;
528 }
529
530 const recovered = yield* recoverSessionForThread({
531 binding,
532 operation: input.operation,
533 });
534 return {
535 adapter: recovered.adapter,
536 instanceId,
537 threadId: input.threadId,
538 isActive: true,
539 } as const;
540 });
541
542 const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: {
543 readonly threadId: ThreadId;
544 readonly currentInstanceId: ProviderInstanceId;
545 }) {
546 const currentAdapters = yield* getAdapterEntries;
547 yield* Effect.forEach(
548 currentAdapters,
549 ([instanceId, adapter]) =>
550 instanceId === input.currentInstanceId
551 ? Effect.void
552 : Effect.gen(function* () {
553 const hasSession = yield* adapter.hasSession(input.threadId);
554 if (!hasSession) {
555 return;
556 }
557
558 yield* adapter.stopSession(input.threadId).pipe(
559 Effect.tap(() =>
560 analytics.record("provider.session.stopped", {
561 provider: adapter.provider,
562 }),
563 ),
564 Effect.catchCause((cause) =>
565 Effect.logWarning("provider.session.stop-stale-failed", {
566 threadId: input.threadId,
567 provider: adapter.provider,
568 cause,
569 }),
570 ),
571 );
572 }),
573 { discard: true },
574 );
575 });
576
577 const startSession: ProviderServiceMethod<"startSession"> = Effect.fn("startSession")(
578 function* (threadId, rawInput) {
579 const parsed = yield* decodeInputOrValidationError({
580 operation: "ProviderService.startSession",
581 schema: ProviderSessionStartInput,
582 payload: rawInput,
583 });
584
585 const resolvedInstanceId = yield* requireBindingInstanceId(
586 "ProviderService.startSession",
587 parsed,
588 );
589 let metricProvider = parsed.provider ?? String(resolvedInstanceId);
590 yield* Effect.annotateCurrentSpan({
591 "provider.operation": "start-session",
592 "provider.instance_id": resolvedInstanceId,
593 "provider.thread_id": threadId,
594 "provider.runtime_mode": parsed.runtimeMode,
595 });
596 return yield* Effect.gen(function* () {
597 const instanceInfo = yield* registry.getInstanceInfo(resolvedInstanceId);
598 const resolvedProvider = instanceInfo.driverKind;
599 metricProvider = resolvedProvider;
600 if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) {
601 return yield* toValidationError(
602 "ProviderService.startSession",
603 `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
604 );
605 }
606 const input = {
607 ...parsed,
608 threadId,
609 provider: resolvedProvider,
610 };
611 if (!instanceInfo.enabled) {
612 return yield* toValidationError(
613 "ProviderService.startSession",
614 `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
615 );
616 }
617 const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
618 const effectiveResumeCursor =
619 input.resumeCursor ??
620 (persistedBinding?.providerInstanceId === resolvedInstanceId
621 ? persistedBinding.resumeCursor
622 : undefined);
623 const effectiveCwd =
624 input.cwd ??
625 (persistedBinding?.providerInstanceId === resolvedInstanceId
626 ? readPersistedCwd(persistedBinding.runtimePayload)
627 : undefined);
628 yield* Effect.annotateCurrentSpan({
629 "provider.kind": resolvedProvider,
630 "provider.resume_cursor.source":
631 input.resumeCursor !== undefined
632 ? "request"
633 : effectiveResumeCursor !== undefined &&
634 persistedBinding?.providerInstanceId === resolvedInstanceId
635 ? "persisted"
636 : "none",
637 "provider.resume_cursor.present": effectiveResumeCursor !== undefined,
638 "provider.cwd.source":
639 input.cwd !== undefined
640 ? "request"
641 : effectiveCwd !== undefined &&
642 persistedBinding?.providerInstanceId === resolvedInstanceId
643 ? "persisted"
644 : "none",
645 "provider.cwd.effective": effectiveCwd ?? "",
646 });
647 const adapter = yield* registry.getByInstance(resolvedInstanceId);
648 yield* prepareMcpSession(threadId, resolvedInstanceId);
649 const session = yield* adapter
650 .startSession({
651 ...input,
652 providerInstanceId: resolvedInstanceId,
653 ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),
654 ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
655 })
656 .pipe(Effect.onError(() => clearMcpSession(threadId)));
657
658 if (session.provider !== adapter.provider) {
659 yield* clearMcpSession(threadId);
660 return yield* toValidationError(
661 "ProviderService.startSession",
662 `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
663 );
664 }
665 const sessionWithInstance = {
666 ...session,
667 providerInstanceId: resolvedInstanceId,
668 };
669
670 yield* stopStaleSessionsForThread({
671 threadId,
672 currentInstanceId: resolvedInstanceId,
673 });
674 yield* upsertSessionBinding(sessionWithInstance, threadId, {
675 modelSelection: input.modelSelection,
676 });
677 yield* analytics.record("provider.session.started", {
678 provider: sessionWithInstance.provider,
679 runtimeMode: input.runtimeMode,
680 hasResumeCursor: sessionWithInstance.resumeCursor !== undefined,
681 hasCwd: typeof effectiveCwd === "string" && effectiveCwd.trim().length > 0,
682 hasModel:
683 typeof input.modelSelection?.model === "string" &&
684 input.modelSelection.model.trim().length > 0,
685 });
686
687 return sessionWithInstance;
688 }).pipe(
689 withMetrics({
690 counter: providerSessionsTotal,
691 attributes: () =>
692 providerMetricAttributes(metricProvider, {
693 operation: "start",
694 }),
695 }),
696 );
697 },
698 );
699
700 const sendTurn: ProviderServiceMethod<"sendTurn"> = Effect.fn("sendTurn")(function* (rawInput) {
701 const parsed = yield* decodeInputOrValidationError({
702 operation: "ProviderService.sendTurn",
703 schema: ProviderSendTurnInput,
704 payload: rawInput,
705 });
706
707 const input = {
708 ...parsed,
709 attachments: parsed.attachments ?? [],
710 };
711 if (!input.input && input.attachments.length === 0) {
712 return yield* toValidationError(
713 "ProviderService.sendTurn",
714 "Either input text or at least one attachment is required",
715 );
716 }
717 yield* Effect.annotateCurrentSpan({
718 "provider.operation": "send-turn",
719 "provider.thread_id": input.threadId,
720 "provider.interaction_mode": input.interactionMode,
721 "provider.attachment_count": input.attachments.length,
722 });
723 let metricProvider = "unknown";
724 let metricModel = input.modelSelection?.model;
725 return yield* Effect.gen(function* () {
726 const routed = yield* resolveRoutableSession({
727 threadId: input.threadId,
728 operation: "ProviderService.sendTurn",
729 allowRecovery: true,
730 });
731 metricProvider = routed.adapter.provider;
732 metricModel = input.modelSelection?.model;
733 yield* Effect.annotateCurrentSpan({
734 "provider.kind": routed.adapter.provider,
735 ...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
736 });
737 // A turn is the clearest sign a session is still alive. The MCP
738 // credential is minted once at session start and cannot be rotated into
739 // an already-spawned agent process, so we keep the existing token valid
740 // rather than issuing a new one: sessions that go a long time between
741 // browser tool calls used to lose the toolkit outright.
742 yield* McpSessionRegistry.touchActiveMcpThread(input.threadId);
743 const turn = yield* routed.adapter.sendTurn(input);
744 yield* directory.upsert({
745 threadId: input.threadId,
746 provider: routed.adapter.provider,
747 providerInstanceId: routed.instanceId,
748 status: "running",
749 ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
750 runtimePayload: {
751 ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
752 activeTurnId: turn.turnId,
753 lastRuntimeEvent: "provider.sendTurn",
754 lastRuntimeEventAt: yield* nowIso,
755 },
756 });
757 yield* analytics.record("provider.turn.sent", {
758 provider: routed.adapter.provider,
759 model: input.modelSelection?.model,
760 interactionMode: input.interactionMode,
761 attachmentCount: input.attachments.length,
762 hasInput: typeof input.input === "string" && input.input.trim().length > 0,
763 });
764 return turn;
765 }).pipe(
766 withMetrics({
767 counter: providerTurnsTotal,
768 timer: providerTurnDuration,
769 attributes: () =>
770 providerTurnMetricAttributes({
771 provider: metricProvider,
772 model: metricModel,
773 extra: {
774 operation: "send",
775 },
776 }),
777 }),
778 );
779 });
780
781 const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(
782 function* (rawInput) {
783 const input = yield* decodeInputOrValidationError({
784 operation: "ProviderService.interruptTurn",
785 schema: ProviderInterruptTurnInput,
786 payload: rawInput,
787 });
788 let metricProvider = "unknown";
789 return yield* Effect.gen(function* () {
790 const routed = yield* resolveRoutableSession({
791 threadId: input.threadId,
792 operation: "ProviderService.interruptTurn",
793 allowRecovery: true,
794 });
795 metricProvider = routed.adapter.provider;
796 yield* Effect.annotateCurrentSpan({
797 "provider.operation": "interrupt-turn",
798 "provider.kind": routed.adapter.provider,
799 "provider.thread_id": input.threadId,
800 "provider.turn_id": input.turnId,
801 });
802 yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
803 yield* analytics.record("provider.turn.interrupted", {
804 provider: routed.adapter.provider,
805 });
806 }).pipe(
807 withMetrics({
808 counter: providerTurnsTotal,
809 outcomeAttributes: () =>
810 providerMetricAttributes(metricProvider, {
811 operation: "interrupt",
812 }),
813 }),
814 );
815 },
816 );
817
818 const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")(
819 function* (rawInput) {
820 const input = yield* decodeInputOrValidationError({
821 operation: "ProviderService.respondToRequest",
822 schema: ProviderRespondToRequestInput,
823 payload: rawInput,
824 });
825 let metricProvider = "unknown";
826 return yield* Effect.gen(function* () {
827 const routed = yield* resolveRoutableSession({
828 threadId: input.threadId,
829 operation: "ProviderService.respondToRequest",
830 allowRecovery: true,
831 });
832 metricProvider = routed.adapter.provider;
833 yield* Effect.annotateCurrentSpan({
834 "provider.operation": "respond-to-request",
835 "provider.kind": routed.adapter.provider,
836 "provider.thread_id": input.threadId,
837 "provider.request_id": input.requestId,
838 });
839 yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
840 yield* analytics.record("provider.request.responded", {
841 provider: routed.adapter.provider,
842 decision: input.decision,
843 });
844 }).pipe(
845 withMetrics({
846 counter: providerTurnsTotal,
847 outcomeAttributes: () =>
848 providerMetricAttributes(metricProvider, {
849 operation: "approval-response",
850 }),
851 }),
852 );
853 },
854 );
855
856 const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn(
857 "respondToUserInput",
858 )(function* (rawInput) {
859 const input = yield* decodeInputOrValidationError({
860 operation: "ProviderService.respondToUserInput",
861 schema: ProviderRespondToUserInputInput,
862 payload: rawInput,
863 });
864 let metricProvider = "unknown";
865 return yield* Effect.gen(function* () {
866 const routed = yield* resolveRoutableSession({
867 threadId: input.threadId,
868 operation: "ProviderService.respondToUserInput",
869 allowRecovery: true,
870 });
871 metricProvider = routed.adapter.provider;
872 yield* Effect.annotateCurrentSpan({
873 "provider.operation": "respond-to-user-input",
874 "provider.kind": routed.adapter.provider,
875 "provider.thread_id": input.threadId,
876 "provider.request_id": input.requestId,
877 });
878 yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
879 }).pipe(
880 withMetrics({
881 counter: providerTurnsTotal,
882 outcomeAttributes: () =>
883 providerMetricAttributes(metricProvider, {
884 operation: "user-input-response",
885 }),
886 }),
887 );
888 });
889
890 const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")(
891 function* (rawInput) {
892 const input = yield* decodeInputOrValidationError({
893 operation: "ProviderService.stopSession",
894 schema: ProviderStopSessionInput,
895 payload: rawInput,
896 });
897 let metricProvider = "unknown";
898 return yield* Effect.gen(function* () {
899 const routed = yield* resolveRoutableSession({
900 threadId: input.threadId,
901 operation: "ProviderService.stopSession",
902 allowRecovery: false,
903 });
904 metricProvider = routed.adapter.provider;
905 yield* Effect.annotateCurrentSpan({
906 "provider.operation": "stop-session",
907 "provider.kind": routed.adapter.provider,
908 "provider.thread_id": input.threadId,
909 });
910 if (routed.isActive) {
911 yield* routed.adapter.stopSession(routed.threadId);
912 }
913 yield* clearMcpSession(input.threadId);
914 lastTouchAtByThread.delete(input.threadId);
915 yield* directory.upsert({
916 threadId: input.threadId,
917 provider: routed.adapter.provider,
918 providerInstanceId: routed.instanceId,
919 status: "stopped",
920 runtimePayload: {
921 activeTurnId: null,
922 },
923 });
924 yield* analytics.record("provider.session.stopped", {
925 provider: routed.adapter.provider,
926 });
927 }).pipe(
928 withMetrics({
929 counter: providerSessionsTotal,
930 outcomeAttributes: () =>
931 providerMetricAttributes(metricProvider, {
932 operation: "stop",
933 }),
934 }),
935 );
936 },
937 );
938
939 const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")(
940 function* () {
941 const currentAdapters = yield* getAdapterEntries;
942 const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
943 adapter.listSessions().pipe(
944 Effect.map((sessions) =>
945 sessions.map((session) => ({
946 ...session,
947 providerInstanceId: instanceId,
948 })),
949 ),
950 ),
951 );
952 const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
953 const persistedBindings = yield* directory.listThreadIds().pipe(
954 Effect.flatMap((threadIds) =>
955 Effect.forEach(
956 threadIds,
957 (threadId) =>
958 directory
959 .getBinding(threadId)
960 .pipe(
961 Effect.orElseSucceed(() =>
962 Option.none<ProviderSessionDirectory.ProviderRuntimeBinding>(),
963 ),
964 ),
965 { concurrency: "unbounded" },
966 ),
967 ),
968 Effect.orElseSucceed(
969 () => [] as Array<Option.Option<ProviderSessionDirectory.ProviderRuntimeBinding>>,
970 ),
971 );
972 const bindingsByThreadId = new Map<
973 ThreadId,
974 ProviderSessionDirectory.ProviderRuntimeBinding
975 >();
976 for (const bindingOption of persistedBindings) {
977 const binding = Option.getOrUndefined(bindingOption);
978 if (binding) {
979 bindingsByThreadId.set(binding.threadId, binding);
980 }
981 }
982
983 const sessions: ProviderSession[] = [];
984 for (const session of activeSessions) {
985 const binding = bindingsByThreadId.get(session.threadId);
986 if (!binding) {
987 sessions.push(session);
988 continue;
989 }
990
991 const overrides: {
992 resumeCursor?: ProviderSession["resumeCursor"];
993 runtimeMode?: ProviderSession["runtimeMode"];
994 providerInstanceId?: ProviderSession["providerInstanceId"];
995 } = {};
996 overrides.providerInstanceId = dieOnMissingBindingInstanceId(
997 "ProviderService.listSessions",
998 binding,
999 );
1000 if (binding.provider !== session.provider) {
1001 return yield* Effect.die(
1002 new Error(
1003 `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,
1004 ),
1005 );
1006 }
1007 if (overrides.providerInstanceId !== session.providerInstanceId) {
1008 return yield* Effect.die(
1009 new Error(
1010 `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,
1011 ),
1012 );
1013 }
1014 if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
1015 overrides.resumeCursor = binding.resumeCursor;
1016 }
1017 if (binding.runtimeMode !== undefined) {
1018 overrides.runtimeMode = binding.runtimeMode;
1019 }
1020 sessions.push(Object.assign({}, session, overrides));
1021 }
1022 return sessions;
1023 },
1024 );
1025
1026 const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) =>
1027 registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));
1028
1029 const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) =>
1030 registry.getInstanceInfo(instanceId);
1031
1032 const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn(
1033 "rollbackConversation",
1034 )(function* (rawInput) {
1035 const input = yield* decodeInputOrValidationError({
1036 operation: "ProviderService.rollbackConversation",
1037 schema: ProviderRollbackConversationInput,
1038 payload: rawInput,
1039 });
1040 if (input.numTurns === 0) {
1041 return;
1042 }
1043 let metricProvider = "unknown";
1044 return yield* Effect.gen(function* () {
1045 const routed = yield* resolveRoutableSession({
1046 threadId: input.threadId,
1047 operation: "ProviderService.rollbackConversation",
1048 allowRecovery: true,
1049 });
1050 metricProvider = routed.adapter.provider;
1051 yield* Effect.annotateCurrentSpan({
1052 "provider.operation": "rollback-conversation",
1053 "provider.kind": routed.adapter.provider,
1054 "provider.thread_id": input.threadId,
1055 "provider.rollback_turns": input.numTurns,
1056 });
1057 yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
1058 yield* analytics.record("provider.conversation.rolled_back", {
1059 provider: routed.adapter.provider,
1060 turns: input.numTurns,
1061 });
1062 }).pipe(
1063 withMetrics({
1064 counter: providerTurnsTotal,
1065 outcomeAttributes: () =>
1066 providerMetricAttributes(metricProvider, {
1067 operation: "rollback",
1068 }),
1069 }),
1070 );
1071 });
1072
1073 const runStopAll = Effect.fn("runStopAll")(function* () {
1074 const threadIds = yield* directory.listThreadIds();
1075 const currentAdapters = yield* getAdapterEntries;
1076 const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
1077 adapter.listSessions().pipe(
1078 Effect.map((sessions) =>
1079 sessions.map((session) => ({
1080 ...session,
1081 providerInstanceId: instanceId,
1082 })),
1083 ),
1084 ),
1085 ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
1086 yield* Effect.forEach(activeSessions, (session) =>
1087 Effect.flatMap(nowIso, (lastRuntimeEventAt) =>
1088 upsertSessionBinding(session, session.threadId, {
1089 lastRuntimeEvent: "provider.stopAll",
1090 lastRuntimeEventAt,
1091 }),
1092 ),
1093 ).pipe(Effect.asVoid);
1094 yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
1095 yield* McpSessionRegistry.revokeAllActiveMcpCredentials();
1096 McpProviderSession.clearAllMcpProviderSessions();
1097 const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
1098 yield* Effect.forEach(bindings, (binding) =>
1099 Effect.gen(function* () {
1100 const providerInstanceId = dieOnMissingBindingInstanceId(
1101 "ProviderService.stopAll",
1102 binding,
1103 );
1104 return yield* directory.upsert({
1105 threadId: binding.threadId,
1106 provider: binding.provider,
1107 providerInstanceId,
1108 status: "stopped",
1109 runtimePayload: {
1110 activeTurnId: null,
1111 lastRuntimeEvent: "provider.stopAll",
1112 lastRuntimeEventAt: yield* nowIso,
1113 },
1114 });
1115 }),
1116 ).pipe(Effect.asVoid);
1117 yield* analytics.record("provider.sessions.stopped_all", {
1118 sessionCount: threadIds.length,
1119 });
1120 yield* analytics.flush;
1121 });
1122
1123 yield* Effect.addFinalizer(() =>
1124 runStopAll().pipe(
1125 Effect.catchCause((cause) =>
1126 Effect.logWarning("failed to stop provider service", {
1127 errorTag: causeErrorTag(cause),
1128 }),
1129 ),
1130 ),
1131 );
1132
1133 return {
1134 startSession,
1135 sendTurn,
1136 interruptTurn,
1137 respondToRequest,
1138 respondToUserInput,
1139 stopSession,
1140 listSessions,
1141 getCapabilities,
1142 getInstanceInfo,
1143 rollbackConversation,
1144 // Each access creates a fresh PubSub subscription so that multiple
1145 // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
1146 // independently receive all runtime events.
1147 get streamEvents(): ProviderServiceMethod<"streamEvents"> {
1148 return Stream.fromPubSub(runtimeEventPubSub);
1149 },
1150 } satisfies ProviderService.ProviderService["Service"];
1151});
1152
1153export const ProviderServiceLive = Layer.effect(
1154 ProviderService.ProviderService,
1155 makeProviderService(),
1156);
1157
1158export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
1159 return Layer.effect(ProviderService.ProviderService, makeProviderService(options));
1160}