Open History to see the last commit
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 requireThreadAbsent,
14} from "./commandInvariants.ts";
15
16const nowIso = () => new Date().toISOString();
17const DEFAULT_ASSISTANT_DELIVERY_MODE = "buffered" as const;
18
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 };
48}
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 defaultModel: command.defaultModel ?? 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.defaultModel !== undefined ? { defaultModel: command.defaultModel } : {}),
108 ...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
109 updatedAt: occurredAt,
110 },
111 };
112 }
113
114 case "project.delete": {
115 yield* requireProject({
116 readModel,
117 command,
118 projectId: command.projectId,
119 });
120 const occurredAt = nowIso();
121 return {
122 ...withEventBase({
123 aggregateKind: "project",
124 aggregateId: command.projectId,
125 occurredAt,
126 commandId: command.commandId,
127 }),
128 type: "project.deleted",
129 payload: {
130 projectId: command.projectId,
131 deletedAt: occurredAt,
132 },
133 };
134 }
135
136 case "thread.create": {
137 yield* requireProject({
138 readModel,
139 command,
140 projectId: command.projectId,
141 });
142 yield* requireThreadAbsent({
143 readModel,
144 command,
145 threadId: command.threadId,
146 });
147 return {
148 ...withEventBase({
149 aggregateKind: "thread",
150 aggregateId: command.threadId,
151 occurredAt: command.createdAt,
152 commandId: command.commandId,
153 }),
154 type: "thread.created",
155 payload: {
156 threadId: command.threadId,
157 projectId: command.projectId,
158 title: command.title,
159 model: command.model,
160 runtimeMode: command.runtimeMode,
161 interactionMode: command.interactionMode,
162 branch: command.branch,
163 worktreePath: command.worktreePath,
164 createdAt: command.createdAt,
165 updatedAt: command.createdAt,
166 },
167 };
168 }
169
170 case "thread.delete": {
171 yield* requireThread({
172 readModel,
173 command,
174 threadId: command.threadId,
175 });
176 const occurredAt = nowIso();
177 return {
178 ...withEventBase({
179 aggregateKind: "thread",
180 aggregateId: command.threadId,
181 occurredAt,
182 commandId: command.commandId,
183 }),
184 type: "thread.deleted",
185 payload: {
186 threadId: command.threadId,
187 deletedAt: occurredAt,
188 },
189 };
190 }
191
192 case "thread.meta.update": {
193 yield* requireThread({
194 readModel,
195 command,
196 threadId: command.threadId,
197 });
198 const occurredAt = nowIso();
199 return {
200 ...withEventBase({
201 aggregateKind: "thread",
202 aggregateId: command.threadId,
203 occurredAt,
204 commandId: command.commandId,
205 }),
206 type: "thread.meta-updated",
207 payload: {
208 threadId: command.threadId,
209 ...(command.title !== undefined ? { title: command.title } : {}),
210 ...(command.model !== undefined ? { model: command.model } : {}),
211 ...(command.branch !== undefined ? { branch: command.branch } : {}),
212 ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
213 updatedAt: occurredAt,
214 },
215 };
216 }
217
218 case "thread.runtime-mode.set": {
219 yield* requireThread({
220 readModel,
221 command,
222 threadId: command.threadId,
223 });
224 const occurredAt = nowIso();
225 return {
226 ...withEventBase({
227 aggregateKind: "thread",
228 aggregateId: command.threadId,
229 occurredAt,
230 commandId: command.commandId,
231 }),
232 type: "thread.runtime-mode-set",
233 payload: {
234 threadId: command.threadId,
235 runtimeMode: command.runtimeMode,
236 updatedAt: occurredAt,
237 },
238 };
239 }
240
241 case "thread.interaction-mode.set": {
242 yield* requireThread({
243 readModel,
244 command,
245 threadId: command.threadId,
246 });
247 const occurredAt = nowIso();
248 return {
249 ...withEventBase({
250 aggregateKind: "thread",
251 aggregateId: command.threadId,
252 occurredAt,
253 commandId: command.commandId,
254 }),
255 type: "thread.interaction-mode-set",
256 payload: {
257 threadId: command.threadId,
258 interactionMode: command.interactionMode,
259 updatedAt: occurredAt,
260 },
261 };
262 }
263
264 case "thread.turn.start": {
265 const targetThread = yield* requireThread({
266 readModel,
267 command,
268 threadId: command.threadId,
269 });
270 const sourceProposedPlan = command.sourceProposedPlan;
271 const sourceThread = sourceProposedPlan
272 ? yield* requireThread({
273 readModel,
274 command,
275 threadId: sourceProposedPlan.threadId,
276 })
277 : null;
278 const sourcePlan =
279 sourceProposedPlan && sourceThread
280 ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
281 : null;
282 if (sourceProposedPlan && !sourcePlan) {
283 return yield* new OrchestrationCommandInvariantError({
284 commandType: command.type,
285 detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
286 });
287 }
288 if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
289 return yield* new OrchestrationCommandInvariantError({
290 commandType: command.type,
291 detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
292 });
293 }
294 const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
295 ...withEventBase({
296 aggregateKind: "thread",
297 aggregateId: command.threadId,
298 occurredAt: command.createdAt,
299 commandId: command.commandId,
300 }),
301 type: "thread.message-sent",
302 payload: {
303 threadId: command.threadId,
304 messageId: command.message.messageId,
305 role: "user",
306 text: command.message.text,
307 attachments: command.message.attachments,
308 turnId: null,
309 streaming: false,
310 createdAt: command.createdAt,
311 updatedAt: command.createdAt,
312 },
313 };
314 const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
315 ...withEventBase({
316 aggregateKind: "thread",
317 aggregateId: command.threadId,
318 occurredAt: command.createdAt,
319 commandId: command.commandId,
320 }),
321 causationEventId: userMessageEvent.eventId,
322 type: "thread.turn-start-requested",
323 payload: {
324 threadId: command.threadId,
325 messageId: command.message.messageId,
326 ...(command.provider !== undefined ? { provider: command.provider } : {}),
327 ...(command.model !== undefined ? { model: command.model } : {}),
328 ...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
329 ...(command.providerOptions !== undefined
330 ? { providerOptions: command.providerOptions }
331 : {}),
332 assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
333 runtimeMode: targetThread.runtimeMode,
334 interactionMode: targetThread.interactionMode,
335 ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
336 createdAt: command.createdAt,
337 },
338 };
339 return [userMessageEvent, turnStartRequestedEvent];
340 }
341
342 case "thread.turn.interrupt": {
343 yield* requireThread({
344 readModel,
345 command,
346 threadId: command.threadId,
347 });
348 return {
349 ...withEventBase({
350 aggregateKind: "thread",
351 aggregateId: command.threadId,
352 occurredAt: command.createdAt,
353 commandId: command.commandId,
354 }),
355 type: "thread.turn-interrupt-requested",
356 payload: {
357 threadId: command.threadId,
358 ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),
359 createdAt: command.createdAt,
360 },
361 };
362 }
363
364 case "thread.approval.respond": {
365 yield* requireThread({
366 readModel,
367 command,
368 threadId: command.threadId,
369 });
370 return {
371 ...withEventBase({
372 aggregateKind: "thread",
373 aggregateId: command.threadId,
374 occurredAt: command.createdAt,
375 commandId: command.commandId,
376 metadata: {
377 requestId: command.requestId,
378 },
379 }),
380 type: "thread.approval-response-requested",
381 payload: {
382 threadId: command.threadId,
383 requestId: command.requestId,
384 decision: command.decision,
385 createdAt: command.createdAt,
386 },
387 };
388 }
389
390 case "thread.user-input.respond": {
391 yield* requireThread({
392 readModel,
393 command,
394 threadId: command.threadId,
395 });
396 return {
397 ...withEventBase({
398 aggregateKind: "thread",
399 aggregateId: command.threadId,
400 occurredAt: command.createdAt,
401 commandId: command.commandId,
402 metadata: {
403 requestId: command.requestId,
404 },
405 }),
406 type: "thread.user-input-response-requested",
407 payload: {
408 threadId: command.threadId,
409 requestId: command.requestId,
410 answers: command.answers,
411 createdAt: command.createdAt,
412 },
413 };
414 }
415
416 case "thread.checkpoint.revert": {
417 yield* requireThread({
418 readModel,
419 command,
420 threadId: command.threadId,
421 });
422 return {
423 ...withEventBase({
424 aggregateKind: "thread",
425 aggregateId: command.threadId,
426 occurredAt: command.createdAt,
427 commandId: command.commandId,
428 }),
429 type: "thread.checkpoint-revert-requested",
430 payload: {
431 threadId: command.threadId,
432 turnCount: command.turnCount,
433 createdAt: command.createdAt,
434 },
435 };
436 }
437
438 case "thread.session.stop": {
439 yield* requireThread({
440 readModel,
441 command,
442 threadId: command.threadId,
443 });
444 return {
445 ...withEventBase({
446 aggregateKind: "thread",
447 aggregateId: command.threadId,
448 occurredAt: command.createdAt,
449 commandId: command.commandId,
450 }),
451 type: "thread.session-stop-requested",
452 payload: {
453 threadId: command.threadId,
454 createdAt: command.createdAt,
455 },
456 };
457 }
458
459 case "thread.session.set": {
460 yield* requireThread({
461 readModel,
462 command,
463 threadId: command.threadId,
464 });
465 return {
466 ...withEventBase({
467 aggregateKind: "thread",
468 aggregateId: command.threadId,
469 occurredAt: command.createdAt,
470 commandId: command.commandId,
471 metadata: {},
472 }),
473 type: "thread.session-set",
474 payload: {
475 threadId: command.threadId,
476 session: command.session,
477 },
478 };
479 }
480
481 case "thread.message.assistant.delta": {
482 yield* requireThread({
483 readModel,
484 command,
485 threadId: command.threadId,
486 });
487 return {
488 ...withEventBase({
489 aggregateKind: "thread",
490 aggregateId: command.threadId,
491 occurredAt: command.createdAt,
492 commandId: command.commandId,
493 }),
494 type: "thread.message-sent",
495 payload: {
496 threadId: command.threadId,
497 messageId: command.messageId,
498 role: "assistant",
499 text: command.delta,
500 turnId: command.turnId ?? null,
501 streaming: true,
502 createdAt: command.createdAt,
503 updatedAt: command.createdAt,
504 },
505 };
506 }
507
508 case "thread.message.assistant.complete": {
509 yield* requireThread({
510 readModel,
511 command,
512 threadId: command.threadId,
513 });
514 return {
515 ...withEventBase({
516 aggregateKind: "thread",
517 aggregateId: command.threadId,
518 occurredAt: command.createdAt,
519 commandId: command.commandId,
520 }),
521 type: "thread.message-sent",
522 payload: {
523 threadId: command.threadId,
524 messageId: command.messageId,
525 role: "assistant",
526 text: "",
527 turnId: command.turnId ?? null,
528 streaming: false,
529 createdAt: command.createdAt,
530 updatedAt: command.createdAt,
531 },
532 };
533 }
534
535 case "thread.proposed-plan.upsert": {
536 yield* requireThread({
537 readModel,
538 command,
539 threadId: command.threadId,
540 });
541 return {
542 ...withEventBase({
543 aggregateKind: "thread",
544 aggregateId: command.threadId,
545 occurredAt: command.createdAt,
546 commandId: command.commandId,
547 }),
548 type: "thread.proposed-plan-upserted",
549 payload: {
550 threadId: command.threadId,
551 proposedPlan: command.proposedPlan,
552 },
553 };
554 }
555
556 case "thread.turn.diff.complete": {
557 yield* requireThread({
558 readModel,
559 command,
560 threadId: command.threadId,
561 });
562 return {
563 ...withEventBase({
564 aggregateKind: "thread",
565 aggregateId: command.threadId,
566 occurredAt: command.createdAt,
567 commandId: command.commandId,
568 }),
569 type: "thread.turn-diff-completed",
570 payload: {
571 threadId: command.threadId,
572 turnId: command.turnId,
573 checkpointTurnCount: command.checkpointTurnCount,
574 checkpointRef: command.checkpointRef,
575 status: command.status,
576 files: command.files,
577 assistantMessageId: command.assistantMessageId ?? null,
578 completedAt: command.completedAt,
579 },
580 };
581 }
582
583 case "thread.revert.complete": {
584 yield* requireThread({
585 readModel,
586 command,
587 threadId: command.threadId,
588 });
589 return {
590 ...withEventBase({
591 aggregateKind: "thread",
592 aggregateId: command.threadId,
593 occurredAt: command.createdAt,
594 commandId: command.commandId,
595 }),
596 type: "thread.reverted",
597 payload: {
598 threadId: command.threadId,
599 turnCount: command.turnCount,
600 },
601 };
602 }
603
604 case "thread.activity.append": {
605 yield* requireThread({
606 readModel,
607 command,
608 threadId: command.threadId,
609 });
610 const requestId =
611 typeof command.activity.payload === "object" &&
612 command.activity.payload !== null &&
613 "requestId" in command.activity.payload &&
614 typeof (command.activity.payload as { requestId?: unknown }).requestId === "string"
615 ? ((command.activity.payload as { requestId: string })
616 .requestId as OrchestrationEvent["metadata"]["requestId"])
617 : undefined;
618 return {
619 ...withEventBase({
620 aggregateKind: "thread",
621 aggregateId: command.threadId,
622 occurredAt: command.createdAt,
623 commandId: command.commandId,
624 ...(requestId !== undefined ? { metadata: { requestId } } : {}),
625 }),
626 type: "thread.activity-appended",
627 payload: {
628 threadId: command.threadId,
629 activity: command.activity,
630 },
631 };
632 }
633
634 default: {
635 command satisfies never;
636 const fallback = command as never as { type: string };
637 return yield* new OrchestrationCommandInvariantError({
638 commandType: fallback.type,
639 detail: `Unknown command type: ${fallback.type}`,
640 });
641 }
642 }
643});