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

orchestrationV2Projection.ts

456 lines16.0 KB

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