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

decider.ts

771 lines22.2 KB

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