Open History to see the last commit
1import type {
2 OrchestrationV2DomainEvent,
3 OrchestrationV2Run,
4 OrchestrationV2ThreadProjection,
5 OrchestrationV2TurnItem,
6} from "@t3tools/contracts";
7import {
8 createOrchestrationV2TurnItemVisibility,
9 isOrchestrationV2TurnItemVisible,
10} from "@t3tools/shared/orchestrationV2Timeline";
11
12export type ApplyOrchestrationV2ProjectionEventOptions = {
13 readonly partialTimeline?: boolean;
14 readonly latestLocalTurnOrdinal?: number | null;
15};
16
17function upsertEntity<T extends { readonly id: unknown }>(
18 items: ReadonlyArray<T>,
19 item: T,
20): ReadonlyArray<T> {
21 const index = items.findIndex((candidate) => candidate.id === item.id);
22 if (index === -1) return [...items, item];
23 const next = [...items];
24 next[index] = item;
25 return next;
26}
27
28function removeVisibleItem(
29 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
30 sourceItemId: OrchestrationV2TurnItem["id"],
31): OrchestrationV2ThreadProjection["visibleTurnItems"] {
32 const index = rows.findIndex((row) => row.sourceItemId === sourceItemId);
33 if (index === -1) return rows;
34 return renumberVisibleItems([...rows.slice(0, index), ...rows.slice(index + 1)]);
35}
36
37function renumberVisibleItems(
38 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
39): OrchestrationV2ThreadProjection["visibleTurnItems"] {
40 return rows.map((row, position) => (row.position === position ? row : { ...row, position }));
41}
42
43function shouldShowLocalTurnItem(
44 projection: OrchestrationV2ThreadProjection,
45 item: OrchestrationV2TurnItem,
46): boolean {
47 return isOrchestrationV2TurnItemVisible({
48 item,
49 runs: projection.runs,
50 attempts: projection.attempts,
51 items: projection.turnItems,
52 });
53}
54
55function activeVisibleTurnItems(
56 projection: OrchestrationV2ThreadProjection,
57): OrchestrationV2ThreadProjection["visibleTurnItems"] {
58 const rows = projection.visibleTurnItems;
59 const isVisible = createOrchestrationV2TurnItemVisibility({
60 runs: projection.runs,
61 attempts: projection.attempts,
62 items: projection.turnItems,
63 });
64 let next: Array<(typeof rows)[number]> | null = null;
65 for (let index = 0; index < rows.length; index += 1) {
66 const row = rows[index]!;
67 const keep = row.visibility !== "local" || isVisible(row.item);
68 if (!keep) {
69 next ??= rows.slice(0, index);
70 continue;
71 }
72 next?.push(row);
73 }
74 return next === null ? rows : renumberVisibleItems(next);
75}
76
77function oldestLocalTurnOrdinal(
78 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
79): number | null {
80 let oldest: number | null = null;
81 for (const row of rows) {
82 if (row.visibility !== "local") continue;
83 if (oldest === null || row.item.ordinal < oldest) {
84 oldest = row.item.ordinal;
85 }
86 }
87 return oldest;
88}
89
90const UNFINISHED_RUN_STATUSES: ReadonlySet<OrchestrationV2Run["status"]> = new Set([
91 "preparing",
92 "queued",
93 "starting",
94 "running",
95 "waiting",
96]);
97
98function shouldDropMissingPartialTurnItem(
99 projection: OrchestrationV2ThreadProjection,
100 item: OrchestrationV2TurnItem,
101 latestLocalTurnOrdinal: number | null | undefined,
102): boolean {
103 if (projection.visibleTurnItems.some((row) => row.sourceItemId === item.id)) {
104 return false;
105 }
106 if (item.runId === null) {
107 return isBelowPartialWindow(projection, item, latestLocalTurnOrdinal);
108 }
109 // A queued run keeps the ordinal it got when queued, so a steer sent later
110 // can raise the watermark past it. Items of a run that has not finished are
111 // new, not unloaded history: the first lands while the run is still queued,
112 // and a bounded window can start after the ones before it.
113 if (
114 projection.runs.some((run) => run.id === item.runId && UNFINISHED_RUN_STATUSES.has(run.status))
115 ) {
116 return false;
117 }
118 // Later items of a run already in the window can raise the watermark first.
119 if (
120 projection.visibleTurnItems.some(
121 (row) =>
122 row.visibility === "local" &&
123 row.item.runId === item.runId &&
124 row.item.ordinal <= item.ordinal,
125 )
126 ) {
127 return false;
128 }
129 return isBelowPartialWindow(projection, item, latestLocalTurnOrdinal);
130}
131
132function isBelowPartialWindow(
133 projection: OrchestrationV2ThreadProjection,
134 item: OrchestrationV2TurnItem,
135 latestLocalTurnOrdinal: number | null | undefined,
136): boolean {
137 if (
138 latestLocalTurnOrdinal !== null &&
139 latestLocalTurnOrdinal !== undefined &&
140 item.ordinal <= latestLocalTurnOrdinal
141 ) {
142 return true;
143 }
144 const oldest = oldestLocalTurnOrdinal(projection.visibleTurnItems);
145 return oldest !== null && item.ordinal < oldest;
146}
147
148function upsertVisibleTurnItem(
149 projection: OrchestrationV2ThreadProjection,
150 item: OrchestrationV2TurnItem,
151 partialTimeline: boolean,
152 latestLocalTurnOrdinal: number | null | undefined,
153): OrchestrationV2ThreadProjection["visibleTurnItems"] {
154 const rows = projection.visibleTurnItems;
155 const index = rows.findIndex((row) => row.sourceItemId === item.id);
156 const next = {
157 position: 0,
158 visibility: "local" as const,
159 sourceThreadId: item.threadId,
160 sourceItemId: item.id,
161 item,
162 };
163 const previous = index === -1 ? undefined : rows[index]!;
164 if (
165 previous !== undefined &&
166 previous.visibility === next.visibility &&
167 previous.sourceThreadId === next.sourceThreadId &&
168 previous.sourceItemId === next.sourceItemId &&
169 previous.item === item
170 ) {
171 return rows;
172 }
173 if (
174 index === -1 &&
175 partialTimeline &&
176 shouldDropMissingPartialTurnItem(projection, item, latestLocalTurnOrdinal)
177 ) {
178 return rows;
179 }
180 const updated = index === -1 ? [...rows] : [...rows.slice(0, index), ...rows.slice(index + 1)];
181 const insertionIndex = updated.findIndex(
182 (row) =>
183 row.visibility === "local" &&
184 (row.item.ordinal > item.ordinal ||
185 (row.item.ordinal === item.ordinal &&
186 String(row.item.id).localeCompare(String(item.id)) > 0)),
187 );
188 updated.splice(insertionIndex === -1 ? updated.length : insertionIndex, 0, next);
189 return renumberVisibleItems(updated);
190}
191
192/** Applies one committed event to a matching thread projection. */
193export function applyOrchestrationV2ProjectionEvent(
194 projection: OrchestrationV2ThreadProjection | null,
195 event: OrchestrationV2DomainEvent,
196 options?: ApplyOrchestrationV2ProjectionEventOptions,
197): OrchestrationV2ThreadProjection | null {
198 if (projection === null || event.threadId !== projection.thread.id) return projection;
199
200 const partialTimeline = options?.partialTimeline === true;
201 const latestLocalTurnOrdinal = options?.latestLocalTurnOrdinal;
202 const base = { ...projection, updatedAt: event.occurredAt };
203 switch (event.type) {
204 case "thread.created":
205 case "thread.archived":
206 case "thread.unarchived":
207 case "thread.deleted":
208 case "thread.settled":
209 case "thread.unsettled":
210 case "thread.snoozed":
211 case "thread.unsnoozed":
212 case "thread.auto-settle-set":
213 case "thread.pinned":
214 case "thread.unpinned":
215 case "thread.pin-reordered":
216 case "thread.active-reordered":
217 case "thread.metadata-updated":
218 case "thread.pull-request-synced":
219 case "thread.runtime-mode-updated":
220 case "thread.interaction-mode-updated":
221 case "thread.model-selection-updated":
222 case "thread.provider-switched":
223 return { ...base, thread: event.payload };
224 // Visited tracking is read state, not activity: skip the updatedAt bump.
225 case "thread.visited":
226 case "thread.marked-unread":
227 return { ...projection, thread: event.payload };
228 case "run.created":
229 case "run.updated": {
230 const next = { ...base, runs: upsertEntity(base.runs, event.payload) };
231 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
232 }
233 case "run.background-work-cancelled":
234 return {
235 ...base,
236 runs: base.runs.map((run) =>
237 run.id === event.payload.runId
238 ? {
239 ...run,
240 restartCancelledBackgroundWork: event.payload.restartCancelledBackgroundWork,
241 }
242 : run,
243 ),
244 };
245 case "run-attempt.created":
246 case "run-attempt.updated": {
247 const next = { ...base, attempts: upsertEntity(base.attempts, event.payload) };
248 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
249 }
250 case "node.updated":
251 return { ...base, nodes: upsertEntity(base.nodes, event.payload) };
252 case "subagent.updated":
253 return { ...base, subagents: upsertEntity(base.subagents, event.payload) };
254 case "provider-session.attached":
255 case "provider-session.updated":
256 return {
257 ...base,
258 providerSessions: upsertEntity(base.providerSessions, event.payload),
259 };
260 case "provider-session.detached":
261 return {
262 ...base,
263 providerSessions: base.providerSessions.filter(
264 (session) => session.id !== event.payload.providerSessionId,
265 ),
266 };
267 case "provider-thread.updated":
268 return { ...base, providerThreads: upsertEntity(base.providerThreads, event.payload) };
269 case "provider-turn.updated":
270 return {
271 ...base,
272 providerTurns: upsertEntity(base.providerTurns, {
273 ...event.payload,
274 ...((event.payload.tokenUsage ??
275 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage) ===
276 undefined
277 ? {}
278 : {
279 tokenUsage:
280 event.payload.tokenUsage ??
281 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage,
282 }),
283 }),
284 };
285 case "runtime-request.updated":
286 return { ...base, runtimeRequests: upsertEntity(base.runtimeRequests, event.payload) };
287 case "message.updated":
288 return { ...base, messages: upsertEntity(base.messages, event.payload) };
289 case "plan.updated":
290 return { ...base, plans: upsertEntity(base.plans, event.payload) };
291 case "turn-item.updated": {
292 if (
293 partialTimeline &&
294 !projection.turnItems.some((candidate) => candidate.id === event.payload.id) &&
295 shouldDropMissingPartialTurnItem(projection, event.payload, latestLocalTurnOrdinal)
296 ) {
297 return projection;
298 }
299 const next = { ...base, turnItems: upsertEntity(base.turnItems, event.payload) };
300 // Only interrupt requests can change another item's visibility. Streaming
301 // text/tool updates must not recheck every row against every run.
302 const previous = projection.turnItems.find((item) => item.id === event.payload.id);
303 const visible =
304 event.payload.type === "run_interrupt_request" || previous?.type === "run_interrupt_request"
305 ? { ...next, visibleTurnItems: activeVisibleTurnItems(next) }
306 : next;
307 return {
308 ...next,
309 visibleTurnItems: shouldShowLocalTurnItem(next, event.payload)
310 ? upsertVisibleTurnItem(visible, event.payload, partialTimeline, latestLocalTurnOrdinal)
311 : removeVisibleItem(visible.visibleTurnItems, event.payload.id),
312 };
313 }
314 case "checkpoint-scope.created":
315 return { ...base, checkpointScopes: upsertEntity(base.checkpointScopes, event.payload) };
316 case "checkpoint.captured":
317 return { ...base, checkpoints: upsertEntity(base.checkpoints, event.payload) };
318 case "checkpoint.rollback-requested":
319 return base;
320 case "context-handoff.updated":
321 return { ...base, contextHandoffs: upsertEntity(base.contextHandoffs, event.payload) };
322 case "context-transfer.created":
323 case "context-transfer.updated":
324 return { ...base, contextTransfers: upsertEntity(base.contextTransfers, event.payload) };
325 }
326}