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

orchestrationV2Projection.ts

391 lines13.5 KB

1import { applyThreadPullRequestLinkUpdate } from "../threadPullRequests.ts";
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​
18// Only this exact pair differs at one index. Both keys are weak so hints
19// neither retain streaming history nor apply to replacement snapshots.
20const arrayReplacements = new WeakMap<
21 ReadonlyArray<unknown>,
22 WeakMap<ReadonlyArray<unknown>, number>
23>();
24​
25export function getProjectionArrayReplacementIndex(
26 previous: ReadonlyArray<unknown>,
27 next: ReadonlyArray<unknown>,
28): number | undefined {
29 return arrayReplacements.get(previous)?.get(next);
31​
32function replaceProjectionArrayItem<T>(
33 items: ReadonlyArray<T>,
34 index: number,
35 item: T,
36): ReadonlyArray<T> {
37 const next = items.slice();
38 next[index] = item;
39 let replacements = arrayReplacements.get(items);
40 if (replacements === undefined) {
41 replacements = new WeakMap();
42 arrayReplacements.set(items, replacements);
43 }
44 replacements.set(next, index);
45 return next;
47​
48function upsertEntity<T extends { readonly id: unknown }>(
49 items: ReadonlyArray<T>,
50 item: T,
51): ReadonlyArray<T> {
52 const index = items.findIndex((candidate) => candidate.id === item.id);
53 if (index === -1) return [...items, item];
54 const next = [...items];
55 next[index] = item;
56 return next;
58​
59function removeVisibleItem(
60 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
61 sourceItemId: OrchestrationV2TurnItem["id"],
62): OrchestrationV2ThreadProjection["visibleTurnItems"] {
63 const index = rows.findIndex((row) => row.sourceItemId === sourceItemId);
64 if (index === -1) return rows;
65 return renumberVisibleItems([...rows.slice(0, index), ...rows.slice(index + 1)]);
67​
68function renumberVisibleItems(
69 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
70): OrchestrationV2ThreadProjection["visibleTurnItems"] {
71 return rows.map((row, position) => (row.position === position ? row : { ...row, position }));
73​
74function shouldShowLocalTurnItem(
75 projection: OrchestrationV2ThreadProjection,
76 item: OrchestrationV2TurnItem,
77): boolean {
78 return isOrchestrationV2TurnItemVisible({
79 item,
80 runs: projection.runs,
81 attempts: projection.attempts,
82 items: projection.turnItems,
83 });
85​
86function activeVisibleTurnItems(
87 projection: OrchestrationV2ThreadProjection,
88): OrchestrationV2ThreadProjection["visibleTurnItems"] {
89 const rows = projection.visibleTurnItems;
90 const isVisible = createOrchestrationV2TurnItemVisibility({
91 runs: projection.runs,
92 attempts: projection.attempts,
93 items: projection.turnItems,
94 });
95 let next: Array<(typeof rows)[number]> | null = null;
96 for (let index = 0; index < rows.length; index += 1) {
97 const row = rows[index]!;
98 const keep = row.visibility !== "local" || isVisible(row.item);
99 if (!keep) {
100 next ??= rows.slice(0, index);
101 continue;
102 }
103 next?.push(row);
104 }
105 return next === null ? rows : renumberVisibleItems(next);
107​
108function oldestLocalTurnOrdinal(
109 rows: OrchestrationV2ThreadProjection["visibleTurnItems"],
110): number | null {
111 let oldest: number | null = null;
112 for (const row of rows) {
113 if (row.visibility !== "local") continue;
114 if (oldest === null || row.item.ordinal < oldest) {
115 oldest = row.item.ordinal;
116 }
117 }
118 return oldest;
120​
121const UNFINISHED_RUN_STATUSES: ReadonlySet<OrchestrationV2Run["status"]> = new Set([
122 "preparing",
123 "queued",
124 "starting",
125 "running",
126 "waiting",
127]);
128​
129function shouldDropMissingPartialTurnItem(
130 projection: OrchestrationV2ThreadProjection,
131 item: OrchestrationV2TurnItem,
132 latestLocalTurnOrdinal: number | null | undefined,
133): boolean {
134 if (projection.visibleTurnItems.some((row) => row.sourceItemId === item.id)) {
135 return false;
136 }
137 if (item.runId === null) {
138 return isBelowPartialWindow(projection, item, latestLocalTurnOrdinal);
139 }
140 // A queued run keeps the ordinal it got when queued, so a steer sent later
141 // can raise the watermark past it. Items of a run that has not finished are
142 // new, not unloaded history: the first lands while the run is still queued,
143 // and a bounded window can start after the ones before it.
144 if (
145 projection.runs.some((run) => run.id === item.runId && UNFINISHED_RUN_STATUSES.has(run.status))
146 ) {
147 return false;
148 }
149 if (
150 projection.visibleTurnItems.some(
151 (row) =>
152 row.visibility === "local" &&
153 row.item.runId === item.runId &&
154 row.item.ordinal <= item.ordinal,
155 )
156 ) {
157 return false;
158 }
159 return isBelowPartialWindow(projection, item, latestLocalTurnOrdinal);
161​
162function isBelowPartialWindow(
163 projection: OrchestrationV2ThreadProjection,
164 item: OrchestrationV2TurnItem,
165 latestLocalTurnOrdinal: number | null | undefined,
166): boolean {
167 if (
168 latestLocalTurnOrdinal !== null &&
169 latestLocalTurnOrdinal !== undefined &&
170 item.ordinal <= latestLocalTurnOrdinal
171 ) {
172 return true;
173 }
174 const oldest = oldestLocalTurnOrdinal(projection.visibleTurnItems);
175 return oldest !== null && item.ordinal < oldest;
177​
178function upsertVisibleTurnItem(
179 projection: OrchestrationV2ThreadProjection,
180 item: OrchestrationV2TurnItem,
181 partialTimeline: boolean,
182 latestLocalTurnOrdinal: number | null | undefined,
183): OrchestrationV2ThreadProjection["visibleTurnItems"] {
184 const rows = projection.visibleTurnItems;
185 // Streamed updates land on the newest rows. Item ids are unique, so the
186 // search can start there.
187 let index = rows.length - 1;
188 while (index >= 0 && rows[index]!.sourceItemId !== item.id) index -= 1;
189 const next = {
190 position: 0,
191 visibility: "local" as const,
192 sourceThreadId: item.threadId,
193 sourceItemId: item.id,
194 item,
195 };
196 const previous = index === -1 ? undefined : rows[index]!;
197 if (
198 previous !== undefined &&
199 previous.visibility === next.visibility &&
200 previous.sourceThreadId === next.sourceThreadId
201 ) {
202 if (previous.item === item) return rows;
203 if (previous.item.ordinal === item.ordinal) {
204 return replaceProjectionArrayItem(rows, index, { ...next, position: previous.position });
205 }
206 }
207 if (
208 index === -1 &&
209 partialTimeline &&
210 shouldDropMissingPartialTurnItem(projection, item, latestLocalTurnOrdinal)
211 ) {
212 return rows;
213 }
214 // The item goes before the first later local row, as if its old row were
215 // removed first. Inserts, reorders, and inherited-to-local changes need
216 // this ordering pass; replacements above preserve every other row.
217 let insertion = rows.length;
218 for (let candidate = 0; candidate < rows.length; candidate += 1) {
219 const row = rows[candidate]!;
220 if (
221 candidate !== index &&
222 row.visibility === "local" &&
223 (row.item.ordinal > item.ordinal ||
224 (row.item.ordinal === item.ordinal &&
225 String(row.item.id).localeCompare(String(item.id)) > 0))
226 ) {
227 insertion = candidate;
228 break;
229 }
230 }
231 const updated: Array<(typeof rows)[number]> = [];
232 for (let source = 0; source < rows.length; source += 1) {
233 if (source === insertion) updated.push(next);
234 if (source !== index) updated.push(rows[source]!);
235 }
236 if (insertion === rows.length) updated.push(next);
237 for (let position = 0; position < updated.length; position += 1) {
238 const row = updated[position]!;
239 if (row.position !== position) updated[position] = { ...row, position };
240 }
241 return updated;
243​
244export function applyOrchestrationV2ProjectionEvent(
245 projection: OrchestrationV2ThreadProjection | null,
246 event: OrchestrationV2DomainEvent,
247 options?: ApplyOrchestrationV2ProjectionEventOptions,
248): OrchestrationV2ThreadProjection | null {
249 if (projection === null || event.threadId !== projection.thread.id) return projection;
250​
251 const partialTimeline = options?.partialTimeline === true;
252 const latestLocalTurnOrdinal = options?.latestLocalTurnOrdinal;
253 const base = { ...projection, updatedAt: event.occurredAt };
254 switch (event.type) {
255 case "thread.pull-request-link-updated":
256 return {
257 ...base,
258 thread: applyThreadPullRequestLinkUpdate(projection.thread, event.payload),
259 };
260 case "thread.created":
261 case "thread.archived":
262 case "thread.unarchived":
263 case "thread.deleted":
264 case "thread.settled":
265 case "thread.unsettled":
266 case "thread.snoozed":
267 case "thread.unsnoozed":
268 case "thread.auto-settle-set":
269 case "thread.pinned":
270 case "thread.unpinned":
271 case "thread.pin-reordered":
272 case "thread.active-reordered":
273 case "thread.metadata-updated":
274 case "thread.pull-request-synced":
275 case "thread.runtime-mode-updated":
276 case "thread.interaction-mode-updated":
277 case "thread.model-selection-updated":
278 case "thread.provider-switched":
279 return { ...base, thread: event.payload };
280 // Visited tracking is read state, not activity: skip the updatedAt bump.
281 case "thread.visited":
282 case "thread.marked-unread":
283 return { ...projection, thread: event.payload };
284 case "run.created":
285 case "run.updated": {
286 const next = { ...base, runs: upsertEntity(base.runs, event.payload) };
287 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
288 }
289 case "run.background-work-cancelled":
290 return {
291 ...base,
292 runs: base.runs.map((run) =>
293 run.id === event.payload.runId
294 ? {
295 ...run,
296 restartCancelledBackgroundWork: event.payload.restartCancelledBackgroundWork,
297 }
298 : run,
299 ),
300 };
301 case "run-attempt.created":
302 case "run-attempt.updated": {
303 const next = { ...base, attempts: upsertEntity(base.attempts, event.payload) };
304 return { ...next, visibleTurnItems: activeVisibleTurnItems(next) };
305 }
306 case "node.updated":
307 return { ...base, nodes: upsertEntity(base.nodes, event.payload) };
308 case "subagent.updated":
309 return { ...base, subagents: upsertEntity(base.subagents, event.payload) };
310 case "provider-session.attached":
311 case "provider-session.updated":
312 return {
313 ...base,
314 providerSessions: upsertEntity(base.providerSessions, event.payload),
315 };
316 case "provider-session.detached":
317 return {
318 ...base,
319 providerSessions: base.providerSessions.filter(
320 (session) => session.id !== event.payload.providerSessionId,
321 ),
322 };
323 case "provider-thread.updated":
324 return { ...base, providerThreads: upsertEntity(base.providerThreads, event.payload) };
325 case "provider-turn.updated":
326 return {
327 ...base,
328 providerTurns: upsertEntity(base.providerTurns, {
329 ...event.payload,
330 ...((event.payload.tokenUsage ??
331 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage) ===
332 undefined
333 ? {}
334 : {
335 tokenUsage:
336 event.payload.tokenUsage ??
337 base.providerTurns.find((turn) => turn.id === event.payload.id)?.tokenUsage,
338 }),
339 }),
340 };
341 case "runtime-request.updated":
342 return { ...base, runtimeRequests: upsertEntity(base.runtimeRequests, event.payload) };
343 case "message.updated":
344 return { ...base, messages: upsertEntity(base.messages, event.payload) };
345 case "plan.updated":
346 return { ...base, plans: upsertEntity(base.plans, event.payload) };
347 case "turn-item.updated": {
348 // Streamed updates land on the newest items, so search from the end.
349 let itemIndex = projection.turnItems.length - 1;
350 while (itemIndex >= 0 && projection.turnItems[itemIndex]!.id !== event.payload.id) {
351 itemIndex -= 1;
352 }
353 if (
354 partialTimeline &&
355 itemIndex === -1 &&
356 shouldDropMissingPartialTurnItem(projection, event.payload, latestLocalTurnOrdinal)
357 ) {
358 return projection;
359 }
360 const turnItems =
361 itemIndex === -1
362 ? [...projection.turnItems, event.payload]
363 : replaceProjectionArrayItem(projection.turnItems, itemIndex, event.payload);
364 const next = { ...base, turnItems };
365 // Only interrupt requests can change another item's visibility. Streaming
366 // text/tool updates must not recheck every row against every run.
367 const previous = itemIndex === -1 ? undefined : projection.turnItems[itemIndex];
368 const visible =
369 event.payload.type === "run_interrupt_request" || previous?.type === "run_interrupt_request"
370 ? { ...next, visibleTurnItems: activeVisibleTurnItems(next) }
371 : next;
372 return {
373 ...next,
374 visibleTurnItems: shouldShowLocalTurnItem(next, event.payload)
375 ? upsertVisibleTurnItem(visible, event.payload, partialTimeline, latestLocalTurnOrdinal)
376 : removeVisibleItem(visible.visibleTurnItems, event.payload.id),
377 };
378 }
379 case "checkpoint-scope.created":
380 return { ...base, checkpointScopes: upsertEntity(base.checkpointScopes, event.payload) };
381 case "checkpoint.captured":
382 return { ...base, checkpoints: upsertEntity(base.checkpoints, event.payload) };
383 case "checkpoint.rollback-requested":
384 return base;
385 case "context-handoff.updated":
386 return { ...base, contextHandoffs: upsertEntity(base.contextHandoffs, event.payload) };
387 case "context-transfer.created":
388 case "context-transfer.updated":
389 return { ...base, contextTransfers: upsertEntity(base.contextTransfers, event.payload) };
390 }