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