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 yield* requireThread({
266 readModel,
267 command,
268 threadId: command.threadId,
269 });
270 const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
271 ...withEventBase({
272 aggregateKind: "thread",
273 aggregateId: command.threadId,
274 occurredAt: command.createdAt,
275 commandId: command.commandId,
276 }),
277 type: "thread.message-sent",
278 payload: {
279 threadId: command.threadId,
280 messageId: command.message.messageId,
281 role: "user",
282 text: command.message.text,
283 attachments: command.message.attachments,
284 turnId: null,
285 streaming: false,
286 createdAt: command.createdAt,
287 updatedAt: command.createdAt,
288 },
289 };
290 const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
291 ...withEventBase({
292 aggregateKind: "thread",
293 aggregateId: command.threadId,
294 occurredAt: command.createdAt,
295 commandId: command.commandId,
296 }),
297 causationEventId: userMessageEvent.eventId,
298 type: "thread.turn-start-requested",
299 payload: {
300 threadId: command.threadId,
301 messageId: command.message.messageId,
302 ...(command.provider !== undefined ? { provider: command.provider } : {}),
303 ...(command.model !== undefined ? { model: command.model } : {}),
304 ...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
305 ...(command.providerOptions !== undefined
306 ? { providerOptions: command.providerOptions }
307 : {}),
308 assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
309 runtimeMode:
310 readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
311 command.runtimeMode,
312 interactionMode:
313 readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
314 command.interactionMode,
315 createdAt: command.createdAt,
316 },
317 };
318 return [userMessageEvent, turnStartRequestedEvent];
319 }
320
321 case "thread.turn.interrupt": {
322 yield* requireThread({
323 readModel,
324 command,
325 threadId: command.threadId,
326 });
327 return {
328 ...withEventBase({
329 aggregateKind: "thread",
330 aggregateId: command.threadId,
331 occurredAt: command.createdAt,
332 commandId: command.commandId,
333 }),
334 type: "thread.turn-interrupt-requested",
335 payload: {
336 threadId: command.threadId,
337 ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),
338 createdAt: command.createdAt,
339 },
340 };
341 }
342
343 case "thread.approval.respond": {
344 yield* requireThread({
345 readModel,
346 command,
347 threadId: command.threadId,
348 });
349 return {
350 ...withEventBase({
351 aggregateKind: "thread",
352 aggregateId: command.threadId,
353 occurredAt: command.createdAt,
354 commandId: command.commandId,
355 metadata: {
356 requestId: command.requestId,
357 },
358 }),
359 type: "thread.approval-response-requested",
360 payload: {
361 threadId: command.threadId,
362 requestId: command.requestId,
363 decision: command.decision,
364 createdAt: command.createdAt,
365 },
366 };
367 }
368
369 case "thread.user-input.respond": {
370 yield* requireThread({
371 readModel,
372 command,
373 threadId: command.threadId,
374 });
375 return {
376 ...withEventBase({
377 aggregateKind: "thread",
378 aggregateId: command.threadId,
379 occurredAt: command.createdAt,
380 commandId: command.commandId,
381 metadata: {
382 requestId: command.requestId,
383 },
384 }),
385 type: "thread.user-input-response-requested",
386 payload: {
387 threadId: command.threadId,
388 requestId: command.requestId,
389 answers: command.answers,
390 createdAt: command.createdAt,
391 },
392 };
393 }
394
395 case "thread.checkpoint.revert": {
396 yield* requireThread({
397 readModel,
398 command,
399 threadId: command.threadId,
400 });
401 return {
402 ...withEventBase({
403 aggregateKind: "thread",
404 aggregateId: command.threadId,
405 occurredAt: command.createdAt,
406 commandId: command.commandId,
407 }),
408 type: "thread.checkpoint-revert-requested",
409 payload: {
410 threadId: command.threadId,
411 turnCount: command.turnCount,
412 createdAt: command.createdAt,
413 },
414 };
415 }
416
417 case "thread.session.stop": {
418 yield* requireThread({
419 readModel,
420 command,
421 threadId: command.threadId,
422 });
423 return {
424 ...withEventBase({
425 aggregateKind: "thread",
426 aggregateId: command.threadId,
427 occurredAt: command.createdAt,
428 commandId: command.commandId,
429 }),
430 type: "thread.session-stop-requested",
431 payload: {
432 threadId: command.threadId,
433 createdAt: command.createdAt,
434 },
435 };
436 }
437
438 case "thread.session.set": {
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 metadata: {},
451 }),
452 type: "thread.session-set",
453 payload: {
454 threadId: command.threadId,
455 session: command.session,
456 },
457 };
458 }
459
460 case "thread.message.assistant.delta": {
461 yield* requireThread({
462 readModel,
463 command,
464 threadId: command.threadId,
465 });
466 return {
467 ...withEventBase({
468 aggregateKind: "thread",
469 aggregateId: command.threadId,
470 occurredAt: command.createdAt,
471 commandId: command.commandId,
472 }),
473 type: "thread.message-sent",
474 payload: {
475 threadId: command.threadId,
476 messageId: command.messageId,
477 role: "assistant",
478 text: command.delta,
479 turnId: command.turnId ?? null,
480 streaming: true,
481 createdAt: command.createdAt,
482 updatedAt: command.createdAt,
483 },
484 };
485 }
486
487 case "thread.message.assistant.complete": {
488 yield* requireThread({
489 readModel,
490 command,
491 threadId: command.threadId,
492 });
493 return {
494 ...withEventBase({
495 aggregateKind: "thread",
496 aggregateId: command.threadId,
497 occurredAt: command.createdAt,
498 commandId: command.commandId,
499 }),
500 type: "thread.message-sent",
501 payload: {
502 threadId: command.threadId,
503 messageId: command.messageId,
504 role: "assistant",
505 text: "",
506 turnId: command.turnId ?? null,
507 streaming: false,
508 createdAt: command.createdAt,
509 updatedAt: command.createdAt,
510 },
511 };
512 }
513
514 case "thread.proposed-plan.upsert": {
515 yield* requireThread({
516 readModel,
517 command,
518 threadId: command.threadId,
519 });
520 return {
521 ...withEventBase({
522 aggregateKind: "thread",
523 aggregateId: command.threadId,
524 occurredAt: command.createdAt,
525 commandId: command.commandId,
526 }),
527 type: "thread.proposed-plan-upserted",
528 payload: {
529 threadId: command.threadId,
530 proposedPlan: command.proposedPlan,
531 },
532 };
533 }
534
535 case "thread.turn.diff.complete": {
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.turn-diff-completed",
549 payload: {
550 threadId: command.threadId,
551 turnId: command.turnId,
552 checkpointTurnCount: command.checkpointTurnCount,
553 checkpointRef: command.checkpointRef,
554 status: command.status,
555 files: command.files,
556 assistantMessageId: command.assistantMessageId ?? null,
557 completedAt: command.completedAt,
558 },
559 };
560 }
561
562 case "thread.revert.complete": {
563 yield* requireThread({
564 readModel,
565 command,
566 threadId: command.threadId,
567 });
568 return {
569 ...withEventBase({
570 aggregateKind: "thread",
571 aggregateId: command.threadId,
572 occurredAt: command.createdAt,
573 commandId: command.commandId,
574 }),
575 type: "thread.reverted",
576 payload: {
577 threadId: command.threadId,
578 turnCount: command.turnCount,
579 },
580 };
581 }
582
583 case "thread.activity.append": {
584 yield* requireThread({
585 readModel,
586 command,
587 threadId: command.threadId,
588 });
589 const requestId =
590 typeof command.activity.payload === "object" &&
591 command.activity.payload !== null &&
592 "requestId" in command.activity.payload &&
593 typeof (command.activity.payload as { requestId?: unknown }).requestId === "string"
594 ? ((command.activity.payload as { requestId: string })
595 .requestId as OrchestrationEvent["metadata"]["requestId"])
596 : undefined;
597 return {
598 ...withEventBase({
599 aggregateKind: "thread",
600 aggregateId: command.threadId,
601 occurredAt: command.createdAt,
602 commandId: command.commandId,
603 ...(requestId !== undefined ? { metadata: { requestId } } : {}),
604 }),
605 type: "thread.activity-appended",
606 payload: {
607 threadId: command.threadId,
608 activity: command.activity,
609 },
610 };
611 }
612
613 default: {
614 command satisfies never;
615 const fallback = command as never as { type: string };
616 return yield* new OrchestrationCommandInvariantError({
617 commandType: fallback.type,
618 detail: `Unknown command type: ${fallback.type}`,
619 });
620 }
621 }
622});