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

threadHistoryPaging.ts

754 lines25.8 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​
504function pendingRequestIdsOf(
505 projection: Pick<OrchestrationV2ThreadProjection, "runtimeRequests">,
506): ReadonlySet<string> {
507 return new Set(
508 projection.runtimeRequests
509 .filter((request) => request.status === "pending")
510 .map((request) => String(request.id)),
511 );
513​
514// Clients build the answer panel of an open question or approval from its row,
515// and a run that kept working pushes that row out of the newest turns.
516function isRetainedDependency(
517 item: OrchestrationV2TurnItem,
518 pendingRequestIds: ReadonlySet<string>,
519): boolean {
520 return (
521 item.type === "run_interrupt_request" ||
522 ((item.type === "user_input_request" || item.type === "approval_request") &&
523 pendingRequestIds.has(String(item.requestId)))
524 );
526​
527/** Retain small requests outside the visible window; later result pages still need them for attempt/run reducers. */
528function retainedInterruptRequestTurnItems(
529 projection: OrchestrationV2ThreadProjection,
530 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
531): OrchestrationV2TurnItem[] {
532 const visibleLocalIds = new Set<string>();
533 for (const row of visible) {
534 if (isLocalProjectedRow(projection, row)) {
535 visibleLocalIds.add(String(row.sourceItemId));
536 }
537 }
538​
539 const pendingRequestIds = pendingRequestIdsOf(projection);
540 const retained: OrchestrationV2TurnItem[] = [];
541 for (const item of projection.turnItems) {
542 if (!isRetainedDependency(item, pendingRequestIds)) {
543 continue;
544 }
545 if (visibleLocalIds.has(String(item.id))) {
546 continue;
547 }
548 retained.push(item);
549 }
550 return retained;
552​
553function localTurnItemsForVisibleWindow(
554 projection: OrchestrationV2ThreadProjection,
555 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
556): OrchestrationV2TurnItem[] {
557 return visible.filter((row) => isLocalProjectedRow(projection, row)).map((row) => row.item);
559​
560function messagesForBoundedProjection(
561 projection: OrchestrationV2ThreadProjection,
562 turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
563): OrchestrationV2ThreadProjection["messages"] {
564 const retainedMessageIds = new Set<string>();
565 for (const item of turnItems) {
566 if ("messageId" in item) {
567 retainedMessageIds.add(String(item.messageId));
568 }
569 }
570​
571 const latestRun = projection.runs.reduce<(typeof projection.runs)[number] | null>(
572 (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest),
573 null,
574 );
575 const retainedRunIds = new Set<string>();
576 for (const run of projection.runs) {
577 if (
578 run.id === latestRun?.id ||
579 run.status === "preparing" ||
580 run.status === "starting" ||
581 run.status === "running" ||
582 run.status === "waiting" ||
583 run.status === "queued"
584 ) {
585 retainedRunIds.add(String(run.id));
586 retainedMessageIds.add(String(run.userMessageId));
587 }
588 }
589​
590 return projection.messages.filter(
591 (message) =>
592 retainedMessageIds.has(String(message.id)) ||
593 (message.runId !== null && retainedRunIds.has(String(message.runId))) ||
594 message.delegatedCompletion !== undefined ||
595 // Keep the workflow script outside the history window; clients use it to open the coordinator thread.
596 message.workflowScript === true,
597 );
599​
600/** Watermark prevents old missing updates from appending newest when bounded windows lack local rows. */
601export function computeLatestLocalTurnOrdinal(
602 turnItems: ReadonlyArray<{ readonly ordinal: number }>,
603): number | null {
604 let latest: number | null = null;
605 for (const item of turnItems) {
606 if (latest === null || item.ordinal > latest) {
607 latest = item.ordinal;
608 }
609 }
610 return latest;
612​
613export function boundedTimelineEncodedBytes(input: {
614 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
615 readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
616}): number {
617 let total = 0;
618 for (const row of input.visibleTurnItems) {
619 total += projectedRowEncodedBytes(row);
620 }
621 for (const item of input.turnItems) {
622 total += bytesOfJson(item);
623 }
624 return total;
626​
627export function buildBoundedThreadProjection(input: {
628 readonly projection: OrchestrationV2ThreadProjection;
629 readonly snapshotSequence: number;
630 readonly policy?: ThreadHistoryPagePolicy | undefined;
631}): BoundedProjectionResult {
632 const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;
633 const threadId = input.projection.thread.id;
634 const runOrdinals = new Map(input.projection.runs.map((run) => [run.id, run.ordinal]));
635 let latestTodoList: (typeof input.projection.plans)[number] | undefined;
636 let latestTodoListOrdinal = -1;
637 for (const plan of input.projection.plans) {
638 const ordinal = plan.runId === null ? undefined : runOrdinals.get(plan.runId);
639 if (
640 plan.kind === "todo_list" &&
641 plan.status !== "superseded" &&
642 ordinal !== undefined &&
643 ordinal >= latestTodoListOrdinal
644 ) {
645 latestTodoList = plan;
646 latestTodoListOrdinal = ordinal;
647 }
648 }
649 const controlProjection = {
650 ...input.projection,
651 plans: input.projection.plans.filter(
652 (plan) => plan.status === "active" || plan.id === latestTodoList?.id,
653 ),
654 contextHandoffs: input.projection.contextHandoffs.filter(
655 (handoff) => handoff.status === "pending" || handoff.status === "ready",
656 ),
657 };
658 const latestLocalTurnOrdinal = computeLatestLocalTurnOrdinal(input.projection.turnItems);
659​
660 const dependencyReserve = (() => {
661 let reserve = 0;
662 const pendingRequestIds = pendingRequestIdsOf(controlProjection);
663 for (const item of controlProjection.turnItems) {
664 if (isRetainedDependency(item, pendingRequestIds)) {
665 reserve += bytesOfJson(item);
666 }
667 }
668 return reserve;
669 })();
670 const controlBytes = bytesOfJson({
671 ...controlProjection,
672 messages: [],
673 turnItems: [],
674 visibleTurnItems: [],
675 });
676 // Control state (checkpoint file lists, the latest task list) cannot be paged, so it may claim at most
677 // half the budget; past that the window would shrink to the one row every page admits.
678 const windowBudget = Math.max(
679 policy.maxEncodedBytes / 2,
680 policy.maxEncodedBytes - dependencyReserve - controlBytes - 1_024,
681 );
682 const windowPolicy: ThreadHistoryPagePolicy = { ...policy, maxEncodedBytes: windowBudget };
683​
684 const window = selectRecentTimelineWindow({
685 items: controlProjection.visibleTurnItems,
686 snapshotSequence: input.snapshotSequence,
687 policy: windowPolicy,
688 rowEncodedBytes: (row) => projectedRowBoundedSnapshotEncodedBytes(row, threadId),
689 });
690 const visibleTurnItems = renumberPositions(window.items);
691 const windowTurnItems = localTurnItemsForVisibleWindow(controlProjection, visibleTurnItems);
692 const dependencyTurnItems = retainedInterruptRequestTurnItems(
693 controlProjection,
694 visibleTurnItems,
695 );
696 const turnItemById = new Map<string, OrchestrationV2TurnItem>();
697 for (const item of windowTurnItems) {
698 turnItemById.set(String(item.id), item);
699 }
700 for (const item of dependencyTurnItems) {
701 turnItemById.set(String(item.id), item);
702 }
703 const turnItems = [...turnItemById.values()];
704​
705 const visiblePlanIds = new Set(
706 turnItems.flatMap((item) =>
707 item.type === "proposed_plan" || item.type === "todo_list" ? [String(item.planId)] : [],
708 ),
709 );
710 const visibleHandoffIds = new Set(
711 turnItems.flatMap((item) => (item.type === "handoff" ? [String(item.contextHandoffId)] : [])),
712 );
713 const plans = input.projection.plans
714 .filter(
715 (plan) =>
716 plan.status === "active" ||
717 plan.id === latestTodoList?.id ||
718 visiblePlanIds.has(String(plan.id)),
719 )
720 .map((plan) =>
721 plan.status === "active" || plan.id === latestTodoList?.id
722 ? plan
723 : plan.kind === "proposed_plan"
724 ? { ...plan, markdown: "", detailInTurnItem: true as const }
725 : { ...plan, explanation: undefined, detailInTurnItem: true as const },
726 );
727 const contextHandoffs = input.projection.contextHandoffs
728 .filter(
729 (handoff) =>
730 handoff.status === "pending" ||
731 handoff.status === "ready" ||
732 visibleHandoffIds.has(String(handoff.id)),
733 )
734 .map((handoff) =>
735 handoff.status === "pending" || handoff.status === "ready"
736 ? handoff
737 : { ...handoff, summaryText: "", detailInTurnItem: true as const },
738 );
739​
740 const projection = {
741 ...controlProjection,
742 plans,
743 contextHandoffs,
744 messages: messagesForBoundedProjection(controlProjection, turnItems),
745 turnItems,
746 visibleTurnItems,
747 };
748 return {
749 projection,
750 historyCursor: window.nextCursor,
751 hasMoreHistory: window.hasMoreHistory,
752 latestLocalTurnOrdinal,
753 };