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

decider.ts

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