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