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

orchestrationV2Projection.ts

330 lines11.5 KB

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