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

ProviderService.ts

1,314 lines49.6 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 increment(providerRuntimeEventsTotal, {
351 provider: canonicalEvent.provider,
352 eventType: canonicalEvent.type,
353 }).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))),
354 ),
355 );
356​
357 // `subscribedAdapters` is our source-of-truth for "which instance adapters
358 // are currently wired into the runtime event bus". It both tracks the set
359 // of live subscriptions (so `reconcileInstanceSubscriptions` can diff and
360 // fork only the *new* or *rebuilt* ones) and serves as the dynamic adapter
361 // list consumed by `stopStaleSessionsForThread`, `listSessions`, and
362 // `runStopAll` — replacing the pre-Slice-D startup snapshot so hot-added
363 // instances become visible to those call sites as soon as settings edits
364 // land.
365 const subscribedAdapters = yield* Ref.make(
366 new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>(),
367 );
368​
369 const getAdapterEntries = Ref.get(subscribedAdapters).pipe(
370 Effect.map((map) => Array.from(map.entries())),
371 );
372​
373 // Rebuild the map of id → adapter from the registry and fork a new event
374 // subscription for every instance that is either brand new or whose adapter
375 // identity changed (indicating the underlying `ProviderInstance` was torn
376 // down and rebuilt by `ProviderInstanceRegistry.reconcile`). Orphaned
377 // fibers for removed/replaced instances exit on their own because their
378 // adapter's `streamEvents` source terminates when the old scope closes.
379 const reconcileInstanceSubscriptions = Effect.gen(function* () {
380 const previous = yield* Ref.get(subscribedAdapters);
381 const currentIds = yield* registry.listInstances();
382 const next = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();
383 for (const id of currentIds) {
384 const adapterOption = yield* registry
385 .getByInstance(id)
386 .pipe(Effect.tapError(Effect.logWarning), Effect.option);
387 if (Option.isNone(adapterOption)) continue;
388 const adapter = adapterOption.value;
389 next.set(id, adapter);
390 if (previous.get(id) !== adapter) {
391 yield* Stream.runForEach(adapter.streamEvents, (event) =>
392 processRuntimeEvent(
393 {
394 instanceId: id,
395 provider: adapter.provider,
396 },
397 event,
398 ),
399 ).pipe(Effect.forkScoped);
400 }
401 }
402 yield* Ref.set(subscribedAdapters, next);
403 });
404​
405 const instanceChanges = yield* registry.subscribeChanges;
406 yield* reconcileInstanceSubscriptions;
407 yield* Stream.runForEach(
408 Stream.fromSubscription(instanceChanges),
409 () => reconcileInstanceSubscriptions,
410 ).pipe(Effect.forkScoped);
411​
412 const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
413 readonly binding: ProviderSessionDirectory.ProviderRuntimeBinding;
414 readonly operation: string;
415 }) {
416 const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding);
417 yield* Effect.annotateCurrentSpan({
418 "provider.operation": "recover-session",
419 "provider.kind": input.binding.provider,
420 "provider.instance_id": bindingInstanceId,
421 "provider.thread_id": input.binding.threadId,
422 });
423 return yield* Effect.gen(function* () {
424 const adapter = yield* registry.getByInstance(bindingInstanceId);
425 const hasResumeCursor =
426 input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
427 const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
428 if (hasActiveSession) {
429 const activeSessions = yield* adapter.listSessions();
430 const existing = activeSessions.find(
431 (session) => session.threadId === input.binding.threadId,
432 );
433 if (existing) {
434 yield* upsertSessionBinding(
435 { ...existing, providerInstanceId: bindingInstanceId },
436 input.binding.threadId,
437 );
438 yield* analytics.record("provider.session.recovered", {
439 provider: existing.provider,
440 strategy: "adopt-existing",
441 hasResumeCursor: existing.resumeCursor !== undefined,
442 });
443 return { adapter, session: existing } as const;
444 }
445 }
446​
447 if (!hasResumeCursor) {
448 return yield* toValidationError(
449 input.operation,
450 `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
451 );
452 }
453​
454 const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
455 const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
456​
457 yield* prepareMcpSession(input.binding.threadId, bindingInstanceId);
458 const resumed = yield* adapter
459 .startSession({
460 threadId: input.binding.threadId,
461 provider: input.binding.provider,
462 providerInstanceId: bindingInstanceId,
463 ...(persistedCwd ? { cwd: persistedCwd } : {}),
464 ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
465 ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
466 runtimeMode: input.binding.runtimeMode ?? "full-access",
467 })
468 .pipe(Effect.onError(() => clearMcpSession(input.binding.threadId)));
469 if (resumed.provider !== adapter.provider) {
470 yield* clearMcpSession(input.binding.threadId);
471 return yield* toValidationError(
472 input.operation,
473 `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
474 );
475 }
476​
477 yield* upsertSessionBinding(
478 { ...resumed, providerInstanceId: bindingInstanceId },
479 input.binding.threadId,
480 );
481 yield* analytics.record("provider.session.recovered", {
482 provider: resumed.provider,
483 strategy: "resume-thread",
484 hasResumeCursor: resumed.resumeCursor !== undefined,
485 });
486 return { adapter, session: resumed } as const;
487 }).pipe(
488 withMetrics({
489 counter: providerSessionsTotal,
490 attributes: providerMetricAttributes(input.binding.provider, {
491 operation: "recover",
492 }),
493 }),
494 );
495 });
496​
497 const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: {
498 readonly threadId: ThreadId;
499 readonly operation: string;
500 readonly allowRecovery: boolean;
501 }) {
502 const bindingOption = yield* directory.getBinding(input.threadId);
503 const binding = Option.getOrUndefined(bindingOption);
504 if (!binding) {
505 return yield* toValidationError(
506 input.operation,
507 `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
508 );
509 }
510 const instanceId = yield* requireBindingInstanceId(input.operation, binding);
511 const adapter = yield* registry.getByInstance(instanceId);
512​
513 const hasRequestedSession = yield* adapter.hasSession(input.threadId);
514 if (hasRequestedSession) {
515 return {
516 adapter,
517 instanceId,
518 threadId: input.threadId,
519 runtimeMode: binding.runtimeMode,
520 isActive: true,
521 } as const;
522 }
523​
524 if (!input.allowRecovery) {
525 return {
526 adapter,
527 instanceId,
528 threadId: input.threadId,
529 runtimeMode: binding.runtimeMode,
530 isActive: false,
531 } as const;
532 }
533​
534 const recovered = yield* recoverSessionForThread({
535 binding,
536 operation: input.operation,
537 });
538 return {
539 adapter: recovered.adapter,
540 instanceId,
541 threadId: input.threadId,
542 runtimeMode: recovered.session.runtimeMode,
543 isActive: true,
544 } as const;
545 });
546​
547 const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: {
548 readonly threadId: ThreadId;
549 readonly currentInstanceId: ProviderInstanceId;
550 }) {
551 const currentAdapters = yield* getAdapterEntries;
552 yield* Effect.forEach(
553 currentAdapters,
554 ([instanceId, adapter]) =>
555 instanceId === input.currentInstanceId
556 ? Effect.void
557 : Effect.gen(function* () {
558 const hasSession = yield* adapter.hasSession(input.threadId);
559 if (!hasSession) {
560 return;
561 }
562​
563 yield* adapter.stopSession(input.threadId).pipe(
564 Effect.tap(() =>
565 analytics.record("provider.session.stopped", {
566 provider: adapter.provider,
567 }),
568 ),
569 Effect.catchCause((cause) =>
570 Effect.logWarning("provider.session.stop-stale-failed", {
571 threadId: input.threadId,
572 provider: adapter.provider,
573 cause,
574 }),
575 ),
576 );
577 }),
578 { discard: true },
579 );
580 });
581​
582 const startSession: ProviderServiceMethod<"startSession"> = Effect.fn("startSession")(
583 function* (threadId, rawInput) {
584 const parsed = yield* decodeInputOrValidationError({
585 operation: "ProviderService.startSession",
586 schema: ProviderSessionStartInput,
587 payload: rawInput,
588 });
589​
590 const resolvedInstanceId = yield* requireBindingInstanceId(
591 "ProviderService.startSession",
592 parsed,
593 );
594 let metricProvider = parsed.provider ?? String(resolvedInstanceId);
595 yield* Effect.annotateCurrentSpan({
596 "provider.operation": "start-session",
597 "provider.instance_id": resolvedInstanceId,
598 "provider.thread_id": threadId,
599 "provider.runtime_mode": parsed.runtimeMode,
600 });
601 return yield* Effect.gen(function* () {
602 const instanceInfo = yield* registry.getInstanceInfo(resolvedInstanceId);
603 const resolvedProvider = instanceInfo.driverKind;
604 metricProvider = resolvedProvider;
605 if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) {
606 return yield* toValidationError(
607 "ProviderService.startSession",
608 `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
609 );
610 }
611 const input = {
612 ...parsed,
613 threadId,
614 provider: resolvedProvider,
615 };
616 if (!instanceInfo.enabled) {
617 return yield* toValidationError(
618 "ProviderService.startSession",
619 `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
620 );
621 }
622 const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
623 if (
624 persistedBinding?.provider === resolvedProvider &&
625 persistedBinding.providerInstanceId !== resolvedInstanceId &&
626 (input.resumeCursor != null || persistedBinding.resumeCursor != null)
627 ) {
628 const previousInstanceId = yield* requireBindingInstanceId(
629 "ProviderService.startSession",
630 persistedBinding,
631 );
632 const previousInfo = yield* registry.getInstanceInfo(previousInstanceId);
633 if (
634 previousInfo.continuationIdentity.continuationKey !==
635 instanceInfo.continuationIdentity.continuationKey
636 ) {
637 return yield* toValidationError(
638 "ProviderService.startSession",
639 `Thread '${threadId}' cannot switch from instance '${previousInstanceId}' to '${resolvedInstanceId}' because their provider resume state is incompatible.`,
640 );
641 }
642 }
643 const effectiveResumeCursor =
644 input.resumeCursor ??
645 (persistedBinding?.providerInstanceId === resolvedInstanceId
646 ? persistedBinding.resumeCursor
647 : undefined);
648 const effectiveCwd =
649 input.cwd ??
650 (persistedBinding?.providerInstanceId === resolvedInstanceId
651 ? readPersistedCwd(persistedBinding.runtimePayload)
652 : undefined);
653 yield* Effect.annotateCurrentSpan({
654 "provider.kind": resolvedProvider,
655 "provider.resume_cursor.source":
656 input.resumeCursor !== undefined
657 ? "request"
658 : effectiveResumeCursor !== undefined &&
659 persistedBinding?.providerInstanceId === resolvedInstanceId
660 ? "persisted"
661 : "none",
662 "provider.resume_cursor.present": effectiveResumeCursor !== undefined,
663 "provider.cwd.source":
664 input.cwd !== undefined
665 ? "request"
666 : effectiveCwd !== undefined &&
667 persistedBinding?.providerInstanceId === resolvedInstanceId
668 ? "persisted"
669 : "none",
670 "provider.cwd.effective": effectiveCwd ?? "",
671 });
672 const adapter = yield* registry.getByInstance(resolvedInstanceId);
673 yield* prepareMcpSession(threadId, resolvedInstanceId);
674 const session = yield* adapter
675 .startSession({
676 ...input,
677 providerInstanceId: resolvedInstanceId,
678 ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),
679 ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
680 })
681 .pipe(Effect.onError(() => clearMcpSession(threadId)));
682​
683 if (session.provider !== adapter.provider) {
684 yield* clearMcpSession(threadId);
685 return yield* toValidationError(
686 "ProviderService.startSession",
687 `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
688 );
689 }
690 const sessionWithInstance = {
691 ...session,
692 providerInstanceId: resolvedInstanceId,
693 };
694​
695 yield* stopStaleSessionsForThread({
696 threadId,
697 currentInstanceId: resolvedInstanceId,
698 });
699 yield* upsertSessionBinding(sessionWithInstance, threadId, {
700 modelSelection: input.modelSelection,
701 });
702 yield* analytics.record("provider.session.started", {
703 provider: sessionWithInstance.provider,
704 runtimeMode: input.runtimeMode,
705 hasResumeCursor: sessionWithInstance.resumeCursor !== undefined,
706 hasCwd: typeof effectiveCwd === "string" && effectiveCwd.trim().length > 0,
707 hasModel:
708 typeof input.modelSelection?.model === "string" &&
709 input.modelSelection.model.trim().length > 0,
710 });
711​
712 // Changing runtime mode restarts the session, so the transition is only
713 // observable here, by diffing against the mode the previous session for
714 // this thread was bound to. Recording it separately is what makes the
715 // "started supervised, switched to full access" funnel answerable.
716 const previousRuntimeMode = persistedBinding?.runtimeMode;
717 if (previousRuntimeMode !== undefined && previousRuntimeMode !== input.runtimeMode) {
718 yield* analytics.record("provider.runtime_mode.changed", {
719 provider: sessionWithInstance.provider,
720 from: previousRuntimeMode,
721 to: input.runtimeMode,
722 });
723 }
724​
725 return sessionWithInstance;
726 }).pipe(
727 withMetrics({
728 counter: providerSessionsTotal,
729 attributes: () =>
730 providerMetricAttributes(metricProvider, {
731 operation: "start",
732 }),
733 }),
734 );
735 },
736 );
737​
738 const sendTurn: ProviderServiceMethod<"sendTurn"> = Effect.fn("sendTurn")(function* (rawInput) {
739 const parsed = yield* decodeInputOrValidationError({
740 operation: "ProviderService.sendTurn",
741 schema: ProviderSendTurnInput,
742 payload: rawInput,
743 });
744​
745 const attachments = parsed.attachments ?? [];
746 if (!parsed.input && attachments.length === 0 && parsed.continuation !== true) {
747 return yield* toValidationError(
748 "ProviderService.sendTurn",
749 "Either input text or at least one attachment is required",
750 );
751 }
752​
753 const inputTextWithCitations =
754 parsed.input === undefined ? undefined : expandAssistantCitationsForProvider(parsed.input);
755 if (inputTextWithCitations !== parsed.input) {
756 yield* decodeInputOrValidationError({
757 operation: "ProviderService.sendTurn",
758 schema: ProviderSendTurnInput.fields.input,
759 payload: inputTextWithCitations,
760 });
761 }
762​
763 // Every attachment gets an on-disk path in the prompt so the model's tools
764 // can dereference the actual file. All attachments then go to the adapter,
765 // and each adapter decides what its provider ingests natively: OpenCode
766 // sends generic files as file parts, the others send images only and rely
767 // on the path line for everything else. Unresolvable ids are skipped here
768 // and surface as adapter errors when the file is read.
769 const attachmentPathLines = attachments.flatMap((attachment) => {
770 const attachmentPath = resolveAttachmentPath({
771 attachmentsDir: serverConfig.attachmentsDir,
772 attachment,
773 });
774 return attachmentPath === null
775 ? []
776 : [`[Attached ${attachment.type} "${attachment.name}" is saved at: ${attachmentPath}]`];
777 });
778 const inputTextWithAttachmentPaths =
779 attachmentPathLines.length === 0
780 ? inputTextWithCitations
781 : [inputTextWithCitations, attachmentPathLines.join("\n")]
782 .filter((part): part is string => typeof part === "string" && part.length > 0)
783 .join("\n\n");
784​
785 const input = {
786 ...parsed,
787 ...(inputTextWithAttachmentPaths !== undefined
788 ? { input: inputTextWithAttachmentPaths }
789 : {}),
790 };
791 yield* Effect.annotateCurrentSpan({
792 "provider.operation": "send-turn",
793 "provider.thread_id": input.threadId,
794 "provider.interaction_mode": input.interactionMode,
795 "provider.attachment_count": attachments.length,
796 });
797 let metricProvider = "unknown";
798 let metricModel = input.modelSelection?.model;
799 return yield* Effect.gen(function* () {
800 let routed = yield* resolveRoutableSession({
801 threadId: input.threadId,
802 operation: "ProviderService.sendTurn",
803 allowRecovery: false,
804 });
805 if (
806 input.continuation === true &&
807 !input.input &&
808 attachments.length === 0 &&
809 routed.adapter.capabilities.promptlessTurnContinuation !== true
810 ) {
811 return yield* toValidationError(
812 "ProviderService.sendTurn",
813 `Provider '${routed.adapter.provider}' requires an explicit continuation prompt`,
814 );
815 }
816 if (!routed.isActive) {
817 routed = yield* resolveRoutableSession({
818 threadId: input.threadId,
819 operation: "ProviderService.sendTurn",
820 allowRecovery: true,
821 });
822 }
823 metricProvider = routed.adapter.provider;
824 metricModel = input.modelSelection?.model;
825 yield* Effect.annotateCurrentSpan({
826 "provider.kind": routed.adapter.provider,
827 ...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
828 });
829 // A turn is the clearest sign a session is still alive. The MCP
830 // credential is minted once at session start and cannot be rotated into
831 // an already-spawned agent process, so we keep the existing token valid
832 // rather than issuing a new one: sessions that go a long time between
833 // browser tool calls used to lose the toolkit outright.
834 yield* McpSessionRegistry.touchActiveMcpThread(input.threadId);
835 const turn = yield* routed.adapter.sendTurn(input);
836 yield* directory.upsert({
837 threadId: input.threadId,
838 provider: routed.adapter.provider,
839 providerInstanceId: routed.instanceId,
840 status: "running",
841 ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
842 runtimePayload: {
843 ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
844 activeTurnId: turn.turnId,
845 lastRuntimeEvent: "provider.sendTurn",
846 lastRuntimeEventAt: yield* nowIso,
847 },
848 });
849 yield* analytics.record("provider.turn.sent", {
850 provider: routed.adapter.provider,
851 model: input.modelSelection?.model,
852 interactionMode: input.interactionMode,
853 // Session-start events alone skew runtime mode toward users who toggle
854 // often, since every toggle restarts the session. Recording it per turn
855 // gives a usage-weighted view and lets it cross with interactionMode.
856 runtimeMode: routed.runtimeMode,
857 attachmentCount: attachments.length,
858 hasInput: typeof input.input === "string" && input.input.trim().length > 0,
859 });
860 return turn;
861 }).pipe(
862 withMetrics({
863 counter: providerTurnsTotal,
864 timer: providerTurnDuration,
865 attributes: () =>
866 providerTurnMetricAttributes({
867 provider: metricProvider,
868 model: metricModel,
869 extra: {
870 operation: "send",
871 },
872 }),
873 }),
874 );
875 });
876​
877 const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(
878 function* (rawInput) {
879 const input = yield* decodeInputOrValidationError({
880 operation: "ProviderService.interruptTurn",
881 schema: ProviderInterruptTurnInput,
882 payload: rawInput,
883 });
884 let metricProvider = "unknown";
885 return yield* Effect.gen(function* () {
886 const routed = yield* resolveRoutableSession({
887 threadId: input.threadId,
888 operation: "ProviderService.interruptTurn",
889 allowRecovery: true,
890 });
891 metricProvider = routed.adapter.provider;
892 yield* Effect.annotateCurrentSpan({
893 "provider.operation": "interrupt-turn",
894 "provider.kind": routed.adapter.provider,
895 "provider.thread_id": input.threadId,
896 "provider.turn_id": input.turnId,
897 });
898 yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
899 yield* analytics.record("provider.turn.interrupted", {
900 provider: routed.adapter.provider,
901 });
902 }).pipe(
903 withMetrics({
904 counter: providerTurnsTotal,
905 outcomeAttributes: () =>
906 providerMetricAttributes(metricProvider, {
907 operation: "interrupt",
908 }),
909 }),
910 );
911 },
912 );
913​
914 const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")(
915 function* (rawInput) {
916 const input = yield* decodeInputOrValidationError({
917 operation: "ProviderService.respondToRequest",
918 schema: ProviderRespondToRequestInput,
919 payload: rawInput,
920 });
921 let metricProvider = "unknown";
922 return yield* Effect.gen(function* () {
923 const routed = yield* resolveRoutableSession({
924 threadId: input.threadId,
925 operation: "ProviderService.respondToRequest",
926 allowRecovery: true,
927 });
928 metricProvider = routed.adapter.provider;
929 yield* Effect.annotateCurrentSpan({
930 "provider.operation": "respond-to-request",
931 "provider.kind": routed.adapter.provider,
932 "provider.thread_id": input.threadId,
933 "provider.request_id": input.requestId,
934 });
935 yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
936 yield* analytics.record("provider.request.responded", {
937 provider: routed.adapter.provider,
938 decision: input.decision,
939 });
940 }).pipe(
941 withMetrics({
942 counter: providerTurnsTotal,
943 outcomeAttributes: () =>
944 providerMetricAttributes(metricProvider, {
945 operation: "approval-response",
946 }),
947 }),
948 );
949 },
950 );
951​
952 const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn(
953 "respondToUserInput",
954 )(function* (rawInput) {
955 const input = yield* decodeInputOrValidationError({
956 operation: "ProviderService.respondToUserInput",
957 schema: ProviderRespondToUserInputInput,
958 payload: rawInput,
959 });
960 let metricProvider = "unknown";
961 return yield* Effect.gen(function* () {
962 const routed = yield* resolveRoutableSession({
963 threadId: input.threadId,
964 operation: "ProviderService.respondToUserInput",
965 allowRecovery: true,
966 });
967 metricProvider = routed.adapter.provider;
968 yield* Effect.annotateCurrentSpan({
969 "provider.operation": "respond-to-user-input",
970 "provider.kind": routed.adapter.provider,
971 "provider.thread_id": input.threadId,
972 "provider.request_id": input.requestId,
973 });
974 yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
975 }).pipe(
976 withMetrics({
977 counter: providerTurnsTotal,
978 outcomeAttributes: () =>
979 providerMetricAttributes(metricProvider, {
980 operation: "user-input-response",
981 }),
982 }),
983 );
984 });
985​
986 const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")(
987 function* (rawInput) {
988 const input = yield* decodeInputOrValidationError({
989 operation: "ProviderService.stopSession",
990 schema: ProviderStopSessionInput,
991 payload: rawInput,
992 });
993 let metricProvider = "unknown";
994 return yield* Effect.gen(function* () {
995 const routed = yield* resolveRoutableSession({
996 threadId: input.threadId,
997 operation: "ProviderService.stopSession",
998 allowRecovery: false,
999 });
1000 metricProvider = routed.adapter.provider;
1001 yield* Effect.annotateCurrentSpan({
1002 "provider.operation": "stop-session",
1003 "provider.kind": routed.adapter.provider,
1004 "provider.thread_id": input.threadId,
1005 });
1006 if (routed.isActive) {
1007 yield* routed.adapter.stopSession(routed.threadId);
1009 yield* clearMcpSession(input.threadId);
1010 yield* directory.upsert({
1011 threadId: input.threadId,
1012 provider: routed.adapter.provider,
1013 providerInstanceId: routed.instanceId,
1014 status: "stopped",
1015 runtimePayload: {
1016 activeTurnId: null,
1017 },
1018 });
1019 yield* analytics.record("provider.session.stopped", {
1020 provider: routed.adapter.provider,
1021 });
1022 }).pipe(
1023 withMetrics({
1024 counter: providerSessionsTotal,
1025 outcomeAttributes: () =>
1026 providerMetricAttributes(metricProvider, {
1027 operation: "stop",
1028 }),
1029 }),
1030 );
1031 },
1032 );
1033​
1034 const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")(
1035 function* () {
1036 const currentAdapters = yield* getAdapterEntries;
1037 const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
1038 adapter.listSessions().pipe(
1039 Effect.map((sessions) =>
1040 sessions.map((session) => ({
1041 ...session,
1042 providerInstanceId: instanceId,
1043 })),
1044 ),
1045 ),
1046 );
1047 const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
1048 // Only live adapter sessions appear in this response. Resolving every
1049 // historical binding here makes each call scale with the full thread
1050 // history instead of the active session set.
1051 const persistedBindings = yield* Effect.forEach(
1052 [...new Set(activeSessions.map((session) => session.threadId))],
1053 (threadId) =>
1054 directory
1055 .getBinding(threadId)
1056 .pipe(
1057 Effect.orElseSucceed(() =>
1058 Option.none<ProviderSessionDirectory.ProviderRuntimeBinding>(),
1059 ),
1060 ),
1061 { concurrency: "unbounded" },
1062 ).pipe(
1063 Effect.orElseSucceed(
1064 () => [] as Array<Option.Option<ProviderSessionDirectory.ProviderRuntimeBinding>>,
1065 ),
1066 );
1067 const bindingsByThreadId = new Map<
1068 ThreadId,
1069 ProviderSessionDirectory.ProviderRuntimeBinding
1070 >();
1071 for (const bindingOption of persistedBindings) {
1072 const binding = Option.getOrUndefined(bindingOption);
1073 if (binding) {
1074 bindingsByThreadId.set(binding.threadId, binding);
1077​
1078 const sessions: ProviderSession[] = [];
1079 for (const session of activeSessions) {
1080 const binding = bindingsByThreadId.get(session.threadId);
1081 if (!binding) {
1082 sessions.push(session);
1083 continue;
1085​
1086 const overrides: {
1087 resumeCursor?: ProviderSession["resumeCursor"];
1088 runtimeMode?: ProviderSession["runtimeMode"];
1089 providerInstanceId?: ProviderSession["providerInstanceId"];
1090 } = {};
1091 overrides.providerInstanceId = dieOnMissingBindingInstanceId(
1092 "ProviderService.listSessions",
1093 binding,
1094 );
1095 if (binding.provider !== session.provider) {
1096 return yield* Effect.die(
1097 new Error(
1098 `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,
1099 ),
1100 );
1102 if (overrides.providerInstanceId !== session.providerInstanceId) {
1103 return yield* Effect.die(
1104 new Error(
1105 `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,
1106 ),
1107 );
1109 if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
1110 overrides.resumeCursor = binding.resumeCursor;
1112 if (binding.runtimeMode !== undefined) {
1113 overrides.runtimeMode = binding.runtimeMode;
1115 sessions.push(Object.assign({}, session, overrides));
1117 return sessions;
1118 },
1119 );
1120​
1121 const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) =>
1122 registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));
1123​
1124 const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) =>
1125 registry.getInstanceInfo(instanceId);
1126​
1127 const assertConversationRollbackSupported: ProviderServiceMethod<"assertConversationRollbackSupported"> =
1128 Effect.fn("assertConversationRollbackSupported")(function* (threadId) {
1129 const routed = yield* resolveRoutableSession({
1130 threadId,
1131 operation: "ProviderService.assertConversationRollbackSupported",
1132 allowRecovery: false,
1133 });
1134 if (routed.adapter.capabilities.supportsConversationRollback === false) {
1135 return yield* toValidationError(
1136 "ProviderService.assertConversationRollbackSupported",
1137 `Provider '${routed.adapter.provider}' does not support conversation rewind.`,
1138 );
1140 });
1141​
1142 const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn(
1143 "rollbackConversation",
1144 )(function* (rawInput) {
1145 const input = yield* decodeInputOrValidationError({
1146 operation: "ProviderService.rollbackConversation",
1147 schema: ProviderRollbackConversationInput,
1148 payload: rawInput,
1149 });
1150 if (input.numTurns === 0) {
1151 return;
1153 let metricProvider = "unknown";
1154 return yield* Effect.gen(function* () {
1155 yield* assertConversationRollbackSupported(input.threadId);
1156 const routed = yield* resolveRoutableSession({
1157 threadId: input.threadId,
1158 operation: "ProviderService.rollbackConversation",
1159 allowRecovery: true,
1160 });
1161 metricProvider = routed.adapter.provider;
1162 yield* Effect.annotateCurrentSpan({
1163 "provider.operation": "rollback-conversation",
1164 "provider.kind": routed.adapter.provider,
1165 "provider.thread_id": input.threadId,
1166 "provider.rollback_turns": input.numTurns,
1167 });
1168 yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
1169 yield* analytics.record("provider.conversation.rolled_back", {
1170 provider: routed.adapter.provider,
1171 turns: input.numTurns,
1172 });
1173 }).pipe(
1174 withMetrics({
1175 counter: providerTurnsTotal,
1176 outcomeAttributes: () =>
1177 providerMetricAttributes(metricProvider, {
1178 operation: "rollback",
1179 }),
1180 }),
1181 );
1182 });
1183​
1184 const uploadFeedback: ProviderServiceMethod<"uploadFeedback"> = Effect.fn("uploadFeedback")(
1185 function* (rawInput) {
1186 const input = yield* decodeInputOrValidationError({
1187 operation: "ProviderService.uploadFeedback",
1188 schema: ProviderUploadFeedbackInput,
1189 payload: rawInput,
1190 });
1191 let routed = yield* resolveRoutableSession({
1192 threadId: input.threadId,
1193 operation: "ProviderService.uploadFeedback",
1194 allowRecovery: false,
1195 });
1196 if (routed.adapter.uploadFeedback === undefined) {
1197 return yield* toValidationError(
1198 "ProviderService.uploadFeedback",
1199 `Provider '${routed.adapter.provider}' does not support feedback uploads.`,
1200 );
1202 if (!routed.isActive) {
1203 routed = yield* resolveRoutableSession({
1204 threadId: input.threadId,
1205 operation: "ProviderService.uploadFeedback",
1206 allowRecovery: true,
1207 });
1209 const uploadFeedback = routed.adapter.uploadFeedback;
1210 if (uploadFeedback === undefined) {
1211 return yield* toValidationError(
1212 "ProviderService.uploadFeedback",
1213 `Provider '${routed.adapter.provider}' does not support feedback uploads.`,
1214 );
1216 yield* Effect.annotateCurrentSpan({
1217 "provider.operation": "upload-feedback",
1218 "provider.kind": routed.adapter.provider,
1219 "provider.thread_id": input.threadId,
1220 });
1221 return yield* uploadFeedback(input);
1222 },
1223 );
1224​
1225 const runStopAll = Effect.fn("runStopAll")(function* () {
1226 const threadIds = yield* directory.listThreadIds();
1227 const currentAdapters = yield* getAdapterEntries;
1228 const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
1229 adapter.listSessions().pipe(
1230 Effect.map((sessions) =>
1231 sessions.map((session) => ({
1232 ...session,
1233 providerInstanceId: instanceId,
1234 })),
1235 ),
1236 ),
1237 ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
1238 yield* Effect.forEach(activeSessions, (session) =>
1239 Effect.flatMap(nowIso, (lastRuntimeEventAt) =>
1240 upsertSessionBinding(session, session.threadId, {
1241 lastRuntimeEvent: "provider.stopAll",
1242 lastRuntimeEventAt,
1243 }),
1244 ),
1245 ).pipe(Effect.asVoid);
1246 yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
1247 yield* McpSessionRegistry.revokeAllActiveMcpCredentials();
1248 McpProviderSession.clearAllMcpProviderSessions();
1249 const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
1250 yield* Effect.forEach(bindings, (binding) =>
1251 Effect.gen(function* () {
1252 const providerInstanceId = dieOnMissingBindingInstanceId(
1253 "ProviderService.stopAll",
1254 binding,
1255 );
1256 return yield* directory.upsert({
1257 threadId: binding.threadId,
1258 provider: binding.provider,
1259 providerInstanceId,
1260 status: "stopped",
1261 runtimePayload: {
1262 activeTurnId: null,
1263 lastRuntimeEvent: "provider.stopAll",
1264 lastRuntimeEventAt: yield* nowIso,
1265 },
1266 });
1267 }),
1268 ).pipe(Effect.asVoid);
1269 yield* analytics.record("provider.sessions.stopped_all", {
1270 sessionCount: threadIds.length,
1271 });
1272 yield* analytics.flush;
1273 });
1274​
1275 yield* Effect.addFinalizer(() =>
1276 runStopAll().pipe(
1277 Effect.catchCause((cause) =>
1278 Effect.logWarning("failed to stop provider service", {
1279 errorTag: causeErrorTag(cause),
1280 }),
1281 ),
1282 ),
1283 );
1284​
1285 return {
1286 startSession,
1287 sendTurn,
1288 interruptTurn,
1289 respondToRequest,
1290 respondToUserInput,
1291 stopSession,
1292 listSessions,
1293 getCapabilities,
1294 getInstanceInfo,
1295 assertConversationRollbackSupported,
1296 rollbackConversation,
1297 uploadFeedback,
1298 // Each access creates a fresh PubSub subscription so that multiple
1299 // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
1300 // independently receive all runtime events.
1301 get streamEvents(): ProviderServiceMethod<"streamEvents"> {
1302 return Stream.fromPubSub(runtimeEventPubSub);
1303 },
1304 } satisfies ProviderService.ProviderService["Service"];
1305});
1306​
1307export const ProviderServiceLive = Layer.effect(
1308 ProviderService.ProviderService,
1309 makeProviderService(),
1311​
1312export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
1313 return Layer.effect(ProviderService.ProviderService, makeProviderService(options));