Open History to see the last commit
1/**
2 * ProviderServiceLive - Cross-provider orchestration layer.
3 *
4 * Routes validated transport/API calls to provider adapters through
5 * `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a
6 * unified provider event stream for subscribers.
7 *
8 * It does not implement provider protocol details (adapter concern).
9 *
10 * @module ProviderServiceLive
11 */
12import {
13 ModelSelection,
14 NonNegativeInt,
15 ThreadId,
16 ProviderInterruptTurnInput,
17 ProviderRespondToRequestInput,
18 ProviderRespondToUserInputInput,
19 ProviderSendTurnInput,
20 ProviderSessionStartInput,
21 ProviderStopSessionInput,
22 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;
81}
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 });
101}
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 }
134}
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 };
155}
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;
165}
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;
177}
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 const effectiveResumeCursor =
624 input.resumeCursor ??
625 (persistedBinding?.providerInstanceId === resolvedInstanceId
626 ? persistedBinding.resumeCursor
627 : undefined);
628 const effectiveCwd =
629 input.cwd ??
630 (persistedBinding?.providerInstanceId === resolvedInstanceId
631 ? readPersistedCwd(persistedBinding.runtimePayload)
632 : undefined);
633 yield* Effect.annotateCurrentSpan({
634 "provider.kind": resolvedProvider,
635 "provider.resume_cursor.source":
636 input.resumeCursor !== undefined
637 ? "request"
638 : effectiveResumeCursor !== undefined &&
639 persistedBinding?.providerInstanceId === resolvedInstanceId
640 ? "persisted"
641 : "none",
642 "provider.resume_cursor.present": effectiveResumeCursor !== undefined,
643 "provider.cwd.source":
644 input.cwd !== undefined
645 ? "request"
646 : effectiveCwd !== undefined &&
647 persistedBinding?.providerInstanceId === resolvedInstanceId
648 ? "persisted"
649 : "none",
650 "provider.cwd.effective": effectiveCwd ?? "",
651 });
652 const adapter = yield* registry.getByInstance(resolvedInstanceId);
653 yield* prepareMcpSession(threadId, resolvedInstanceId);
654 const session = yield* adapter
655 .startSession({
656 ...input,
657 providerInstanceId: resolvedInstanceId,
658 ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),
659 ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
660 })
661 .pipe(Effect.onError(() => clearMcpSession(threadId)));
662
663 if (session.provider !== adapter.provider) {
664 yield* clearMcpSession(threadId);
665 return yield* toValidationError(
666 "ProviderService.startSession",
667 `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
668 );
669 }
670 const sessionWithInstance = {
671 ...session,
672 providerInstanceId: resolvedInstanceId,
673 };
674
675 yield* stopStaleSessionsForThread({
676 threadId,
677 currentInstanceId: resolvedInstanceId,
678 });
679 yield* upsertSessionBinding(sessionWithInstance, threadId, {
680 modelSelection: input.modelSelection,
681 });
682 yield* analytics.record("provider.session.started", {
683 provider: sessionWithInstance.provider,
684 runtimeMode: input.runtimeMode,
685 hasResumeCursor: sessionWithInstance.resumeCursor !== undefined,
686 hasCwd: typeof effectiveCwd === "string" && effectiveCwd.trim().length > 0,
687 hasModel:
688 typeof input.modelSelection?.model === "string" &&
689 input.modelSelection.model.trim().length > 0,
690 });
691
692 // Changing runtime mode restarts the session, so the transition is only
693 // observable here, by diffing against the mode the previous session for
694 // this thread was bound to. Recording it separately is what makes the
695 // "started supervised, switched to full access" funnel answerable.
696 const previousRuntimeMode = persistedBinding?.runtimeMode;
697 if (previousRuntimeMode !== undefined && previousRuntimeMode !== input.runtimeMode) {
698 yield* analytics.record("provider.runtime_mode.changed", {
699 provider: sessionWithInstance.provider,
700 from: previousRuntimeMode,
701 to: input.runtimeMode,
702 });
703 }
704
705 return sessionWithInstance;
706 }).pipe(
707 withMetrics({
708 counter: providerSessionsTotal,
709 attributes: () =>
710 providerMetricAttributes(metricProvider, {
711 operation: "start",
712 }),
713 }),
714 );
715 },
716 );
717
718 const sendTurn: ProviderServiceMethod<"sendTurn"> = Effect.fn("sendTurn")(function* (rawInput) {
719 const parsed = yield* decodeInputOrValidationError({
720 operation: "ProviderService.sendTurn",
721 schema: ProviderSendTurnInput,
722 payload: rawInput,
723 });
724
725 const attachments = parsed.attachments ?? [];
726 if (!parsed.input && attachments.length === 0) {
727 return yield* toValidationError(
728 "ProviderService.sendTurn",
729 "Either input text or at least one attachment is required",
730 );
731 }
732
733 const inputTextWithCitations =
734 parsed.input === undefined ? undefined : expandAssistantCitationsForProvider(parsed.input);
735 if (inputTextWithCitations !== parsed.input) {
736 yield* decodeInputOrValidationError({
737 operation: "ProviderService.sendTurn",
738 schema: ProviderSendTurnInput.fields.input,
739 payload: inputTextWithCitations,
740 });
741 }
742
743 // Every attachment gets an on-disk path in the prompt so the model's tools
744 // can dereference the actual file. All attachments then go to the adapter,
745 // and each adapter decides what its provider ingests natively: OpenCode
746 // sends generic files as file parts, the others send images only and rely
747 // on the path line for everything else. Unresolvable ids are skipped here
748 // and surface as adapter errors when the file is read.
749 const attachmentPathLines = attachments.flatMap((attachment) => {
750 const attachmentPath = resolveAttachmentPath({
751 attachmentsDir: serverConfig.attachmentsDir,
752 attachment,
753 });
754 return attachmentPath === null
755 ? []
756 : [`[Attached ${attachment.type} "${attachment.name}" is saved at: ${attachmentPath}]`];
757 });
758 const inputTextWithAttachmentPaths =
759 attachmentPathLines.length === 0
760 ? inputTextWithCitations
761 : [inputTextWithCitations, attachmentPathLines.join("\n")]
762 .filter((part): part is string => typeof part === "string" && part.length > 0)
763 .join("\n\n");
764
765 const input = {
766 ...parsed,
767 ...(inputTextWithAttachmentPaths !== undefined
768 ? { input: inputTextWithAttachmentPaths }
769 : {}),
770 };
771 yield* Effect.annotateCurrentSpan({
772 "provider.operation": "send-turn",
773 "provider.thread_id": input.threadId,
774 "provider.interaction_mode": input.interactionMode,
775 "provider.attachment_count": attachments.length,
776 });
777 let metricProvider = "unknown";
778 let metricModel = input.modelSelection?.model;
779 return yield* Effect.gen(function* () {
780 const routed = yield* resolveRoutableSession({
781 threadId: input.threadId,
782 operation: "ProviderService.sendTurn",
783 allowRecovery: true,
784 });
785 metricProvider = routed.adapter.provider;
786 metricModel = input.modelSelection?.model;
787 yield* Effect.annotateCurrentSpan({
788 "provider.kind": routed.adapter.provider,
789 ...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
790 });
791 // A turn is the clearest sign a session is still alive. The MCP
792 // credential is minted once at session start and cannot be rotated into
793 // an already-spawned agent process, so we keep the existing token valid
794 // rather than issuing a new one: sessions that go a long time between
795 // browser tool calls used to lose the toolkit outright.
796 yield* McpSessionRegistry.touchActiveMcpThread(input.threadId);
797 const turn = yield* routed.adapter.sendTurn(input);
798 yield* directory.upsert({
799 threadId: input.threadId,
800 provider: routed.adapter.provider,
801 providerInstanceId: routed.instanceId,
802 status: "running",
803 ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
804 runtimePayload: {
805 ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
806 activeTurnId: turn.turnId,
807 lastRuntimeEvent: "provider.sendTurn",
808 lastRuntimeEventAt: yield* nowIso,
809 },
810 });
811 yield* analytics.record("provider.turn.sent", {
812 provider: routed.adapter.provider,
813 model: input.modelSelection?.model,
814 interactionMode: input.interactionMode,
815 // Session-start events alone skew runtime mode toward users who toggle
816 // often, since every toggle restarts the session. Recording it per turn
817 // gives a usage-weighted view and lets it cross with interactionMode.
818 runtimeMode: routed.runtimeMode,
819 attachmentCount: attachments.length,
820 hasInput: typeof input.input === "string" && input.input.trim().length > 0,
821 });
822 return turn;
823 }).pipe(
824 withMetrics({
825 counter: providerTurnsTotal,
826 timer: providerTurnDuration,
827 attributes: () =>
828 providerTurnMetricAttributes({
829 provider: metricProvider,
830 model: metricModel,
831 extra: {
832 operation: "send",
833 },
834 }),
835 }),
836 );
837 });
838
839 const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(
840 function* (rawInput) {
841 const input = yield* decodeInputOrValidationError({
842 operation: "ProviderService.interruptTurn",
843 schema: ProviderInterruptTurnInput,
844 payload: rawInput,
845 });
846 let metricProvider = "unknown";
847 return yield* Effect.gen(function* () {
848 const routed = yield* resolveRoutableSession({
849 threadId: input.threadId,
850 operation: "ProviderService.interruptTurn",
851 allowRecovery: true,
852 });
853 metricProvider = routed.adapter.provider;
854 yield* Effect.annotateCurrentSpan({
855 "provider.operation": "interrupt-turn",
856 "provider.kind": routed.adapter.provider,
857 "provider.thread_id": input.threadId,
858 "provider.turn_id": input.turnId,
859 });
860 yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
861 yield* analytics.record("provider.turn.interrupted", {
862 provider: routed.adapter.provider,
863 });
864 }).pipe(
865 withMetrics({
866 counter: providerTurnsTotal,
867 outcomeAttributes: () =>
868 providerMetricAttributes(metricProvider, {
869 operation: "interrupt",
870 }),
871 }),
872 );
873 },
874 );
875
876 const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")(
877 function* (rawInput) {
878 const input = yield* decodeInputOrValidationError({
879 operation: "ProviderService.respondToRequest",
880 schema: ProviderRespondToRequestInput,
881 payload: rawInput,
882 });
883 let metricProvider = "unknown";
884 return yield* Effect.gen(function* () {
885 const routed = yield* resolveRoutableSession({
886 threadId: input.threadId,
887 operation: "ProviderService.respondToRequest",
888 allowRecovery: true,
889 });
890 metricProvider = routed.adapter.provider;
891 yield* Effect.annotateCurrentSpan({
892 "provider.operation": "respond-to-request",
893 "provider.kind": routed.adapter.provider,
894 "provider.thread_id": input.threadId,
895 "provider.request_id": input.requestId,
896 });
897 yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
898 yield* analytics.record("provider.request.responded", {
899 provider: routed.adapter.provider,
900 decision: input.decision,
901 });
902 }).pipe(
903 withMetrics({
904 counter: providerTurnsTotal,
905 outcomeAttributes: () =>
906 providerMetricAttributes(metricProvider, {
907 operation: "approval-response",
908 }),
909 }),
910 );
911 },
912 );
913
914 const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn(
915 "respondToUserInput",
916 )(function* (rawInput) {
917 const input = yield* decodeInputOrValidationError({
918 operation: "ProviderService.respondToUserInput",
919 schema: ProviderRespondToUserInputInput,
920 payload: rawInput,
921 });
922 let metricProvider = "unknown";
923 return yield* Effect.gen(function* () {
924 const routed = yield* resolveRoutableSession({
925 threadId: input.threadId,
926 operation: "ProviderService.respondToUserInput",
927 allowRecovery: true,
928 });
929 metricProvider = routed.adapter.provider;
930 yield* Effect.annotateCurrentSpan({
931 "provider.operation": "respond-to-user-input",
932 "provider.kind": routed.adapter.provider,
933 "provider.thread_id": input.threadId,
934 "provider.request_id": input.requestId,
935 });
936 yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
937 }).pipe(
938 withMetrics({
939 counter: providerTurnsTotal,
940 outcomeAttributes: () =>
941 providerMetricAttributes(metricProvider, {
942 operation: "user-input-response",
943 }),
944 }),
945 );
946 });
947
948 const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")(
949 function* (rawInput) {
950 const input = yield* decodeInputOrValidationError({
951 operation: "ProviderService.stopSession",
952 schema: ProviderStopSessionInput,
953 payload: rawInput,
954 });
955 let metricProvider = "unknown";
956 return yield* Effect.gen(function* () {
957 const routed = yield* resolveRoutableSession({
958 threadId: input.threadId,
959 operation: "ProviderService.stopSession",
960 allowRecovery: false,
961 });
962 metricProvider = routed.adapter.provider;
963 yield* Effect.annotateCurrentSpan({
964 "provider.operation": "stop-session",
965 "provider.kind": routed.adapter.provider,
966 "provider.thread_id": input.threadId,
967 });
968 if (routed.isActive) {
969 yield* routed.adapter.stopSession(routed.threadId);
970 }
971 yield* clearMcpSession(input.threadId);
972 yield* directory.upsert({
973 threadId: input.threadId,
974 provider: routed.adapter.provider,
975 providerInstanceId: routed.instanceId,
976 status: "stopped",
977 runtimePayload: {
978 activeTurnId: null,
979 },
980 });
981 yield* analytics.record("provider.session.stopped", {
982 provider: routed.adapter.provider,
983 });
984 }).pipe(
985 withMetrics({
986 counter: providerSessionsTotal,
987 outcomeAttributes: () =>
988 providerMetricAttributes(metricProvider, {
989 operation: "stop",
990 }),
991 }),
992 );
993 },
994 );
995
996 const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")(
997 function* () {
998 const currentAdapters = yield* getAdapterEntries;
999 const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
1000 adapter.listSessions().pipe(
1001 Effect.map((sessions) =>
1002 sessions.map((session) => ({
1003 ...session,
1004 providerInstanceId: instanceId,
1005 })),
1006 ),
1007 ),
1008 );
1009 const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
1010 // Only live adapter sessions appear in this response. Resolving every
1011 // historical binding here makes each call scale with the full thread
1012 // history instead of the active session set.
1013 const persistedBindings = yield* Effect.forEach(
1014 [...new Set(activeSessions.map((session) => session.threadId))],
1015 (threadId) =>
1016 directory
1017 .getBinding(threadId)
1018 .pipe(
1019 Effect.orElseSucceed(() =>
1020 Option.none<ProviderSessionDirectory.ProviderRuntimeBinding>(),
1021 ),
1022 ),
1023 { concurrency: "unbounded" },
1024 ).pipe(
1025 Effect.orElseSucceed(
1026 () => [] as Array<Option.Option<ProviderSessionDirectory.ProviderRuntimeBinding>>,
1027 ),
1028 );
1029 const bindingsByThreadId = new Map<
1030 ThreadId,
1031 ProviderSessionDirectory.ProviderRuntimeBinding
1032 >();
1033 for (const bindingOption of persistedBindings) {
1034 const binding = Option.getOrUndefined(bindingOption);
1035 if (binding) {
1036 bindingsByThreadId.set(binding.threadId, binding);
1037 }
1038 }
1039
1040 const sessions: ProviderSession[] = [];
1041 for (const session of activeSessions) {
1042 const binding = bindingsByThreadId.get(session.threadId);
1043 if (!binding) {
1044 sessions.push(session);
1045 continue;
1046 }
1047
1048 const overrides: {
1049 resumeCursor?: ProviderSession["resumeCursor"];
1050 runtimeMode?: ProviderSession["runtimeMode"];
1051 providerInstanceId?: ProviderSession["providerInstanceId"];
1052 } = {};
1053 overrides.providerInstanceId = dieOnMissingBindingInstanceId(
1054 "ProviderService.listSessions",
1055 binding,
1056 );
1057 if (binding.provider !== session.provider) {
1058 return yield* Effect.die(
1059 new Error(
1060 `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,
1061 ),
1062 );
1063 }
1064 if (overrides.providerInstanceId !== session.providerInstanceId) {
1065 return yield* Effect.die(
1066 new Error(
1067 `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,
1068 ),
1069 );
1070 }
1071 if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
1072 overrides.resumeCursor = binding.resumeCursor;
1073 }
1074 if (binding.runtimeMode !== undefined) {
1075 overrides.runtimeMode = binding.runtimeMode;
1076 }
1077 sessions.push(Object.assign({}, session, overrides));
1078 }
1079 return sessions;
1080 },
1081 );
1082
1083 const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) =>
1084 registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));
1085
1086 const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) =>
1087 registry.getInstanceInfo(instanceId);
1088
1089 const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn(
1090 "rollbackConversation",
1091 )(function* (rawInput) {
1092 const input = yield* decodeInputOrValidationError({
1093 operation: "ProviderService.rollbackConversation",
1094 schema: ProviderRollbackConversationInput,
1095 payload: rawInput,
1096 });
1097 if (input.numTurns === 0) {
1098 return;
1099 }
1100 let metricProvider = "unknown";
1101 return yield* Effect.gen(function* () {
1102 const routed = yield* resolveRoutableSession({
1103 threadId: input.threadId,
1104 operation: "ProviderService.rollbackConversation",
1105 allowRecovery: true,
1106 });
1107 metricProvider = routed.adapter.provider;
1108 yield* Effect.annotateCurrentSpan({
1109 "provider.operation": "rollback-conversation",
1110 "provider.kind": routed.adapter.provider,
1111 "provider.thread_id": input.threadId,
1112 "provider.rollback_turns": input.numTurns,
1113 });
1114 yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
1115 yield* analytics.record("provider.conversation.rolled_back", {
1116 provider: routed.adapter.provider,
1117 turns: input.numTurns,
1118 });
1119 }).pipe(
1120 withMetrics({
1121 counter: providerTurnsTotal,
1122 outcomeAttributes: () =>
1123 providerMetricAttributes(metricProvider, {
1124 operation: "rollback",
1125 }),
1126 }),
1127 );
1128 });
1129
1130 const uploadFeedback: ProviderServiceMethod<"uploadFeedback"> = Effect.fn("uploadFeedback")(
1131 function* (rawInput) {
1132 const input = yield* decodeInputOrValidationError({
1133 operation: "ProviderService.uploadFeedback",
1134 schema: ProviderUploadFeedbackInput,
1135 payload: rawInput,
1136 });
1137 let routed = yield* resolveRoutableSession({
1138 threadId: input.threadId,
1139 operation: "ProviderService.uploadFeedback",
1140 allowRecovery: false,
1141 });
1142 if (routed.adapter.uploadFeedback === undefined) {
1143 return yield* toValidationError(
1144 "ProviderService.uploadFeedback",
1145 `Provider '${routed.adapter.provider}' does not support feedback uploads.`,
1146 );
1147 }
1148 if (!routed.isActive) {
1149 routed = yield* resolveRoutableSession({
1150 threadId: input.threadId,
1151 operation: "ProviderService.uploadFeedback",
1152 allowRecovery: true,
1153 });
1154 }
1155 const uploadFeedback = routed.adapter.uploadFeedback;
1156 if (uploadFeedback === undefined) {
1157 return yield* toValidationError(
1158 "ProviderService.uploadFeedback",
1159 `Provider '${routed.adapter.provider}' does not support feedback uploads.`,
1160 );
1161 }
1162 yield* Effect.annotateCurrentSpan({
1163 "provider.operation": "upload-feedback",
1164 "provider.kind": routed.adapter.provider,
1165 "provider.thread_id": input.threadId,
1166 });
1167 return yield* uploadFeedback(input);
1168 },
1169 );
1170
1171 const runStopAll = Effect.fn("runStopAll")(function* () {
1172 const threadIds = yield* directory.listThreadIds();
1173 const currentAdapters = yield* getAdapterEntries;
1174 const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
1175 adapter.listSessions().pipe(
1176 Effect.map((sessions) =>
1177 sessions.map((session) => ({
1178 ...session,
1179 providerInstanceId: instanceId,
1180 })),
1181 ),
1182 ),
1183 ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
1184 yield* Effect.forEach(activeSessions, (session) =>
1185 Effect.flatMap(nowIso, (lastRuntimeEventAt) =>
1186 upsertSessionBinding(session, session.threadId, {
1187 lastRuntimeEvent: "provider.stopAll",
1188 lastRuntimeEventAt,
1189 }),
1190 ),
1191 ).pipe(Effect.asVoid);
1192 yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
1193 yield* McpSessionRegistry.revokeAllActiveMcpCredentials();
1194 McpProviderSession.clearAllMcpProviderSessions();
1195 const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
1196 yield* Effect.forEach(bindings, (binding) =>
1197 Effect.gen(function* () {
1198 const providerInstanceId = dieOnMissingBindingInstanceId(
1199 "ProviderService.stopAll",
1200 binding,
1201 );
1202 return yield* directory.upsert({
1203 threadId: binding.threadId,
1204 provider: binding.provider,
1205 providerInstanceId,
1206 status: "stopped",
1207 runtimePayload: {
1208 activeTurnId: null,
1209 lastRuntimeEvent: "provider.stopAll",
1210 lastRuntimeEventAt: yield* nowIso,
1211 },
1212 });
1213 }),
1214 ).pipe(Effect.asVoid);
1215 yield* analytics.record("provider.sessions.stopped_all", {
1216 sessionCount: threadIds.length,
1217 });
1218 yield* analytics.flush;
1219 });
1220
1221 yield* Effect.addFinalizer(() =>
1222 runStopAll().pipe(
1223 Effect.catchCause((cause) =>
1224 Effect.logWarning("failed to stop provider service", {
1225 errorTag: causeErrorTag(cause),
1226 }),
1227 ),
1228 ),
1229 );
1230
1231 return {
1232 startSession,
1233 sendTurn,
1234 interruptTurn,
1235 respondToRequest,
1236 respondToUserInput,
1237 stopSession,
1238 listSessions,
1239 getCapabilities,
1240 getInstanceInfo,
1241 rollbackConversation,
1242 uploadFeedback,
1243 // Each access creates a fresh PubSub subscription so that multiple
1244 // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
1245 // independently receive all runtime events.
1246 get streamEvents(): ProviderServiceMethod<"streamEvents"> {
1247 return Stream.fromPubSub(runtimeEventPubSub);
1248 },
1249 } satisfies ProviderService.ProviderService["Service"];
1250});
1251
1252export const ProviderServiceLive = Layer.effect(
1253 ProviderService.ProviderService,
1254 makeProviderService(),
1255);
1256
1257export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
1258 return Layer.effect(ProviderService.ProviderService, makeProviderService(options));
1259}