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

ProviderService.ts

1,248 lines46.7 KB

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