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

ProviderService.ts

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