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

orchestrationV2Projection.ts

286 lines10.1 KB

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