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