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

ProviderService.ts

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