Open History to see the last commit
1import type {
2 OrchestrationCommand,
3 OrchestrationEvent,
4 OrchestrationReadModel,
5} from "@t3tools/contracts";
6import { Effect } from "effect";
7
8import { OrchestrationCommandInvariantError } from "./Errors.ts";
9import {
10 listThreadsByProjectId,
11 requireProject,
12 requireProjectAbsent,
13 requireThread,
14 requireThreadArchived,
15 requireThreadAbsent,
16 requireThreadNotArchived,
17} from "./commandInvariants.ts";
18import { projectEvent } from "./projector.ts";
19
20const nowIso = () => new Date().toISOString();
21const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
22 eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
23 aggregateKind: "thread",
24 aggregateId: "" as OrchestrationEvent["aggregateId"],
25 occurredAt: nowIso(),
26 commandId: null,
27 causationEventId: null,
28 correlationId: null,
29 metadata: {},
30};
31
32function withEventBase(
33 input: Pick<OrchestrationCommand, "commandId"> & {
34 readonly aggregateKind: OrchestrationEvent["aggregateKind"];
35 readonly aggregateId: OrchestrationEvent["aggregateId"];
36 readonly occurredAt: string;
37 readonly metadata?: OrchestrationEvent["metadata"];
38 },
39): Omit<OrchestrationEvent, "sequence" | "type" | "payload"> {
40 return {
41 ...defaultMetadata,
42 eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
43 aggregateKind: input.aggregateKind,
44 aggregateId: input.aggregateId,
45 occurredAt: input.occurredAt,
46 commandId: input.commandId,
47 correlationId: input.commandId,
48 metadata: input.metadata ?? {},
49 };
50}
51
52type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
53
54type DecideOrchestrationCommandResult =
55 | PlannedOrchestrationEvent
56 | ReadonlyArray<PlannedOrchestrationEvent>;
57
58const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
59 commands,
60 readModel,
61}: {
62 readonly commands: ReadonlyArray<OrchestrationCommand>;
63 readonly readModel: OrchestrationReadModel;
64}): Effect.fn.Return<ReadonlyArray<PlannedOrchestrationEvent>, OrchestrationCommandInvariantError> {
65 let nextReadModel = readModel;
66 let nextSequence = readModel.snapshotSequence;
67 const plannedEvents: PlannedOrchestrationEvent[] = [];
68
69 for (const nextCommand of commands) {
70 const decided = yield* decideOrchestrationCommand({
71 command: nextCommand,
72 readModel: nextReadModel,
73 });
74 const nextEvents = Array.isArray(decided) ? decided : [decided];
75 for (const nextEvent of nextEvents) {
76 plannedEvents.push(nextEvent);
77 nextSequence += 1;
78 nextReadModel = yield* projectEvent(nextReadModel, {
79 ...nextEvent,
80 sequence: nextSequence,
81 }).pipe(Effect.orDie);
82 }
83 }
84
85 return plannedEvents;
86});
87
88export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({
89 command,
90 readModel,
91}: {
92 readonly command: OrchestrationCommand;
93 readonly readModel: OrchestrationReadModel;
94}): Effect.fn.Return<DecideOrchestrationCommandResult, OrchestrationCommandInvariantError> {
95 switch (command.type) {
96 case "project.create": {
97 yield* requireProjectAbsent({
98 readModel,
99 command,
100 projectId: command.projectId,
101 });
102
103 return {
104 ...withEventBase({
105 aggregateKind: "project",
106 aggregateId: command.projectId,
107 occurredAt: command.createdAt,
108 commandId: command.commandId,
109 }),
110 type: "project.created",
111 payload: {
112 projectId: command.projectId,
113 title: command.title,
114 workspaceRoot: command.workspaceRoot,
115 defaultModelSelection: command.defaultModelSelection ?? null,
116 scripts: [],
117 createdAt: command.createdAt,
118 updatedAt: command.createdAt,
119 },
120 };
121 }
122
123 case "project.meta.update": {
124 yield* requireProject({
125 readModel,
126 command,
127 projectId: command.projectId,
128 });
129 const occurredAt = nowIso();
130 return {
131 ...withEventBase({
132 aggregateKind: "project",
133 aggregateId: command.projectId,
134 occurredAt,
135 commandId: command.commandId,
136 }),
137 type: "project.meta-updated",
138 payload: {
139 projectId: command.projectId,
140 ...(command.title !== undefined ? { title: command.title } : {}),
141 ...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
142 ...(command.defaultModelSelection !== undefined
143 ? { defaultModelSelection: command.defaultModelSelection }
144 : {}),
145 ...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
146 updatedAt: occurredAt,
147 },
148 };
149 }
150
151 case "project.delete": {
152 yield* requireProject({
153 readModel,
154 command,
155 projectId: command.projectId,
156 });
157 const activeThreads = listThreadsByProjectId(readModel, command.projectId).filter(
158 (thread) => thread.deletedAt === null,
159 );
160 if (activeThreads.length > 0 && command.force !== true) {
161 return yield* new OrchestrationCommandInvariantError({
162 commandType: command.type,
163 detail: `Project '${command.projectId}' is not empty and cannot be deleted without force=true.`,
164 });
165 }
166 if (activeThreads.length > 0) {
167 return yield* decideCommandSequence({
168 readModel,
169 commands: [
170 ...activeThreads.map(
171 (thread): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({
172 type: "thread.delete",
173 commandId: command.commandId,
174 threadId: thread.id,
175 }),
176 ),
177 {
178 type: "project.delete",
179 commandId: command.commandId,
180 projectId: command.projectId,
181 },
182 ],
183 });
184 }
185
186 const occurredAt = nowIso();
187 return {
188 ...withEventBase({
189 aggregateKind: "project",
190 aggregateId: command.projectId,
191 occurredAt,
192 commandId: command.commandId,
193 }),
194 type: "project.deleted" as const,
195 payload: {
196 projectId: command.projectId,
197 deletedAt: occurredAt,
198 },
199 };
200 }
201
202 case "thread.create": {
203 yield* requireProject({
204 readModel,
205 command,
206 projectId: command.projectId,
207 });
208 yield* requireThreadAbsent({
209 readModel,
210 command,
211 threadId: command.threadId,
212 });
213 return {
214 ...withEventBase({
215 aggregateKind: "thread",
216 aggregateId: command.threadId,
217 occurredAt: command.createdAt,
218 commandId: command.commandId,
219 }),
220 type: "thread.created",
221 payload: {
222 threadId: command.threadId,
223 projectId: command.projectId,
224 title: command.title,
225 modelSelection: command.modelSelection,
226 runtimeMode: command.runtimeMode,
227 interactionMode: command.interactionMode,
228 branch: command.branch,
229 worktreePath: command.worktreePath,
230 createdAt: command.createdAt,
231 updatedAt: command.createdAt,
232 },
233 };
234 }
235
236 case "thread.delete": {
237 yield* requireThread({
238 readModel,
239 command,
240 threadId: command.threadId,
241 });
242 const occurredAt = nowIso();
243 return {
244 ...withEventBase({
245 aggregateKind: "thread",
246 aggregateId: command.threadId,
247 occurredAt,
248 commandId: command.commandId,
249 }),
250 type: "thread.deleted",
251 payload: {
252 threadId: command.threadId,
253 deletedAt: occurredAt,
254 },
255 };
256 }
257
258 case "thread.archive": {
259 yield* requireThreadNotArchived({
260 readModel,
261 command,
262 threadId: command.threadId,
263 });
264 const occurredAt = nowIso();
265 return {
266 ...withEventBase({
267 aggregateKind: "thread",
268 aggregateId: command.threadId,
269 occurredAt,
270 commandId: command.commandId,
271 }),
272 type: "thread.archived",
273 payload: {
274 threadId: command.threadId,
275 archivedAt: occurredAt,
276 updatedAt: occurredAt,
277 },
278 };
279 }
280
281 case "thread.unarchive": {
282 yield* requireThreadArchived({
283 readModel,
284 command,
285 threadId: command.threadId,
286 });
287 const occurredAt = nowIso();
288 return {
289 ...withEventBase({
290 aggregateKind: "thread",
291 aggregateId: command.threadId,
292 occurredAt,
293 commandId: command.commandId,
294 }),
295 type: "thread.unarchived",
296 payload: {
297 threadId: command.threadId,
298 updatedAt: occurredAt,
299 },
300 };
301 }
302
303 case "thread.meta.update": {
304 yield* requireThread({
305 readModel,
306 command,
307 threadId: command.threadId,
308 });
309 const occurredAt = nowIso();
310 return {
311 ...withEventBase({
312 aggregateKind: "thread",
313 aggregateId: command.threadId,
314 occurredAt,
315 commandId: command.commandId,
316 }),
317 type: "thread.meta-updated",
318 payload: {
319 threadId: command.threadId,
320 ...(command.title !== undefined ? { title: command.title } : {}),
321 ...(command.modelSelection !== undefined
322 ? { modelSelection: command.modelSelection }
323 : {}),
324 ...(command.branch !== undefined ? { branch: command.branch } : {}),
325 ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
326 updatedAt: occurredAt,
327 },
328 };
329 }
330
331 case "thread.runtime-mode.set": {
332 yield* requireThread({
333 readModel,
334 command,
335 threadId: command.threadId,
336 });
337 const occurredAt = nowIso();
338 return {
339 ...withEventBase({
340 aggregateKind: "thread",
341 aggregateId: command.threadId,
342 occurredAt,
343 commandId: command.commandId,
344 }),
345 type: "thread.runtime-mode-set",
346 payload: {
347 threadId: command.threadId,
348 runtimeMode: command.runtimeMode,
349 updatedAt: occurredAt,
350 },
351 };
352 }
353
354 case "thread.interaction-mode.set": {
355 yield* requireThread({
356 readModel,
357 command,
358 threadId: command.threadId,
359 });
360 const occurredAt = nowIso();
361 return {
362 ...withEventBase({
363 aggregateKind: "thread",
364 aggregateId: command.threadId,
365 occurredAt,
366 commandId: command.commandId,
367 }),
368 type: "thread.interaction-mode-set",
369 payload: {
370 threadId: command.threadId,
371 interactionMode: command.interactionMode,
372 updatedAt: occurredAt,
373 },
374 };
375 }
376
377 case "thread.turn.start": {
378 const targetThread = yield* requireThread({
379 readModel,
380 command,
381 threadId: command.threadId,
382 });
383 const sourceProposedPlan = command.sourceProposedPlan;
384 const sourceThread = sourceProposedPlan
385 ? yield* requireThread({
386 readModel,
387 command,
388 threadId: sourceProposedPlan.threadId,
389 })
390 : null;
391 const sourcePlan =
392 sourceProposedPlan && sourceThread
393 ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
394 : null;
395 if (sourceProposedPlan && !sourcePlan) {
396 return yield* new OrchestrationCommandInvariantError({
397 commandType: command.type,
398 detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
399 });
400 }
401 if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
402 return yield* new OrchestrationCommandInvariantError({
403 commandType: command.type,
404 detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
405 });
406 }
407 const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
408 ...withEventBase({
409 aggregateKind: "thread",
410 aggregateId: command.threadId,
411 occurredAt: command.createdAt,
412 commandId: command.commandId,
413 }),
414 type: "thread.message-sent",
415 payload: {
416 threadId: command.threadId,
417 messageId: command.message.messageId,
418 role: "user",
419 text: command.message.text,
420 attachments: command.message.attachments,
421 turnId: null,
422 streaming: false,
423 createdAt: command.createdAt,
424 updatedAt: command.createdAt,
425 },
426 };
427 const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
428 ...withEventBase({
429 aggregateKind: "thread",
430 aggregateId: command.threadId,
431 occurredAt: command.createdAt,
432 commandId: command.commandId,
433 }),
434 causationEventId: userMessageEvent.eventId,
435 type: "thread.turn-start-requested",
436 payload: {
437 threadId: command.threadId,
438 messageId: command.message.messageId,
439 ...(command.modelSelection !== undefined
440 ? { modelSelection: command.modelSelection }
441 : {}),
442 ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
443 runtimeMode: targetThread.runtimeMode,
444 interactionMode: targetThread.interactionMode,
445 ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
446 createdAt: command.createdAt,
447 },
448 };
449 return [userMessageEvent, turnStartRequestedEvent];
450 }
451
452 case "thread.turn.interrupt": {
453 yield* requireThread({
454 readModel,
455 command,
456 threadId: command.threadId,
457 });
458 return {
459 ...withEventBase({
460 aggregateKind: "thread",
461 aggregateId: command.threadId,
462 occurredAt: command.createdAt,
463 commandId: command.commandId,
464 }),
465 type: "thread.turn-interrupt-requested",
466 payload: {
467 threadId: command.threadId,
468 ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),
469 createdAt: command.createdAt,
470 },
471 };
472 }
473
474 case "thread.approval.respond": {
475 yield* requireThread({
476 readModel,
477 command,
478 threadId: command.threadId,
479 });
480 return {
481 ...withEventBase({
482 aggregateKind: "thread",
483 aggregateId: command.threadId,
484 occurredAt: command.createdAt,
485 commandId: command.commandId,
486 metadata: {
487 requestId: command.requestId,
488 },
489 }),
490 type: "thread.approval-response-requested",
491 payload: {
492 threadId: command.threadId,
493 requestId: command.requestId,
494 decision: command.decision,
495 createdAt: command.createdAt,
496 },
497 };
498 }
499
500 case "thread.user-input.respond": {
501 yield* requireThread({
502 readModel,
503 command,
504 threadId: command.threadId,
505 });
506 return {
507 ...withEventBase({
508 aggregateKind: "thread",
509 aggregateId: command.threadId,
510 occurredAt: command.createdAt,
511 commandId: command.commandId,
512 metadata: {
513 requestId: command.requestId,
514 },
515 }),
516 type: "thread.user-input-response-requested",
517 payload: {
518 threadId: command.threadId,
519 requestId: command.requestId,
520 answers: command.answers,
521 createdAt: command.createdAt,
522 },
523 };
524 }
525
526 case "thread.checkpoint.revert": {
527 yield* requireThread({
528 readModel,
529 command,
530 threadId: command.threadId,
531 });
532 return {
533 ...withEventBase({
534 aggregateKind: "thread",
535 aggregateId: command.threadId,
536 occurredAt: command.createdAt,
537 commandId: command.commandId,
538 }),
539 type: "thread.checkpoint-revert-requested",
540 payload: {
541 threadId: command.threadId,
542 turnCount: command.turnCount,
543 createdAt: command.createdAt,
544 },
545 };
546 }
547
548 case "thread.session.stop": {
549 yield* requireThread({
550 readModel,
551 command,
552 threadId: command.threadId,
553 });
554 return {
555 ...withEventBase({
556 aggregateKind: "thread",
557 aggregateId: command.threadId,
558 occurredAt: command.createdAt,
559 commandId: command.commandId,
560 }),
561 type: "thread.session-stop-requested",
562 payload: {
563 threadId: command.threadId,
564 createdAt: command.createdAt,
565 },
566 };
567 }
568
569 case "thread.session.set": {
570 yield* requireThread({
571 readModel,
572 command,
573 threadId: command.threadId,
574 });
575 return {
576 ...withEventBase({
577 aggregateKind: "thread",
578 aggregateId: command.threadId,
579 occurredAt: command.createdAt,
580 commandId: command.commandId,
581 metadata: {},
582 }),
583 type: "thread.session-set",
584 payload: {
585 threadId: command.threadId,
586 session: command.session,
587 },
588 };
589 }
590
591 case "thread.message.assistant.delta": {
592 yield* requireThread({
593 readModel,
594 command,
595 threadId: command.threadId,
596 });
597 return {
598 ...withEventBase({
599 aggregateKind: "thread",
600 aggregateId: command.threadId,
601 occurredAt: command.createdAt,
602 commandId: command.commandId,
603 }),
604 type: "thread.message-sent",
605 payload: {
606 threadId: command.threadId,
607 messageId: command.messageId,
608 role: "assistant",
609 text: command.delta,
610 turnId: command.turnId ?? null,
611 streaming: true,
612 createdAt: command.createdAt,
613 updatedAt: command.createdAt,
614 },
615 };
616 }
617
618 case "thread.message.assistant.complete": {
619 yield* requireThread({
620 readModel,
621 command,
622 threadId: command.threadId,
623 });
624 return {
625 ...withEventBase({
626 aggregateKind: "thread",
627 aggregateId: command.threadId,
628 occurredAt: command.createdAt,
629 commandId: command.commandId,
630 }),
631 type: "thread.message-sent",
632 payload: {
633 threadId: command.threadId,
634 messageId: command.messageId,
635 role: "assistant",
636 text: "",
637 turnId: command.turnId ?? null,
638 streaming: false,
639 createdAt: command.createdAt,
640 updatedAt: command.createdAt,
641 },
642 };
643 }
644
645 case "thread.proposed-plan.upsert": {
646 yield* requireThread({
647 readModel,
648 command,
649 threadId: command.threadId,
650 });
651 return {
652 ...withEventBase({
653 aggregateKind: "thread",
654 aggregateId: command.threadId,
655 occurredAt: command.createdAt,
656 commandId: command.commandId,
657 }),
658 type: "thread.proposed-plan-upserted",
659 payload: {
660 threadId: command.threadId,
661 proposedPlan: command.proposedPlan,
662 },
663 };
664 }
665
666 case "thread.turn.diff.complete": {
667 yield* requireThread({
668 readModel,
669 command,
670 threadId: command.threadId,
671 });
672 return {
673 ...withEventBase({
674 aggregateKind: "thread",
675 aggregateId: command.threadId,
676 occurredAt: command.createdAt,
677 commandId: command.commandId,
678 }),
679 type: "thread.turn-diff-completed",
680 payload: {
681 threadId: command.threadId,
682 turnId: command.turnId,
683 checkpointTurnCount: command.checkpointTurnCount,
684 checkpointRef: command.checkpointRef,
685 status: command.status,
686 files: command.files,
687 assistantMessageId: command.assistantMessageId ?? null,
688 completedAt: command.completedAt,
689 },
690 };
691 }
692
693 case "thread.revert.complete": {
694 yield* requireThread({
695 readModel,
696 command,
697 threadId: command.threadId,
698 });
699 return {
700 ...withEventBase({
701 aggregateKind: "thread",
702 aggregateId: command.threadId,
703 occurredAt: command.createdAt,
704 commandId: command.commandId,
705 }),
706 type: "thread.reverted",
707 payload: {
708 threadId: command.threadId,
709 turnCount: command.turnCount,
710 },
711 };
712 }
713
714 case "thread.activity.append": {
715 yield* requireThread({
716 readModel,
717 command,
718 threadId: command.threadId,
719 });
720 const requestId =
721 typeof command.activity.payload === "object" &&
722 command.activity.payload !== null &&
723 "requestId" in command.activity.payload &&
724 typeof (command.activity.payload as { requestId?: unknown }).requestId === "string"
725 ? ((command.activity.payload as { requestId: string })
726 .requestId as OrchestrationEvent["metadata"]["requestId"])
727 : undefined;
728 return {
729 ...withEventBase({
730 aggregateKind: "thread",
731 aggregateId: command.threadId,
732 occurredAt: command.createdAt,
733 commandId: command.commandId,
734 ...(requestId !== undefined ? { metadata: { requestId } } : {}),
735 }),
736 type: "thread.activity-appended",
737 payload: {
738 threadId: command.threadId,
739 activity: command.activity,
740 },
741 };
742 }
743
744 default: {
745 command satisfies never;
746 const fallback = command as never as { type: string };
747 return yield* new OrchestrationCommandInvariantError({
748 commandType: fallback.type,
749 detail: `Unknown command type: ${fallback.type}`,
750 });
751 }
752 }
753});