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