Open History to see the last commit
1/**
2 * ProviderServiceLive - Cross-provider orchestration layer.
3 *
4 * Routes validated transport/API calls to provider adapters through
5 * `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a
6 * unified provider event stream for subscribers.
7 *
8 * It does not implement provider protocol details (adapter concern).
9 *
10 * @module ProviderServiceLive
11 */
12import {
13 ModelSelection,
14 NonNegativeInt,
15 ThreadId,
16 ProviderInterruptTurnInput,
17 ProviderRespondToRequestInput,
18 ProviderRespondToUserInputInput,
19 ProviderSendTurnInput,
20 ProviderSessionStartInput,
21 ProviderStopSessionInput,
22 type ProviderRuntimeEvent,
23 type ProviderSession,
24} from "@t3tools/contracts";
25import { Effect, Layer, Option, PubSub, Queue, Schema, SchemaIssue, Stream } from "effect";
26
27import { ProviderValidationError } from "../Errors.ts";
28import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
29import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
30import {
31 ProviderSessionDirectory,
32 type ProviderRuntimeBinding,
33} from "../Services/ProviderSessionDirectory.ts";
34import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
35import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
36import { ServerSettingsService } from "../../serverSettings.ts";
37
38export interface ProviderServiceLiveOptions {
39 readonly canonicalEventLogPath?: string;
40 readonly canonicalEventLogger?: EventNdjsonLogger;
41}
42
43const ProviderRollbackConversationInput = Schema.Struct({
44 threadId: ThreadId,
45 numTurns: NonNegativeInt,
46});
47
48function toValidationError(
49 operation: string,
50 issue: string,
51 cause?: unknown,
52): ProviderValidationError {
53 return new ProviderValidationError({
54 operation,
55 issue,
56 ...(cause !== undefined ? { cause } : {}),
57 });
58}
59
60const decodeInputOrValidationError = <S extends Schema.Top>(input: {
61 readonly operation: string;
62 readonly schema: S;
63 readonly payload: unknown;
64}) =>
65 Schema.decodeUnknownEffect(input.schema)(input.payload).pipe(
66 Effect.mapError(
67 (schemaError) =>
68 new ProviderValidationError({
69 operation: input.operation,
70 issue: SchemaIssue.makeFormatterDefault()(schemaError.issue),
71 cause: schemaError,
72 }),
73 ),
74 );
75
76function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "stopped" | "error" {
77 switch (session.status) {
78 case "connecting":
79 return "starting";
80 case "error":
81 return "error";
82 case "closed":
83 return "stopped";
84 case "ready":
85 case "running":
86 default:
87 return "running";
88 }
89}
90
91function toRuntimePayloadFromSession(
92 session: ProviderSession,
93 extra?: {
94 readonly modelSelection?: unknown;
95 readonly lastRuntimeEvent?: string;
96 readonly lastRuntimeEventAt?: string;
97 },
98): Record<string, unknown> {
99 return {
100 cwd: session.cwd ?? null,
101 model: session.model ?? null,
102 activeTurnId: session.activeTurnId ?? null,
103 lastError: session.lastError ?? null,
104 ...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),
105 ...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
106 ...(extra?.lastRuntimeEventAt !== undefined
107 ? { lastRuntimeEventAt: extra.lastRuntimeEventAt }
108 : {}),
109 };
110}
111
112function readPersistedModelSelection(
113 runtimePayload: ProviderRuntimeBinding["runtimePayload"],
114): ModelSelection | undefined {
115 if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
116 return undefined;
117 }
118 const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined;
119 return Schema.is(ModelSelection)(raw) ? raw : undefined;
120}
121
122function readPersistedCwd(
123 runtimePayload: ProviderRuntimeBinding["runtimePayload"],
124): string | undefined {
125 if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
126 return undefined;
127 }
128 const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined;
129 if (typeof rawCwd !== "string") return undefined;
130 const trimmed = rawCwd.trim();
131 return trimmed.length > 0 ? trimmed : undefined;
132}
133
134const makeProviderService = (options?: ProviderServiceLiveOptions) =>
135 Effect.gen(function* () {
136 const analytics = yield* Effect.service(AnalyticsService);
137 const serverSettings = yield* ServerSettingsService;
138 const canonicalEventLogger =
139 options?.canonicalEventLogger ??
140 (options?.canonicalEventLogPath !== undefined
141 ? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
142 stream: "canonical",
143 })
144 : undefined);
145
146 const registry = yield* ProviderAdapterRegistry;
147 const directory = yield* ProviderSessionDirectory;
148 const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
149 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
150
151 const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
152 Effect.succeed(event).pipe(
153 Effect.tap((canonicalEvent) =>
154 canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
155 ),
156 Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
157 Effect.asVoid,
158 );
159
160 const upsertSessionBinding = (
161 session: ProviderSession,
162 threadId: ThreadId,
163 extra?: {
164 readonly modelSelection?: unknown;
165 readonly lastRuntimeEvent?: string;
166 readonly lastRuntimeEventAt?: string;
167 },
168 ) =>
169 directory.upsert({
170 threadId,
171 provider: session.provider,
172 runtimeMode: session.runtimeMode,
173 status: toRuntimeStatus(session),
174 ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
175 runtimePayload: toRuntimePayloadFromSession(session, extra),
176 });
177
178 const providers = yield* registry.listProviders();
179 const adapters = yield* Effect.forEach(providers, (provider) =>
180 registry.getByProvider(provider),
181 );
182 const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
183 publishRuntimeEvent(event);
184
185 const worker = Effect.forever(
186 Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
187 );
188 yield* Effect.forkScoped(worker);
189
190 yield* Effect.forEach(adapters, (adapter) =>
191 Stream.runForEach(adapter.streamEvents, (event) =>
192 Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
193 ).pipe(Effect.forkScoped),
194 ).pipe(Effect.asVoid);
195
196 const recoverSessionForThread = (input: {
197 readonly binding: ProviderRuntimeBinding;
198 readonly operation: string;
199 }) =>
200 Effect.gen(function* () {
201 const adapter = yield* registry.getByProvider(input.binding.provider);
202 const hasResumeCursor =
203 input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
204 const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
205 if (hasActiveSession) {
206 const activeSessions = yield* adapter.listSessions();
207 const existing = activeSessions.find(
208 (session) => session.threadId === input.binding.threadId,
209 );
210 if (existing) {
211 yield* upsertSessionBinding(existing, input.binding.threadId);
212 yield* analytics.record("provider.session.recovered", {
213 provider: existing.provider,
214 strategy: "adopt-existing",
215 hasResumeCursor: existing.resumeCursor !== undefined,
216 });
217 return { adapter, session: existing } as const;
218 }
219 }
220
221 if (!hasResumeCursor) {
222 return yield* toValidationError(
223 input.operation,
224 `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
225 );
226 }
227
228 const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
229 const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
230
231 const resumed = yield* adapter.startSession({
232 threadId: input.binding.threadId,
233 provider: input.binding.provider,
234 ...(persistedCwd ? { cwd: persistedCwd } : {}),
235 ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
236 ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
237 runtimeMode: input.binding.runtimeMode ?? "full-access",
238 });
239 if (resumed.provider !== adapter.provider) {
240 return yield* toValidationError(
241 input.operation,
242 `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
243 );
244 }
245
246 yield* upsertSessionBinding(resumed, input.binding.threadId);
247 yield* analytics.record("provider.session.recovered", {
248 provider: resumed.provider,
249 strategy: "resume-thread",
250 hasResumeCursor: resumed.resumeCursor !== undefined,
251 });
252 return { adapter, session: resumed } as const;
253 });
254
255 const resolveRoutableSession = (input: {
256 readonly threadId: ThreadId;
257 readonly operation: string;
258 readonly allowRecovery: boolean;
259 }) =>
260 Effect.gen(function* () {
261 const bindingOption = yield* directory.getBinding(input.threadId);
262 const binding = Option.getOrUndefined(bindingOption);
263 if (!binding) {
264 return yield* toValidationError(
265 input.operation,
266 `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
267 );
268 }
269 const adapter = yield* registry.getByProvider(binding.provider);
270
271 const hasRequestedSession = yield* adapter.hasSession(input.threadId);
272 if (hasRequestedSession) {
273 return { adapter, threadId: input.threadId, isActive: true } as const;
274 }
275
276 if (!input.allowRecovery) {
277 return { adapter, threadId: input.threadId, isActive: false } as const;
278 }
279
280 const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
281 return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
282 });
283
284 const startSession: ProviderServiceShape["startSession"] = (threadId, rawInput) =>
285 Effect.gen(function* () {
286 const parsed = yield* decodeInputOrValidationError({
287 operation: "ProviderService.startSession",
288 schema: ProviderSessionStartInput,
289 payload: rawInput,
290 });
291
292 const input = {
293 ...parsed,
294 threadId,
295 provider: parsed.provider ?? "codex",
296 };
297 const settings = yield* serverSettings.getSettings.pipe(
298 Effect.mapError((error) =>
299 toValidationError(
300 "ProviderService.startSession",
301 `Failed to load provider settings: ${error.message}`,
302 error,
303 ),
304 ),
305 );
306 if (!settings.providers[input.provider].enabled) {
307 return yield* toValidationError(
308 "ProviderService.startSession",
309 `Provider '${input.provider}' is disabled in T3 Code settings.`,
310 );
311 }
312 const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
313 const effectiveResumeCursor =
314 input.resumeCursor ??
315 (persistedBinding?.provider === input.provider
316 ? persistedBinding.resumeCursor
317 : undefined);
318 const adapter = yield* registry.getByProvider(input.provider);
319 const session = yield* adapter.startSession({
320 ...input,
321 ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
322 });
323
324 if (session.provider !== adapter.provider) {
325 return yield* toValidationError(
326 "ProviderService.startSession",
327 `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
328 );
329 }
330
331 yield* upsertSessionBinding(session, threadId, {
332 modelSelection: input.modelSelection,
333 });
334 yield* analytics.record("provider.session.started", {
335 provider: session.provider,
336 runtimeMode: input.runtimeMode,
337 hasResumeCursor: session.resumeCursor !== undefined,
338 hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
339 hasModel:
340 typeof input.modelSelection?.model === "string" &&
341 input.modelSelection.model.trim().length > 0,
342 });
343
344 return session;
345 });
346
347 const sendTurn: ProviderServiceShape["sendTurn"] = (rawInput) =>
348 Effect.gen(function* () {
349 const parsed = yield* decodeInputOrValidationError({
350 operation: "ProviderService.sendTurn",
351 schema: ProviderSendTurnInput,
352 payload: rawInput,
353 });
354
355 const input = {
356 ...parsed,
357 attachments: parsed.attachments ?? [],
358 };
359 if (!input.input && input.attachments.length === 0) {
360 return yield* toValidationError(
361 "ProviderService.sendTurn",
362 "Either input text or at least one attachment is required",
363 );
364 }
365 const routed = yield* resolveRoutableSession({
366 threadId: input.threadId,
367 operation: "ProviderService.sendTurn",
368 allowRecovery: true,
369 });
370 const turn = yield* routed.adapter.sendTurn(input);
371 yield* directory.upsert({
372 threadId: input.threadId,
373 provider: routed.adapter.provider,
374 status: "running",
375 ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
376 runtimePayload: {
377 ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
378 activeTurnId: turn.turnId,
379 lastRuntimeEvent: "provider.sendTurn",
380 lastRuntimeEventAt: new Date().toISOString(),
381 },
382 });
383 yield* analytics.record("provider.turn.sent", {
384 provider: routed.adapter.provider,
385 model: input.modelSelection?.model,
386 interactionMode: input.interactionMode,
387 attachmentCount: input.attachments.length,
388 hasInput: typeof input.input === "string" && input.input.trim().length > 0,
389 });
390 return turn;
391 });
392
393 const interruptTurn: ProviderServiceShape["interruptTurn"] = (rawInput) =>
394 Effect.gen(function* () {
395 const input = yield* decodeInputOrValidationError({
396 operation: "ProviderService.interruptTurn",
397 schema: ProviderInterruptTurnInput,
398 payload: rawInput,
399 });
400 const routed = yield* resolveRoutableSession({
401 threadId: input.threadId,
402 operation: "ProviderService.interruptTurn",
403 allowRecovery: true,
404 });
405 yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
406 yield* analytics.record("provider.turn.interrupted", {
407 provider: routed.adapter.provider,
408 });
409 });
410
411 const respondToRequest: ProviderServiceShape["respondToRequest"] = (rawInput) =>
412 Effect.gen(function* () {
413 const input = yield* decodeInputOrValidationError({
414 operation: "ProviderService.respondToRequest",
415 schema: ProviderRespondToRequestInput,
416 payload: rawInput,
417 });
418 const routed = yield* resolveRoutableSession({
419 threadId: input.threadId,
420 operation: "ProviderService.respondToRequest",
421 allowRecovery: true,
422 });
423 yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
424 yield* analytics.record("provider.request.responded", {
425 provider: routed.adapter.provider,
426 decision: input.decision,
427 });
428 });
429
430 const respondToUserInput: ProviderServiceShape["respondToUserInput"] = (rawInput) =>
431 Effect.gen(function* () {
432 const input = yield* decodeInputOrValidationError({
433 operation: "ProviderService.respondToUserInput",
434 schema: ProviderRespondToUserInputInput,
435 payload: rawInput,
436 });
437 const routed = yield* resolveRoutableSession({
438 threadId: input.threadId,
439 operation: "ProviderService.respondToUserInput",
440 allowRecovery: true,
441 });
442 yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
443 });
444
445 const stopSession: ProviderServiceShape["stopSession"] = (rawInput) =>
446 Effect.gen(function* () {
447 const input = yield* decodeInputOrValidationError({
448 operation: "ProviderService.stopSession",
449 schema: ProviderStopSessionInput,
450 payload: rawInput,
451 });
452 const routed = yield* resolveRoutableSession({
453 threadId: input.threadId,
454 operation: "ProviderService.stopSession",
455 allowRecovery: false,
456 });
457 if (routed.isActive) {
458 yield* routed.adapter.stopSession(routed.threadId);
459 }
460 yield* directory.remove(input.threadId);
461 yield* analytics.record("provider.session.stopped", {
462 provider: routed.adapter.provider,
463 });
464 });
465
466 const listSessions: ProviderServiceShape["listSessions"] = () =>
467 Effect.gen(function* () {
468 const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
469 adapter.listSessions(),
470 );
471 const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
472 const persistedBindings = yield* directory.listThreadIds().pipe(
473 Effect.flatMap((threadIds) =>
474 Effect.forEach(
475 threadIds,
476 (threadId) =>
477 directory
478 .getBinding(threadId)
479 .pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),
480 { concurrency: "unbounded" },
481 ),
482 ),
483 Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
484 );
485 const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
486 for (const bindingOption of persistedBindings) {
487 const binding = Option.getOrUndefined(bindingOption);
488 if (binding) {
489 bindingsByThreadId.set(binding.threadId, binding);
490 }
491 }
492
493 return activeSessions.map((session) => {
494 const binding = bindingsByThreadId.get(session.threadId);
495 if (!binding) {
496 return session;
497 }
498
499 const overrides: {
500 resumeCursor?: ProviderSession["resumeCursor"];
501 runtimeMode?: ProviderSession["runtimeMode"];
502 } = {};
503 if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
504 overrides.resumeCursor = binding.resumeCursor;
505 }
506 if (binding.runtimeMode !== undefined) {
507 overrides.runtimeMode = binding.runtimeMode;
508 }
509 return Object.assign({}, session, overrides);
510 });
511 });
512
513 const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
514 registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
515
516 const rollbackConversation: ProviderServiceShape["rollbackConversation"] = (rawInput) =>
517 Effect.gen(function* () {
518 const input = yield* decodeInputOrValidationError({
519 operation: "ProviderService.rollbackConversation",
520 schema: ProviderRollbackConversationInput,
521 payload: rawInput,
522 });
523 if (input.numTurns === 0) {
524 return;
525 }
526 const routed = yield* resolveRoutableSession({
527 threadId: input.threadId,
528 operation: "ProviderService.rollbackConversation",
529 allowRecovery: true,
530 });
531 yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
532 yield* analytics.record("provider.conversation.rolled_back", {
533 provider: routed.adapter.provider,
534 turns: input.numTurns,
535 });
536 });
537
538 const runStopAll = () =>
539 Effect.gen(function* () {
540 const threadIds = yield* directory.listThreadIds();
541 const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
542 adapter.listSessions(),
543 ).pipe(
544 Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)),
545 );
546 yield* Effect.forEach(activeSessions, (session) =>
547 upsertSessionBinding(session, session.threadId, {
548 lastRuntimeEvent: "provider.stopAll",
549 lastRuntimeEventAt: new Date().toISOString(),
550 }),
551 ).pipe(Effect.asVoid);
552 yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
553 yield* Effect.forEach(threadIds, (threadId) =>
554 directory.getProvider(threadId).pipe(
555 Effect.flatMap((provider) =>
556 directory.upsert({
557 threadId,
558 provider,
559 status: "stopped",
560 runtimePayload: {
561 activeTurnId: null,
562 lastRuntimeEvent: "provider.stopAll",
563 lastRuntimeEventAt: new Date().toISOString(),
564 },
565 }),
566 ),
567 ),
568 ).pipe(Effect.asVoid);
569 yield* analytics.record("provider.sessions.stopped_all", {
570 sessionCount: threadIds.length,
571 });
572 yield* analytics.flush;
573 });
574
575 yield* Effect.addFinalizer(() =>
576 Effect.catch(runStopAll(), (cause) =>
577 Effect.logWarning("failed to stop provider service", { cause }),
578 ),
579 );
580
581 return {
582 startSession,
583 sendTurn,
584 interruptTurn,
585 respondToRequest,
586 respondToUserInput,
587 stopSession,
588 listSessions,
589 getCapabilities,
590 rollbackConversation,
591 // Each access creates a fresh PubSub subscription so that multiple
592 // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
593 // independently receive all runtime events.
594 get streamEvents(): ProviderServiceShape["streamEvents"] {
595 return Stream.fromPubSub(runtimeEventPubSub);
596 },
597 } satisfies ProviderServiceShape;
598 });
599
600export const ProviderServiceLive = Layer.effect(ProviderService, makeProviderService());
601
602export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
603 return Layer.effect(ProviderService, makeProviderService(options));
604}