Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9
10import { RunFinalizationService } from "./RunFinalizationService.ts";
11import { ResourceCleanupService } from "./ResourceCleanupService.ts";
12import { EffectOutboxV2, type OrchestrationEffectV2 } from "./EffectOutbox.ts";
13import { CheckpointRollbackServiceV2 } from "./CheckpointRollbackService.ts";
14import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
15import { ProviderTurnControlServiceV2 } from "./ProviderTurnControlService.ts";
16import { ProviderTurnStartServiceV2 } from "./ProviderTurnStartService.ts";
17import { RuntimeRequestServiceV2 } from "./RuntimeRequestService.ts";
18
19export class OrchestrationEffectExecutionError extends Schema.TaggedErrorClass<OrchestrationEffectExecutionError>()(
20 "OrchestrationEffectExecutionError",
21 {
22 effectId: Schema.String,
23 effectType: Schema.String,
24 cause: Schema.optional(Schema.Defect()),
25 },
26) {}
27
28export interface OrchestrationEffectExecutorV2Shape {
29 readonly execute: (
30 effect: OrchestrationEffectV2,
31 ) => Effect.Effect<void, OrchestrationEffectExecutionError>;
32}
33
34export class OrchestrationEffectExecutorV2 extends Context.Service<
35 OrchestrationEffectExecutorV2,
36 OrchestrationEffectExecutorV2Shape
37>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectExecutorV2") {}
38
39export const executorLayer: Layer.Layer<
40 OrchestrationEffectExecutorV2,
41 never,
42 | ProviderSessionManagerV2
43 | RunFinalizationService
44 | CheckpointRollbackServiceV2
45 | ProviderTurnControlServiceV2
46 | ProviderTurnStartServiceV2
47 | RuntimeRequestServiceV2
48> = Layer.effect(
49 OrchestrationEffectExecutorV2,
50 Effect.gen(function* () {
51 const runFinalization = yield* RunFinalizationService;
52 const resourceCleanup = yield* ResourceCleanupService;
53 const checkpointRollback = yield* CheckpointRollbackServiceV2;
54 const providerSessions = yield* ProviderSessionManagerV2;
55 const providerTurnControl = yield* ProviderTurnControlServiceV2;
56 const providerTurnStart = yield* ProviderTurnStartServiceV2;
57 const runtimeRequests = yield* RuntimeRequestServiceV2;
58 return OrchestrationEffectExecutorV2.of({
59 execute: (effect) => {
60 switch (effect.request.type) {
61 case "provider-session.detach":
62 return providerSessions
63 .detach({
64 providerSessionId: effect.request.providerSessionId,
65 threadId: effect.threadId,
66 ...(effect.request.detail === undefined ? {} : { detail: effect.request.detail }),
67 })
68 .pipe(
69 Effect.mapError(
70 (cause) =>
71 new OrchestrationEffectExecutionError({
72 effectId: effect.id,
73 effectType: effect.request.type,
74 cause,
75 }),
76 ),
77 );
78 case "provider-turn.start":
79 return providerTurnStart
80 .start({ threadId: effect.threadId, runId: effect.request.runId })
81 .pipe(
82 Effect.mapError(
83 (cause) =>
84 new OrchestrationEffectExecutionError({
85 effectId: effect.id,
86 effectType: effect.request.type,
87 cause,
88 }),
89 ),
90 );
91 case "provider-turn.interrupt":
92 return providerTurnControl
93 .interrupt({
94 threadId: effect.threadId,
95 providerSessionId: effect.request.providerSessionId,
96 providerThreadId: effect.request.providerThreadId,
97 providerTurnId: effect.request.providerTurnId,
98 })
99 .pipe(
100 Effect.mapError(
101 (cause) =>
102 new OrchestrationEffectExecutionError({
103 effectId: effect.id,
104 effectType: effect.request.type,
105 cause,
106 }),
107 ),
108 );
109 case "provider-turn.steer":
110 return providerTurnControl
111 .steer({
112 threadId: effect.threadId,
113 providerSessionId: effect.request.providerSessionId,
114 providerThreadId: effect.request.providerThreadId,
115 providerTurnId: effect.request.providerTurnId,
116 messageId: effect.request.messageId,
117 })
118 .pipe(
119 Effect.mapError(
120 (cause) =>
121 new OrchestrationEffectExecutionError({
122 effectId: effect.id,
123 effectType: effect.request.type,
124 cause,
125 }),
126 ),
127 );
128 case "provider-turn.restart":
129 return providerTurnControl
130 .interruptAndAwaitTerminal({
131 threadId: effect.threadId,
132 providerSessionId: effect.request.providerSessionId,
133 providerThreadId: effect.request.providerThreadId,
134 providerTurnId: effect.request.providerTurnId,
135 interruptedAttemptId: effect.request.interruptedAttemptId,
136 ...(effect.request.sessionTransition?.type === "replace"
137 ? {
138 replacementProviderSessionId:
139 effect.request.sessionTransition.replacementProviderSessionId,
140 }
141 : {}),
142 })
143 .pipe(
144 Effect.andThen(
145 effect.request.sessionTransition?.type === "replace"
146 ? providerSessions.detach({
147 providerSessionId: effect.request.providerSessionId,
148 threadId: effect.threadId,
149 detail: "Selection change requires a provider session restart.",
150 })
151 : effect.request.sessionTransition?.type === "detach"
152 ? providerSessions.detach({
153 providerSessionId: effect.request.providerSessionId,
154 threadId: effect.threadId,
155 detail: "Provider thread handoff replaced this session binding.",
156 })
157 : Effect.void,
158 ),
159 Effect.andThen(
160 providerTurnStart.start({
161 threadId: effect.threadId,
162 runId: effect.request.runId,
163 }),
164 ),
165 Effect.mapError(
166 (cause) =>
167 new OrchestrationEffectExecutionError({
168 effectId: effect.id,
169 effectType: effect.request.type,
170 cause,
171 }),
172 ),
173 );
174 case "runtime-request.respond":
175 return runtimeRequests
176 .respond({
177 threadId: effect.threadId,
178 providerSessionId: effect.request.providerSessionId,
179 requestId: effect.request.requestId,
180 ...(effect.request.decision === undefined
181 ? {}
182 : { decision: effect.request.decision }),
183 ...(effect.request.answers === undefined
184 ? {}
185 : { answers: effect.request.answers }),
186 })
187 .pipe(
188 Effect.mapError(
189 (cause) =>
190 new OrchestrationEffectExecutionError({
191 effectId: effect.id,
192 effectType: effect.request.type,
193 cause,
194 }),
195 ),
196 );
197 case "provider-thread.rollback":
198 return checkpointRollback
199 .execute({
200 threadId: effect.threadId,
201 providerThreadId: effect.request.providerThreadId,
202 checkpointId: effect.request.checkpointId,
203 scopeId: effect.request.scopeId,
204 })
205 .pipe(
206 Effect.mapError(
207 (cause) =>
208 new OrchestrationEffectExecutionError({
209 effectId: effect.id,
210 effectType: effect.request.type,
211 cause,
212 }),
213 ),
214 );
215 case "checkpoint.capture":
216 return runFinalization
217 .finalize({
218 threadId: effect.threadId,
219 runId: effect.request.runId,
220 scopeId: effect.request.scopeId,
221 })
222 .pipe(
223 Effect.mapError(
224 (cause) =>
225 new OrchestrationEffectExecutionError({
226 effectId: effect.id,
227 effectType: effect.request.type,
228 cause,
229 }),
230 ),
231 );
232 case "terminal.cleanup":
233 return resourceCleanup.cleanupTerminals(effect.threadId).pipe(
234 Effect.mapError(
235 (cause) =>
236 new OrchestrationEffectExecutionError({
237 effectId: effect.id,
238 effectType: effect.request.type,
239 cause,
240 }),
241 ),
242 );
243 case "attachment.cleanup":
244 return resourceCleanup.cleanupAttachments(effect.request.attachmentIds).pipe(
245 Effect.mapError(
246 (cause) =>
247 new OrchestrationEffectExecutionError({
248 effectId: effect.id,
249 effectType: effect.request.type,
250 cause,
251 }),
252 ),
253 );
254 }
255 },
256 });
257 }),
258);
259
260export class OrchestrationEffectWorkerError extends Schema.TaggedErrorClass<OrchestrationEffectWorkerError>()(
261 "OrchestrationEffectWorkerError",
262 {
263 operation: Schema.String,
264 effectId: Schema.optional(Schema.String),
265 cause: Schema.optional(Schema.Defect()),
266 },
267) {}
268
269const isOrchestrationEffectWorkerError = Schema.is(OrchestrationEffectWorkerError);
270
271export interface OrchestrationEffectWorkerV2Shape {
272 readonly awaitWork: Effect.Effect<void>;
273 readonly runOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
274 readonly drain: (maxEffects?: number) => Effect.Effect<number, OrchestrationEffectWorkerError>;
275}
276
277export class OrchestrationEffectWorkerV2 extends Context.Service<
278 OrchestrationEffectWorkerV2,
279 OrchestrationEffectWorkerV2Shape
280>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectWorkerV2") {}
281
282export interface OrchestrationEffectWorkerOptions {
283 readonly workerId?: string;
284 readonly leaseDurationMs?: number;
285 readonly maxAttempts?: number;
286}
287
288export const layerWithOptions = (
289 options: OrchestrationEffectWorkerOptions = {},
290): Layer.Layer<
291 OrchestrationEffectWorkerV2,
292 never,
293 EffectOutboxV2 | OrchestrationEffectExecutorV2
294> =>
295 Layer.effect(
296 OrchestrationEffectWorkerV2,
297 Effect.gen(function* () {
298 const outbox = yield* EffectOutboxV2;
299 const executor = yield* OrchestrationEffectExecutorV2;
300 const workerId = options.workerId ?? `orchestration-v2:${process.pid}`;
301 const leaseDurationMs = Math.max(1, options.leaseDurationMs ?? 30_000);
302 const maxAttempts = Math.max(1, options.maxAttempts ?? 5);
303 const wasCancelled = (effectId: string) =>
304 outbox.get(effectId).pipe(
305 Effect.map(
306 Option.match({
307 onNone: () => false,
308 onSome: (effect) => effect.status === "cancelled",
309 }),
310 ),
311 );
312
313 const runOnce = Effect.gen(function* () {
314 const claimed = yield* outbox.claimNext({ workerId, leaseDurationMs });
315 if (Option.isNone(claimed)) {
316 return false;
317 }
318 const effect = claimed.value;
319 // Cancellation can commit after the durable claim but before the
320 // process-local Deferred is registered. Re-read the authoritative row
321 // once before starting external work; later cancellations use the
322 // Deferred raced below.
323 if (yield* wasCancelled(effect.id)) {
324 yield* outbox.clearCancellation(effect.id);
325 return true;
326 }
327 const execution = executor.execute(effect).pipe(Effect.as("executed" as const));
328 const cancellation = outbox
329 .awaitCancellation(effect.id)
330 .pipe(Effect.as("cancelled" as const));
331 const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe(
332 Effect.ensuring(outbox.clearCancellation(effect.id)),
333 );
334 if (Exit.isSuccess(exit) && exit.value === "cancelled") {
335 return true;
336 }
337 if (Exit.isSuccess(exit)) {
338 const completed = yield* outbox.succeed({ effectId: effect.id, workerId });
339 if (!completed) {
340 if (yield* wasCancelled(effect.id)) return true;
341 return yield* new OrchestrationEffectWorkerError({
342 operation: "complete",
343 effectId: effect.id,
344 cause: "The worker no longer owns the effect lease.",
345 });
346 }
347 return true;
348 }
349
350 const error = Cause.pretty(exit.cause);
351 yield* Effect.logWarning("Orchestration effect execution failed", {
352 effectId: effect.id,
353 effectType: effect.request.type,
354 attemptCount: effect.attemptCount,
355 error,
356 });
357 const updated =
358 effect.attemptCount >= maxAttempts
359 ? yield* outbox.fail({ effectId: effect.id, workerId, error })
360 : yield* outbox.retry({
361 effectId: effect.id,
362 workerId,
363 error,
364 delayMs: Math.min(30_000, 100 * 2 ** Math.max(0, effect.attemptCount - 1)),
365 });
366 if (!updated) {
367 if (yield* wasCancelled(effect.id)) return true;
368 return yield* new OrchestrationEffectWorkerError({
369 operation: "reschedule",
370 effectId: effect.id,
371 cause: "The worker no longer owns the effect lease.",
372 });
373 }
374 return true;
375 }).pipe(
376 Effect.mapError((cause) =>
377 isOrchestrationEffectWorkerError(cause)
378 ? cause
379 : new OrchestrationEffectWorkerError({ operation: "run", cause }),
380 ),
381 );
382
383 return OrchestrationEffectWorkerV2.of({
384 awaitWork: outbox.awaitAvailable,
385 runOnce,
386 drain: (maxEffects = Number.MAX_SAFE_INTEGER) =>
387 Effect.gen(function* () {
388 let completed = 0;
389 while (completed < maxEffects && (yield* runOnce)) {
390 completed += 1;
391 }
392 return completed;
393 }),
394 });
395 }),
396 );
397
398export const layer = layerWithOptions();
399
400export interface OrchestrationEffectDaemonOptions {
401 readonly concurrency?: number;
402}
403
404export const DEFAULT_EFFECT_WORKER_CONCURRENCY = 4;
405
406export const runDaemonWithOptions = (options: OrchestrationEffectDaemonOptions = {}) =>
407 Effect.scoped(
408 Effect.gen(function* () {
409 const worker = yield* OrchestrationEffectWorkerV2;
410 const requestedConcurrency = options.concurrency ?? DEFAULT_EFFECT_WORKER_CONCURRENCY;
411 const concurrency = Number.isFinite(requestedConcurrency)
412 ? Math.max(1, Math.floor(requestedConcurrency))
413 : DEFAULT_EFFECT_WORKER_CONCURRENCY;
414 // Notifications only reduce latency; the durable outbox remains authoritative.
415 // Every slot polls after a bounded delay so a missed or coalesced wakeup can
416 // never strand committed work. Consuming the outbox signal directly also
417 // avoids lifecycle coupling between a separate fan-out fiber and subscribers.
418 const runWorker = Effect.forever(
419 worker.runOnce.pipe(
420 Effect.catchCause((cause) =>
421 Effect.logWarning("Orchestration effect worker failed", cause).pipe(Effect.as(false)),
422 ),
423 Effect.flatMap((worked) =>
424 worked
425 ? Effect.yieldNow
426 : Effect.raceFirst(worker.awaitWork, Effect.sleep(Duration.millis(50))),
427 ),
428 ),
429 );
430
431 return yield* Effect.all(
432 Array.from({ length: concurrency }, () => runWorker),
433 {
434 concurrency: "unbounded",
435 discard: true,
436 },
437 );
438 }),
439 );
440
441export const runDaemon = runDaemonWithOptions();
442
443export const daemonLayer: Layer.Layer<never, never, OrchestrationEffectWorkerV2> =
444 Layer.effectDiscard(runDaemon.pipe(Effect.forkScoped));