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

decider.ts

1,180 lines39.2 KB

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 );
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;
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 );
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 );
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.modelSelection !== undefined
658 ? { modelSelection: command.modelSelection }
659 : {}),
660 ...(branch !== undefined ? { branch } : {}),
661 ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
662 updatedAt: occurredAt,
663 },
664 };
665 }
666​
667 case "thread.runtime-mode.set": {
668 yield* requireThread({
669 readModel,
670 command,
671 threadId: command.threadId,
672 });
673 const occurredAt = yield* nowIso;
674 return {
675 ...(yield* withEventBase({
676 aggregateKind: "thread",
677 aggregateId: command.threadId,
678 occurredAt,
679 commandId: command.commandId,
680 })),
681 type: "thread.runtime-mode-set",
682 payload: {
683 threadId: command.threadId,
684 runtimeMode: command.runtimeMode,
685 updatedAt: occurredAt,
686 },
687 };
688 }
689​
690 case "thread.interaction-mode.set": {
691 yield* requireThread({
692 readModel,
693 command,
694 threadId: command.threadId,
695 });
696 const occurredAt = yield* nowIso;
697 return {
698 ...(yield* withEventBase({
699 aggregateKind: "thread",
700 aggregateId: command.threadId,
701 occurredAt,
702 commandId: command.commandId,
703 })),
704 type: "thread.interaction-mode-set",
705 payload: {
706 threadId: command.threadId,
707 interactionMode: command.interactionMode,
708 updatedAt: occurredAt,
709 },
710 };
711 }
712​
713 case "thread.turn.start": {
714 const targetThread = yield* requireThread({
715 readModel,
716 command,
717 threadId: command.threadId,
718 });
719 const sourceProposedPlan = command.sourceProposedPlan;
720 const sourceThread = sourceProposedPlan
721 ? yield* requireThread({
722 readModel,
723 command,
724 threadId: sourceProposedPlan.threadId,
725 })
726 : null;
727 const sourcePlan =
728 sourceProposedPlan && sourceThread
729 ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)
730 : null;
731 if (sourceProposedPlan && !sourcePlan) {
732 return yield* new OrchestrationCommandInvariantError({
733 commandType: command.type,
734 detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,
735 });
736 }
737 if (sourceThread && sourceThread.projectId !== targetThread.projectId) {
738 return yield* new OrchestrationCommandInvariantError({
739 commandType: command.type,
740 detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,
741 });
742 }
743 const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
744 ...(yield* withEventBase({
745 aggregateKind: "thread",
746 aggregateId: command.threadId,
747 occurredAt: command.createdAt,
748 commandId: command.commandId,
749 })),
750 type: "thread.message-sent",
751 payload: {
752 threadId: command.threadId,
753 messageId: command.message.messageId,
754 role: "user",
755 text: command.message.text,
756 attachments: command.message.attachments,
757 turnId: null,
758 streaming: false,
759 createdAt: command.createdAt,
760 updatedAt: command.createdAt,
761 },
762 };
763 const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
764 ...(yield* withEventBase({
765 aggregateKind: "thread",
766 aggregateId: command.threadId,
767 occurredAt: command.createdAt,
768 commandId: command.commandId,
769 })),
770 causationEventId: userMessageEvent.eventId,
771 type: "thread.turn-start-requested",
772 payload: {
773 threadId: command.threadId,
774 messageId: command.message.messageId,
775 ...(command.modelSelection !== undefined
776 ? { modelSelection: command.modelSelection }
777 : {}),
778 ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),
779 runtimeMode: targetThread.runtimeMode,
780 interactionMode: targetThread.interactionMode,
781 ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
782 createdAt: command.createdAt,
783 },
784 };
785 // Real activity resets ANY override: it wakes an explicitly settled
786 // thread, and it clears a keep-active pin back to neutral so the
787 // thread can auto-settle again after this burst of work goes stale.
788 // A snooze clears the same way — sending a message to a snoozed
789 // thread is the user re-engaging, so the return ticket is spent.
790 const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
791 if (targetThread.settledOverride !== null) {
792 lifecycleResetEvents.push({
793 ...(yield* withEventBase({
794 aggregateKind: "thread",
795 aggregateId: command.threadId,
796 occurredAt: command.createdAt,
797 commandId: command.commandId,
798 })),
799 type: "thread.unsettled",
800 payload: {
801 threadId: command.threadId,
802 reason: "activity",
803 updatedAt: command.createdAt,
804 },
805 });
806 }
807 if (targetThread.snoozedUntil != null) {
808 lifecycleResetEvents.push({
809 ...(yield* withEventBase({
810 aggregateKind: "thread",
811 aggregateId: command.threadId,
812 occurredAt: command.createdAt,
813 commandId: command.commandId,
814 })),
815 type: "thread.unsnoozed",
816 payload: {
817 threadId: command.threadId,
818 reason: "activity",
819 updatedAt: command.createdAt,
820 },
821 });
822 }
823 return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
824 }
825​
826 case "thread.turn.interrupt": {
827 yield* requireThread({
828 readModel,
829 command,
830 threadId: command.threadId,
831 });
832 return {
833 ...(yield* withEventBase({
834 aggregateKind: "thread",
835 aggregateId: command.threadId,
836 occurredAt: command.createdAt,
837 commandId: command.commandId,
838 })),
839 type: "thread.turn-interrupt-requested",
840 payload: {
841 threadId: command.threadId,
842 ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),
843 createdAt: command.createdAt,
844 },
845 };
846 }
847​
848 case "thread.approval.respond": {
849 yield* requireThread({
850 readModel,
851 command,
852 threadId: command.threadId,
853 });
854 return {
855 ...(yield* withEventBase({
856 aggregateKind: "thread",
857 aggregateId: command.threadId,
858 occurredAt: command.createdAt,
859 commandId: command.commandId,
860 metadata: {
861 requestId: command.requestId,
862 },
863 })),
864 type: "thread.approval-response-requested",
865 payload: {
866 threadId: command.threadId,
867 requestId: command.requestId,
868 decision: command.decision,
869 createdAt: command.createdAt,
870 },
871 };
872 }
873​
874 case "thread.user-input.respond": {
875 yield* requireThread({
876 readModel,
877 command,
878 threadId: command.threadId,
879 });
880 return {
881 ...(yield* withEventBase({
882 aggregateKind: "thread",
883 aggregateId: command.threadId,
884 occurredAt: command.createdAt,
885 commandId: command.commandId,
886 metadata: {
887 requestId: command.requestId,
888 },
889 })),
890 type: "thread.user-input-response-requested",
891 payload: {
892 threadId: command.threadId,
893 requestId: command.requestId,
894 answers: command.answers,
895 createdAt: command.createdAt,
896 },
897 };
898 }
899​
900 case "thread.checkpoint.revert": {
901 yield* requireThread({
902 readModel,
903 command,
904 threadId: command.threadId,
905 });
906 return {
907 ...(yield* withEventBase({
908 aggregateKind: "thread",
909 aggregateId: command.threadId,
910 occurredAt: command.createdAt,
911 commandId: command.commandId,
912 })),
913 type: "thread.checkpoint-revert-requested",
914 payload: {
915 threadId: command.threadId,
916 turnCount: command.turnCount,
917 createdAt: command.createdAt,
918 },
919 };
920 }
921​
922 case "thread.session.stop": {
923 yield* requireThread({
924 readModel,
925 command,
926 threadId: command.threadId,
927 });
928 return {
929 ...(yield* withEventBase({
930 aggregateKind: "thread",
931 aggregateId: command.threadId,
932 occurredAt: command.createdAt,
933 commandId: command.commandId,
934 })),
935 type: "thread.session-stop-requested",
936 payload: {
937 threadId: command.threadId,
938 createdAt: command.createdAt,
939 },
940 };
941 }
942​
943 case "thread.session.set": {
944 const thread = yield* requireThread({
945 readModel,
946 command,
947 threadId: command.threadId,
948 });
949 const sessionSetEvent: Omit<OrchestrationEvent, "sequence"> = {
950 ...(yield* withEventBase({
951 aggregateKind: "thread",
952 aggregateId: command.threadId,
953 occurredAt: command.createdAt,
954 commandId: command.commandId,
955 metadata: {},
956 })),
957 type: "thread.session-set",
958 payload: {
959 threadId: command.threadId,
960 session: command.session,
961 },
962 };
963 // Only a session coming alive is activity worth waking a settled thread
964 // for — status writes like ready/stopped/error arrive after the fact and
965 // must not fight a user's explicit settle. Snooze is deliberately NOT
966 // cleared here: snooze never pauses the agent, so its session starting
967 // or erroring is not the user re-engaging. Blocked/failed work still
968 // surfaces immediately — effectiveSnoozed refuses to classify a thread
969 // with a raised hand (approval / input / failure / fresh completion)
970 // as snoozed, without spending the return ticket.
971 const isSessionActivity =
972 command.session.status === "starting" || command.session.status === "running";
973 // Real activity resets ANY override (settled wakes, active unpins).
974 if (thread.settledOverride === null || !isSessionActivity) {
975 return sessionSetEvent;
976 }
977 const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
978 ...(yield* withEventBase({
979 aggregateKind: "thread",
980 aggregateId: command.threadId,
981 occurredAt: command.createdAt,
982 commandId: command.commandId,
983 })),
984 type: "thread.unsettled",
985 payload: {
986 threadId: command.threadId,
987 reason: "activity",
988 updatedAt: command.createdAt,
989 },
990 };
991 return [unsettledEvent, sessionSetEvent];
992 }
993​
994 case "thread.message.assistant.delta": {
995 yield* requireThread({
996 readModel,
997 command,
998 threadId: command.threadId,
999 });
1000 return {
1001 ...(yield* withEventBase({
1002 aggregateKind: "thread",
1003 aggregateId: command.threadId,
1004 occurredAt: command.createdAt,
1005 commandId: command.commandId,
1006 })),
1007 type: "thread.message-sent",
1008 payload: {
1009 threadId: command.threadId,
1010 messageId: command.messageId,
1011 role: "assistant",
1012 text: command.delta,
1013 turnId: command.turnId ?? null,
1014 streaming: true,
1015 createdAt: command.createdAt,
1016 updatedAt: command.createdAt,
1017 },
1018 };
1020​
1021 case "thread.message.assistant.complete": {
1022 yield* requireThread({
1023 readModel,
1024 command,
1025 threadId: command.threadId,
1026 });
1027 return {
1028 ...(yield* withEventBase({
1029 aggregateKind: "thread",
1030 aggregateId: command.threadId,
1031 occurredAt: command.createdAt,
1032 commandId: command.commandId,
1033 })),
1034 type: "thread.message-sent",
1035 payload: {
1036 threadId: command.threadId,
1037 messageId: command.messageId,
1038 role: "assistant",
1039 text: "",
1040 turnId: command.turnId ?? null,
1041 streaming: false,
1042 createdAt: command.createdAt,
1043 updatedAt: command.createdAt,
1044 },
1045 };
1047​
1048 case "thread.proposed-plan.upsert": {
1049 yield* requireThread({
1050 readModel,
1051 command,
1052 threadId: command.threadId,
1053 });
1054 return {
1055 ...(yield* withEventBase({
1056 aggregateKind: "thread",
1057 aggregateId: command.threadId,
1058 occurredAt: command.createdAt,
1059 commandId: command.commandId,
1060 })),
1061 type: "thread.proposed-plan-upserted",
1062 payload: {
1063 threadId: command.threadId,
1064 proposedPlan: command.proposedPlan,
1065 },
1066 };
1068​
1069 case "thread.turn.diff.complete": {
1070 yield* requireThread({
1071 readModel,
1072 command,
1073 threadId: command.threadId,
1074 });
1075 return {
1076 ...(yield* withEventBase({
1077 aggregateKind: "thread",
1078 aggregateId: command.threadId,
1079 occurredAt: command.createdAt,
1080 commandId: command.commandId,
1081 })),
1082 type: "thread.turn-diff-completed",
1083 payload: {
1084 threadId: command.threadId,
1085 turnId: command.turnId,
1086 checkpointTurnCount: command.checkpointTurnCount,
1087 checkpointRef: command.checkpointRef,
1088 status: command.status,
1089 files: command.files,
1090 assistantMessageId: command.assistantMessageId ?? null,
1091 completedAt: command.completedAt,
1092 },
1093 };
1095​
1096 case "thread.revert.complete": {
1097 yield* requireThread({
1098 readModel,
1099 command,
1100 threadId: command.threadId,
1101 });
1102 return {
1103 ...(yield* withEventBase({
1104 aggregateKind: "thread",
1105 aggregateId: command.threadId,
1106 occurredAt: command.createdAt,
1107 commandId: command.commandId,
1108 })),
1109 type: "thread.reverted",
1110 payload: {
1111 threadId: command.threadId,
1112 turnCount: command.turnCount,
1113 },
1114 };
1116​
1117 case "thread.activity.append": {
1118 const thread = yield* requireThread({
1119 readModel,
1120 command,
1121 threadId: command.threadId,
1122 });
1123 const requestId =
1124 typeof command.activity.payload === "object" &&
1125 command.activity.payload !== null &&
1126 "requestId" in command.activity.payload &&
1127 typeof (command.activity.payload as { requestId?: unknown }).requestId === "string"
1128 ? ((command.activity.payload as { requestId: string })
1129 .requestId as OrchestrationEvent["metadata"]["requestId"])
1130 : undefined;
1131 const activityAppendedEvent: Omit<OrchestrationEvent, "sequence"> = {
1132 ...(yield* withEventBase({
1133 aggregateKind: "thread",
1134 aggregateId: command.threadId,
1135 occurredAt: command.createdAt,
1136 commandId: command.commandId,
1137 ...(requestId !== undefined ? { metadata: { requestId } } : {}),
1138 })),
1139 type: "thread.activity-appended",
1140 payload: {
1141 threadId: command.threadId,
1142 activity: command.activity,
1143 },
1144 };
1145 // An approval or user-input request is blocked-on-you work — it must
1146 // never stay hidden inside a settled slim row.
1147 const wakesSettledThread =
1148 command.activity.kind === "approval.requested" ||
1149 command.activity.kind === "user-input.requested";
1150 // Real activity resets ANY override (settled wakes, active unpins).
1151 if (thread.settledOverride === null || !wakesSettledThread) {
1152 return activityAppendedEvent;
1154 const unsettledEvent: Omit<OrchestrationEvent, "sequence"> = {
1155 ...(yield* withEventBase({
1156 aggregateKind: "thread",
1157 aggregateId: command.threadId,
1158 occurredAt: command.createdAt,
1159 commandId: command.commandId,
1160 })),
1161 type: "thread.unsettled",
1162 payload: {
1163 threadId: command.threadId,
1164 reason: "activity",
1165 updatedAt: command.createdAt,
1166 },
1167 };
1168 return [unsettledEvent, activityAppendedEvent];
1170​
1171 default: {
1172 command satisfies never;
1173 const fallback = command as never as { type: string };
1174 return yield* new OrchestrationCommandInvariantError({
1175 commandType: fallback.type,
1176 detail: `Unknown command type: ${fallback.type}`,
1177 });
1180});