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

ProviderService.ts

602 lines21.3 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 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;
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 });
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 }
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 };
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;
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;
133​
134const makeProviderService = Effect.fn("makeProviderService")(function* (
135 options?: ProviderServiceLiveOptions,
136) {
137 const analytics = yield* Effect.service(AnalyticsService);
138 const serverSettings = yield* ServerSettingsService;
139 const canonicalEventLogger =
140 options?.canonicalEventLogger ??
141 (options?.canonicalEventLogPath !== undefined
142 ? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
143 stream: "canonical",
144 })
145 : undefined);
146​
147 const registry = yield* ProviderAdapterRegistry;
148 const directory = yield* ProviderSessionDirectory;
149 const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
150 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
151​
152 const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
153 Effect.succeed(event).pipe(
154 Effect.tap((canonicalEvent) =>
155 canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
156 ),
157 Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
158 Effect.asVoid,
159 );
160​
161 const upsertSessionBinding = (
162 session: ProviderSession,
163 threadId: ThreadId,
164 extra?: {
165 readonly modelSelection?: unknown;
166 readonly lastRuntimeEvent?: string;
167 readonly lastRuntimeEventAt?: string;
168 },
169 ) =>
170 directory.upsert({
171 threadId,
172 provider: session.provider,
173 runtimeMode: session.runtimeMode,
174 status: toRuntimeStatus(session),
175 ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
176 runtimePayload: toRuntimePayloadFromSession(session, extra),
177 });
178​
179 const providers = yield* registry.listProviders();
180 const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider));
181 const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
182 publishRuntimeEvent(event);
183​
184 const worker = Effect.forever(
185 Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
186 );
187 yield* Effect.forkScoped(worker);
188​
189 yield* Effect.forEach(adapters, (adapter) =>
190 Stream.runForEach(adapter.streamEvents, (event) =>
191 Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
192 ).pipe(Effect.forkScoped),
193 ).pipe(Effect.asVoid);
194​
195 const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
196 readonly binding: ProviderRuntimeBinding;
197 readonly operation: string;
198 }) {
199 const adapter = yield* registry.getByProvider(input.binding.provider);
200 const hasResumeCursor =
201 input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
202 const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
203 if (hasActiveSession) {
204 const activeSessions = yield* adapter.listSessions();
205 const existing = activeSessions.find(
206 (session) => session.threadId === input.binding.threadId,
207 );
208 if (existing) {
209 yield* upsertSessionBinding(existing, input.binding.threadId);
210 yield* analytics.record("provider.session.recovered", {
211 provider: existing.provider,
212 strategy: "adopt-existing",
213 hasResumeCursor: existing.resumeCursor !== undefined,
214 });
215 return { adapter, session: existing } as const;
216 }
217 }
218​
219 if (!hasResumeCursor) {
220 return yield* toValidationError(
221 input.operation,
222 `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
223 );
224 }
225​
226 const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
227 const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
228​
229 const resumed = yield* adapter.startSession({
230 threadId: input.binding.threadId,
231 provider: input.binding.provider,
232 ...(persistedCwd ? { cwd: persistedCwd } : {}),
233 ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
234 ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
235 runtimeMode: input.binding.runtimeMode ?? "full-access",
236 });
237 if (resumed.provider !== adapter.provider) {
238 return yield* toValidationError(
239 input.operation,
240 `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
241 );
242 }
243​
244 yield* upsertSessionBinding(resumed, input.binding.threadId);
245 yield* analytics.record("provider.session.recovered", {
246 provider: resumed.provider,
247 strategy: "resume-thread",
248 hasResumeCursor: resumed.resumeCursor !== undefined,
249 });
250 return { adapter, session: resumed } as const;
251 });
252​
253 const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: {
254 readonly threadId: ThreadId;
255 readonly operation: string;
256 readonly allowRecovery: boolean;
257 }) {
258 const bindingOption = yield* directory.getBinding(input.threadId);
259 const binding = Option.getOrUndefined(bindingOption);
260 if (!binding) {
261 return yield* toValidationError(
262 input.operation,
263 `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
264 );
265 }
266 const adapter = yield* registry.getByProvider(binding.provider);
267​
268 const hasRequestedSession = yield* adapter.hasSession(input.threadId);
269 if (hasRequestedSession) {
270 return { adapter, threadId: input.threadId, isActive: true } as const;
271 }
272​
273 if (!input.allowRecovery) {
274 return { adapter, threadId: input.threadId, isActive: false } as const;
275 }
276​
277 const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
278 return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
279 });
280​
281 const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")(
282 function* (threadId, rawInput) {
283 const parsed = yield* decodeInputOrValidationError({
284 operation: "ProviderService.startSession",
285 schema: ProviderSessionStartInput,
286 payload: rawInput,
287 });
288​
289 const input = {
290 ...parsed,
291 threadId,
292 provider: parsed.provider ?? "codex",
293 };
294 const settings = yield* serverSettings.getSettings.pipe(
295 Effect.mapError((error) =>
296 toValidationError(
297 "ProviderService.startSession",
298 `Failed to load provider settings: ${error.message}`,
299 error,
300 ),
301 ),
302 );
303 if (!settings.providers[input.provider].enabled) {
304 return yield* toValidationError(
305 "ProviderService.startSession",
306 `Provider '${input.provider}' is disabled in T3 Code settings.`,
307 );
308 }
309 const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
310 const effectiveResumeCursor =
311 input.resumeCursor ??
312 (persistedBinding?.provider === input.provider ? persistedBinding.resumeCursor : undefined);
313 const adapter = yield* registry.getByProvider(input.provider);
314 const session = yield* adapter.startSession({
315 ...input,
316 ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
317 });
318​
319 if (session.provider !== adapter.provider) {
320 return yield* toValidationError(
321 "ProviderService.startSession",
322 `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
323 );
324 }
325​
326 yield* upsertSessionBinding(session, threadId, {
327 modelSelection: input.modelSelection,
328 });
329 yield* analytics.record("provider.session.started", {
330 provider: session.provider,
331 runtimeMode: input.runtimeMode,
332 hasResumeCursor: session.resumeCursor !== undefined,
333 hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
334 hasModel:
335 typeof input.modelSelection?.model === "string" &&
336 input.modelSelection.model.trim().length > 0,
337 });
338​
339 return session;
340 },
341 );
342​
343 const sendTurn: ProviderServiceShape["sendTurn"] = Effect.fn("sendTurn")(function* (rawInput) {
344 const parsed = yield* decodeInputOrValidationError({
345 operation: "ProviderService.sendTurn",
346 schema: ProviderSendTurnInput,
347 payload: rawInput,
348 });
349​
350 const input = {
351 ...parsed,
352 attachments: parsed.attachments ?? [],
353 };
354 if (!input.input && input.attachments.length === 0) {
355 return yield* toValidationError(
356 "ProviderService.sendTurn",
357 "Either input text or at least one attachment is required",
358 );
359 }
360 const routed = yield* resolveRoutableSession({
361 threadId: input.threadId,
362 operation: "ProviderService.sendTurn",
363 allowRecovery: true,
364 });
365 const turn = yield* routed.adapter.sendTurn(input);
366 yield* directory.upsert({
367 threadId: input.threadId,
368 provider: routed.adapter.provider,
369 status: "running",
370 ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
371 runtimePayload: {
372 ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
373 activeTurnId: turn.turnId,
374 lastRuntimeEvent: "provider.sendTurn",
375 lastRuntimeEventAt: new Date().toISOString(),
376 },
377 });
378 yield* analytics.record("provider.turn.sent", {
379 provider: routed.adapter.provider,
380 model: input.modelSelection?.model,
381 interactionMode: input.interactionMode,
382 attachmentCount: input.attachments.length,
383 hasInput: typeof input.input === "string" && input.input.trim().length > 0,
384 });
385 return turn;
386 });
387​
388 const interruptTurn: ProviderServiceShape["interruptTurn"] = Effect.fn("interruptTurn")(
389 function* (rawInput) {
390 const input = yield* decodeInputOrValidationError({
391 operation: "ProviderService.interruptTurn",
392 schema: ProviderInterruptTurnInput,
393 payload: rawInput,
394 });
395 const routed = yield* resolveRoutableSession({
396 threadId: input.threadId,
397 operation: "ProviderService.interruptTurn",
398 allowRecovery: true,
399 });
400 yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
401 yield* analytics.record("provider.turn.interrupted", {
402 provider: routed.adapter.provider,
403 });
404 },
405 );
406​
407 const respondToRequest: ProviderServiceShape["respondToRequest"] = Effect.fn("respondToRequest")(
408 function* (rawInput) {
409 const input = yield* decodeInputOrValidationError({
410 operation: "ProviderService.respondToRequest",
411 schema: ProviderRespondToRequestInput,
412 payload: rawInput,
413 });
414 const routed = yield* resolveRoutableSession({
415 threadId: input.threadId,
416 operation: "ProviderService.respondToRequest",
417 allowRecovery: true,
418 });
419 yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
420 yield* analytics.record("provider.request.responded", {
421 provider: routed.adapter.provider,
422 decision: input.decision,
423 });
424 },
425 );
426​
427 const respondToUserInput: ProviderServiceShape["respondToUserInput"] = Effect.fn(
428 "respondToUserInput",
429 )(function* (rawInput) {
430 const input = yield* decodeInputOrValidationError({
431 operation: "ProviderService.respondToUserInput",
432 schema: ProviderRespondToUserInputInput,
433 payload: rawInput,
434 });
435 const routed = yield* resolveRoutableSession({
436 threadId: input.threadId,
437 operation: "ProviderService.respondToUserInput",
438 allowRecovery: true,
439 });
440 yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
441 });
442​
443 const stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")(
444 function* (rawInput) {
445 const input = yield* decodeInputOrValidationError({
446 operation: "ProviderService.stopSession",
447 schema: ProviderStopSessionInput,
448 payload: rawInput,
449 });
450 const routed = yield* resolveRoutableSession({
451 threadId: input.threadId,
452 operation: "ProviderService.stopSession",
453 allowRecovery: false,
454 });
455 if (routed.isActive) {
456 yield* routed.adapter.stopSession(routed.threadId);
457 }
458 yield* directory.remove(input.threadId);
459 yield* analytics.record("provider.session.stopped", {
460 provider: routed.adapter.provider,
461 });
462 },
463 );
464​
465 const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")(
466 function* () {
467 const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
468 adapter.listSessions(),
469 );
470 const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
471 const persistedBindings = yield* directory.listThreadIds().pipe(
472 Effect.flatMap((threadIds) =>
473 Effect.forEach(
474 threadIds,
475 (threadId) =>
476 directory
477 .getBinding(threadId)
478 .pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),
479 { concurrency: "unbounded" },
480 ),
481 ),
482 Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
483 );
484 const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
485 for (const bindingOption of persistedBindings) {
486 const binding = Option.getOrUndefined(bindingOption);
487 if (binding) {
488 bindingsByThreadId.set(binding.threadId, binding);
489 }
490 }
491​
492 return activeSessions.map((session) => {
493 const binding = bindingsByThreadId.get(session.threadId);
494 if (!binding) {
495 return session;
496 }
497​
498 const overrides: {
499 resumeCursor?: ProviderSession["resumeCursor"];
500 runtimeMode?: ProviderSession["runtimeMode"];
501 } = {};
502 if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
503 overrides.resumeCursor = binding.resumeCursor;
504 }
505 if (binding.runtimeMode !== undefined) {
506 overrides.runtimeMode = binding.runtimeMode;
507 }
508 return Object.assign({}, session, overrides);
509 });
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"] = Effect.fn(
517 "rollbackConversation",
518 )(function* (rawInput) {
519 const input = yield* decodeInputOrValidationError({
520 operation: "ProviderService.rollbackConversation",
521 schema: ProviderRollbackConversationInput,
522 payload: rawInput,
523 });
524 if (input.numTurns === 0) {
525 return;
526 }
527 const routed = yield* resolveRoutableSession({
528 threadId: input.threadId,
529 operation: "ProviderService.rollbackConversation",
530 allowRecovery: true,
531 });
532 yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
533 yield* analytics.record("provider.conversation.rolled_back", {
534 provider: routed.adapter.provider,
535 turns: input.numTurns,
536 });
537 });
538​
539 const runStopAll = Effect.fn("runStopAll")(function* () {
540 const threadIds = yield* directory.listThreadIds();
541 const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
542 adapter.listSessions(),
543 ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
544 yield* Effect.forEach(activeSessions, (session) =>
545 upsertSessionBinding(session, session.threadId, {
546 lastRuntimeEvent: "provider.stopAll",
547 lastRuntimeEventAt: new Date().toISOString(),
548 }),
549 ).pipe(Effect.asVoid);
550 yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
551 yield* Effect.forEach(threadIds, (threadId) =>
552 directory.getProvider(threadId).pipe(
553 Effect.flatMap((provider) =>
554 directory.upsert({
555 threadId,
556 provider,
557 status: "stopped",
558 runtimePayload: {
559 activeTurnId: null,
560 lastRuntimeEvent: "provider.stopAll",
561 lastRuntimeEventAt: new Date().toISOString(),
562 },
563 }),
564 ),
565 ),
566 ).pipe(Effect.asVoid);
567 yield* analytics.record("provider.sessions.stopped_all", {
568 sessionCount: threadIds.length,
569 });
570 yield* analytics.flush;
571 });
572​
573 yield* Effect.addFinalizer(() =>
574 Effect.catch(runStopAll(), (cause) =>
575 Effect.logWarning("failed to stop provider service", { cause }),
576 ),
577 );
578​
579 return {
580 startSession,
581 sendTurn,
582 interruptTurn,
583 respondToRequest,
584 respondToUserInput,
585 stopSession,
586 listSessions,
587 getCapabilities,
588 rollbackConversation,
589 // Each access creates a fresh PubSub subscription so that multiple
590 // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
591 // independently receive all runtime events.
592 get streamEvents(): ProviderServiceShape["streamEvents"] {
593 return Stream.fromPubSub(runtimeEventPubSub);
594 },
595 } satisfies ProviderServiceShape;
596});
597​
598export const ProviderServiceLive = Layer.effect(ProviderService, makeProviderService());
599​
600export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
601 return Layer.effect(ProviderService, makeProviderService(options));