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

decider.ts

765 lines22.0 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 yield* requireThread({
317 readModel,
318 command,
319 threadId: command.threadId,
320 });
321 const occurredAt = yield* nowIso;
322 return {
323 ...(yield* withEventBase({
324 aggregateKind: "thread",
325 aggregateId: command.threadId,
326 occurredAt,
327 commandId: command.commandId,
328 })),
329 type: "thread.meta-updated",
330 payload: {
331 threadId: command.threadId,
332 ...(command.title !== undefined ? { title: command.title } : {}),
333 ...(command.modelSelection !== undefined
334 ? { modelSelection: command.modelSelection }
335 : {}),
336 ...(command.branch !== undefined ? { branch: command.branch } : {}),
337 ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
338 updatedAt: occurredAt,
339 },
340 };
341 }
342​
343 case "thread.runtime-mode.set": {
344 yield* requireThread({
345 readModel,
346 command,
347 threadId: command.threadId,
348 });
349 const occurredAt = yield* nowIso;
350 return {
351 ...(yield* withEventBase({
352 aggregateKind: "thread",
353 aggregateId: command.threadId,
354 occurredAt,
355 commandId: command.commandId,
356 })),
357 type: "thread.runtime-mode-set",
358 payload: {
359 threadId: command.threadId,
360 runtimeMode: command.runtimeMode,
361 updatedAt: occurredAt,
362 },
363 };
364 }
365​
366 case "thread.interaction-mode.set": {
367 yield* requireThread({
368 readModel,
369 command,
370 threadId: command.threadId,
371 });
372 const occurredAt = yield* nowIso;
373 return {
374 ...(yield* withEventBase({
375 aggregateKind: "thread",
376 aggregateId: command.threadId,
377 occurredAt,
378 commandId: command.commandId,
379 })),
380 type: "thread.interaction-mode-set",
381 payload: {
382 threadId: command.threadId,
383 interactionMode: command.interactionMode,
384 updatedAt: occurredAt,
385 },
386 };
387 }
388​
389 case "thread.turn.start": {
390 const targetThread = yield* requireThread({
391 readModel,
392 command,
393 threadId: command.threadId,
394 });
395 const sourceProposedPlan = command.sourceProposedPlan;
396 const sourceThread = sourceProposedPlan
397 ? yield* requireThread({
398 readModel,
399 command,
400 threadId: sourceProposedPlan.threadId,
401 })
402 : null;
403 const sourcePlan =
404 sourceProposedPlan && sourceThread
405 ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
406 : null;
407 if (sourceProposedPlan && !sourcePlan) {
408 return yield* new OrchestrationCommandInvariantError({
409 commandType: command.type,
410 detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
411 });
412 }
413 if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
414 return yield* new OrchestrationCommandInvariantError({
415 commandType: command.type,
416 detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
417 });
418 }
419 const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
420 ...(yield* withEventBase({
421 aggregateKind: "thread",
422 aggregateId: command.threadId,
423 occurredAt: command.createdAt,
424 commandId: command.commandId,
425 })),
426 type: "thread.message-sent",
427 payload: {
428 threadId: command.threadId,
429 messageId: command.message.messageId,
430 role: "user",
431 text: command.message.text,
432 attachments: command.message.attachments,
433 turnId: null,
434 streaming: false,
435 createdAt: command.createdAt,
436 updatedAt: command.createdAt,
437 },
438 };
439 const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
440 ...(yield* withEventBase({
441 aggregateKind: "thread",
442 aggregateId: command.threadId,
443 occurredAt: command.createdAt,
444 commandId: command.commandId,
445 })),
446 causationEventId: userMessageEvent.eventId,
447 type: "thread.turn-start-requested",
448 payload: {
449 threadId: command.threadId,
450 messageId: command.message.messageId,
451 ...(command.modelSelection !== undefined
452 ? { modelSelection: command.modelSelection }
453 : {}),
454 ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
455 runtimeMode: targetThread.runtimeMode,
456 interactionMode: targetThread.interactionMode,
457 ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
458 createdAt: command.createdAt,
459 },
460 };
461 return [userMessageEvent, turnStartRequestedEvent];
462 }
463​
464 case "thread.turn.interrupt": {
465 yield* requireThread({
466 readModel,
467 command,
468 threadId: command.threadId,
469 });
470 return {
471 ...(yield* withEventBase({
472 aggregateKind: "thread",
473 aggregateId: command.threadId,
474 occurredAt: command.createdAt,
475 commandId: command.commandId,
476 })),
477 type: "thread.turn-interrupt-requested",
478 payload: {
479 threadId: command.threadId,
480 ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),
481 createdAt: command.createdAt,
482 },
483 };
484 }
485​
486 case "thread.approval.respond": {
487 yield* requireThread({
488 readModel,
489 command,
490 threadId: command.threadId,
491 });
492 return {
493 ...(yield* withEventBase({
494 aggregateKind: "thread",
495 aggregateId: command.threadId,
496 occurredAt: command.createdAt,
497 commandId: command.commandId,
498 metadata: {
499 requestId: command.requestId,
500 },
501 })),
502 type: "thread.approval-response-requested",
503 payload: {
504 threadId: command.threadId,
505 requestId: command.requestId,
506 decision: command.decision,
507 createdAt: command.createdAt,
508 },
509 };
510 }
511​
512 case "thread.user-input.respond": {
513 yield* requireThread({
514 readModel,
515 command,
516 threadId: command.threadId,
517 });
518 return {
519 ...(yield* withEventBase({
520 aggregateKind: "thread",
521 aggregateId: command.threadId,
522 occurredAt: command.createdAt,
523 commandId: command.commandId,
524 metadata: {
525 requestId: command.requestId,
526 },
527 })),
528 type: "thread.user-input-response-requested",
529 payload: {
530 threadId: command.threadId,
531 requestId: command.requestId,
532 answers: command.answers,
533 createdAt: command.createdAt,
534 },
535 };
536 }
537​
538 case "thread.checkpoint.revert": {
539 yield* requireThread({
540 readModel,
541 command,
542 threadId: command.threadId,
543 });
544 return {
545 ...(yield* withEventBase({
546 aggregateKind: "thread",
547 aggregateId: command.threadId,
548 occurredAt: command.createdAt,
549 commandId: command.commandId,
550 })),
551 type: "thread.checkpoint-revert-requested",
552 payload: {
553 threadId: command.threadId,
554 turnCount: command.turnCount,
555 createdAt: command.createdAt,
556 },
557 };
558 }
559​
560 case "thread.session.stop": {
561 yield* requireThread({
562 readModel,
563 command,
564 threadId: command.threadId,
565 });
566 return {
567 ...(yield* withEventBase({
568 aggregateKind: "thread",
569 aggregateId: command.threadId,
570 occurredAt: command.createdAt,
571 commandId: command.commandId,
572 })),
573 type: "thread.session-stop-requested",
574 payload: {
575 threadId: command.threadId,
576 createdAt: command.createdAt,
577 },
578 };
579 }
580​
581 case "thread.session.set": {
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 metadata: {},
594 })),
595 type: "thread.session-set",
596 payload: {
597 threadId: command.threadId,
598 session: command.session,
599 },
600 };
601 }
602​
603 case "thread.message.assistant.delta": {
604 yield* requireThread({
605 readModel,
606 command,
607 threadId: command.threadId,
608 });
609 return {
610 ...(yield* withEventBase({
611 aggregateKind: "thread",
612 aggregateId: command.threadId,
613 occurredAt: command.createdAt,
614 commandId: command.commandId,
615 })),
616 type: "thread.message-sent",
617 payload: {
618 threadId: command.threadId,
619 messageId: command.messageId,
620 role: "assistant",
621 text: command.delta,
622 turnId: command.turnId ?? null,
623 streaming: true,
624 createdAt: command.createdAt,
625 updatedAt: command.createdAt,
626 },
627 };
628 }
629​
630 case "thread.message.assistant.complete": {
631 yield* requireThread({
632 readModel,
633 command,
634 threadId: command.threadId,
635 });
636 return {
637 ...(yield* withEventBase({
638 aggregateKind: "thread",
639 aggregateId: command.threadId,
640 occurredAt: command.createdAt,
641 commandId: command.commandId,
642 })),
643 type: "thread.message-sent",
644 payload: {
645 threadId: command.threadId,
646 messageId: command.messageId,
647 role: "assistant",
648 text: "",
649 turnId: command.turnId ?? null,
650 streaming: false,
651 createdAt: command.createdAt,
652 updatedAt: command.createdAt,
653 },
654 };
655 }
656​
657 case "thread.proposed-plan.upsert": {
658 yield* requireThread({
659 readModel,
660 command,
661 threadId: command.threadId,
662 });
663 return {
664 ...(yield* withEventBase({
665 aggregateKind: "thread",
666 aggregateId: command.threadId,
667 occurredAt: command.createdAt,
668 commandId: command.commandId,
669 })),
670 type: "thread.proposed-plan-upserted",
671 payload: {
672 threadId: command.threadId,
673 proposedPlan: command.proposedPlan,
674 },
675 };
676 }
677​
678 case "thread.turn.diff.complete": {
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.turn-diff-completed",
692 payload: {
693 threadId: command.threadId,
694 turnId: command.turnId,
695 checkpointTurnCount: command.checkpointTurnCount,
696 checkpointRef: command.checkpointRef,
697 status: command.status,
698 files: command.files,
699 assistantMessageId: command.assistantMessageId ?? null,
700 completedAt: command.completedAt,
701 },
702 };
703 }
704​
705 case "thread.revert.complete": {
706 yield* requireThread({
707 readModel,
708 command,
709 threadId: command.threadId,
710 });
711 return {
712 ...(yield* withEventBase({
713 aggregateKind: "thread",
714 aggregateId: command.threadId,
715 occurredAt: command.createdAt,
716 commandId: command.commandId,
717 })),
718 type: "thread.reverted",
719 payload: {
720 threadId: command.threadId,
721 turnCount: command.turnCount,
722 },
723 };
724 }
725​
726 case "thread.activity.append": {
727 yield* requireThread({
728 readModel,
729 command,
730 threadId: command.threadId,
731 });
732 const requestId =
733 typeof command.activity.payload === "object" &&
734 command.activity.payload !== null &&
735 "requestId" in command.activity.payload &&
736 typeof (command.activity.payload as { requestId?: unknown }).requestId === "string"
737 ? ((command.activity.payload as { requestId: string })
738 .requestId as OrchestrationEvent["metadata"]["requestId"])
739 : undefined;
740 return {
741 ...(yield* withEventBase({
742 aggregateKind: "thread",
743 aggregateId: command.threadId,
744 occurredAt: command.createdAt,
745 commandId: command.commandId,
746 ...(requestId !== undefined ? { metadata: { requestId } } : {}),
747 })),
748 type: "thread.activity-appended",
749 payload: {
750 threadId: command.threadId,
751 activity: command.activity,
752 },
753 };
754 }
755​
756 default: {
757 command satisfies never;
758 const fallback = command as never as { type: string };
759 return yield* new OrchestrationCommandInvariantError({
760 commandType: fallback.type,
761 detail: `Unknown command type: ${fallback.type}`,
762 });
763 }
764 }
765});