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

ProviderService.ts

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