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

ProviderService.ts

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