Open History to see the last commit
1import type {
2 OrchestrationV2ProjectedTurnItem,
3 OrchestrationV2ThreadProjection,
4 OrchestrationV2TurnItem,
5 ThreadId,
6 TurnItemId,
7} from "@t3tools/contracts";
8import { usageLimitBlockedRun } from "@t3tools/shared/orchestrationV2ThreadError";
9import * as Schema from "effect/Schema";
10
11/**
12 * Every window stops at the byte budget. A window that holds a user turn also
13 * stops at `maxUserTurns` or `maxTurnItems` rows, which keeps ordinary turns
14 * whole (V1 kept 500 activities). Any other window, such as an agent-driven
15 * thread or the inside of one very long turn, stops at `maxItems` rows.
16 */
17export const THREAD_HISTORY_PAGE_POLICY = {
18 maxUserTurns: 10,
19 maxItems: 75,
20 maxTurnItems: 500,
21 maxEncodedBytes: 1_048_576,
22} as const;
23
24export const THREAD_HISTORY_INLINE_WORK_ITEM_LIMIT = 150;
25
26export const OLDER_THREAD_USER_TURN_LIMIT = 20;
27
28export function isConversationHistoryItem(item: Pick<OrchestrationV2TurnItem, "type">): boolean {
29 return !["command_execution", "reasoning", "file_change", "dynamic_tool"].includes(item.type);
30}
31export const THREAD_HISTORY_MAX_RAW_TURNS = 150;
32
33export const THREAD_HISTORY_SNAPSHOT_ROW_LIMIT = THREAD_HISTORY_PAGE_POLICY.maxItems + 2;
34/** The snapshot query's row limit once the history has a user turn. */
35export const THREAD_HISTORY_TURN_SNAPSHOT_ROW_LIMIT = THREAD_HISTORY_PAGE_POLICY.maxTurnItems + 2;
36
37const THREAD_HISTORY_CURSOR_MAX_LENGTH = 4_096;
38
39export type ThreadHistoryPagePolicy = {
40 readonly maxUserTurns?: number | undefined;
41 readonly maxItems: number;
42 /** Defaults to `maxItems`. */
43 readonly maxTurnItems?: number | undefined;
44 readonly maxEncodedBytes: number;
45};
46
47export type ThreadHistoryCursorPayload = {
48 readonly v: 1;
49 readonly seq: number;
50 readonly st: string;
51 readonly si: string;
52 readonly p: number;
53 readonly inclusive?: boolean;
54};
55
56type HistoryRow = Pick<
57 OrchestrationV2ProjectedTurnItem,
58 "position" | "visibility" | "sourceThreadId" | "sourceItemId"
59> & {
60 readonly item: Pick<OrchestrationV2TurnItem, "type"> & {
61 readonly id?: string;
62 readonly messageId?: string;
63 readonly inputIntent?: string;
64 readonly createdBy?: string;
65 readonly runId?: string | null;
66 readonly status?: OrchestrationV2TurnItem["status"];
67 readonly parentItemId?: string | null;
68 readonly ordinal?: number;
69 readonly runStatus?: string | undefined;
70 readonly attemptId?: string | null | undefined;
71 readonly attemptStatus?: string | null | undefined;
72 readonly persistentOutput?: boolean;
73 readonly deferredWork?: OrchestrationV2TurnItem["deferredWork"];
74 };
75};
76export type SelectTimelinePageResult<Row extends HistoryRow = OrchestrationV2ProjectedTurnItem> = {
77 readonly items: ReadonlyArray<Row>;
78 readonly nextCursor: string | null;
79 readonly hasMoreHistory: boolean;
80};
81
82export type BoundedProjectionResult = {
83 readonly projection: OrchestrationV2ThreadProjection;
84 readonly historyCursor: string | null;
85 readonly hasMoreHistory: boolean;
86 readonly latestLocalTurnOrdinal: number | null;
87};
88
89export class InvalidThreadHistoryCursorError extends Schema.TaggedError<InvalidThreadHistoryCursorError>()(
90 "InvalidThreadHistoryCursorError",
91 {},
92) {
93 override get message(): string {
94 return "Invalid thread history cursor.";
95 }
96}
97
98function bytesOfJson(value: unknown): number {
99 return Buffer.byteLength(JSON.stringify(value), "utf8");
100}
101
102export function projectedRowEncodedBytes(row: HistoryRow): number {
103 return bytesOfJson(row);
104}
105
106/** Charge local items twice because bounded snapshots also include projection.turnItems; inherited rows appear only once. */
107export function projectedRowBoundedSnapshotEncodedBytes(
108 row: OrchestrationV2ProjectedTurnItem,
109 threadId: ThreadId | string,
110): number {
111 const rowBytes = projectedRowEncodedBytes(row);
112 if (row.visibility === "local" || String(row.sourceThreadId) === String(threadId)) {
113 return rowBytes + bytesOfJson(row.item);
114 }
115 return rowBytes;
116}
117
118function renumberPositions<Row extends HistoryRow>(items: ReadonlyArray<Row>): Row[] {
119 return items.map((row, position) => (row.position === position ? row : { ...row, position }));
120}
121
122function encodeCursorPayload(payload: ThreadHistoryCursorPayload): string {
123 return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
124}
125
126export function encodeThreadHistoryCursor(input: {
127 readonly snapshotSequence: number;
128 readonly sourceThreadId: ThreadId | string;
129 readonly sourceItemId: TurnItemId | string;
130 readonly position: number;
131 readonly inclusive?: boolean;
132}): string {
133 return encodeCursorPayload({
134 v: 1,
135 seq: input.snapshotSequence,
136 st: String(input.sourceThreadId),
137 si: String(input.sourceItemId),
138 p: input.position,
139 ...(input.inclusive ? { inclusive: true } : {}),
140 });
141}
142
143export function decodeThreadHistoryCursor(cursor: string): ThreadHistoryCursorPayload {
144 if (cursor.length === 0 || cursor.length > THREAD_HISTORY_CURSOR_MAX_LENGTH) {
145 throw new InvalidThreadHistoryCursorError();
146 }
147 let parsed: unknown;
148 try {
149 const json = Buffer.from(cursor, "base64url").toString("utf8");
150 parsed = JSON.parse(json) as unknown;
151 } catch {
152 throw new InvalidThreadHistoryCursorError();
153 }
154 if (
155 typeof parsed !== "object" ||
156 parsed === null ||
157 !("v" in parsed) ||
158 parsed.v !== 1 ||
159 !("seq" in parsed) ||
160 typeof parsed.seq !== "number" ||
161 !Number.isInteger(parsed.seq) ||
162 parsed.seq < 0 ||
163 !("st" in parsed) ||
164 typeof parsed.st !== "string" ||
165 parsed.st.length === 0 ||
166 !("si" in parsed) ||
167 typeof parsed.si !== "string" ||
168 parsed.si.length === 0 ||
169 !("p" in parsed) ||
170 typeof parsed.p !== "number" ||
171 !Number.isInteger(parsed.p) ||
172 parsed.p < 0 ||
173 ("inclusive" in parsed && typeof parsed.inclusive !== "boolean")
174 ) {
175 throw new InvalidThreadHistoryCursorError();
176 }
177 return parsed as ThreadHistoryCursorPayload;
178}
179
180function isThreadHistoryTurnStart(item: HistoryRow["item"]): boolean {
181 return (
182 item.type === "user_message" &&
183 (item.inputIntent === "turn_start" || item.inputIntent === "queued_turn")
184 );
185}
186
187export const DEFERRED_WORK_ITEM_TYPES = [
188 "command_execution",
189 "reasoning",
190 "file_change",
191 "file_search",
192 "web_search",
193 "dynamic_tool",
194] as const;
195
196function isDeferrableWorkItem(item: HistoryRow["item"]): boolean {
197 return (
198 item.status === "completed" &&
199 item.persistentOutput !== true &&
200 DEFERRED_WORK_ITEM_TYPES.some((type) => type === item.type)
201 );
202}
203
204export function deferWorkHistoryRows<Row extends HistoryRow>(items: ReadonlyArray<Row>): Row[] {
205 const blocked = new Set(
206 items.flatMap(({ item }) =>
207 item.runId != null &&
208 (item.type === "run_interrupt_request" ||
209 item.type === "run_interrupt_result" ||
210 (item.type === "error" && item.status === "failed" && item.parentItemId == null))
211 ? [item.runId]
212 : [],
213 ),
214 );
215 const segments = new Map<string, number>();
216 const groups = new Map<string, Row[]>();
217 for (const row of items) {
218 const item = row.item;
219 if (item.runId == null) continue;
220 if (item.type === "user_message") segments.set(item.runId, (segments.get(item.runId) ?? 0) + 1);
221 if (
222 (item.runStatus !== "completed" && item.attemptStatus !== "superseded") ||
223 blocked.has(item.runId) ||
224 !isDeferrableWorkItem(item)
225 )
226 continue;
227 const key = `${row.sourceThreadId}:${item.runId}:${segments.get(item.runId) ?? 0}:${item.attemptId ?? ""}`;
228 const group = groups.get(key) ?? [];
229 group.push(row);
230 groups.set(key, group);
231 }
232 const omitted = new Set<Row>();
233 const anchors = new Map<Row, Row>();
234 for (const group of groups.values()) {
235 if (group.length <= THREAD_HISTORY_INLINE_WORK_ITEM_LIMIT) continue;
236 const first = group[0]!;
237 const last = group.at(-1)!;
238 for (const row of group.slice(1)) omitted.add(row);
239 anchors.set(first, {
240 ...first,
241 item: {
242 ...first.item,
243 deferredWork: {
244 cursor: encodeThreadHistoryCursor({
245 snapshotSequence: 0,
246 sourceThreadId: last.sourceThreadId,
247 sourceItemId: last.sourceItemId,
248 position: last.item.ordinal ?? last.position,
249 inclusive: true,
250 }),
251 itemCount: group.length,
252 lastOrdinal: last.item.ordinal ?? last.position,
253 },
254 },
255 });
256 }
257 return items.flatMap((row) => (omitted.has(row) ? [] : [anchors.get(row) ?? row]));
258}
259
260export function selectDeferredWorkPage<Row extends HistoryRow>(input: {
261 readonly items: ReadonlyArray<Row>;
262 readonly cursor: string;
263 readonly throughEntryId?: string | undefined;
264 readonly snapshotSequence: number;
265 readonly rowEncodedBytes?: ((row: Row) => number) | undefined;
266}): SelectTimelinePageResult<Row> {
267 const cursor = decodeThreadHistoryCursor(input.cursor);
268 const end = findCursorEndIndex(input.items, cursor);
269 const start = input.items.findIndex((row) => row.sourceItemId === input.throughEntryId);
270 if (start < 0 || start >= end) throw new InvalidThreadHistoryCursorError();
271 const anchor = input.items[start]!;
272 const items = input.items
273 .slice(start, end)
274 .filter(
275 (row) =>
276 row.sourceThreadId === anchor.sourceThreadId &&
277 row.item.runId === anchor.item.runId &&
278 row.item.attemptId === anchor.item.attemptId &&
279 isDeferrableWorkItem(row.item),
280 );
281 return selectOlderTimelinePage({
282 items,
283 exclusiveEndIndex: items.length,
284 snapshotSequence: input.snapshotSequence,
285 rowEncodedBytes: input.rowEncodedBytes,
286 policy: THREAD_HISTORY_PAGE_POLICY,
287 });
288}
289
290/** Notifications can start wake turns when they are the run's first input; match ProjectionStore run_starts. */
291function threadHistoryTurnStarts(items: ReadonlyArray<HistoryRow["item"]>): ReadonlyArray<boolean> {
292 const startedRuns = new Set<string>();
293 return items.map((item) => {
294 if (item.type !== "user_message" && item.type !== "notification") return false;
295 const firstInput = item.runId != null && !startedRuns.has(item.runId);
296 if (item.runId != null) startedRuns.add(item.runId);
297 return item.type === "notification" ? firstInput : isThreadHistoryTurnStart(item);
298 });
299}
300
301export function isThreadHistoryUserTurn(item: HistoryRow["item"]): boolean {
302 return (
303 isThreadHistoryTurnStart(item) && item.type === "user_message" && item.createdBy === "user"
304 );
305}
306
307/**
308 * Always admit at least one row so oversized items cannot deadlock paging.
309 */
310function selectOlderTimelinePage<Row extends HistoryRow>(input: {
311 readonly items: ReadonlyArray<Row>;
312 readonly exclusiveEndIndex: number;
313 readonly snapshotSequence: number;
314 readonly policy?: ThreadHistoryPagePolicy | undefined;
315 readonly rowEncodedBytes?: ((row: Row) => number) | undefined;
316}): SelectTimelinePageResult<Row> {
317 const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;
318 const rowCost = input.rowEncodedBytes ?? projectedRowEncodedBytes;
319 const end = Math.min(Math.max(input.exclusiveEndIndex, 0), input.items.length);
320 if (end <= 0) {
321 return { items: [], nextCursor: null, hasMoreHistory: false };
322 }
323
324 const selected: Row[] = [];
325 let encodedBytes = 0;
326 let userTurns = 0;
327 let rawTurns = 0;
328 const candidates = input.items.slice(0, end);
329 const turnStarts = threadHistoryTurnStarts(candidates.map((row) => row.item));
330 const turnLimit = candidates.some((row) => isThreadHistoryUserTurn(row.item))
331 ? policy.maxUserTurns
332 : undefined;
333 const maxItems =
334 turnLimit === undefined ? policy.maxItems : (policy.maxTurnItems ?? policy.maxItems);
335 for (let index = end - 1; index >= 0; index -= 1) {
336 const row = input.items[index]!;
337 if (
338 selected.length > 0 &&
339 (selected.length >= maxItems ||
340 (turnLimit !== undefined &&
341 (userTurns >= turnLimit || rawTurns >= THREAD_HISTORY_MAX_RAW_TURNS)))
342 ) {
343 break;
344 }
345 const rowBytes = rowCost(row);
346 if (selected.length > 0 && encodedBytes + rowBytes > policy.maxEncodedBytes) break;
347 selected.push(row);
348 encodedBytes += rowBytes;
349 if (isThreadHistoryUserTurn(row.item)) userTurns += 1;
350 if (turnStarts[index]) rawTurns += 1;
351 }
352 // Inside a turn longer than the window, no selected row starts a user turn.
353 // Later pages and the snapshot query see only such rows and use `maxItems`,
354 // so this page uses it too.
355 if (userTurns === 0) selected.splice(policy.maxItems);
356 selected.reverse();
357
358 const oldest = selected[0];
359 const oldestIndex = oldest
360 ? input.items.findIndex(
361 (row) =>
362 row.sourceThreadId === oldest.sourceThreadId && row.sourceItemId === oldest.sourceItemId,
363 )
364 : -1;
365 const hasMoreHistory = oldestIndex > 0;
366 const nextCursor =
367 hasMoreHistory && oldest
368 ? encodeThreadHistoryCursor({
369 snapshotSequence: input.snapshotSequence,
370 sourceThreadId: oldest.sourceThreadId,
371 sourceItemId: oldest.sourceItemId,
372 position: oldest.position,
373 })
374 : null;
375
376 return {
377 items: renumberPositions(selected),
378 nextCursor,
379 hasMoreHistory,
380 };
381}
382
383export function selectRecentTimelineWindow(input: {
384 readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
385 readonly snapshotSequence: number;
386 readonly policy?: ThreadHistoryPagePolicy | undefined;
387 readonly rowEncodedBytes?: ((row: OrchestrationV2ProjectedTurnItem) => number) | undefined;
388}): SelectTimelinePageResult {
389 return selectOlderTimelinePage({
390 items: input.items,
391 exclusiveEndIndex: input.items.length,
392 snapshotSequence: input.snapshotSequence,
393 ...(input.policy === undefined ? {} : { policy: input.policy }),
394 ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }),
395 });
396}
397
398function findCursorEndIndex(
399 items: ReadonlyArray<HistoryRow>,
400 cursor: ThreadHistoryCursorPayload,
401): number {
402 const byIdentity = items.findIndex(
403 (row) => String(row.sourceThreadId) === cursor.st && String(row.sourceItemId) === cursor.si,
404 );
405 if (byIdentity !== -1) {
406 return byIdentity + (cursor.inclusive ? 1 : 0);
407 }
408 // Inclusive deferred cursors carry source ordinals; ordinary cursors carry visible positions.
409 const byPosition = items.findIndex((row) =>
410 cursor.inclusive
411 ? String(row.sourceThreadId) === cursor.st && (row.item.ordinal ?? row.position) > cursor.p
412 : row.position >= cursor.p,
413 );
414 return byPosition === -1 ? items.length : byPosition;
415}
416
417/**
418 * Older pages allow twice the turns, and a targeted page widens further so it
419 * reaches `throughEntryId`. Callers that re-bound a page must reuse this policy
420 * or they drop the target again.
421 */
422export function olderHistoryPagePolicy<Row extends HistoryRow>(input: {
423 readonly items: ReadonlyArray<Row>;
424 readonly cursor: string;
425 readonly policy?: ThreadHistoryPagePolicy | undefined;
426 readonly throughEntryId?: string | undefined;
427}): ThreadHistoryPagePolicy {
428 const policy = input.policy ?? {
429 ...THREAD_HISTORY_PAGE_POLICY,
430 maxUserTurns: OLDER_THREAD_USER_TURN_LIMIT,
431 };
432 if (input.throughEntryId === undefined) return policy;
433 const anchorIndex = findCursorEndIndex(input.items, decodeThreadHistoryCursor(input.cursor));
434 const targetIndex = input.items.findIndex(
435 (row) => (row.item.messageId ?? row.item.id) === input.throughEntryId,
436 );
437 if (targetIndex < 0 || targetIndex >= anchorIndex) return policy;
438 const turns = input.items
439 .slice(targetIndex, anchorIndex)
440 .filter((row) => isThreadHistoryUserTurn(row.item)).length;
441 return {
442 ...policy,
443 maxUserTurns: Math.min(
444 OLDER_THREAD_USER_TURN_LIMIT * 2,
445 Math.max(
446 OLDER_THREAD_USER_TURN_LIMIT,
447 turns + (isThreadHistoryUserTurn(input.items[targetIndex]!.item) ? 0 : 1),
448 ),
449 ),
450 maxItems: policy.maxItems * 2,
451 maxTurnItems: (policy.maxTurnItems ?? policy.maxItems) * 2,
452 };
453}
454
455export function selectHistoryPageFromCursor<Row extends HistoryRow>(input: {
456 readonly items: ReadonlyArray<Row>;
457 readonly cursor: string;
458 readonly snapshotSequence: number;
459 readonly policy?: ThreadHistoryPagePolicy | undefined;
460 readonly rowEncodedBytes?: ((row: Row) => number) | undefined;
461 readonly throughEntryId?: string | undefined;
462}): SelectTimelinePageResult<Row> {
463 const decoded = decodeThreadHistoryCursor(input.cursor);
464 return selectOlderTimelinePage({
465 items: input.items,
466 exclusiveEndIndex: findCursorEndIndex(input.items, decoded),
467 snapshotSequence: input.snapshotSequence,
468 ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }),
469 policy: olderHistoryPagePolicy(input),
470 });
471}
472
473/**
474 * Row and byte budgets can split a turn between an interrupt result and its
475 * older request. Clients read a superseded result without a request as a
476 * legacy steer and hide it, so a page carries the requests its results need.
477 */
478export function missingInterruptRequests<Row extends HistoryRow>(
479 items: ReadonlyArray<Row>,
480 page: ReadonlyArray<Pick<HistoryRow, "item" | "sourceThreadId" | "sourceItemId" | "position">>,
481): Row[] {
482 const runs = new Set<string>();
483 for (const row of page) {
484 if (row.item.type === "run_interrupt_result" && row.item.runId != null)
485 runs.add(row.item.runId);
486 }
487 for (const row of page) {
488 if (row.item.type === "run_interrupt_request" && row.item.runId != null)
489 runs.delete(row.item.runId);
490 }
491 if (runs.size === 0) return [];
492 return items.filter(
493 (row) =>
494 row.item.type === "run_interrupt_request" &&
495 row.item.runId != null &&
496 runs.has(row.item.runId),
497 );
498}
499
500function isLocalProjectedRow(
501 projection: OrchestrationV2ThreadProjection,
502 row: OrchestrationV2ProjectedTurnItem,
503): boolean {
504 return row.visibility === "local" || String(row.sourceThreadId) === String(projection.thread.id);
505}
506
507function pendingRequestIdsOf(
508 projection: Pick<OrchestrationV2ThreadProjection, "runtimeRequests">,
509): ReadonlySet<string> {
510 return new Set(
511 projection.runtimeRequests
512 .filter((request) => request.status === "pending")
513 .map((request) => String(request.id)),
514 );
515}
516
517// Clients build the answer panel of an open question or approval from its row,
518// and a run that kept working pushes that row out of the newest turns.
519function isRetainedDependency(
520 item: OrchestrationV2TurnItem,
521 pendingRequestIds: ReadonlySet<string>,
522): boolean {
523 return (
524 item.type === "run_interrupt_request" ||
525 ((item.type === "user_input_request" || item.type === "approval_request") &&
526 pendingRequestIds.has(String(item.requestId)))
527 );
528}
529
530// usageLimitBlockedRun needs the limited run's root error and the notification that started each
531// later run, and a long chain of wakes pushes both out of the window. Starts are kept as stubs
532// without their unbounded detail, and dropped past a quarter of the budget (clients then show
533// the plain latest run).
534function limitRecoveryItems(
535 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,
536 maxEncodedBytes: number,
537): ReadonlyMap<string, OrchestrationV2TurnItem> {
538 const items = new Map<string, OrchestrationV2TurnItem>();
539 const blocked = usageLimitBlockedRun(projection.runs, projection.turnItems, null);
540 if (blocked === null) return items;
541 const laterRoots = new Set<string>();
542 for (const run of projection.runs) {
543 if (run.ordinal > blocked.ordinal && run.rootNodeId !== null) {
544 laterRoots.add(String(run.rootNodeId));
545 }
546 }
547 if (laterRoots.size === 0) return items;
548 const firstInputs = new Map<string, OrchestrationV2TurnItem>();
549 for (const item of projection.turnItems) {
550 if (item.type === "error" && item.runId === blocked.id && item.nodeId === blocked.rootNodeId) {
551 items.set(String(item.id), item);
552 } else if (
553 (item.type === "user_message" || item.type === "notification") &&
554 item.nodeId !== null &&
555 laterRoots.has(String(item.nodeId))
556 ) {
557 const first = firstInputs.get(String(item.nodeId));
558 if (first === undefined || item.ordinal < first.ordinal) {
559 firstInputs.set(String(item.nodeId), item);
560 }
561 }
562 }
563 let startBytes = 0;
564 const starts: Array<OrchestrationV2TurnItem> = [];
565 for (const item of firstInputs.values()) {
566 if (item.type !== "notification") continue;
567 const { detail: _detail, ...rest } = item;
568 const stub = { ...rest, title: null, summary: item.summary.slice(0, 120).trimEnd() };
569 startBytes += bytesOfJson(stub);
570 starts.push(stub);
571 }
572 if (startBytes <= maxEncodedBytes / 4) {
573 for (const stub of starts) items.set(String(stub.id), stub);
574 }
575 return items;
576}
577
578/** Retain small requests outside the visible window; later result pages still need them for attempt/run reducers. */
579function retainedInterruptRequestTurnItems(
580 projection: OrchestrationV2ThreadProjection,
581 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
582 limitItems: ReadonlyMap<string, OrchestrationV2TurnItem>,
583): OrchestrationV2TurnItem[] {
584 const visibleLocalIds = new Set<string>();
585 for (const row of visible) {
586 if (isLocalProjectedRow(projection, row)) {
587 visibleLocalIds.add(String(row.sourceItemId));
588 }
589 }
590
591 const pendingRequestIds = pendingRequestIdsOf(projection);
592 const retained: OrchestrationV2TurnItem[] = [];
593 for (const item of projection.turnItems) {
594 if (!isRetainedDependency(item, pendingRequestIds)) {
595 continue;
596 }
597 if (visibleLocalIds.has(String(item.id))) {
598 continue;
599 }
600 retained.push(item);
601 }
602 for (const [id, item] of limitItems) {
603 if (!visibleLocalIds.has(id)) retained.push(item);
604 }
605 return retained;
606}
607
608function localTurnItemsForVisibleWindow(
609 projection: OrchestrationV2ThreadProjection,
610 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
611): OrchestrationV2TurnItem[] {
612 return visible.filter((row) => isLocalProjectedRow(projection, row)).map((row) => row.item);
613}
614
615function messagesForBoundedProjection(
616 projection: OrchestrationV2ThreadProjection,
617 turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
618): OrchestrationV2ThreadProjection["messages"] {
619 const retainedMessageIds = new Set<string>();
620 for (const item of turnItems) {
621 if ("messageId" in item) {
622 retainedMessageIds.add(String(item.messageId));
623 }
624 }
625
626 const latestRun = projection.runs.reduce<(typeof projection.runs)[number] | null>(
627 (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest),
628 null,
629 );
630 const retainedRunIds = new Set<string>();
631 for (const run of projection.runs) {
632 if (
633 run.id === latestRun?.id ||
634 run.status === "preparing" ||
635 run.status === "starting" ||
636 run.status === "running" ||
637 run.status === "waiting" ||
638 run.status === "queued"
639 ) {
640 retainedRunIds.add(String(run.id));
641 retainedMessageIds.add(String(run.userMessageId));
642 }
643 }
644
645 return projection.messages.filter(
646 (message) =>
647 retainedMessageIds.has(String(message.id)) ||
648 (message.runId !== null && retainedRunIds.has(String(message.runId))) ||
649 message.delegatedCompletion !== undefined ||
650 // Keep the workflow script outside the history window; clients use it to open the coordinator thread.
651 message.workflowScript === true,
652 );
653}
654
655/** Watermark prevents old missing updates from appending newest when bounded windows lack local rows. */
656export function computeLatestLocalTurnOrdinal(
657 turnItems: ReadonlyArray<{ readonly ordinal: number }>,
658): number | null {
659 let latest: number | null = null;
660 for (const item of turnItems) {
661 if (latest === null || item.ordinal > latest) {
662 latest = item.ordinal;
663 }
664 }
665 return latest;
666}
667
668export function boundedTimelineEncodedBytes(input: {
669 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
670 readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
671}): number {
672 let total = 0;
673 for (const row of input.visibleTurnItems) {
674 total += projectedRowEncodedBytes(row);
675 }
676 for (const item of input.turnItems) {
677 total += bytesOfJson(item);
678 }
679 return total;
680}
681
682export function buildBoundedThreadProjection(input: {
683 readonly projection: OrchestrationV2ThreadProjection;
684 readonly snapshotSequence: number;
685 readonly policy?: ThreadHistoryPagePolicy | undefined;
686}): BoundedProjectionResult {
687 const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;
688 const threadId = input.projection.thread.id;
689 const runOrdinals = new Map(input.projection.runs.map((run) => [run.id, run.ordinal]));
690 let latestTodoList: (typeof input.projection.plans)[number] | undefined;
691 let latestTodoListOrdinal = -1;
692 for (const plan of input.projection.plans) {
693 const ordinal = plan.runId === null ? undefined : runOrdinals.get(plan.runId);
694 if (
695 plan.kind === "todo_list" &&
696 plan.status !== "superseded" &&
697 ordinal !== undefined &&
698 ordinal >= latestTodoListOrdinal
699 ) {
700 latestTodoList = plan;
701 latestTodoListOrdinal = ordinal;
702 }
703 }
704 const controlProjection = {
705 ...input.projection,
706 plans: input.projection.plans.filter(
707 (plan) => plan.status === "active" || plan.id === latestTodoList?.id,
708 ),
709 contextHandoffs: input.projection.contextHandoffs.filter(
710 (handoff) => handoff.status === "pending" || handoff.status === "ready",
711 ),
712 };
713 const latestLocalTurnOrdinal = computeLatestLocalTurnOrdinal(input.projection.turnItems);
714
715 const limitItems = limitRecoveryItems(controlProjection, policy.maxEncodedBytes);
716 const dependencyReserve = (() => {
717 let reserve = 0;
718 const pendingRequestIds = pendingRequestIdsOf(controlProjection);
719 for (const item of controlProjection.turnItems) {
720 if (isRetainedDependency(item, pendingRequestIds)) {
721 reserve += bytesOfJson(item);
722 }
723 }
724 for (const item of limitItems.values()) reserve += bytesOfJson(item);
725 return reserve;
726 })();
727 const controlBytes = bytesOfJson({
728 ...controlProjection,
729 messages: [],
730 turnItems: [],
731 visibleTurnItems: [],
732 });
733 // Control state cannot be paged, so the window keeps half the budget; dependency cards take their reserve from that half.
734 const windowBudget = Math.max(
735 Math.max(policy.maxEncodedBytes / 2 - dependencyReserve, 0),
736 policy.maxEncodedBytes - dependencyReserve - controlBytes - 1_024,
737 );
738 const windowPolicy: ThreadHistoryPagePolicy = { ...policy, maxEncodedBytes: windowBudget };
739
740 const window = selectRecentTimelineWindow({
741 items: controlProjection.visibleTurnItems,
742 snapshotSequence: input.snapshotSequence,
743 policy: windowPolicy,
744 rowEncodedBytes: (row) => projectedRowBoundedSnapshotEncodedBytes(row, threadId),
745 });
746 const visibleTurnItems = renumberPositions(window.items);
747 const windowTurnItems = localTurnItemsForVisibleWindow(controlProjection, visibleTurnItems);
748 const dependencyTurnItems = retainedInterruptRequestTurnItems(
749 controlProjection,
750 visibleTurnItems,
751 limitItems,
752 );
753 const turnItemById = new Map<string, OrchestrationV2TurnItem>();
754 for (const item of windowTurnItems) {
755 turnItemById.set(String(item.id), item);
756 }
757 for (const item of dependencyTurnItems) {
758 turnItemById.set(String(item.id), item);
759 }
760 const turnItems = [...turnItemById.values()];
761
762 const visiblePlanIds = new Set(
763 turnItems.flatMap((item) =>
764 item.type === "proposed_plan" || item.type === "todo_list" ? [String(item.planId)] : [],
765 ),
766 );
767 const visibleHandoffIds = new Set(
768 turnItems.flatMap((item) => (item.type === "handoff" ? [String(item.contextHandoffId)] : [])),
769 );
770 const plans = input.projection.plans
771 .filter(
772 (plan) =>
773 plan.status === "active" ||
774 plan.id === latestTodoList?.id ||
775 visiblePlanIds.has(String(plan.id)),
776 )
777 .map((plan) =>
778 plan.status === "active" || plan.id === latestTodoList?.id
779 ? plan
780 : plan.kind === "proposed_plan"
781 ? { ...plan, markdown: "", detailInTurnItem: true as const }
782 : { ...plan, explanation: undefined, detailInTurnItem: true as const },
783 );
784 const contextHandoffs = input.projection.contextHandoffs
785 .filter(
786 (handoff) =>
787 handoff.status === "pending" ||
788 handoff.status === "ready" ||
789 visibleHandoffIds.has(String(handoff.id)),
790 )
791 .map((handoff) =>
792 handoff.status === "pending" || handoff.status === "ready"
793 ? handoff
794 : { ...handoff, summaryText: "", detailInTurnItem: true as const },
795 );
796
797 const projection = {
798 ...controlProjection,
799 plans,
800 contextHandoffs,
801 messages: messagesForBoundedProjection(controlProjection, turnItems),
802 turnItems,
803 visibleTurnItems,
804 };
805 return {
806 projection,
807 historyCursor: window.nextCursor,
808 hasMoreHistory: window.hasMoreHistory,
809 latestLocalTurnOrdinal,
810 };
811}