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

threadHistoryPaging.ts

755 lines25.8 KB

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