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

ProviderService.ts

1,349 lines50.9 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 ProviderUploadFeedbackInput,
23 type ProviderInstanceId,
24 type ProviderDriverKind,
25 type ProviderRuntimeEvent,
26 type ProviderSession,
27} from "@t3tools/contracts";
28import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations";
29import { causeErrorTag } from "@t3tools/shared/observability";
30import * as DateTime from "effect/DateTime";
31import * as Effect from "effect/Effect";
32import * as Layer from "effect/Layer";
33import * as Option from "effect/Option";
34import * as PubSub from "effect/PubSub";
35import * as Ref from "effect/Ref";
36import * as Schema from "effect/Schema";
37import * as SchemaIssue from "effect/SchemaIssue";
38import * as Stream from "effect/Stream";
39​
40import { resolveAttachmentPath } from "../../attachmentStore.ts";
41import * as ServerConfig from "../../config.ts";
42import {
43 increment,
44 providerMetricAttributes,
45 providerRuntimeEventsTotal,
46 providerSessionsTotal,
47 providerTurnDuration,
48 providerTurnsTotal,
49 providerTurnMetricAttributes,
50 withMetrics,
51} from "../../observability/Metrics.ts";
52import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts";
53import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
54import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
55import * as ProviderService from "../Services/ProviderService.ts";
56import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts";
57import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
58import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
59import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
60import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
61import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
62import * as ServerSettings from "../../serverSettings.ts";
63const isModelSelection = Schema.is(ModelSelection);
64​
65/**
66 * Hook for tests that want to override the canonical event logger pulled
67 * from `ProviderEventLoggers`. Production wiring leaves this undefined and
68 * reads the logger off the tag.
69 */
70export interface ProviderServiceLiveOptions {
71 readonly canonicalEventLogger?: EventNdjsonLogger;
72 /**
73 * Overrides MCP credential issuance. The real issuer reads a module-global
74 * registry that only a running MCP server installs, which makes the
75 * agent-browser-access gate unobservable from a unit test; this seam lets a
76 * test see whether a credential was requested at all.
77 */
78 readonly issueMcpCredential?: typeof McpSessionRegistry.issueActiveMcpCredential;
79 /** Same seam as `issueMcpCredential`, for observing the deny path's revoke. */
80 readonly revokeMcpCredential?: typeof McpSessionRegistry.revokeActiveMcpThread;
82​
83type ProviderServiceMethod<Name extends keyof ProviderService.ProviderService["Service"]> =
84 ProviderService.ProviderService["Service"][Name];
85​
86const ProviderRollbackConversationInput = Schema.Struct({
87 threadId: ThreadId,
88 numTurns: NonNegativeInt,
89});
90​
91function toValidationError(
92 operation: string,
93 issue: string,
94 cause?: unknown,
95): ProviderValidationError {
96 return new ProviderValidationError({
97 operation,
98 issue,
99 ...(cause !== undefined ? { cause } : {}),
100 });
102​
103const decodeInputOrValidationError = <S extends Schema.Top>(input: {
104 readonly operation: string;
105 readonly schema: S;
106 readonly payload: unknown;
107}) => {
108 const decodeProviderRequestInput = Schema.decodeUnknownEffect(input.schema);
109 return decodeProviderRequestInput(input.payload).pipe(
110 Effect.mapError(
111 (schemaError) =>
112 new ProviderValidationError({
113 operation: input.operation,
114 issue: SchemaIssue.makeFormatterDefault()(schemaError.issue),
115 cause: schemaError,
116 }),
117 ),
118 );
119};
120​
121function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "stopped" | "error" {
122 switch (session.status) {
123 case "connecting":
124 return "starting";
125 case "error":
126 return "error";
127 case "closed":
128 return "stopped";
129 case "ready":
130 case "running":
131 default:
132 return "running";
133 }
135​
136function toRuntimePayloadFromSession(
137 session: ProviderSession,
138 extra?: {
139 readonly modelSelection?: unknown;
140 readonly lastRuntimeEvent?: string;
141 readonly lastRuntimeEventAt?: string;
142 },
143): Record<string, unknown> {
144 return {
145 cwd: session.cwd ?? null,
146 model: session.model ?? null,
147 activeTurnId: session.activeTurnId ?? null,
148 lastError: session.lastError ?? null,
149 ...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),
150 ...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
151 ...(extra?.lastRuntimeEventAt !== undefined
152 ? { lastRuntimeEventAt: extra.lastRuntimeEventAt }
153 : {}),
154 };
156​
157function readPersistedModelSelection(
158 runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"],
159): ModelSelection | undefined {
160 if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
161 return undefined;
162 }
163 const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined;
164 return isModelSelection(raw) ? raw : undefined;
166​
167function readPersistedCwd(
168 runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"],
169): string | undefined {
170 if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
171 return undefined;
172 }
173 const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined;
174 if (typeof rawCwd !== "string") return undefined;
175 const trimmed = rawCwd.trim();
176 return trimmed.length > 0 ? trimmed : undefined;
178​
179const dieOnMissingBindingInstanceId = (
180 operation: string,
181 payload: {
182 readonly providerInstanceId?: ProviderInstanceId | undefined;
183 readonly provider?: ProviderDriverKind | undefined;
184 },
185): ProviderInstanceId => {
186 if (payload.providerInstanceId !== undefined) {
187 return payload.providerInstanceId;
188 }
189 throw new Error(
190 payload.provider
191 ? `${operation}: provider instance id is required for provider '${payload.provider}'.`
192 : `${operation}: provider instance id is required.`,
193 );
194};
195​
196const correlateRuntimeEventWithInstance = (
197 source: {
198 readonly instanceId: ProviderInstanceId;
199 readonly provider: ProviderDriverKind;
200 },
201 event: ProviderRuntimeEvent,
202): ProviderRuntimeEvent => {
203 if (event.provider !== source.provider) {
204 throw new Error(
205 `ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`,
206 );
207 }
208 if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) {
209 throw new Error(
210 `ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`,
211 );
212 }
213 return { ...event, providerInstanceId: source.instanceId };
214};
215​
216const makeProviderService = Effect.fn("makeProviderService")(function* (
217 options?: ProviderServiceLiveOptions,
218) {
219 const analytics = yield* Effect.service(AnalyticsService.AnalyticsService);
220 const serverConfig = yield* ServerConfig.ServerConfig;
221 const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
222 // Options-provided logger wins (test overrides); otherwise we take whatever
223 // the `ProviderEventLoggers` tag exposes — `undefined` means "no canonical
224 // log writer is attached", which downstream code already handles as a
225 // no-op.
226 const canonicalEventLogger = options?.canonicalEventLogger ?? eventLoggers.canonical;
227​
228 const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
229 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
230 const serverSettings = yield* ServerSettings.ServerSettingsService;
231 const issueMcpCredential =
232 options?.issueMcpCredential ?? McpSessionRegistry.issueActiveMcpCredential;
233 const revokeMcpCredential =
234 options?.revokeMcpCredential ?? McpSessionRegistry.revokeActiveMcpThread;
235 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
236 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
237 /**
238 * Attach the `t3-code` MCP server to the session that is about to start.
239 *
240 * This is the only place a credential is minted, so withholding one here is
241 * what disables agent browser access everywhere: every adapter already
242 * treats a missing session as "no MCP server", and the `/mcp` endpoint
243 * accepts nothing but tokens issued from this path.
244 */
245 /**
246 * Deny on an unreadable settings file rather than letting the read failure
247 * escape: adding `ServerSettingsError` to `ProviderServiceError` would widen
248 * a union every caller handles, for a branch that only decides whether one
249 * optional toolset is attached. Denying is the safe direction — an explicit
250 * "off" silently becoming "on" would violate the user's stated choice,
251 * whereas the reverse costs an agent one toolset and is visible immediately.
252 */
253 const agentBrowserAccessEnabled = serverSettings.getSettings.pipe(
254 Effect.map((settings) => settings.enableAgentBrowserAccess),
255 Effect.catch((cause) =>
256 Effect.logWarning(
257 "Could not read server settings; withholding agent browser access for this session.",
258 { cause },
259 ).pipe(Effect.as(false)),
260 ),
261 );
262​
263 const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
264 Effect.gen(function* () {
265 if (!(yield* agentBrowserAccessEnabled)) {
266 // Revoke as well as clear. Every other prepare path reaches
267 // `issueActiveMcpCredential`, which revokes the thread first, so
268 // skipping it here would leave a previously issued bearer token valid
269 // against `/mcp` for the rest of its liveness window — and later turns
270 // would keep refreshing it. A session restart (runtime mode, cwd,
271 // model) re-prepares without stopping, so it relies on this.
272 yield* revokeMcpCredential(threadId);
273 yield* Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId));
274 return undefined;
275 }
276 const credential = yield* issueMcpCredential({ threadId, providerInstanceId });
277 if (credential) {
278 yield* Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config));
279 }
280 return credential;
281 });
282 const clearMcpSession = (threadId: ThreadId) =>
283 McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(
284 Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))),
285 );
286​
287 const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
288 Effect.succeed(event).pipe(
289 Effect.tap((canonicalEvent) =>
290 canonicalEventLogger
291 ? canonicalEventLogger.write(canonicalEvent, canonicalEvent.threadId)
292 : Effect.void,
293 ),
294 Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
295 Effect.asVoid,
296 );
297​
298 const requireBindingInstanceId = (
299 operation: string,
300 payload: {
301 readonly providerInstanceId?: ProviderInstanceId | undefined;
302 readonly provider?: ProviderDriverKind | undefined;
303 },
304 ): Effect.Effect<ProviderInstanceId, ProviderValidationError> =>
305 payload.providerInstanceId !== undefined
306 ? Effect.succeed(payload.providerInstanceId)
307 : Effect.fail(
308 toValidationError(
309 operation,
310 payload.provider
311 ? `Provider instance id is required for provider '${payload.provider}'.`
312 : "Provider instance id is required.",
313 ),
314 );
315​
316 const upsertSessionBinding = (
317 session: ProviderSession,
318 threadId: ThreadId,
319 extra?: {
320 readonly modelSelection?: unknown;
321 readonly lastRuntimeEvent?: string;
322 readonly lastRuntimeEventAt?: string;
323 },
324 ) =>
325 Effect.gen(function* () {
326 const providerInstanceId = yield* requireBindingInstanceId(
327 "ProviderService.upsertSessionBinding",
328 session,
329 );
330 yield* directory.upsert({
331 threadId,
332 provider: session.provider,
333 providerInstanceId,
334 runtimeMode: session.runtimeMode,
335 status: toRuntimeStatus(session),
336 ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
337 runtimePayload: toRuntimePayloadFromSession(session, extra),
338 });
339 });
340​
341 const processRuntimeEvent = (
342 source: {
343 readonly instanceId: ProviderInstanceId;
344 readonly provider: ProviderDriverKind;
345 },
346 event: ProviderRuntimeEvent,
347 ): Effect.Effect<void> =>
348 Effect.sync(() => correlateRuntimeEventWithInstance(source, event)).pipe(
349 Effect.flatMap((canonicalEvent) => {
350 const resumeCursor =
351 canonicalEvent.type === "session.configured"
352 ? canonicalEvent.payload.resumeCursor
353 : undefined;
354 const resumeCursorPersistence =
355 resumeCursor === undefined
356 ? Effect.void
357 : directory
358 .updateResumeCursorIfCurrentInstance({
359 threadId: canonicalEvent.threadId,
360 providerInstanceId: source.instanceId,
361 resumeCursor,
362 })
363 .pipe(
364 Effect.tap((updated) =>
365 updated
366 ? Effect.void
367 : Effect.logDebug("provider.session.resume-cursor-update-stale", {
368 threadId: canonicalEvent.threadId,
369 provider: canonicalEvent.provider,
370 providerInstanceId: source.instanceId,
371 }),
372 ),
373 Effect.catchCause((cause) =>
374 Effect.logWarning("provider.session.resume-cursor-persist-failed", {
375 threadId: canonicalEvent.threadId,
376 provider: canonicalEvent.provider,
377 cause,
378 }),
379 ),
380 );
381​
382 return increment(providerRuntimeEventsTotal, {
383 provider: canonicalEvent.provider,
384 eventType: canonicalEvent.type,
385 }).pipe(
386 Effect.andThen(resumeCursorPersistence),
387 Effect.andThen(publishRuntimeEvent(canonicalEvent)),
388 );
389 }),
390 );
391​
392 // `subscribedAdapters` is our source-of-truth for "which instance adapters
393 // are currently wired into the runtime event bus". It both tracks the set
394 // of live subscriptions (so `reconcileInstanceSubscriptions` can diff and
395 // fork only the *new* or *rebuilt* ones) and serves as the dynamic adapter
396 // list consumed by `stopStaleSessionsForThread`, `listSessions`, and
397 // `runStopAll` — replacing the pre-Slice-D startup snapshot so hot-added
398 // instances become visible to those call sites as soon as settings edits
399 // land.
400 const subscribedAdapters = yield* Ref.make(
401 new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>(),
402 );
403​
404 const getAdapterEntries = Ref.get(subscribedAdapters).pipe(
405 Effect.map((map) => Array.from(map.entries())),
406 );
407​
408 // Rebuild the map of id → adapter from the registry and fork a new event
409 // subscription for every instance that is either brand new or whose adapter
410 // identity changed (indicating the underlying `ProviderInstance` was torn
411 // down and rebuilt by `ProviderInstanceRegistry.reconcile`). Orphaned
412 // fibers for removed/replaced instances exit on their own because their
413 // adapter's `streamEvents` source terminates when the old scope closes.
414 const reconcileInstanceSubscriptions = Effect.gen(function* () {
415 const previous = yield* Ref.get(subscribedAdapters);
416 const currentIds = yield* registry.listInstances();
417 const next = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();
418 for (const id of currentIds) {
419 const adapterOption = yield* registry
420 .getByInstance(id)
421 .pipe(Effect.tapError(Effect.logWarning), Effect.option);
422 if (Option.isNone(adapterOption)) continue;
423 const adapter = adapterOption.value;
424 next.set(id, adapter);
425 if (previous.get(id) !== adapter) {
426 yield* Stream.runForEach(adapter.streamEvents, (event) =>
427 processRuntimeEvent(
428 {
429 instanceId: id,
430 provider: adapter.provider,
431 },
432 event,
433 ),
434 ).pipe(Effect.forkScoped);
435 }
436 }
437 yield* Ref.set(subscribedAdapters, next);
438 });
439​
440 const instanceChanges = yield* registry.subscribeChanges;
441 yield* reconcileInstanceSubscriptions;
442 yield* Stream.runForEach(
443 Stream.fromSubscription(instanceChanges),
444 () => reconcileInstanceSubscriptions,
445 ).pipe(Effect.forkScoped);
446​
447 const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
448 readonly binding: ProviderSessionDirectory.ProviderRuntimeBinding;
449 readonly operation: string;
450 }) {
451 const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding);
452 yield* Effect.annotateCurrentSpan({
453 "provider.operation": "recover-session",
454 "provider.kind": input.binding.provider,
455 "provider.instance_id": bindingInstanceId,
456 "provider.thread_id": input.binding.threadId,
457 });
458 return yield* Effect.gen(function* () {
459 const adapter = yield* registry.getByInstance(bindingInstanceId);
460 const hasResumeCursor =
461 input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
462 const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
463 if (hasActiveSession) {
464 const activeSessions = yield* adapter.listSessions();
465 const existing = activeSessions.find(
466 (session) => session.threadId === input.binding.threadId,
467 );
468 if (existing) {
469 yield* upsertSessionBinding(
470 { ...existing, providerInstanceId: bindingInstanceId },
471 input.binding.threadId,
472 );
473 yield* analytics.record("provider.session.recovered", {
474 provider: existing.provider,
475 strategy: "adopt-existing",
476 hasResumeCursor: existing.resumeCursor !== undefined,
477 });
478 return { adapter, session: existing } as const;
479 }
480 }
481​
482 if (!hasResumeCursor) {
483 return yield* toValidationError(
484 input.operation,
485 `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
486 );
487 }
488​
489 const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
490 const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
491​
492 yield* prepareMcpSession(input.binding.threadId, bindingInstanceId);
493 const resumed = yield* adapter
494 .startSession({
495 threadId: input.binding.threadId,
496 provider: input.binding.provider,
497 providerInstanceId: bindingInstanceId,
498 ...(persistedCwd ? { cwd: persistedCwd } : {}),
499 ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
500 ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
501 runtimeMode: input.binding.runtimeMode ?? "full-access",
502 })
503 .pipe(Effect.onError(() => clearMcpSession(input.binding.threadId)));
504 if (resumed.provider !== adapter.provider) {
505 yield* clearMcpSession(input.binding.threadId);
506 return yield* toValidationError(
507 input.operation,
508 `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
509 );
510 }
511​
512 yield* upsertSessionBinding(
513 { ...resumed, providerInstanceId: bindingInstanceId },
514 input.binding.threadId,
515 );
516 yield* analytics.record("provider.session.recovered", {
517 provider: resumed.provider,
518 strategy: "resume-thread",
519 hasResumeCursor: resumed.resumeCursor !== undefined,
520 });
521 return { adapter, session: resumed } as const;
522 }).pipe(
523 withMetrics({
524 counter: providerSessionsTotal,
525 attributes: providerMetricAttributes(input.binding.provider, {
526 operation: "recover",
527 }),
528 }),
529 );
530 });
531​
532 const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: {
533 readonly threadId: ThreadId;
534 readonly operation: string;
535 readonly allowRecovery: boolean;
536 }) {
537 const bindingOption = yield* directory.getBinding(input.threadId);
538 const binding = Option.getOrUndefined(bindingOption);
539 if (!binding) {
540 return yield* toValidationError(
541 input.operation,
542 `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
543 );
544 }
545 const instanceId = yield* requireBindingInstanceId(input.operation, binding);
546 const adapter = yield* registry.getByInstance(instanceId);
547​
548 const hasRequestedSession = yield* adapter.hasSession(input.threadId);
549 if (hasRequestedSession) {
550 return {
551 adapter,
552 instanceId,
553 threadId: input.threadId,
554 runtimeMode: binding.runtimeMode,
555 isActive: true,
556 } as const;
557 }
558​
559 if (!input.allowRecovery) {
560 return {
561 adapter,
562 instanceId,
563 threadId: input.threadId,
564 runtimeMode: binding.runtimeMode,
565 isActive: false,
566 } as const;
567 }
568​
569 const recovered = yield* recoverSessionForThread({
570 binding,
571 operation: input.operation,
572 });
573 return {
574 adapter: recovered.adapter,
575 instanceId,
576 threadId: input.threadId,
577 runtimeMode: recovered.session.runtimeMode,
578 isActive: true,
579 } as const;
580 });
581​
582 const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: {
583 readonly threadId: ThreadId;
584 readonly currentInstanceId: ProviderInstanceId;
585 }) {
586 const currentAdapters = yield* getAdapterEntries;
587 yield* Effect.forEach(
588 currentAdapters,
589 ([instanceId, adapter]) =>
590 instanceId === input.currentInstanceId
591 ? Effect.void
592 : Effect.gen(function* () {
593 const hasSession = yield* adapter.hasSession(input.threadId);
594 if (!hasSession) {
595 return;
596 }
597​
598 yield* adapter.stopSession(input.threadId).pipe(
599 Effect.tap(() =>
600 analytics.record("provider.session.stopped", {
601 provider: adapter.provider,
602 }),
603 ),
604 Effect.catchCause((cause) =>
605 Effect.logWarning("provider.session.stop-stale-failed", {
606 threadId: input.threadId,
607 provider: adapter.provider,
608 cause,
609 }),
610 ),
611 );
612 }),
613 { discard: true },
614 );
615 });
616​
617 const startSession: ProviderServiceMethod<"startSession"> = Effect.fn("startSession")(
618 function* (threadId, rawInput) {
619 const parsed = yield* decodeInputOrValidationError({
620 operation: "ProviderService.startSession",
621 schema: ProviderSessionStartInput,
622 payload: rawInput,
623 });
624​
625 const resolvedInstanceId = yield* requireBindingInstanceId(
626 "ProviderService.startSession",
627 parsed,
628 );
629 let metricProvider = parsed.provider ?? String(resolvedInstanceId);
630 yield* Effect.annotateCurrentSpan({
631 "provider.operation": "start-session",
632 "provider.instance_id": resolvedInstanceId,
633 "provider.thread_id": threadId,
634 "provider.runtime_mode": parsed.runtimeMode,
635 });
636 return yield* Effect.gen(function* () {
637 const instanceInfo = yield* registry.getInstanceInfo(resolvedInstanceId);
638 const resolvedProvider = instanceInfo.driverKind;
639 metricProvider = resolvedProvider;
640 if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) {
641 return yield* toValidationError(
642 "ProviderService.startSession",
643 `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
644 );
645 }
646 const input = {
647 ...parsed,
648 threadId,
649 provider: resolvedProvider,
650 };
651 if (!instanceInfo.enabled) {
652 return yield* toValidationError(
653 "ProviderService.startSession",
654 `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
655 );
656 }
657 const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
658 if (
659 persistedBinding?.provider === resolvedProvider &&
660 persistedBinding.providerInstanceId !== resolvedInstanceId &&
661 (input.resumeCursor != null || persistedBinding.resumeCursor != null)
662 ) {
663 const previousInstanceId = yield* requireBindingInstanceId(
664 "ProviderService.startSession",
665 persistedBinding,
666 );
667 const previousInfo = yield* registry.getInstanceInfo(previousInstanceId);
668 if (
669 previousInfo.continuationIdentity.continuationKey !==
670 instanceInfo.continuationIdentity.continuationKey
671 ) {
672 return yield* toValidationError(
673 "ProviderService.startSession",
674 `Thread '${threadId}' cannot switch from instance '${previousInstanceId}' to '${resolvedInstanceId}' because their provider resume state is incompatible.`,
675 );
676 }
677 }
678 const effectiveResumeCursor =
679 input.resumeCursor ??
680 (persistedBinding?.providerInstanceId === resolvedInstanceId
681 ? persistedBinding.resumeCursor
682 : undefined);
683 const effectiveCwd =
684 input.cwd ??
685 (persistedBinding?.providerInstanceId === resolvedInstanceId
686 ? readPersistedCwd(persistedBinding.runtimePayload)
687 : undefined);
688 yield* Effect.annotateCurrentSpan({
689 "provider.kind": resolvedProvider,
690 "provider.resume_cursor.source":
691 input.resumeCursor !== undefined
692 ? "request"
693 : effectiveResumeCursor !== undefined &&
694 persistedBinding?.providerInstanceId === resolvedInstanceId
695 ? "persisted"
696 : "none",
697 "provider.resume_cursor.present": effectiveResumeCursor !== undefined,
698 "provider.cwd.source":
699 input.cwd !== undefined
700 ? "request"
701 : effectiveCwd !== undefined &&
702 persistedBinding?.providerInstanceId === resolvedInstanceId
703 ? "persisted"
704 : "none",
705 "provider.cwd.effective": effectiveCwd ?? "",
706 });
707 const adapter = yield* registry.getByInstance(resolvedInstanceId);
708 yield* prepareMcpSession(threadId, resolvedInstanceId);
709 const session = yield* adapter
710 .startSession({
711 ...input,
712 providerInstanceId: resolvedInstanceId,
713 ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),
714 ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
715 })
716 .pipe(Effect.onError(() => clearMcpSession(threadId)));
717​
718 if (session.provider !== adapter.provider) {
719 yield* clearMcpSession(threadId);
720 return yield* toValidationError(
721 "ProviderService.startSession",
722 `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
723 );
724 }
725 const sessionWithInstance = {
726 ...session,
727 providerInstanceId: resolvedInstanceId,
728 };
729​
730 yield* stopStaleSessionsForThread({
731 threadId,
732 currentInstanceId: resolvedInstanceId,
733 });
734 yield* upsertSessionBinding(sessionWithInstance, threadId, {
735 modelSelection: input.modelSelection,
736 });
737 yield* analytics.record("provider.session.started", {
738 provider: sessionWithInstance.provider,
739 runtimeMode: input.runtimeMode,
740 hasResumeCursor: sessionWithInstance.resumeCursor !== undefined,
741 hasCwd: typeof effectiveCwd === "string" && effectiveCwd.trim().length > 0,
742 hasModel:
743 typeof input.modelSelection?.model === "string" &&
744 input.modelSelection.model.trim().length > 0,
745 });
746​
747 // Changing runtime mode restarts the session, so the transition is only
748 // observable here, by diffing against the mode the previous session for
749 // this thread was bound to. Recording it separately is what makes the
750 // "started supervised, switched to full access" funnel answerable.
751 const previousRuntimeMode = persistedBinding?.runtimeMode;
752 if (previousRuntimeMode !== undefined && previousRuntimeMode !== input.runtimeMode) {
753 yield* analytics.record("provider.runtime_mode.changed", {
754 provider: sessionWithInstance.provider,
755 from: previousRuntimeMode,
756 to: input.runtimeMode,
757 });
758 }
759​
760 return sessionWithInstance;
761 }).pipe(
762 withMetrics({
763 counter: providerSessionsTotal,
764 attributes: () =>
765 providerMetricAttributes(metricProvider, {
766 operation: "start",
767 }),
768 }),
769 );
770 },
771 );
772​
773 const sendTurn: ProviderServiceMethod<"sendTurn"> = Effect.fn("sendTurn")(function* (rawInput) {
774 const parsed = yield* decodeInputOrValidationError({
775 operation: "ProviderService.sendTurn",
776 schema: ProviderSendTurnInput,
777 payload: rawInput,
778 });
779​
780 const attachments = parsed.attachments ?? [];
781 if (!parsed.input && attachments.length === 0 && parsed.continuation !== true) {
782 return yield* toValidationError(
783 "ProviderService.sendTurn",
784 "Either input text or at least one attachment is required",
785 );
786 }
787​
788 const inputTextWithCitations =
789 parsed.input === undefined ? undefined : expandAssistantCitationsForProvider(parsed.input);
790 if (inputTextWithCitations !== parsed.input) {
791 yield* decodeInputOrValidationError({
792 operation: "ProviderService.sendTurn",
793 schema: ProviderSendTurnInput.fields.input,
794 payload: inputTextWithCitations,
795 });
796 }
797​
798 // Every attachment gets an on-disk path in the prompt so the model's tools
799 // can dereference the actual file. All attachments then go to the adapter,
800 // and each adapter decides what its provider ingests natively: OpenCode
801 // sends generic files as file parts, the others send images only and rely
802 // on the path line for everything else. Unresolvable ids are skipped here
803 // and surface as adapter errors when the file is read.
804 const attachmentPathLines = attachments.flatMap((attachment) => {
805 const attachmentPath = resolveAttachmentPath({
806 attachmentsDir: serverConfig.attachmentsDir,
807 attachment,
808 });
809 return attachmentPath === null
810 ? []
811 : [`[Attached ${attachment.type} "${attachment.name}" is saved at: ${attachmentPath}]`];
812 });
813 const inputTextWithAttachmentPaths =
814 attachmentPathLines.length === 0
815 ? inputTextWithCitations
816 : [inputTextWithCitations, attachmentPathLines.join("\n")]
817 .filter((part): part is string => typeof part === "string" && part.length > 0)
818 .join("\n\n");
819​
820 const input = {
821 ...parsed,
822 ...(inputTextWithAttachmentPaths !== undefined
823 ? { input: inputTextWithAttachmentPaths }
824 : {}),
825 };
826 yield* Effect.annotateCurrentSpan({
827 "provider.operation": "send-turn",
828 "provider.thread_id": input.threadId,
829 "provider.interaction_mode": input.interactionMode,
830 "provider.attachment_count": attachments.length,
831 });
832 let metricProvider = "unknown";
833 let metricModel = input.modelSelection?.model;
834 return yield* Effect.gen(function* () {
835 let routed = yield* resolveRoutableSession({
836 threadId: input.threadId,
837 operation: "ProviderService.sendTurn",
838 allowRecovery: false,
839 });
840 if (
841 input.continuation === true &&
842 !input.input &&
843 attachments.length === 0 &&
844 routed.adapter.capabilities.promptlessTurnContinuation !== true
845 ) {
846 return yield* toValidationError(
847 "ProviderService.sendTurn",
848 `Provider '${routed.adapter.provider}' requires an explicit continuation prompt`,
849 );
850 }
851 if (!routed.isActive) {
852 routed = yield* resolveRoutableSession({
853 threadId: input.threadId,
854 operation: "ProviderService.sendTurn",
855 allowRecovery: true,
856 });
857 }
858 metricProvider = routed.adapter.provider;
859 metricModel = input.modelSelection?.model;
860 yield* Effect.annotateCurrentSpan({
861 "provider.kind": routed.adapter.provider,
862 ...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
863 });
864 // A turn is the clearest sign a session is still alive. The MCP
865 // credential is minted once at session start and cannot be rotated into
866 // an already-spawned agent process, so we keep the existing token valid
867 // rather than issuing a new one: sessions that go a long time between
868 // browser tool calls used to lose the toolkit outright.
869 yield* McpSessionRegistry.touchActiveMcpThread(input.threadId);
870 const turn = yield* routed.adapter.sendTurn(input);
871 yield* directory.upsert({
872 threadId: input.threadId,
873 provider: routed.adapter.provider,
874 providerInstanceId: routed.instanceId,
875 status: "running",
876 ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
877 runtimePayload: {
878 ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
879 activeTurnId: turn.turnId,
880 lastRuntimeEvent: "provider.sendTurn",
881 lastRuntimeEventAt: yield* nowIso,
882 },
883 });
884 yield* analytics.record("provider.turn.sent", {
885 provider: routed.adapter.provider,
886 model: input.modelSelection?.model,
887 interactionMode: input.interactionMode,
888 // Session-start events alone skew runtime mode toward users who toggle
889 // often, since every toggle restarts the session. Recording it per turn
890 // gives a usage-weighted view and lets it cross with interactionMode.
891 runtimeMode: routed.runtimeMode,
892 attachmentCount: attachments.length,
893 hasInput: typeof input.input === "string" && input.input.trim().length > 0,
894 });
895 return turn;
896 }).pipe(
897 withMetrics({
898 counter: providerTurnsTotal,
899 timer: providerTurnDuration,
900 attributes: () =>
901 providerTurnMetricAttributes({
902 provider: metricProvider,
903 model: metricModel,
904 extra: {
905 operation: "send",
906 },
907 }),
908 }),
909 );
910 });
911​
912 const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(
913 function* (rawInput) {
914 const input = yield* decodeInputOrValidationError({
915 operation: "ProviderService.interruptTurn",
916 schema: ProviderInterruptTurnInput,
917 payload: rawInput,
918 });
919 let metricProvider = "unknown";
920 return yield* Effect.gen(function* () {
921 const routed = yield* resolveRoutableSession({
922 threadId: input.threadId,
923 operation: "ProviderService.interruptTurn",
924 allowRecovery: true,
925 });
926 metricProvider = routed.adapter.provider;
927 yield* Effect.annotateCurrentSpan({
928 "provider.operation": "interrupt-turn",
929 "provider.kind": routed.adapter.provider,
930 "provider.thread_id": input.threadId,
931 "provider.turn_id": input.turnId,
932 });
933 yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
934 yield* analytics.record("provider.turn.interrupted", {
935 provider: routed.adapter.provider,
936 });
937 }).pipe(
938 withMetrics({
939 counter: providerTurnsTotal,
940 outcomeAttributes: () =>
941 providerMetricAttributes(metricProvider, {
942 operation: "interrupt",
943 }),
944 }),
945 );
946 },
947 );
948​
949 const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")(
950 function* (rawInput) {
951 const input = yield* decodeInputOrValidationError({
952 operation: "ProviderService.respondToRequest",
953 schema: ProviderRespondToRequestInput,
954 payload: rawInput,
955 });
956 let metricProvider = "unknown";
957 return yield* Effect.gen(function* () {
958 const routed = yield* resolveRoutableSession({
959 threadId: input.threadId,
960 operation: "ProviderService.respondToRequest",
961 allowRecovery: true,
962 });
963 metricProvider = routed.adapter.provider;
964 yield* Effect.annotateCurrentSpan({
965 "provider.operation": "respond-to-request",
966 "provider.kind": routed.adapter.provider,
967 "provider.thread_id": input.threadId,
968 "provider.request_id": input.requestId,
969 });
970 yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
971 yield* analytics.record("provider.request.responded", {
972 provider: routed.adapter.provider,
973 decision: input.decision,
974 });
975 }).pipe(
976 withMetrics({
977 counter: providerTurnsTotal,
978 outcomeAttributes: () =>
979 providerMetricAttributes(metricProvider, {
980 operation: "approval-response",
981 }),
982 }),
983 );
984 },
985 );
986​
987 const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn(
988 "respondToUserInput",
989 )(function* (rawInput) {
990 const input = yield* decodeInputOrValidationError({
991 operation: "ProviderService.respondToUserInput",
992 schema: ProviderRespondToUserInputInput,
993 payload: rawInput,
994 });
995 let metricProvider = "unknown";
996 return yield* Effect.gen(function* () {
997 const routed = yield* resolveRoutableSession({
998 threadId: input.threadId,
999 operation: "ProviderService.respondToUserInput",
1000 allowRecovery: true,
1001 });
1002 metricProvider = routed.adapter.provider;
1003 yield* Effect.annotateCurrentSpan({
1004 "provider.operation": "respond-to-user-input",
1005 "provider.kind": routed.adapter.provider,
1006 "provider.thread_id": input.threadId,
1007 "provider.request_id": input.requestId,
1008 });
1009 yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
1010 }).pipe(
1011 withMetrics({
1012 counter: providerTurnsTotal,
1013 outcomeAttributes: () =>
1014 providerMetricAttributes(metricProvider, {
1015 operation: "user-input-response",
1016 }),
1017 }),
1018 );
1019 });
1020​
1021 const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")(
1022 function* (rawInput) {
1023 const input = yield* decodeInputOrValidationError({
1024 operation: "ProviderService.stopSession",
1025 schema: ProviderStopSessionInput,
1026 payload: rawInput,
1027 });
1028 let metricProvider = "unknown";
1029 return yield* Effect.gen(function* () {
1030 const routed = yield* resolveRoutableSession({
1031 threadId: input.threadId,
1032 operation: "ProviderService.stopSession",
1033 allowRecovery: false,
1034 });
1035 metricProvider = routed.adapter.provider;
1036 yield* Effect.annotateCurrentSpan({
1037 "provider.operation": "stop-session",
1038 "provider.kind": routed.adapter.provider,
1039 "provider.thread_id": input.threadId,
1040 });
1041 if (routed.isActive) {
1042 yield* routed.adapter.stopSession(routed.threadId);
1044 yield* clearMcpSession(input.threadId);
1045 yield* directory.upsert({
1046 threadId: input.threadId,
1047 provider: routed.adapter.provider,
1048 providerInstanceId: routed.instanceId,
1049 status: "stopped",
1050 runtimePayload: {
1051 activeTurnId: null,
1052 },
1053 });
1054 yield* analytics.record("provider.session.stopped", {
1055 provider: routed.adapter.provider,
1056 });
1057 }).pipe(
1058 withMetrics({
1059 counter: providerSessionsTotal,
1060 outcomeAttributes: () =>
1061 providerMetricAttributes(metricProvider, {
1062 operation: "stop",
1063 }),
1064 }),
1065 );
1066 },
1067 );
1068​
1069 const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")(
1070 function* () {
1071 const currentAdapters = yield* getAdapterEntries;
1072 const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
1073 adapter.listSessions().pipe(
1074 Effect.map((sessions) =>
1075 sessions.map((session) => ({
1076 ...session,
1077 providerInstanceId: instanceId,
1078 })),
1079 ),
1080 ),
1081 );
1082 const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
1083 // Only live adapter sessions appear in this response. Resolving every
1084 // historical binding here makes each call scale with the full thread
1085 // history instead of the active session set.
1086 const persistedBindings = yield* Effect.forEach(
1087 [...new Set(activeSessions.map((session) => session.threadId))],
1088 (threadId) =>
1089 directory
1090 .getBinding(threadId)
1091 .pipe(
1092 Effect.orElseSucceed(() =>
1093 Option.none<ProviderSessionDirectory.ProviderRuntimeBinding>(),
1094 ),
1095 ),
1096 { concurrency: "unbounded" },
1097 ).pipe(
1098 Effect.orElseSucceed(
1099 () => [] as Array<Option.Option<ProviderSessionDirectory.ProviderRuntimeBinding>>,
1100 ),
1101 );
1102 const bindingsByThreadId = new Map<
1103 ThreadId,
1104 ProviderSessionDirectory.ProviderRuntimeBinding
1105 >();
1106 for (const bindingOption of persistedBindings) {
1107 const binding = Option.getOrUndefined(bindingOption);
1108 if (binding) {
1109 bindingsByThreadId.set(binding.threadId, binding);
1112​
1113 const sessions: ProviderSession[] = [];
1114 for (const session of activeSessions) {
1115 const binding = bindingsByThreadId.get(session.threadId);
1116 if (!binding) {
1117 sessions.push(session);
1118 continue;
1120​
1121 const overrides: {
1122 resumeCursor?: ProviderSession["resumeCursor"];
1123 runtimeMode?: ProviderSession["runtimeMode"];
1124 providerInstanceId?: ProviderSession["providerInstanceId"];
1125 } = {};
1126 overrides.providerInstanceId = dieOnMissingBindingInstanceId(
1127 "ProviderService.listSessions",
1128 binding,
1129 );
1130 if (binding.provider !== session.provider) {
1131 return yield* Effect.die(
1132 new Error(
1133 `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,
1134 ),
1135 );
1137 if (overrides.providerInstanceId !== session.providerInstanceId) {
1138 return yield* Effect.die(
1139 new Error(
1140 `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,
1141 ),
1142 );
1144 if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
1145 overrides.resumeCursor = binding.resumeCursor;
1147 if (binding.runtimeMode !== undefined) {
1148 overrides.runtimeMode = binding.runtimeMode;
1150 sessions.push(Object.assign({}, session, overrides));
1152 return sessions;
1153 },
1154 );
1155​
1156 const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) =>
1157 registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));
1158​
1159 const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) =>
1160 registry.getInstanceInfo(instanceId);
1161​
1162 const assertConversationRollbackSupported: ProviderServiceMethod<"assertConversationRollbackSupported"> =
1163 Effect.fn("assertConversationRollbackSupported")(function* (threadId) {
1164 const routed = yield* resolveRoutableSession({
1165 threadId,
1166 operation: "ProviderService.assertConversationRollbackSupported",
1167 allowRecovery: false,
1168 });
1169 if (routed.adapter.capabilities.supportsConversationRollback === false) {
1170 return yield* toValidationError(
1171 "ProviderService.assertConversationRollbackSupported",
1172 `Provider '${routed.adapter.provider}' does not support conversation rewind.`,
1173 );
1175 });
1176​
1177 const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn(
1178 "rollbackConversation",
1179 )(function* (rawInput) {
1180 const input = yield* decodeInputOrValidationError({
1181 operation: "ProviderService.rollbackConversation",
1182 schema: ProviderRollbackConversationInput,
1183 payload: rawInput,
1184 });
1185 if (input.numTurns === 0) {
1186 return;
1188 let metricProvider = "unknown";
1189 return yield* Effect.gen(function* () {
1190 yield* assertConversationRollbackSupported(input.threadId);
1191 const routed = yield* resolveRoutableSession({
1192 threadId: input.threadId,
1193 operation: "ProviderService.rollbackConversation",
1194 allowRecovery: true,
1195 });
1196 metricProvider = routed.adapter.provider;
1197 yield* Effect.annotateCurrentSpan({
1198 "provider.operation": "rollback-conversation",
1199 "provider.kind": routed.adapter.provider,
1200 "provider.thread_id": input.threadId,
1201 "provider.rollback_turns": input.numTurns,
1202 });
1203 yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
1204 yield* analytics.record("provider.conversation.rolled_back", {
1205 provider: routed.adapter.provider,
1206 turns: input.numTurns,
1207 });
1208 }).pipe(
1209 withMetrics({
1210 counter: providerTurnsTotal,
1211 outcomeAttributes: () =>
1212 providerMetricAttributes(metricProvider, {
1213 operation: "rollback",
1214 }),
1215 }),
1216 );
1217 });
1218​
1219 const uploadFeedback: ProviderServiceMethod<"uploadFeedback"> = Effect.fn("uploadFeedback")(
1220 function* (rawInput) {
1221 const input = yield* decodeInputOrValidationError({
1222 operation: "ProviderService.uploadFeedback",
1223 schema: ProviderUploadFeedbackInput,
1224 payload: rawInput,
1225 });
1226 let routed = yield* resolveRoutableSession({
1227 threadId: input.threadId,
1228 operation: "ProviderService.uploadFeedback",
1229 allowRecovery: false,
1230 });
1231 if (routed.adapter.uploadFeedback === undefined) {
1232 return yield* toValidationError(
1233 "ProviderService.uploadFeedback",
1234 `Provider '${routed.adapter.provider}' does not support feedback uploads.`,
1235 );
1237 if (!routed.isActive) {
1238 routed = yield* resolveRoutableSession({
1239 threadId: input.threadId,
1240 operation: "ProviderService.uploadFeedback",
1241 allowRecovery: true,
1242 });
1244 const uploadFeedback = routed.adapter.uploadFeedback;
1245 if (uploadFeedback === undefined) {
1246 return yield* toValidationError(
1247 "ProviderService.uploadFeedback",
1248 `Provider '${routed.adapter.provider}' does not support feedback uploads.`,
1249 );
1251 yield* Effect.annotateCurrentSpan({
1252 "provider.operation": "upload-feedback",
1253 "provider.kind": routed.adapter.provider,
1254 "provider.thread_id": input.threadId,
1255 });
1256 return yield* uploadFeedback(input);
1257 },
1258 );
1259​
1260 const runStopAll = Effect.fn("runStopAll")(function* () {
1261 const threadIds = yield* directory.listThreadIds();
1262 const currentAdapters = yield* getAdapterEntries;
1263 const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
1264 adapter.listSessions().pipe(
1265 Effect.map((sessions) =>
1266 sessions.map((session) => ({
1267 ...session,
1268 providerInstanceId: instanceId,
1269 })),
1270 ),
1271 ),
1272 ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
1273 yield* Effect.forEach(activeSessions, (session) =>
1274 Effect.flatMap(nowIso, (lastRuntimeEventAt) =>
1275 upsertSessionBinding(session, session.threadId, {
1276 lastRuntimeEvent: "provider.stopAll",
1277 lastRuntimeEventAt,
1278 }),
1279 ),
1280 ).pipe(Effect.asVoid);
1281 yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
1282 yield* McpSessionRegistry.revokeAllActiveMcpCredentials();
1283 McpProviderSession.clearAllMcpProviderSessions();
1284 const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
1285 yield* Effect.forEach(bindings, (binding) =>
1286 Effect.gen(function* () {
1287 const providerInstanceId = dieOnMissingBindingInstanceId(
1288 "ProviderService.stopAll",
1289 binding,
1290 );
1291 return yield* directory.upsert({
1292 threadId: binding.threadId,
1293 provider: binding.provider,
1294 providerInstanceId,
1295 status: "stopped",
1296 runtimePayload: {
1297 activeTurnId: null,
1298 lastRuntimeEvent: "provider.stopAll",
1299 lastRuntimeEventAt: yield* nowIso,
1300 },
1301 });
1302 }),
1303 ).pipe(Effect.asVoid);
1304 yield* analytics.record("provider.sessions.stopped_all", {
1305 sessionCount: threadIds.length,
1306 });
1307 yield* analytics.flush;
1308 });
1309​
1310 yield* Effect.addFinalizer(() =>
1311 runStopAll().pipe(
1312 Effect.catchCause((cause) =>
1313 Effect.logWarning("failed to stop provider service", {
1314 errorTag: causeErrorTag(cause),
1315 }),
1316 ),
1317 ),
1318 );
1319​
1320 return {
1321 startSession,
1322 sendTurn,
1323 interruptTurn,
1324 respondToRequest,
1325 respondToUserInput,
1326 stopSession,
1327 listSessions,
1328 getCapabilities,
1329 getInstanceInfo,
1330 assertConversationRollbackSupported,
1331 rollbackConversation,
1332 uploadFeedback,
1333 // Each access creates a fresh PubSub subscription so that multiple
1334 // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
1335 // independently receive all runtime events.
1336 get streamEvents(): ProviderServiceMethod<"streamEvents"> {
1337 return Stream.fromPubSub(runtimeEventPubSub);
1338 },
1339 } satisfies ProviderService.ProviderService["Service"];
1340});
1341​
1342export const ProviderServiceLive = Layer.effect(
1343 ProviderService.ProviderService,
1344 makeProviderService(),
1346​
1347export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
1348 return Layer.effect(ProviderService.ProviderService, makeProviderService(options));