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

ProviderService.ts

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