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