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

decider.ts

689 lines19.4 KB

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