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