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

ProviderService.ts

1,139 lines41.1 KB

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