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

threadHistoryPaging.ts

729 lines24.9 KB

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