Open History to see the last commit
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 requireActiveProjectWorkspaceRootAbsent,
16 requireProject,
17 requireProjectAbsent,
18 requireThread,
19 requireThreadArchived,
20 requireThreadAbsent,
21 requireThreadNotArchived,
22} from "./commandInvariants.ts";
23import { projectEvent } from "./projector.ts";
24
25const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
26
27// Session adoption takes seconds; a user message still unadopted after this
28// window is a failed/stale start, not pending work. Mirrors the client's
29// QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts.
30const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
31
32/**
33 * Blocked-on-you work derived from the thread's retained activities: an
34 * approval or user-input request with no later resolution for the same
35 * requestId. The server-side twin of the shell's hasPendingApprovals /
36 * hasPendingUserInput flags, which the decider read model does not carry.
37 * The clearing rules MUST match ProjectionPipeline's pending accounting —
38 * resolved activities always clear, respond.failed clears only when the
39 * failure detail marks the request stale/unknown — or settle would be
40 * rejected on threads whose shell flags read as clear.
41 */
42function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): boolean {
43 const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
44 if (detail === null) return false;
45 return (
46 detail.includes("stale pending approval request") ||
47 detail.includes("unknown pending approval request") ||
48 detail.includes("unknown pending permission request") ||
49 detail.includes("stale pending user-input request") ||
50 detail.includes("unknown pending user-input request") ||
51 detail.includes("unknown pending user input request") ||
52 detail.includes("unknown pending codex user input request")
53 );
54}
55
56// Scans the read model's activities, which the projector caps at the most
57// recent 500. That bound is safe here: an OPEN approval/user-input request
58// blocks its turn, so the thread cannot accumulate hundreds of later
59// activities while one is outstanding — a request that has scrolled out of
60// the window is one whose turn kept running, i.e. it was resolved or went
61// stale. (The projection pipeline's pendingApprovalCount reads the same
62// capped stream and stays consistent with this view.)
63function hasOpenBlockingRequest(thread: {
64 readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;
65}): boolean {
66 const openRequestIds = new Set<string>();
67 for (const activity of thread.activities) {
68 const payload =
69 typeof activity.payload === "object" && activity.payload !== null
70 ? (activity.payload as Record<string, unknown>)
71 : null;
72 const requestId = typeof payload?.requestId === "string" ? payload.requestId : null;
73 if (requestId === null) continue;
74 if (activity.kind === "approval.requested" || activity.kind === "user-input.requested") {
75 openRequestIds.add(requestId);
76 } else if (activity.kind === "approval.resolved" || activity.kind === "user-input.resolved") {
77 openRequestIds.delete(requestId);
78 } else if (
79 (activity.kind === "provider.approval.respond.failed" ||
80 activity.kind === "provider.user-input.respond.failed") &&
81 isStaleRequestFailureDetail(payload)
82 ) {
83 openRequestIds.delete(requestId);
84 }
85 }
86 return openRequestIds.size > 0;
87}
88
89/**
90 * A queued turn start — a user message no turn has picked up yet — is work
91 * in flight even though session is still null (turn.start emits
92 * message-sent + turn-start-requested; the session arrives later). Detection
93 * mirrors the client's hasQueuedTurnStart: the newest user message is
94 * strictly newer than every latestTurn timestamp (adoption stamps the new
95 * turn's requestedAt with the message time, clearing this), and only within
96 * the adoption grace window — historical threads whose last user message
97 * postdates their turn timestamps (older-server data, mid-turn messages)
98 * must not be blocked forever. A failed session start (status "error")
99 * clears the block immediately.
100 *
101 * The age check is bounded on BOTH sides: message timestamps are
102 * client-supplied, so a client clock ahead of the server yields a negative
103 * age. Without the lower bound that negative age satisfies `<= grace` for
104 * as long as the skew lasts, extending the block far past the intended two
105 * minutes.
106 */
107function threadHasQueuedTurnStart(
108 thread: {
109 readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
110 readonly latestTurn: {
111 readonly requestedAt: string;
112 readonly startedAt: string | null;
113 readonly completedAt: string | null;
114 } | null;
115 readonly session: { readonly status: string } | null;
116 },
117 occurredAt: string,
118): boolean {
119 const latestUserMessageAtMs = thread.messages.reduce(
120 (latest, message) =>
121 message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
122 Number.NEGATIVE_INFINITY,
123 );
124 const latestTurnAtMs =
125 thread.latestTurn === null
126 ? Number.NEGATIVE_INFINITY
127 : Math.max(
128 ...[
129 thread.latestTurn.requestedAt,
130 thread.latestTurn.startedAt,
131 thread.latestTurn.completedAt,
132 ].map((candidate) =>
133 candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),
134 ),
135 );
136 const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;
137 return (
138 thread.session?.status !== "error" &&
139 Number.isFinite(latestUserMessageAtMs) &&
140 latestUserMessageAtMs > latestTurnAtMs &&
141 Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS
142 );
143}
144
145function withEventBase(
146 input: Pick<OrchestrationCommand, "commandId"> & {
147 readonly aggregateKind: OrchestrationEvent["aggregateKind"];
148 readonly aggregateId: OrchestrationEvent["aggregateId"];
149 readonly occurredAt: string;
150 readonly metadata?: OrchestrationEvent["metadata"];
151 },
152): Effect.Effect<
153 Omit<OrchestrationEvent, "sequence" | "type" | "payload">,
154 PlatformError.PlatformError,
155 Crypto.Crypto
156> {
157 return Crypto.Crypto.pipe(
158 Effect.flatMap((crypto) =>
159 crypto.randomUUIDv4.pipe(
160 Effect.map((eventId) => ({
161 eventId: EventId.make(eventId),
162 aggregateKind: input.aggregateKind,
163 aggregateId: input.aggregateId,
164 occurredAt: input.occurredAt,
165 commandId: input.commandId,
166 causationEventId: null,
167 correlationId: input.commandId,
168 metadata: input.metadata ?? {},
169 })),
170 ),
171 ),
172 );
173}
174
175type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
176
177type DecideOrchestrationCommandResult =
178 | PlannedOrchestrationEvent
179 | ReadonlyArray<PlannedOrchestrationEvent>;
180
181const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
182 commands,
183 readModel,
184}: {
185 readonly commands: ReadonlyArray<OrchestrationCommand>;
186 readonly readModel: OrchestrationReadModel;
187}): Effect.fn.Return<
188 ReadonlyArray<PlannedOrchestrationEvent>,
189 OrchestrationCommandInvariantError | PlatformError.PlatformError,
190 Crypto.Crypto
191> {
192 let nextReadModel = readModel;
193 let nextSequence = readModel.snapshotSequence;
194 const plannedEvents: PlannedOrchestrationEvent[] = [];
195
196 for (const nextCommand of commands) {
197 const decided = yield* decideOrchestrationCommand({
198 command: nextCommand,
199 readModel: nextReadModel,
200 });
201 const nextEvents = Array.isArray(decided) ? decided : [decided];
202 for (const nextEvent of nextEvents) {
203 plannedEvents.push(nextEvent);
204 nextSequence += 1;
205 nextReadModel = yield* projectEvent(nextReadModel, {
206 ...nextEvent,
207 sequence: nextSequence,
208 }).pipe(Effect.orDie);
209 }
210 }
211
212 return plannedEvents;
213});
214
215export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({
216 command,
217 readModel,
218}: {
219 readonly command: OrchestrationCommand;
220 readonly readModel: OrchestrationReadModel;
221}): Effect.fn.Return<
222 DecideOrchestrationCommandResult,
223 OrchestrationCommandInvariantError | PlatformError.PlatformError,
224 Crypto.Crypto
225> {
226 switch (command.type) {
227 case "project.create": {
228 yield* requireProjectAbsent({
229 readModel,
230 command,
231 projectId: command.projectId,
232 });
233 yield* requireActiveProjectWorkspaceRootAbsent({
234 readModel,
235 command,
236 workspaceRoot: command.workspaceRoot,
237 exceptProjectId: command.projectId,
238 });
239
240 return {
241 ...(yield* withEventBase({
242 aggregateKind: "project",
243 aggregateId: command.projectId,
244 occurredAt: command.createdAt,
245 commandId: command.commandId,
246 })),
247 type: "project.created",
248 payload: {
249 projectId: command.projectId,
250 title: command.title,
251 workspaceRoot: command.workspaceRoot,
252 defaultModelSelection: command.defaultModelSelection ?? null,
253 scripts: [],
254 createdAt: command.createdAt,
255 updatedAt: command.createdAt,
256 },
257 };
258 }
259
260 case "project.meta.update": {
261 yield* requireProject({
262 readModel,
263 command,
264 projectId: command.projectId,
265 });
266 if (command.workspaceRoot !== undefined) {
267 yield* requireActiveProjectWorkspaceRootAbsent({
268 readModel,
269 command,
270 workspaceRoot: command.workspaceRoot,
271 exceptProjectId: command.projectId,
272 });
273 }
274 const occurredAt = yield* nowIso;
275 return {
276 ...(yield* withEventBase({
277 aggregateKind: "project",
278 aggregateId: command.projectId,
279 occurredAt,
280 commandId: command.commandId,
281 })),
282 type: "project.meta-updated",
283 payload: {
284 projectId: command.projectId,
285 ...(command.title !== undefined ? { title: command.title } : {}),
286 ...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
287 ...(command.defaultModelSelection !== undefined
288 ? { defaultModelSelection: command.defaultModelSelection }
289 : {}),
290 ...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
291 updatedAt: occurredAt,
292 },
293 };
294 }
295
296 case "project.delete": {
297 yield* requireProject({
298 readModel,
299 command,
300 projectId: command.projectId,
301 });
302 const activeThreads = listThreadsByProjectId(readModel, command.projectId).filter(
303 (thread) => thread.deletedAt === null,
304 );
305 if (activeThreads.length > 0 && command.force !== true) {
306 return yield* new OrchestrationCommandInvariantError({
307 commandType: command.type,
308 detail: `Project '${command.projectId}' is not empty and cannot be deleted without force=true.`,
309 });
310 }
311 if (activeThreads.length > 0) {
312 return yield* decideCommandSequence({
313 readModel,
314 commands: [
315 ...activeThreads.map(
316 (thread): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({
317 type: "thread.delete",
318 commandId: command.commandId,
319 threadId: thread.id,
320 }),
321 ),
322 {
323 type: "project.delete",
324 commandId: command.commandId,
325 projectId: command.projectId,
326 },
327 ],
328 });
329 }
330
331 const occurredAt = yield* nowIso;
332 return {
333 ...(yield* withEventBase({
334 aggregateKind: "project",
335 aggregateId: command.projectId,
336 occurredAt,
337 commandId: command.commandId,
338 })),
339 type: "project.deleted" as const,
340 payload: {
341 projectId: command.projectId,
342 deletedAt: occurredAt,
343 },
344 };
345 }
346
347 case "thread.create": {
348 yield* requireProject({
349 readModel,
350 command,
351 projectId: command.projectId,
352 });
353 yield* requireThreadAbsent({
354 readModel,
355 command,
356 threadId: command.threadId,
357 });
358 return {
359 ...(yield* withEventBase({
360 aggregateKind: "thread",
361 aggregateId: command.threadId,
362 occurredAt: command.createdAt,
363 commandId: command.commandId,
364 })),
365 type: "thread.created",
366 payload: {
367 threadId: command.threadId,
368 projectId: command.projectId,
369 title: command.title,
370 modelSelection: command.modelSelection,
371 runtimeMode: command.runtimeMode,
372 interactionMode: command.interactionMode,
373 branch: command.branch,
374 worktreePath: command.worktreePath,
375 createdAt: command.createdAt,
376 updatedAt: command.createdAt,
377 },
378 };
379 }
380
381 case "thread.delete": {
382 yield* requireThread({
383 readModel,
384 command,
385 threadId: command.threadId,
386 });
387 const occurredAt = yield* nowIso;
388 return {
389 ...(yield* withEventBase({
390 aggregateKind: "thread",
391 aggregateId: command.threadId,
392 occurredAt,
393 commandId: command.commandId,
394 })),
395 type: "thread.deleted",
396 payload: {
397 threadId: command.threadId,
398 deletedAt: occurredAt,
399 },
400 };
401 }
402
403 case "thread.archive": {
404 yield* requireThreadNotArchived({
405 readModel,
406 command,
407 threadId: command.threadId,
408 });
409 const occurredAt = yield* nowIso;
410 return {
411 ...(yield* withEventBase({
412 aggregateKind: "thread",
413 aggregateId: command.threadId,
414 occurredAt,
415 commandId: command.commandId,
416 })),
417 type: "thread.archived",
418 payload: {
419 threadId: command.threadId,
420 archivedAt: occurredAt,
421 updatedAt: occurredAt,
422 },
423 };
424 }
425
426 case "thread.unarchive": {
427 yield* requireThreadArchived({
428 readModel,
429 command,
430 threadId: command.threadId,
431 });
432 const occurredAt = yield* nowIso;
433 return {
434 ...(yield* withEventBase({
435 aggregateKind: "thread",
436 aggregateId: command.threadId,
437 occurredAt,
438 commandId: command.commandId,
439 })),
440 type: "thread.unarchived",
441 payload: {
442 threadId: command.threadId,
443 updatedAt: occurredAt,
444 },
445 };
446 }
447
448 case "thread.settle": {
449 const thread = yield* requireThreadNotArchived({
450 readModel,
451 command,
452 threadId: command.threadId,
453 });
454 // Server-side twin of the client's canSettle session check: a stale
455 // or raced client must not settle a thread whose session is coming
456 // alive or working.
457 if (thread.session?.status === "starting" || thread.session?.status === "running") {
458 return yield* Effect.fail(
459 new OrchestrationCommandInvariantError({
460 commandType: command.type,
461 detail: `thread ${command.threadId} has an active session and cannot be settled`,
462 }),
463 );
464 }
465 // Pending approval / user-input requests are blocked-on-you work: a
466 // raced or stale client must not park them behind a settled override
467 // that would surface only after the request resolves.
468 if (hasOpenBlockingRequest(thread)) {
469 return yield* Effect.fail(
470 new OrchestrationCommandInvariantError({
471 commandType: command.type,
472 detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be settled`,
473 }),
474 );
475 }
476 const occurredAt = yield* nowIso;
477 // Settling inside the adoption window would hide just-requested work.
478 if (threadHasQueuedTurnStart(thread, occurredAt)) {
479 return yield* Effect.fail(
480 new OrchestrationCommandInvariantError({
481 commandType: command.type,
482 detail: `thread ${command.threadId} has a queued turn start and cannot be settled`,
483 }),
484 );
485 }
486 // Settling an already-settled thread re-emits with the original
487 // settledAt: the engine rejects zero-event commands, and bulk-settle /
488 // double-click must stay silent no-ops rather than surface errors.
489 const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
490 return {
491 ...(yield* withEventBase({
492 aggregateKind: "thread",
493 aggregateId: command.threadId,
494 occurredAt,
495 commandId: command.commandId,
496 })),
497 type: "thread.settled",
498 payload: {
499 threadId: command.threadId,
500 settledAt: alreadySettled ? thread.settledAt : occurredAt,
501 // A re-emission is a projected no-op: keep the existing updatedAt
502 // so duplicate settles neither rewind nor churn ordering. A fresh
503 // settle stamps the command time.
504 updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
505 },
506 };
507 }
508
509 case "thread.unsettle": {
510 const thread = yield* requireThreadNotArchived({
511 readModel,
512 command,
513 threadId: command.threadId,
514 });
515 // Idempotent by re-emission (see thread.settle): reducing the event a
516 // second time lands on the same override state. A re-emission keeps
517 // the existing updatedAt so duplicates do not churn ordering.
518 const alreadyPinnedActive = thread.settledOverride === "active";
519 const occurredAt = yield* nowIso;
520 return {
521 ...(yield* withEventBase({
522 aggregateKind: "thread",
523 aggregateId: command.threadId,
524 occurredAt,
525 commandId: command.commandId,
526 })),
527 type: "thread.unsettled",
528 payload: {
529 threadId: command.threadId,
530 reason: command.reason,
531 updatedAt: alreadyPinnedActive ? thread.updatedAt : occurredAt,
532 },
533 };
534 }
535
536 case "thread.snooze": {
537 const thread = yield* requireThreadNotArchived({
538 readModel,
539 command,
540 threadId: command.threadId,
541 });
542 const occurredAt = yield* nowIso;
543 // A wake time in the past would create a thread that is snoozed and
544 // woken at once — the row would never leave the inbox but still carry
545 // snooze state. Reject instead of silently normalizing. The negated
546 // comparison also catches unparseable wake times (IsoDateTime is
547 // structurally just a string): NaN fails every comparison, and an
548 // unparseable snoozedUntil must never persist.
549 if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {
550 return yield* Effect.fail(
551 new OrchestrationCommandInvariantError({
552 commandType: command.type,
553 detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,
554 }),
555 );
556 }
557 // Blocked-on-you work must not be snoozed away: a pending approval or
558 // user-input request is the agent waiting on the user, and hiding it
559 // defeats the request. (A running session IS snoozable — snooze only
560 // affects visibility, never the agent.)
561 if (hasOpenBlockingRequest(thread)) {
562 return yield* Effect.fail(
563 new OrchestrationCommandInvariantError({
564 commandType: command.type,
565 detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,
566 }),
567 );
568 }
569 // A queued turn start — a user message no turn has adopted yet — is
570 // invisible pending work: no session, no pending flags. Snoozing in
571 // that window would hide a just-requested turn exactly the way settle
572 // would.
573 if (threadHasQueuedTurnStart(thread, occurredAt)) {
574 return yield* Effect.fail(
575 new OrchestrationCommandInvariantError({
576 commandType: command.type,
577 detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,
578 }),
579 );
580 }
581 // Re-snoozing an already-snoozed thread to the SAME wake time is a
582 // duplicate (double-click, raced clients): re-emit with the original
583 // timestamps so the projection is a no-op. A different wake time is a
584 // real change and stamps fresh.
585 const existingSnoozedAt =
586 thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null
587 ? thread.snoozedAt
588 : null;
589 return {
590 ...(yield* withEventBase({
591 aggregateKind: "thread",
592 aggregateId: command.threadId,
593 occurredAt,
594 commandId: command.commandId,
595 })),
596 type: "thread.snoozed",
597 payload: {
598 threadId: command.threadId,
599 snoozedUntil: command.snoozedUntil,
600 snoozedAt: existingSnoozedAt ?? occurredAt,
601 updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,
602 },
603 };
604 }
605
606 case "thread.unsnooze": {
607 const thread = yield* requireThreadNotArchived({
608 readModel,
609 command,
610 threadId: command.threadId,
611 });
612 // Idempotent by re-emission (see thread.settle): waking a thread that
613 // is not snoozed lands on the same null state without churning
614 // updatedAt.
615 const alreadyAwake = thread.snoozedUntil == null;
616 const occurredAt = yield* nowIso;
617 return {
618 ...(yield* withEventBase({
619 aggregateKind: "thread",
620 aggregateId: command.threadId,
621 occurredAt,
622 commandId: command.commandId,
623 })),
624 type: "thread.unsnoozed",
625 payload: {
626 threadId: command.threadId,
627 reason: command.reason,
628 updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,
629 },
630 };
631 }
632
633 case "thread.meta.update": {
634 const thread = yield* requireThread({
635 readModel,
636 command,
637 threadId: command.threadId,
638 });
639 const branch =
640 command.branch !== undefined &&
641 command.expectedBranch !== undefined &&
642 thread.branch !== command.expectedBranch
643 ? thread.branch
644 : command.branch;
645 const occurredAt = yield* nowIso;
646 return {
647 ...(yield* withEventBase({
648 aggregateKind: "thread",
649 aggregateId: command.threadId,
650 occurredAt,
651 commandId: command.commandId,
652 })),
653 type: "thread.meta-updated",
654 payload: {
655 threadId: command.threadId,
656 ...(command.title !== undefined ? { title: command.title } : {}),
657 ...(command.regenerateTitle === true
658 ? {
659 regenerateTitle: true as const,
660 previousTitle: thread.title,
661 titleRegeneration: {
662 requestId: command.commandId,
663 startedAt: occurredAt,
664 },
665 }
666 : {}),
667 ...(command.title !== undefined && thread.titleRegeneration != null
668 ? { titleRegeneration: null }
669 : {}),
670 ...(command.modelSelection !== undefined
671 ? { modelSelection: command.modelSelection }
672 : {}),
673 ...(branch !== undefined ? { branch } : {}),
674 ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
675 updatedAt: occurredAt,
676 },
677 };
678 }
679
680 case "thread.title.regeneration.complete": {
681 const thread = yield* requireThread({
682 readModel,
683 command,
684 threadId: command.threadId,
685 });
686 const requestIsCurrent = thread.titleRegeneration?.requestId === command.requestId;
687 const occurredAt = yield* nowIso;
688 return {
689 ...(yield* withEventBase({
690 aggregateKind: "thread",
691 aggregateId: command.threadId,
692 occurredAt,
693 commandId: command.commandId,
694 })),
695 type: "thread.meta-updated",
696 payload: {
697 threadId: command.threadId,
698 ...(requestIsCurrent && command.title !== undefined ? { title: command.title } : {}),
699 ...(requestIsCurrent ? { titleRegeneration: null } : {}),
700 updatedAt: requestIsCurrent ? occurredAt : thread.updatedAt,
701 },
702 };
703 }
704
705 case "thread.runtime-mode.set": {
706 yield* requireThread({
707 readModel,
708 command,
709 threadId: command.threadId,
710 });
711 const occurredAt = yield* nowIso;
712 return {
713 ...(yield* withEventBase({
714 aggregateKind: "thread",
715 aggregateId: command.threadId,
716 occurredAt,
717 commandId: command.commandId,
718 })),
719 type: "thread.runtime-mode-set",
720 payload: {
721 threadId: command.threadId,
722 runtimeMode: command.runtimeMode,
723 updatedAt: occurredAt,
724 },
725 };
726 }
727
728 case "thread.interaction-mode.set": {
729 yield* requireThread({
730 readModel,
731 command,
732 threadId: command.threadId,
733 });
734 const occurredAt = yield* nowIso;
735 return {
736 ...(yield* withEventBase({
737 aggregateKind: "thread",
738 aggregateId: command.threadId,
739 occurredAt,
740 commandId: command.commandId,
741 })),
742 type: "thread.interaction-mode-set",
743 payload: {
744 threadId: command.threadId,
745 interactionMode: command.interactionMode,
746 updatedAt: occurredAt,
747 },
748 };
749 }
750
751 case "thread.turn.start": {
752 const targetThread = yield* requireThread({
753 readModel,
754 command,
755 threadId: command.threadId,
756 });
757 const sourceProposedPlan = command.sourceProposedPlan;
758 const sourceThread = sourceProposedPlan
759 ? yield* requireThread({
760 readModel,
761 command,
762 threadId: sourceProposedPlan.threadId,
763 })
764 : null;
765 const sourcePlan =
766 sourceProposedPlan && sourceThread
767 ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
768 : null;
769 if (sourceProposedPlan && !sourcePlan) {
770 return yield* new OrchestrationCommandInvariantError({
771 commandType: command.type,
772 detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
773 });
774 }
775 if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
776 return yield* new OrchestrationCommandInvariantError({
777 commandType: command.type,
778 detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
779 });
780 }
781 const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
782 ...(yield* withEventBase({
783 aggregateKind: "thread",
784 aggregateId: command.threadId,
785 occurredAt: command.createdAt,
786 commandId: command.commandId,
787 })),
788 type: "thread.message-sent",
789 payload: {
790 threadId: command.threadId,
791 messageId: command.message.messageId,
792 role: "user",
793 text: command.message.text,
794 attachments: command.message.attachments,
795 turnId: null,
796 streaming: false,
797 createdAt: command.createdAt,
798 updatedAt: command.createdAt,
799 },
800 };
801 const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
802 ...(yield* withEventBase({
803 aggregateKind: "thread",
804 aggregateId: command.threadId,
805 occurredAt: command.createdAt,
806 commandId: command.commandId,
807 })),
808 causationEventId: userMessageEvent.eventId,
809 type: "thread.turn-start-requested",
810 payload: {
811 threadId: command.threadId,
812 messageId: command.message.messageId,
813 ...(command.modelSelection !== undefined
814 ? { modelSelection: command.modelSelection }
815 : {}),
816 ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
817 runtimeMode: targetThread.runtimeMode,
818 interactionMode: targetThread.interactionMode,
819 ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
820 createdAt: command.createdAt,
821 },
822 };
823 // Real activity resets ANY override: it wakes an explicitly settled
824 // thread, and it clears a keep-active pin back to neutral so the
825 // thread can auto-settle again after this burst of work goes stale.
826 // A snooze clears the same way — sending a message to a snoozed
827 // thread is the user re-engaging, so the return ticket is spent.
828 const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
829 if (targetThread.settledOverride !== null) {
830 lifecycleResetEvents.push({
831 ...(yield* withEventBase({
832 aggregateKind: "thread",
833 aggregateId: command.threadId,
834 occurredAt: command.createdAt,
835 commandId: command.commandId,
836 })),
837 type: "thread.unsettled",
838 payload: {
839 threadId: command.threadId,
840 reason: "activity",
841 updatedAt: command.createdAt,
842 },
843 });
844 }
845 if (targetThread.snoozedUntil != null) {
846 lifecycleResetEvents.push({
847 ...(yield* withEventBase({
848 aggregateKind: "thread",
849 aggregateId: command.threadId,
850 occurredAt: command.createdAt,
851 commandId: command.commandId,
852 })),
853 type: "thread.unsnoozed",
854 payload: {
855 threadId: command.threadId,
856 reason: "activity",
857 updatedAt: command.createdAt,
858 },
859 });
860 }
861 return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
862 }
863
864 case "thread.turn.interrupt": {
865 yield* requireThread({
866 readModel,
867 command,
868 threadId: command.threadId,
869 });
870 return {
871 ...(yield* withEventBase({
872 aggregateKind: "thread",
873 aggregateId: command.threadId,
874 occurredAt: command.createdAt,
875 commandId: command.commandId,
876 })),
877 type: "thread.turn-interrupt-requested",
878 payload: {
879 threadId: command.threadId,
880 ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),
881 createdAt: command.createdAt,
882 },
883 };
884 }
885
886 case "thread.approval.respond": {
887 yield* requireThread({
888 readModel,
889 command,
890 threadId: command.threadId,
891 });
892 return {
893 ...(yield* withEventBase({
894 aggregateKind: "thread",
895 aggregateId: command.threadId,
896 occurredAt: command.createdAt,
897 commandId: command.commandId,
898 metadata: {
899 requestId: command.requestId,
900 },
901 })),
902 type: "thread.approval-response-requested",
903 payload: {
904 threadId: command.threadId,
905 requestId: command.requestId,
906 decision: command.decision,
907 createdAt: command.createdAt,
908 },
909 };
910 }
911
912 case "thread.user-input.respond": {
913 yield* requireThread({
914 readModel,
915 command,
916 threadId: command.threadId,
917 });
918 return {
919 ...(yield* withEventBase({
920 aggregateKind: "thread",
921 aggregateId: command.threadId,
922 occurredAt: command.createdAt,
923 commandId: command.commandId,
924 metadata: {
925 requestId: command.requestId,
926 },
927 })),
928 type: "thread.user-input-response-requested",
929 payload: {
930 threadId: command.threadId,
931 requestId: command.requestId,
932 answers: command.answers,
933 createdAt: command.createdAt,
934 },
935 };
936 }
937
938 case "thread.checkpoint.revert": {
939 yield* requireThread({
940 readModel,
941 command,
942 threadId: command.threadId,
943 });
944 return {
945 ...(yield* withEventBase({
946 aggregateKind: "thread",
947 aggregateId: command.threadId,
948 occurredAt: command.createdAt,
949 commandId: command.commandId,
950 })),
951 type: "thread.checkpoint-revert-requested",
952 payload: {
953 threadId: command.threadId,
954 turnCount: command.turnCount,
955 createdAt: command.createdAt,
956 },
957 };
958 }
959
960 case "thread.session.stop": {
961 yield* requireThread({
962 readModel,
963 command,
964 threadId: command.threadId,
965 });
966 return {
967 ...(yield* withEventBase({
968 aggregateKind: "thread",
969 aggregateId: command.threadId,
970 occurredAt: command.createdAt,
971 commandId: command.commandId,
972 })),
973 type: "thread.session-stop-requested",
974 payload: {
975 threadId: command.threadId,
976 createdAt: command.createdAt,
977 },
978 };
979 }
980
981 case "thread.session.set": {
982 const thread = yield* requireThread({
983 readModel,
984 command,
985 threadId: command.threadId,
986 });
987 const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
988 ...(yield* withEventBase({
989 aggregateKind: "thread",
990 aggregateId: command.threadId,
991 occurredAt: command.createdAt,
992 commandId: command.commandId,
993 metadata: {},
994 })),
995 type: "thread.session-set",
996 payload: {
997 threadId: command.threadId,
998 session: command.session,
999 },
1000 };
1001 // Only a session coming alive is activity worth waking a settled thread
1002 // for — status writes like ready/stopped/error arrive after the fact and
1003 // must not fight a user's explicit settle. Snooze is deliberately NOT
1004 // cleared here: snooze never pauses the agent, so its session starting
1005 // or erroring is not the user re-engaging. Blocked/failed work still
1006 // surfaces immediately — effectiveSnoozed refuses to classify a thread
1007 // with a raised hand (approval / input / failure / fresh completion)
1008 // as snoozed, without spending the return ticket.
1009 const isSessionActivity =
1010 command.session.status === "starting" || command.session.status === "running";
1011 // Real activity resets ANY override (settled wakes, active unpins).
1012 if (thread.settledOverride === null || !isSessionActivity) {
1013 return sessionSetEvent;
1014 }
1015 const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
1016 ...(yield* withEventBase({
1017 aggregateKind: "thread",
1018 aggregateId: command.threadId,
1019 occurredAt: command.createdAt,
1020 commandId: command.commandId,
1021 })),
1022 type: "thread.unsettled",
1023 payload: {
1024 threadId: command.threadId,
1025 reason: "activity",
1026 updatedAt: command.createdAt,
1027 },
1028 };
1029 return [unsettledEvent, sessionSetEvent];
1030 }
1031
1032 case "thread.message.assistant.delta": {
1033 yield* requireThread({
1034 readModel,
1035 command,
1036 threadId: command.threadId,
1037 });
1038 return {
1039 ...(yield* withEventBase({
1040 aggregateKind: "thread",
1041 aggregateId: command.threadId,
1042 occurredAt: command.createdAt,
1043 commandId: command.commandId,
1044 })),
1045 type: "thread.message-sent",
1046 payload: {
1047 threadId: command.threadId,
1048 messageId: command.messageId,
1049 role: "assistant",
1050 text: command.delta,
1051 turnId: command.turnId ?? null,
1052 streaming: true,
1053 createdAt: command.createdAt,
1054 updatedAt: command.createdAt,
1055 },
1056 };
1057 }
1058
1059 case "thread.message.assistant.complete": {
1060 yield* requireThread({
1061 readModel,
1062 command,
1063 threadId: command.threadId,
1064 });
1065 return {
1066 ...(yield* withEventBase({
1067 aggregateKind: "thread",
1068 aggregateId: command.threadId,
1069 occurredAt: command.createdAt,
1070 commandId: command.commandId,
1071 })),
1072 type: "thread.message-sent",
1073 payload: {
1074 threadId: command.threadId,
1075 messageId: command.messageId,
1076 role: "assistant",
1077 text: "",
1078 turnId: command.turnId ?? null,
1079 streaming: false,
1080 createdAt: command.createdAt,
1081 updatedAt: command.createdAt,
1082 },
1083 };
1084 }
1085
1086 case "thread.proposed-plan.upsert": {
1087 yield* requireThread({
1088 readModel,
1089 command,
1090 threadId: command.threadId,
1091 });
1092 return {
1093 ...(yield* withEventBase({
1094 aggregateKind: "thread",
1095 aggregateId: command.threadId,
1096 occurredAt: command.createdAt,
1097 commandId: command.commandId,
1098 })),
1099 type: "thread.proposed-plan-upserted",
1100 payload: {
1101 threadId: command.threadId,
1102 proposedPlan: command.proposedPlan,
1103 },
1104 };
1105 }
1106
1107 case "thread.turn.diff.complete": {
1108 yield* requireThread({
1109 readModel,
1110 command,
1111 threadId: command.threadId,
1112 });
1113 return {
1114 ...(yield* withEventBase({
1115 aggregateKind: "thread",
1116 aggregateId: command.threadId,
1117 occurredAt: command.createdAt,
1118 commandId: command.commandId,
1119 })),
1120 type: "thread.turn-diff-completed",
1121 payload: {
1122 threadId: command.threadId,
1123 turnId: command.turnId,
1124 checkpointTurnCount: command.checkpointTurnCount,
1125 checkpointRef: command.checkpointRef,
1126 status: command.status,
1127 files: command.files,
1128 assistantMessageId: command.assistantMessageId ?? null,
1129 completedAt: command.completedAt,
1130 },
1131 };
1132 }
1133
1134 case "thread.revert.complete": {
1135 yield* requireThread({
1136 readModel,
1137 command,
1138 threadId: command.threadId,
1139 });
1140 return {
1141 ...(yield* withEventBase({
1142 aggregateKind: "thread",
1143 aggregateId: command.threadId,
1144 occurredAt: command.createdAt,
1145 commandId: command.commandId,
1146 })),
1147 type: "thread.reverted",
1148 payload: {
1149 threadId: command.threadId,
1150 turnCount: command.turnCount,
1151 },
1152 };
1153 }
1154
1155 case "thread.activity.append": {
1156 const thread = yield* requireThread({
1157 readModel,
1158 command,
1159 threadId: command.threadId,
1160 });
1161 const requestId =
1162 typeof command.activity.payload === "object" &&
1163 command.activity.payload !== null &&
1164 "requestId" in command.activity.payload &&
1165 typeof (command.activity.payload as { requestId?: unknown }).requestId === "string"
1166 ? ((command.activity.payload as { requestId: string })
1167 .requestId as OrchestrationEvent["metadata"]["requestId"])
1168 : undefined;
1169 const activityAppendedEvent: Omit<OrchestrationEvent, "sequence"> = {
1170 ...(yield* withEventBase({
1171 aggregateKind: "thread",
1172 aggregateId: command.threadId,
1173 occurredAt: command.createdAt,
1174 commandId: command.commandId,
1175 ...(requestId !== undefined ? { metadata: { requestId } } : {}),
1176 })),
1177 type: "thread.activity-appended",
1178 payload: {
1179 threadId: command.threadId,
1180 activity: command.activity,
1181 },
1182 };
1183 // An approval or user-input request is blocked-on-you work — it must
1184 // never stay hidden inside a settled slim row.
1185 const wakesSettledThread =
1186 command.activity.kind === "approval.requested" ||
1187 command.activity.kind === "user-input.requested";
1188 // Real activity resets ANY override (settled wakes, active unpins).
1189 if (thread.settledOverride === null || !wakesSettledThread) {
1190 return activityAppendedEvent;
1191 }
1192 const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
1193 ...(yield* withEventBase({
1194 aggregateKind: "thread",
1195 aggregateId: command.threadId,
1196 occurredAt: command.createdAt,
1197 commandId: command.commandId,
1198 })),
1199 type: "thread.unsettled",
1200 payload: {
1201 threadId: command.threadId,
1202 reason: "activity",
1203 updatedAt: command.createdAt,
1204 },
1205 };
1206 return [unsettledEvent, activityAppendedEvent];
1207 }
1208
1209 default: {
1210 command satisfies never;
1211 const fallback = command as never as { type: string };
1212 return yield* new OrchestrationCommandInvariantError({
1213 commandType: fallback.type,
1214 detail: `Unknown command type: ${fallback.type}`,
1215 });
1216 }
1217 }
1218});