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

CheckpointReactor.ts

737 lines23.3 KB

1import {
2 CommandId,
3 EventId,
4 MessageId,
5 ProviderSessionId,
6 ProviderThreadId,
7 ThreadId,
8 TurnId,
9 type OrchestrationEvent,
10 type ProviderRuntimeEvent,
11} from "@t3tools/contracts";
12import { Cause, Effect, Layer, Option, Queue, Stream } from "effect";
13​
14import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
15import {
16 checkpointRefForThreadTurn,
17 resolveThreadWorkspaceCwd,
18} from "../../checkpointing/Utils.ts";
19import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
20import { ProviderService } from "../../provider/Services/ProviderService.ts";
21import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
22import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
23import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
24import { OrchestrationDispatchError } from "../Errors.ts";
25​
26type ReactorInput =
27 | {
28 readonly source: "runtime";
29 readonly event: ProviderRuntimeEvent;
30 }
31 | {
32 readonly source: "domain";
33 readonly event: OrchestrationEvent;
34 };
35​
36function toTurnId(value: string | undefined): TurnId | null {
37 return value === undefined ? null : TurnId.makeUnsafe(value);
39​
40function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
41 return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
43​
44function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
45 if (left === null || left === undefined || right === null || right === undefined) {
46 return false;
47 }
48 return left === right;
50​
51function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
52 switch (status) {
53 case "failed":
54 return "error";
55 case "cancelled":
56 case "interrupted":
57 return "missing";
58 case "completed":
59 default:
60 return "ready";
61 }
63​
64const serverCommandId = (tag: string): CommandId =>
65 CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
66​
67const make = Effect.gen(function* () {
68 const orchestrationEngine = yield* OrchestrationEngineService;
69 const providerService = yield* ProviderService;
70 const checkpointStore = yield* CheckpointStore;
71​
72 const appendRevertFailureActivity = (input: {
73 readonly threadId: ThreadId;
74 readonly turnCount: number;
75 readonly detail: string;
76 readonly createdAt: string;
77 }) =>
78 orchestrationEngine.dispatch({
79 type: "thread.activity.append",
80 commandId: serverCommandId("checkpoint-revert-failure"),
81 threadId: input.threadId,
82 activity: {
83 id: EventId.makeUnsafe(crypto.randomUUID()),
84 tone: "error",
85 kind: "checkpoint.revert.failed",
86 summary: "Checkpoint revert failed",
87 payload: {
88 turnCount: input.turnCount,
89 detail: input.detail,
90 },
91 turnId: null,
92 createdAt: input.createdAt,
93 },
94 createdAt: input.createdAt,
95 });
96​
97 const appendCaptureFailureActivity = (input: {
98 readonly sessionId: ProviderSessionId;
99 readonly turnId: TurnId | null;
100 readonly detail: string;
101 readonly createdAt: string;
102 }) =>
103 Effect.gen(function* () {
104 const readModel = yield* orchestrationEngine.getReadModel();
105 const thread = readModel.threads.find(
106 (entry) => entry.session?.providerSessionId === input.sessionId,
107 );
108 if (!thread) {
109 return;
110 }
111 yield* orchestrationEngine.dispatch({
112 type: "thread.activity.append",
113 commandId: serverCommandId("checkpoint-capture-failure"),
114 threadId: thread.id,
115 activity: {
116 id: EventId.makeUnsafe(crypto.randomUUID()),
117 tone: "error",
118 kind: "checkpoint.capture.failed",
119 summary: "Checkpoint capture failed",
120 payload: {
121 detail: input.detail,
122 },
123 turnId: input.turnId,
124 createdAt: input.createdAt,
125 },
126 createdAt: input.createdAt,
127 });
128 });
129​
130 const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
131 threadId: ThreadId,
132 ): Effect.fn.Return<
133 Option.Option<{ readonly sessionId: ProviderSessionId; readonly cwd: string }>
134 > {
135 const readModel = yield* orchestrationEngine.getReadModel();
136 const thread = readModel.threads.find((entry) => entry.id === threadId);
137 const projectedSessionId = thread?.session?.providerSessionId ?? null;
138 const projectedProviderThreadId = thread?.session?.providerThreadId ?? undefined;
139​
140 const sessions = yield* providerService.listSessions();
141​
142 const findSessionWithCwd = (
143 session: (typeof sessions)[number] | undefined,
144 ): Option.Option<{ readonly sessionId: ProviderSessionId; readonly cwd: string }> => {
145 if (!session?.cwd) {
146 return Option.none();
147 }
148 return Option.some({ sessionId: session.sessionId, cwd: session.cwd });
149 };
150​
151 if (projectedSessionId !== null) {
152 const projectedSession = sessions.find((session) => session.sessionId === projectedSessionId);
153 const fromProjected = findSessionWithCwd(projectedSession);
154 if (Option.isSome(fromProjected)) {
155 return fromProjected;
156 }
157 }
158​
159 if (projectedProviderThreadId) {
160 const matchedSession = sessions.find(
161 (session) => session.threadId === projectedProviderThreadId,
162 );
163 const fromProviderThread = findSessionWithCwd(matchedSession);
164 if (Option.isSome(fromProviderThread)) {
165 return fromProviderThread;
166 }
167 }
168​
169 return Option.none();
170 });
171​
172 const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
173 event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
174 ) {
175 const turnId = toTurnId(event.turnId);
176 if (!turnId) {
177 return;
178 }
179​
180 const readModel = yield* orchestrationEngine.getReadModel();
181 const thread = readModel.threads.find(
182 (entry) => entry.session?.providerSessionId === event.sessionId,
183 );
184 if (!thread) {
185 return;
186 }
187​
188 const projectedProviderThreadId = thread.session?.providerThreadId ?? null;
189 const eventProviderThreadId = toProviderThreadId(event.threadId);
190 if (
191 projectedProviderThreadId !== null &&
192 eventProviderThreadId !== null &&
193 !sameId(projectedProviderThreadId, eventProviderThreadId)
194 ) {
195 return;
196 }
197​
198 // When a primary turn is active, only that turn may produce completion checkpoints.
199 if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
200 return;
201 }
202​
203 if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
204 return;
205 }
206​
207 const sessionRuntime = yield* resolveSessionRuntimeForThread(thread.id);
208 const checkpointCwd =
209 Option.match(sessionRuntime, {
210 onNone: () => undefined,
211 onSome: (runtime) => runtime.cwd,
212 }) ??
213 resolveThreadWorkspaceCwd({
214 thread,
215 projects: readModel.projects,
216 });
217 if (!checkpointCwd) {
218 yield* Effect.logWarning("checkpoint capture skipped: no active provider session cwd", {
219 threadId: thread.id,
220 turnId,
221 });
222 return;
223 }
224​
225 const currentTurnCount = thread.checkpoints.reduce(
226 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
227 0,
228 );
229 const nextTurnCount = currentTurnCount + 1;
230 const fromTurnCount = Math.max(0, nextTurnCount - 1);
231 const fromCheckpointRef = checkpointRefForThreadTurn(thread.id, fromTurnCount);
232 const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, nextTurnCount);
233​
234 const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({
235 cwd: checkpointCwd,
236 checkpointRef: fromCheckpointRef,
237 });
238 if (!fromCheckpointExists) {
239 yield* Effect.logWarning("checkpoint completion missing pre-turn baseline", {
240 threadId: thread.id,
241 turnId,
242 fromTurnCount,
243 });
244 }
245​
246 yield* checkpointStore.captureCheckpoint({
247 cwd: checkpointCwd,
248 checkpointRef: targetCheckpointRef,
249 });
250​
251 const files = yield* checkpointStore
252 .diffCheckpoints({
253 cwd: checkpointCwd,
254 fromCheckpointRef,
255 toCheckpointRef: targetCheckpointRef,
256 fallbackFromToHead: false,
257 })
258 .pipe(
259 Effect.map((diff) =>
260 parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
261 path: file.path,
262 kind: "modified" as const,
263 additions: file.additions,
264 deletions: file.deletions,
265 })),
266 ),
267 Effect.tapError((error) =>
268 appendCaptureFailureActivity({
269 sessionId: event.sessionId,
270 turnId,
271 detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
272 createdAt: event.createdAt,
273 }),
274 ),
275 Effect.catch((error) =>
276 Effect.logWarning("failed to derive checkpoint file summary", {
277 threadId: thread.id,
278 turnId,
279 turnCount: nextTurnCount,
280 detail: error.message,
281 }).pipe(Effect.as([])),
282 ),
283 );
284​
285 const assistantMessageId =
286 thread.messages
287 .toReversed()
288 .find((entry) => entry.role === "assistant" && entry.turnId === turnId)?.id ??
289 MessageId.makeUnsafe(`assistant:${turnId}`);
290​
291 const now = event.createdAt;
292 yield* orchestrationEngine.dispatch({
293 type: "thread.turn.diff.complete",
294 commandId: serverCommandId("checkpoint-turn-diff-complete"),
295 threadId: thread.id,
296 turnId,
297 completedAt: now,
298 checkpointRef: targetCheckpointRef,
299 status: checkpointStatusFromRuntime(event.status),
300 files,
301 assistantMessageId,
302 checkpointTurnCount: nextTurnCount,
303 createdAt: now,
304 });
305​
306 yield* orchestrationEngine.dispatch({
307 type: "thread.activity.append",
308 commandId: serverCommandId("checkpoint-captured-activity"),
309 threadId: thread.id,
310 activity: {
311 id: EventId.makeUnsafe(crypto.randomUUID()),
312 tone: "info",
313 kind: "checkpoint.captured",
314 summary: "Checkpoint captured",
315 payload: {
316 turnCount: nextTurnCount,
317 ...(event.status !== undefined ? { status: event.status } : {}),
318 },
319 turnId,
320 createdAt: now,
321 },
322 createdAt: now,
323 });
324 });
325​
326 const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* (
327 event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>,
328 ) {
329 const turnId = toTurnId(event.turnId);
330 if (!turnId) {
331 return;
332 }
333​
334 const readModel = yield* orchestrationEngine.getReadModel();
335 const thread = readModel.threads.find(
336 (entry) => entry.session?.providerSessionId === event.sessionId,
337 );
338 if (!thread) {
339 return;
340 }
341​
342 const checkpointCwdFromThreadOrProject = resolveThreadWorkspaceCwd({
343 thread,
344 projects: readModel.projects,
345 });
346 const checkpointCwd =
347 checkpointCwdFromThreadOrProject ??
348 Option.match(yield* resolveSessionRuntimeForThread(thread.id), {
349 onNone: () => undefined,
350 onSome: (runtime) => runtime.cwd,
351 });
352 if (!checkpointCwd) {
353 yield* Effect.logWarning("checkpoint pre-turn capture skipped: no workspace cwd", {
354 threadId: thread.id,
355 turnId,
356 });
357 return;
358 }
359​
360 const currentTurnCount = thread.checkpoints.reduce(
361 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
362 0,
363 );
364 const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
365 const baselineExists = yield* checkpointStore.hasCheckpointRef({
366 cwd: checkpointCwd,
367 checkpointRef: baselineCheckpointRef,
368 });
369 if (baselineExists) {
370 return;
371 }
372​
373 yield* checkpointStore.captureCheckpoint({
374 cwd: checkpointCwd,
375 checkpointRef: baselineCheckpointRef,
376 });
377 });
378​
379 const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
380 event: Extract<
381 OrchestrationEvent,
382 { type: "thread.turn-start-requested" | "thread.message-sent" }
383 >,
384 ) {
385 if (event.type === "thread.message-sent") {
386 if (
387 event.payload.role !== "user" ||
388 event.payload.streaming ||
389 event.payload.turnId !== null
390 ) {
391 return;
392 }
393 }
394​
395 const threadId = event.payload.threadId;
396 const readModel = yield* orchestrationEngine.getReadModel();
397 const thread = readModel.threads.find((entry) => entry.id === threadId);
398 if (!thread) {
399 return;
400 }
401​
402 const checkpointCwdFromThreadOrProject = resolveThreadWorkspaceCwd({
403 thread,
404 projects: readModel.projects,
405 });
406 const checkpointCwd =
407 checkpointCwdFromThreadOrProject ??
408 Option.match(yield* resolveSessionRuntimeForThread(threadId), {
409 onNone: () => undefined,
410 onSome: (runtime) => runtime.cwd,
411 });
412 if (!checkpointCwd) {
413 yield* Effect.logWarning("checkpoint pre-turn capture skipped: no workspace cwd", {
414 threadId,
415 });
416 return;
417 }
418​
419 const currentTurnCount = thread.checkpoints.reduce(
420 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
421 0,
422 );
423 const baselineCheckpointRef = checkpointRefForThreadTurn(threadId, currentTurnCount);
424 const baselineExists = yield* checkpointStore.hasCheckpointRef({
425 cwd: checkpointCwd,
426 checkpointRef: baselineCheckpointRef,
427 });
428 if (baselineExists) {
429 return;
430 }
431​
432 yield* checkpointStore.captureCheckpoint({
433 cwd: checkpointCwd,
434 checkpointRef: baselineCheckpointRef,
435 });
436 });
437​
438 const handleRevertRequested = Effect.fnUntraced(function* (
439 event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
440 ) {
441 const now = new Date().toISOString();
442​
443 const readModel = yield* orchestrationEngine.getReadModel();
444 const thread = readModel.threads.find((entry) => entry.id === event.payload.threadId);
445 if (!thread) {
446 yield* appendRevertFailureActivity({
447 threadId: event.payload.threadId,
448 turnCount: event.payload.turnCount,
449 detail: "Thread was not found in read model.",
450 createdAt: now,
451 }).pipe(Effect.catch(() => Effect.void));
452 return;
453 }
454​
455 const sessionRuntime = yield* resolveSessionRuntimeForThread(event.payload.threadId);
456 if (Option.isNone(sessionRuntime)) {
457 yield* appendRevertFailureActivity({
458 threadId: event.payload.threadId,
459 turnCount: event.payload.turnCount,
460 detail: "No active provider session with workspace cwd is bound to this thread.",
461 createdAt: now,
462 }).pipe(Effect.catch(() => Effect.void));
463 return;
464 }
465​
466 const currentTurnCount = thread.checkpoints.reduce(
467 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
468 0,
469 );
470​
471 if (event.payload.turnCount > currentTurnCount) {
472 yield* appendRevertFailureActivity({
473 threadId: event.payload.threadId,
474 turnCount: event.payload.turnCount,
475 detail: `Checkpoint turn count ${event.payload.turnCount} exceeds current turn count ${currentTurnCount}.`,
476 createdAt: now,
477 }).pipe(Effect.catch(() => Effect.void));
478 return;
479 }
480​
481 const targetCheckpointRef =
482 event.payload.turnCount === 0
483 ? checkpointRefForThreadTurn(event.payload.threadId, 0)
484 : thread.checkpoints.find(
485 (checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount,
486 )?.checkpointRef;
487​
488 if (!targetCheckpointRef) {
489 yield* appendRevertFailureActivity({
490 threadId: event.payload.threadId,
491 turnCount: event.payload.turnCount,
492 detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`,
493 createdAt: now,
494 }).pipe(Effect.catch(() => Effect.void));
495 return;
496 }
497​
498 const restored = yield* checkpointStore.restoreCheckpoint({
499 cwd: sessionRuntime.value.cwd,
500 checkpointRef: targetCheckpointRef,
501 fallbackToHead: event.payload.turnCount === 0,
502 });
503 if (!restored) {
504 yield* appendRevertFailureActivity({
505 threadId: event.payload.threadId,
506 turnCount: event.payload.turnCount,
507 detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`,
508 createdAt: now,
509 }).pipe(Effect.catch(() => Effect.void));
510 return;
511 }
512​
513 const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
514 if (rolledBackTurns > 0) {
515 yield* providerService.rollbackConversation({
516 sessionId: sessionRuntime.value.sessionId,
517 numTurns: rolledBackTurns,
518 });
519 }
520​
521 const staleCheckpointRefs = thread.checkpoints
522 .filter((checkpoint) => checkpoint.checkpointTurnCount > event.payload.turnCount)
523 .map((checkpoint) => checkpoint.checkpointRef);
524​
525 if (staleCheckpointRefs.length > 0) {
526 yield* checkpointStore.deleteCheckpointRefs({
527 cwd: sessionRuntime.value.cwd,
528 checkpointRefs: staleCheckpointRefs,
529 });
530 }
531​
532 yield* orchestrationEngine
533 .dispatch({
534 type: "thread.revert.complete",
535 commandId: serverCommandId("checkpoint-revert-complete"),
536 threadId: event.payload.threadId,
537 turnCount: event.payload.turnCount,
538 createdAt: now,
539 })
540 .pipe(
541 Effect.catch((error) =>
542 appendRevertFailureActivity({
543 threadId: event.payload.threadId,
544 turnCount: event.payload.turnCount,
545 detail: error.message,
546 createdAt: now,
547 }),
548 ),
549 Effect.asVoid,
550 );
551 });
552​
553 const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
554 if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
555 yield* ensurePreTurnBaselineFromDomainTurnStart(event);
556 return;
557 }
558​
559 if (event.type === "thread.checkpoint-revert-requested") {
560 yield* handleRevertRequested(event).pipe(
561 Effect.catch((error) =>
562 appendRevertFailureActivity({
563 threadId: event.payload.threadId,
564 turnCount: event.payload.turnCount,
565 detail: error.message,
566 createdAt: new Date().toISOString(),
567 }),
568 ),
569 );
570 }
571 });
572​
573 const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) {
574 if (event.type === "turn.started") {
575 yield* ensurePreTurnBaselineFromTurnStart(event);
576 return;
577 }
578​
579 if (event.type === "turn.completed") {
580 const turnId = toTurnId(event.turnId);
581 yield* captureCheckpointFromTurnCompletion(event).pipe(
582 Effect.catch((error) =>
583 appendCaptureFailureActivity({
584 sessionId: event.sessionId,
585 turnId,
586 detail: error.message,
587 createdAt: new Date().toISOString(),
588 }).pipe(Effect.catch(() => Effect.void)),
589 ),
590 );
591 return;
592 }
593​
594 if (event.type === "checkpoint.captured") {
595 const turnId = toTurnId(event.turnId);
596 if (!turnId) {
597 return;
598 }
599​
600 const readModel = yield* orchestrationEngine.getReadModel();
601 const thread = readModel.threads.find(
602 (entry) => entry.session?.providerSessionId === event.sessionId,
603 );
604 if (!thread) {
605 return;
606 }
607​
608 if (
609 thread.checkpoints.some(
610 (checkpoint) =>
611 checkpoint.turnId === turnId || checkpoint.checkpointTurnCount === event.turnCount,
612 )
613 ) {
614 return;
615 }
616​
617 const sessionRuntime = yield* resolveSessionRuntimeForThread(thread.id);
618 if (Option.isNone(sessionRuntime)) {
619 return;
620 }
621​
622 const fromTurnCount = Math.max(0, event.turnCount - 1);
623 const fromCheckpointRef = checkpointRefForThreadTurn(thread.id, fromTurnCount);
624 const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, event.turnCount);
625​
626 const targetExists = yield* checkpointStore.hasCheckpointRef({
627 cwd: sessionRuntime.value.cwd,
628 checkpointRef: targetCheckpointRef,
629 });
630 if (!targetExists) {
631 yield* checkpointStore.captureCheckpoint({
632 cwd: sessionRuntime.value.cwd,
633 checkpointRef: targetCheckpointRef,
634 });
635 }
636​
637 const files = yield* checkpointStore
638 .diffCheckpoints({
639 cwd: sessionRuntime.value.cwd,
640 fromCheckpointRef,
641 toCheckpointRef: targetCheckpointRef,
642 fallbackFromToHead: false,
643 })
644 .pipe(
645 Effect.map((diff) =>
646 parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
647 path: file.path,
648 kind: "modified" as const,
649 additions: file.additions,
650 deletions: file.deletions,
651 })),
652 ),
653 Effect.catch(() => Effect.succeed([])),
654 );
655​
656 const assistantMessageId =
657 thread.messages
658 .toReversed()
659 .find((entry) => entry.role === "assistant" && entry.turnId === turnId)?.id ??
660 MessageId.makeUnsafe(`assistant:${turnId}`);
661​
662 yield* orchestrationEngine.dispatch({
663 type: "thread.turn.diff.complete",
664 commandId: serverCommandId("checkpoint-runtime-captured-diff-complete"),
665 threadId: thread.id,
666 turnId,
667 completedAt: event.createdAt,
668 checkpointRef: targetCheckpointRef,
669 status: checkpointStatusFromRuntime(event.status),
670 files,
671 assistantMessageId,
672 checkpointTurnCount: event.turnCount,
673 createdAt: event.createdAt,
674 });
675 }
676 });
677​
678 const processInput = (
679 input: ReactorInput,
680 ): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError, never> =>
681 input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
682​
683 const processInputSafely = (input: ReactorInput) =>
684 processInput(input).pipe(
685 Effect.catchCause((cause) => {
686 if (Cause.hasInterruptsOnly(cause)) {
687 return Effect.failCause(cause);
688 }
689 return Effect.logWarning("checkpoint reactor failed to process input", {
690 source: input.source,
691 eventType: input.event.type,
692 cause: Cause.pretty(cause),
693 });
694 }),
695 );
696​
697 const start: CheckpointReactorShape["start"] = Effect.gen(function* () {
698 const queue = yield* Queue.unbounded<ReactorInput>();
699 yield* Effect.addFinalizer(() => Queue.shutdown(queue).pipe(Effect.asVoid));
700​
701 yield* Effect.forkScoped(
702 Effect.forever(Queue.take(queue).pipe(Effect.flatMap(processInputSafely))),
703 );
704​
705 yield* Effect.forkScoped(
706 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
707 if (
708 event.type !== "thread.turn-start-requested" &&
709 event.type !== "thread.message-sent" &&
710 event.type !== "thread.checkpoint-revert-requested"
711 ) {
712 return Effect.void;
713 }
714 return Queue.offer(queue, { source: "domain", event }).pipe(Effect.asVoid);
715 }),
716 );
717​
718 yield* Effect.forkScoped(
719 Stream.runForEach(providerService.streamEvents, (event) => {
720 if (
721 event.type !== "turn.started" &&
722 event.type !== "turn.completed" &&
723 event.type !== "checkpoint.captured"
724 ) {
725 return Effect.void;
726 }
727 return Queue.offer(queue, { source: "runtime", event }).pipe(Effect.asVoid);
728 }),
729 );
730 });
731​
732 return {
733 start,
734 } satisfies CheckpointReactorShape;
735});
736​
737export const CheckpointReactorLive = Layer.effect(CheckpointReactor, make);