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