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 && parsed.continuation !== true) {
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 let routed = yield* resolveRoutableSession({
781 threadId: input.threadId,
782 operation: "ProviderService.sendTurn",
783 allowRecovery: false,
784 });
785 if (
786 input.continuation === true &&
787 !input.input &&
788 attachments.length === 0 &&
789 routed.adapter.capabilities.promptlessTurnContinuation !== true
790 ) {
791 return yield* toValidationError(
792 "ProviderService.sendTurn",
793 `Provider '${routed.adapter.provider}' requires an explicit continuation prompt`,
794 );
795 }
796 if (!routed.isActive) {
797 routed = yield* resolveRoutableSession({
798 threadId: input.threadId,
799 operation: "ProviderService.sendTurn",
800 allowRecovery: true,
801 });
802 }
803 metricProvider = routed.adapter.provider;
804 metricModel = input.modelSelection?.model;
805 yield* Effect.annotateCurrentSpan({
806 "provider.kind": routed.adapter.provider,
807 ...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
808 });
809 // A turn is the clearest sign a session is still alive. The MCP
810 // credential is minted once at session start and cannot be rotated into
811 // an already-spawned agent process, so we keep the existing token valid
812 // rather than issuing a new one: sessions that go a long time between
813 // browser tool calls used to lose the toolkit outright.
814 yield* McpSessionRegistry.touchActiveMcpThread(input.threadId);
815 const turn = yield* routed.adapter.sendTurn(input);
816 yield* directory.upsert({
817 threadId: input.threadId,
818 provider: routed.adapter.provider,
819 providerInstanceId: routed.instanceId,
820 status: "running",
821 ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
822 runtimePayload: {
823 ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
824 activeTurnId: turn.turnId,
825 lastRuntimeEvent: "provider.sendTurn",
826 lastRuntimeEventAt: yield* nowIso,
827 },
828 });
829 yield* analytics.record("provider.turn.sent", {
830 provider: routed.adapter.provider,
831 model: input.modelSelection?.model,
832 interactionMode: input.interactionMode,
833 // Session-start events alone skew runtime mode toward users who toggle
834 // often, since every toggle restarts the session. Recording it per turn
835 // gives a usage-weighted view and lets it cross with interactionMode.
836 runtimeMode: routed.runtimeMode,
837 attachmentCount: attachments.length,
838 hasInput: typeof input.input === "string" && input.input.trim().length > 0,
839 });
840 return turn;
841 }).pipe(
842 withMetrics({
843 counter: providerTurnsTotal,
844 timer: providerTurnDuration,
845 attributes: () =>
846 providerTurnMetricAttributes({
847 provider: metricProvider,
848 model: metricModel,
849 extra: {
850 operation: "send",
851 },
852 }),
853 }),
854 );
855 });
856
857 const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(
858 function* (rawInput) {
859 const input = yield* decodeInputOrValidationError({
860 operation: "ProviderService.interruptTurn",
861 schema: ProviderInterruptTurnInput,
862 payload: rawInput,
863 });
864 let metricProvider = "unknown";
865 return yield* Effect.gen(function* () {
866 const routed = yield* resolveRoutableSession({
867 threadId: input.threadId,
868 operation: "ProviderService.interruptTurn",
869 allowRecovery: true,
870 });
871 metricProvider = routed.adapter.provider;
872 yield* Effect.annotateCurrentSpan({
873 "provider.operation": "interrupt-turn",
874 "provider.kind": routed.adapter.provider,
875 "provider.thread_id": input.threadId,
876 "provider.turn_id": input.turnId,
877 });
878 yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
879 yield* analytics.record("provider.turn.interrupted", {
880 provider: routed.adapter.provider,
881 });
882 }).pipe(
883 withMetrics({
884 counter: providerTurnsTotal,
885 outcomeAttributes: () =>
886 providerMetricAttributes(metricProvider, {
887 operation: "interrupt",
888 }),
889 }),
890 );
891 },
892 );
893
894 const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")(
895 function* (rawInput) {
896 const input = yield* decodeInputOrValidationError({
897 operation: "ProviderService.respondToRequest",
898 schema: ProviderRespondToRequestInput,
899 payload: rawInput,
900 });
901 let metricProvider = "unknown";
902 return yield* Effect.gen(function* () {
903 const routed = yield* resolveRoutableSession({
904 threadId: input.threadId,
905 operation: "ProviderService.respondToRequest",
906 allowRecovery: true,
907 });
908 metricProvider = routed.adapter.provider;
909 yield* Effect.annotateCurrentSpan({
910 "provider.operation": "respond-to-request",
911 "provider.kind": routed.adapter.provider,
912 "provider.thread_id": input.threadId,
913 "provider.request_id": input.requestId,
914 });
915 yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
916 yield* analytics.record("provider.request.responded", {
917 provider: routed.adapter.provider,
918 decision: input.decision,
919 });
920 }).pipe(
921 withMetrics({
922 counter: providerTurnsTotal,
923 outcomeAttributes: () =>
924 providerMetricAttributes(metricProvider, {
925 operation: "approval-response",
926 }),
927 }),
928 );
929 },
930 );
931
932 const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn(
933 "respondToUserInput",
934 )(function* (rawInput) {
935 const input = yield* decodeInputOrValidationError({
936 operation: "ProviderService.respondToUserInput",
937 schema: ProviderRespondToUserInputInput,
938 payload: rawInput,
939 });
940 let metricProvider = "unknown";
941 return yield* Effect.gen(function* () {
942 const routed = yield* resolveRoutableSession({
943 threadId: input.threadId,
944 operation: "ProviderService.respondToUserInput",
945 allowRecovery: true,
946 });
947 metricProvider = routed.adapter.provider;
948 yield* Effect.annotateCurrentSpan({
949 "provider.operation": "respond-to-user-input",
950 "provider.kind": routed.adapter.provider,
951 "provider.thread_id": input.threadId,
952 "provider.request_id": input.requestId,
953 });
954 yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
955 }).pipe(
956 withMetrics({
957 counter: providerTurnsTotal,
958 outcomeAttributes: () =>
959 providerMetricAttributes(metricProvider, {
960 operation: "user-input-response",
961 }),
962 }),
963 );
964 });
965
966 const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")(
967 function* (rawInput) {
968 const input = yield* decodeInputOrValidationError({
969 operation: "ProviderService.stopSession",
970 schema: ProviderStopSessionInput,
971 payload: rawInput,
972 });
973 let metricProvider = "unknown";
974 return yield* Effect.gen(function* () {
975 const routed = yield* resolveRoutableSession({
976 threadId: input.threadId,
977 operation: "ProviderService.stopSession",
978 allowRecovery: false,
979 });
980 metricProvider = routed.adapter.provider;
981 yield* Effect.annotateCurrentSpan({
982 "provider.operation": "stop-session",
983 "provider.kind": routed.adapter.provider,
984 "provider.thread_id": input.threadId,
985 });
986 if (routed.isActive) {
987 yield* routed.adapter.stopSession(routed.threadId);
988 }
989 yield* clearMcpSession(input.threadId);
990 yield* directory.upsert({
991 threadId: input.threadId,
992 provider: routed.adapter.provider,
993 providerInstanceId: routed.instanceId,
994 status: "stopped",
995 runtimePayload: {
996 activeTurnId: null,
997 },
998 });
999 yield* analytics.record("provider.session.stopped", {
1000 provider: routed.adapter.provider,
1001 });
1002 }).pipe(
1003 withMetrics({
1004 counter: providerSessionsTotal,
1005 outcomeAttributes: () =>
1006 providerMetricAttributes(metricProvider, {
1007 operation: "stop",
1008 }),
1009 }),
1010 );
1011 },
1012 );
1013
1014 const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")(
1015 function* () {
1016 const currentAdapters = yield* getAdapterEntries;
1017 const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
1018 adapter.listSessions().pipe(
1019 Effect.map((sessions) =>
1020 sessions.map((session) => ({
1021 ...session,
1022 providerInstanceId: instanceId,
1023 })),
1024 ),
1025 ),
1026 );
1027 const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
1028 // Only live adapter sessions appear in this response. Resolving every
1029 // historical binding here makes each call scale with the full thread
1030 // history instead of the active session set.
1031 const persistedBindings = yield* Effect.forEach(
1032 [...new Set(activeSessions.map((session) => session.threadId))],
1033 (threadId) =>
1034 directory
1035 .getBinding(threadId)
1036 .pipe(
1037 Effect.orElseSucceed(() =>
1038 Option.none<ProviderSessionDirectory.ProviderRuntimeBinding>(),
1039 ),
1040 ),
1041 { concurrency: "unbounded" },
1042 ).pipe(
1043 Effect.orElseSucceed(
1044 () => [] as Array<Option.Option<ProviderSessionDirectory.ProviderRuntimeBinding>>,
1045 ),
1046 );
1047 const bindingsByThreadId = new Map<
1048 ThreadId,
1049 ProviderSessionDirectory.ProviderRuntimeBinding
1050 >();
1051 for (const bindingOption of persistedBindings) {
1052 const binding = Option.getOrUndefined(bindingOption);
1053 if (binding) {
1054 bindingsByThreadId.set(binding.threadId, binding);
1055 }
1056 }
1057
1058 const sessions: ProviderSession[] = [];
1059 for (const session of activeSessions) {
1060 const binding = bindingsByThreadId.get(session.threadId);
1061 if (!binding) {
1062 sessions.push(session);
1063 continue;
1064 }
1065
1066 const overrides: {
1067 resumeCursor?: ProviderSession["resumeCursor"];
1068 runtimeMode?: ProviderSession["runtimeMode"];
1069 providerInstanceId?: ProviderSession["providerInstanceId"];
1070 } = {};
1071 overrides.providerInstanceId = dieOnMissingBindingInstanceId(
1072 "ProviderService.listSessions",
1073 binding,
1074 );
1075 if (binding.provider !== session.provider) {
1076 return yield* Effect.die(
1077 new Error(
1078 `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,
1079 ),
1080 );
1081 }
1082 if (overrides.providerInstanceId !== session.providerInstanceId) {
1083 return yield* Effect.die(
1084 new Error(
1085 `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,
1086 ),
1087 );
1088 }
1089 if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
1090 overrides.resumeCursor = binding.resumeCursor;
1091 }
1092 if (binding.runtimeMode !== undefined) {
1093 overrides.runtimeMode = binding.runtimeMode;
1094 }
1095 sessions.push(Object.assign({}, session, overrides));
1096 }
1097 return sessions;
1098 },
1099 );
1100
1101 const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) =>
1102 registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));
1103
1104 const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) =>
1105 registry.getInstanceInfo(instanceId);
1106
1107 const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn(
1108 "rollbackConversation",
1109 )(function* (rawInput) {
1110 const input = yield* decodeInputOrValidationError({
1111 operation: "ProviderService.rollbackConversation",
1112 schema: ProviderRollbackConversationInput,
1113 payload: rawInput,
1114 });
1115 if (input.numTurns === 0) {
1116 return;
1117 }
1118 let metricProvider = "unknown";
1119 return yield* Effect.gen(function* () {
1120 const routed = yield* resolveRoutableSession({
1121 threadId: input.threadId,
1122 operation: "ProviderService.rollbackConversation",
1123 allowRecovery: true,
1124 });
1125 metricProvider = routed.adapter.provider;
1126 yield* Effect.annotateCurrentSpan({
1127 "provider.operation": "rollback-conversation",
1128 "provider.kind": routed.adapter.provider,
1129 "provider.thread_id": input.threadId,
1130 "provider.rollback_turns": input.numTurns,
1131 });
1132 yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
1133 yield* analytics.record("provider.conversation.rolled_back", {
1134 provider: routed.adapter.provider,
1135 turns: input.numTurns,
1136 });
1137 }).pipe(
1138 withMetrics({
1139 counter: providerTurnsTotal,
1140 outcomeAttributes: () =>
1141 providerMetricAttributes(metricProvider, {
1142 operation: "rollback",
1143 }),
1144 }),
1145 );
1146 });
1147
1148 const uploadFeedback: ProviderServiceMethod<"uploadFeedback"> = Effect.fn("uploadFeedback")(
1149 function* (rawInput) {
1150 const input = yield* decodeInputOrValidationError({
1151 operation: "ProviderService.uploadFeedback",
1152 schema: ProviderUploadFeedbackInput,
1153 payload: rawInput,
1154 });
1155 let routed = yield* resolveRoutableSession({
1156 threadId: input.threadId,
1157 operation: "ProviderService.uploadFeedback",
1158 allowRecovery: false,
1159 });
1160 if (routed.adapter.uploadFeedback === undefined) {
1161 return yield* toValidationError(
1162 "ProviderService.uploadFeedback",
1163 `Provider '${routed.adapter.provider}' does not support feedback uploads.`,
1164 );
1165 }
1166 if (!routed.isActive) {
1167 routed = yield* resolveRoutableSession({
1168 threadId: input.threadId,
1169 operation: "ProviderService.uploadFeedback",
1170 allowRecovery: true,
1171 });
1172 }
1173 const uploadFeedback = routed.adapter.uploadFeedback;
1174 if (uploadFeedback === undefined) {
1175 return yield* toValidationError(
1176 "ProviderService.uploadFeedback",
1177 `Provider '${routed.adapter.provider}' does not support feedback uploads.`,
1178 );
1179 }
1180 yield* Effect.annotateCurrentSpan({
1181 "provider.operation": "upload-feedback",
1182 "provider.kind": routed.adapter.provider,
1183 "provider.thread_id": input.threadId,
1184 });
1185 return yield* uploadFeedback(input);
1186 },
1187 );
1188
1189 const runStopAll = Effect.fn("runStopAll")(function* () {
1190 const threadIds = yield* directory.listThreadIds();
1191 const currentAdapters = yield* getAdapterEntries;
1192 const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
1193 adapter.listSessions().pipe(
1194 Effect.map((sessions) =>
1195 sessions.map((session) => ({
1196 ...session,
1197 providerInstanceId: instanceId,
1198 })),
1199 ),
1200 ),
1201 ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
1202 yield* Effect.forEach(activeSessions, (session) =>
1203 Effect.flatMap(nowIso, (lastRuntimeEventAt) =>
1204 upsertSessionBinding(session, session.threadId, {
1205 lastRuntimeEvent: "provider.stopAll",
1206 lastRuntimeEventAt,
1207 }),
1208 ),
1209 ).pipe(Effect.asVoid);
1210 yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
1211 yield* McpSessionRegistry.revokeAllActiveMcpCredentials();
1212 McpProviderSession.clearAllMcpProviderSessions();
1213 const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
1214 yield* Effect.forEach(bindings, (binding) =>
1215 Effect.gen(function* () {
1216 const providerInstanceId = dieOnMissingBindingInstanceId(
1217 "ProviderService.stopAll",
1218 binding,
1219 );
1220 return yield* directory.upsert({
1221 threadId: binding.threadId,
1222 provider: binding.provider,
1223 providerInstanceId,
1224 status: "stopped",
1225 runtimePayload: {
1226 activeTurnId: null,
1227 lastRuntimeEvent: "provider.stopAll",
1228 lastRuntimeEventAt: yield* nowIso,
1229 },
1230 });
1231 }),
1232 ).pipe(Effect.asVoid);
1233 yield* analytics.record("provider.sessions.stopped_all", {
1234 sessionCount: threadIds.length,
1235 });
1236 yield* analytics.flush;
1237 });
1238
1239 yield* Effect.addFinalizer(() =>
1240 runStopAll().pipe(
1241 Effect.catchCause((cause) =>
1242 Effect.logWarning("failed to stop provider service", {
1243 errorTag: causeErrorTag(cause),
1244 }),
1245 ),
1246 ),
1247 );
1248
1249 return {
1250 startSession,
1251 sendTurn,
1252 interruptTurn,
1253 respondToRequest,
1254 respondToUserInput,
1255 stopSession,
1256 listSessions,
1257 getCapabilities,
1258 getInstanceInfo,
1259 rollbackConversation,
1260 uploadFeedback,
1261 // Each access creates a fresh PubSub subscription so that multiple
1262 // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
1263 // independently receive all runtime events.
1264 get streamEvents(): ProviderServiceMethod<"streamEvents"> {
1265 return Stream.fromPubSub(runtimeEventPubSub);
1266 },
1267 } satisfies ProviderService.ProviderService["Service"];
1268});
1269
1270export const ProviderServiceLive = Layer.effect(
1271 ProviderService.ProviderService,
1272 makeProviderService(),
1273);
1274
1275export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
1276 return Layer.effect(ProviderService.ProviderService, makeProviderService(options));
1277}