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