Open History to see the last commit
1import type {
2 OrchestrationV2ProjectedTurnItem,
3 OrchestrationV2ThreadProjection,
4 OrchestrationV2TurnItem,
5 ThreadId,
6 TurnItemId,
7} from "@t3tools/contracts";
8
9/**
10 * Match the V1 conversation windows. Item/byte budgets only apply to histories
11 * without turn starts; tool activity must not split an ordinary conversation turn.
12 */
13export const THREAD_HISTORY_PAGE_POLICY = {
14 maxUserTurns: 10,
15 maxItems: 75,
16 maxEncodedBytes: 1_048_576,
17} as const;
18
19export const OLDER_THREAD_USER_TURN_LIMIT = 20;
20
21/** Load conversation rows before the bulk of a turn's folded tool activity. */
22export function isConversationHistoryItem(item: Pick<OrchestrationV2TurnItem, "type">): boolean {
23 return !["command_execution", "reasoning", "file_change", "dynamic_tool"].includes(item.type);
24}
25export const THREAD_HISTORY_MAX_RAW_TURNS = 150;
26
27/** Extra rows let the projection query retain an inclusive cursor and prove another page exists. */
28export const THREAD_HISTORY_SNAPSHOT_ROW_LIMIT = THREAD_HISTORY_PAGE_POLICY.maxItems + 2;
29
30/** Reject absurd cursors before base64 work or JSON parse. */
31export const THREAD_HISTORY_CURSOR_MAX_LENGTH = 4_096;
32
33export type ThreadHistoryPagePolicy = {
34 readonly maxUserTurns?: number | undefined;
35 readonly maxItems: number;
36 readonly maxEncodedBytes: number;
37};
38
39export type ThreadHistoryCursorPayload = {
40 readonly v: 1;
41 readonly seq: number;
42 readonly st: string;
43 readonly si: string;
44 readonly p: number;
45};
46
47type HistoryRow = Pick<
48 OrchestrationV2ProjectedTurnItem,
49 "position" | "visibility" | "sourceThreadId" | "sourceItemId"
50> & {
51 readonly item: Pick<OrchestrationV2TurnItem, "type"> & {
52 readonly id?: string;
53 readonly messageId?: string;
54 readonly inputIntent?: string;
55 readonly createdBy?: string;
56 };
57};
58export type SelectTimelinePageResult<Row extends HistoryRow = OrchestrationV2ProjectedTurnItem> = {
59 readonly items: ReadonlyArray<Row>;
60 readonly nextCursor: string | null;
61 readonly hasMoreHistory: boolean;
62};
63
64export type BoundedProjectionResult = {
65 readonly projection: OrchestrationV2ThreadProjection;
66 readonly historyCursor: string | null;
67 readonly hasMoreHistory: boolean;
68 /** Max ordinal across the authoritative full projection's local turnItems. */
69 readonly latestLocalTurnOrdinal: number | null;
70 readonly payloadBudgetExceeded: boolean;
71};
72
73export class InvalidThreadHistoryCursorError extends Error {
74 readonly _tag = "InvalidThreadHistoryCursorError";
75 constructor(message = "Invalid thread history cursor.") {
76 super(message);
77 this.name = "InvalidThreadHistoryCursorError";
78 }
79}
80
81function bytesOfJson(value: unknown): number {
82 return Buffer.byteLength(JSON.stringify(value), "utf8");
83}
84
85/** Ordinary history-page cost: one projected row (item is nested once). */
86export function projectedRowEncodedBytes(row: HistoryRow): number {
87 return bytesOfJson(row);
88}
89
90/**
91 * Bounded-snapshot cost: local rows also land in `projection.turnItems`, so
92 * charge the nested item a second time. Inherited rows only appear in the
93 * visible list.
94 */
95export function projectedRowBoundedSnapshotEncodedBytes(
96 row: OrchestrationV2ProjectedTurnItem,
97 threadId: ThreadId | string,
98): number {
99 const rowBytes = projectedRowEncodedBytes(row);
100 if (row.visibility === "local" || String(row.sourceThreadId) === String(threadId)) {
101 return rowBytes + bytesOfJson(row.item);
102 }
103 return rowBytes;
104}
105
106function renumberPositions<Row extends HistoryRow>(items: ReadonlyArray<Row>): Row[] {
107 return items.map((row, position) => (row.position === position ? row : { ...row, position }));
108}
109
110function encodeCursorPayload(payload: ThreadHistoryCursorPayload): string {
111 return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
112}
113
114export function encodeThreadHistoryCursor(input: {
115 readonly snapshotSequence: number;
116 readonly sourceThreadId: ThreadId | string;
117 readonly sourceItemId: TurnItemId | string;
118 readonly position: number;
119}): string {
120 return encodeCursorPayload({
121 v: 1,
122 seq: input.snapshotSequence,
123 st: String(input.sourceThreadId),
124 si: String(input.sourceItemId),
125 p: input.position,
126 });
127}
128
129export function decodeThreadHistoryCursor(cursor: string): ThreadHistoryCursorPayload {
130 if (cursor.length === 0 || cursor.length > THREAD_HISTORY_CURSOR_MAX_LENGTH) {
131 throw new InvalidThreadHistoryCursorError();
132 }
133 let parsed: unknown;
134 try {
135 const json = Buffer.from(cursor, "base64url").toString("utf8");
136 parsed = JSON.parse(json) as unknown;
137 } catch {
138 throw new InvalidThreadHistoryCursorError();
139 }
140 if (
141 typeof parsed !== "object" ||
142 parsed === null ||
143 !("v" in parsed) ||
144 (parsed as { v: unknown }).v !== 1 ||
145 !("seq" in parsed) ||
146 typeof (parsed as { seq: unknown }).seq !== "number" ||
147 !Number.isInteger((parsed as { seq: number }).seq) ||
148 (parsed as { seq: number }).seq < 0 ||
149 !("st" in parsed) ||
150 typeof (parsed as { st: unknown }).st !== "string" ||
151 (parsed as { st: string }).st.length === 0 ||
152 !("si" in parsed) ||
153 typeof (parsed as { si: unknown }).si !== "string" ||
154 (parsed as { si: string }).si.length === 0 ||
155 !("p" in parsed) ||
156 typeof (parsed as { p: unknown }).p !== "number" ||
157 !Number.isInteger((parsed as { p: number }).p) ||
158 (parsed as { p: number }).p < 0
159 ) {
160 throw new InvalidThreadHistoryCursorError();
161 }
162 return parsed as ThreadHistoryCursorPayload;
163}
164
165export function isThreadHistoryTurnStart(item: HistoryRow["item"]): boolean {
166 return (
167 item.type === "user_message" &&
168 (item.inputIntent === "turn_start" || item.inputIntent === "queued_turn")
169 );
170}
171
172/** Steering belongs to its existing turn and must not consume another page slot. */
173export function isThreadHistoryUserTurn(item: HistoryRow["item"]): boolean {
174 return (
175 isThreadHistoryTurnStart(item) && item.type === "user_message" && item.createdBy === "user"
176 );
177}
178
179/**
180 * Walk a chronological timeline backward from the exclusive end, collecting rows
181 * through complete user turns. Histories without turn starts use row budgets
182 * and always admit at least one row so oversized items cannot deadlock paging.
183 */
184function selectOlderTimelinePage<Row extends HistoryRow>(input: {
185 readonly items: ReadonlyArray<Row>;
186 readonly exclusiveEndIndex: number;
187 readonly snapshotSequence: number;
188 readonly policy?: ThreadHistoryPagePolicy | undefined;
189 readonly rowEncodedBytes?: ((row: Row) => number) | undefined;
190}): SelectTimelinePageResult<Row> {
191 const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;
192 const rowCost = input.rowEncodedBytes ?? projectedRowEncodedBytes;
193 const end = Math.min(Math.max(input.exclusiveEndIndex, 0), input.items.length);
194 if (end <= 0) {
195 return { items: [], nextCursor: null, hasMoreHistory: false };
196 }
197
198 const selected: Row[] = [];
199 let encodedBytes = 0;
200 let userTurns = 0;
201 let rawTurns = 0;
202 const turnLimit = input.items.slice(0, end).some((row) => isThreadHistoryUserTurn(row.item))
203 ? policy.maxUserTurns
204 : undefined;
205 for (let index = end - 1; index >= 0; index -= 1) {
206 const row = input.items[index]!;
207 const rowBytes = turnLimit === undefined ? rowCost(row) : 0;
208 if (
209 selected.length > 0 &&
210 (turnLimit === undefined
211 ? selected.length >= policy.maxItems || encodedBytes + rowBytes > policy.maxEncodedBytes
212 : userTurns >= turnLimit || rawTurns >= THREAD_HISTORY_MAX_RAW_TURNS)
213 ) {
214 break;
215 }
216 selected.push(row);
217 encodedBytes += rowBytes;
218 if (isThreadHistoryUserTurn(row.item)) userTurns += 1;
219 if (isThreadHistoryTurnStart(row.item)) rawTurns += 1;
220 }
221 selected.reverse();
222
223 const oldest = selected[0];
224 const oldestIndex = oldest
225 ? input.items.findIndex(
226 (row) =>
227 row.sourceThreadId === oldest.sourceThreadId && row.sourceItemId === oldest.sourceItemId,
228 )
229 : -1;
230 const hasMoreHistory = oldestIndex > 0;
231 const nextCursor =
232 hasMoreHistory && oldest
233 ? encodeThreadHistoryCursor({
234 snapshotSequence: input.snapshotSequence,
235 sourceThreadId: oldest.sourceThreadId,
236 sourceItemId: oldest.sourceItemId,
237 position: oldest.position,
238 })
239 : null;
240
241 return {
242 items: renumberPositions(selected),
243 nextCursor,
244 hasMoreHistory,
245 };
246}
247
248export function selectRecentTimelineWindow(input: {
249 readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
250 readonly snapshotSequence: number;
251 readonly policy?: ThreadHistoryPagePolicy | undefined;
252 readonly rowEncodedBytes?: ((row: OrchestrationV2ProjectedTurnItem) => number) | undefined;
253}): SelectTimelinePageResult {
254 return selectOlderTimelinePage({
255 items: input.items,
256 exclusiveEndIndex: input.items.length,
257 snapshotSequence: input.snapshotSequence,
258 ...(input.policy === undefined ? {} : { policy: input.policy }),
259 ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }),
260 });
261}
262
263function findCursorIndex(
264 items: ReadonlyArray<Pick<HistoryRow, "sourceThreadId" | "sourceItemId">>,
265 cursor: ThreadHistoryCursorPayload,
266): number {
267 const byIdentity = items.findIndex(
268 (row) => String(row.sourceThreadId) === cursor.st && String(row.sourceItemId) === cursor.si,
269 );
270 if (byIdentity !== -1) {
271 return byIdentity;
272 }
273 // Identity miss can happen if the cursor item was deleted; fall back to the
274 // recorded position clamped into the current timeline so pagination can
275 // continue from a stable-ish anchor rather than failing hard. Clamp to
276 // items.length (exclusive end) so a shrunken timeline never 400s forever.
277 // decodeThreadHistoryCursor already guarantees p is a non-negative integer.
278 return Math.min(cursor.p, items.length);
279}
280
281export function selectHistoryPageFromCursor<Row extends HistoryRow>(input: {
282 readonly items: ReadonlyArray<Row>;
283 readonly cursor: string;
284 readonly snapshotSequence: number;
285 readonly policy?: ThreadHistoryPagePolicy | undefined;
286 readonly rowEncodedBytes?: ((row: Row) => number) | undefined;
287 readonly throughEntryId?: string | undefined;
288}): SelectTimelinePageResult<Row> {
289 const decoded = decodeThreadHistoryCursor(input.cursor);
290 const anchorIndex = findCursorIndex(input.items, decoded);
291 let policy = input.policy ?? {
292 ...THREAD_HISTORY_PAGE_POLICY,
293 maxUserTurns: OLDER_THREAD_USER_TURN_LIMIT,
294 };
295 if (input.throughEntryId !== undefined) {
296 const targetIndex = input.items.findIndex(
297 (row) => (row.item.messageId ?? row.item.id) === input.throughEntryId,
298 );
299 if (targetIndex >= 0 && targetIndex < anchorIndex) {
300 // A search jump can combine two pages, but never grow into an unbounded read.
301 const turns = input.items
302 .slice(targetIndex, anchorIndex)
303 .filter((row) => isThreadHistoryUserTurn(row.item)).length;
304 policy = {
305 ...policy,
306 maxUserTurns: Math.min(
307 OLDER_THREAD_USER_TURN_LIMIT * 2,
308 Math.max(
309 OLDER_THREAD_USER_TURN_LIMIT,
310 turns + (isThreadHistoryUserTurn(input.items[targetIndex]!.item) ? 0 : 1),
311 ),
312 ),
313 maxItems: policy.maxItems * 2,
314 };
315 }
316 }
317 return selectOlderTimelinePage({
318 items: input.items,
319 exclusiveEndIndex: anchorIndex,
320 snapshotSequence: input.snapshotSequence,
321 ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }),
322 policy,
323 });
324}
325
326function isLocalProjectedRow(
327 projection: OrchestrationV2ThreadProjection,
328 row: OrchestrationV2ProjectedTurnItem,
329): boolean {
330 return row.visibility === "local" || String(row.sourceThreadId) === String(projection.thread.id);
331}
332
333/**
334 * Visibility for superseded `run_interrupt_result` rows depends on a matching
335 * `run_interrupt_request` in `turnItems`. Keep every small request item from the
336 * full projection even when it sits outside the recent visible window, so a
337 * later history page that introduces the matching result still has the request
338 * available for live attempt/run reducers.
339 */
340function retainedInterruptRequestTurnItems(
341 projection: OrchestrationV2ThreadProjection,
342 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
343): OrchestrationV2TurnItem[] {
344 const visibleLocalIds = new Set<string>();
345 for (const row of visible) {
346 if (isLocalProjectedRow(projection, row)) {
347 visibleLocalIds.add(String(row.sourceItemId));
348 }
349 }
350
351 const retained: OrchestrationV2TurnItem[] = [];
352 for (const item of projection.turnItems) {
353 if (item.type !== "run_interrupt_request") {
354 continue;
355 }
356 // Already covered by local turnItems for the visible window.
357 if (visibleLocalIds.has(String(item.id))) {
358 continue;
359 }
360 retained.push(item);
361 }
362 return retained;
363}
364
365function localTurnItemsForVisibleWindow(
366 projection: OrchestrationV2ThreadProjection,
367 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
368): OrchestrationV2TurnItem[] {
369 const localIds = new Set<string>();
370 for (const row of visible) {
371 if (isLocalProjectedRow(projection, row)) {
372 localIds.add(String(row.sourceItemId));
373 }
374 }
375 if (localIds.size === 0) {
376 return [];
377 }
378 return projection.turnItems.filter((item) => localIds.has(String(item.id)));
379}
380
381function messagesForBoundedProjection(
382 projection: OrchestrationV2ThreadProjection,
383 turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
384): OrchestrationV2ThreadProjection["messages"] {
385 const retainedMessageIds = new Set<string>();
386 for (const item of turnItems) {
387 if ("messageId" in item) {
388 retainedMessageIds.add(String(item.messageId));
389 }
390 }
391
392 const latestRun = projection.runs.reduce<(typeof projection.runs)[number] | null>(
393 (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest),
394 null,
395 );
396 const retainedRunIds = new Set<string>();
397 for (const run of projection.runs) {
398 if (
399 run.id === latestRun?.id ||
400 run.status === "preparing" ||
401 run.status === "starting" ||
402 run.status === "running" ||
403 run.status === "waiting" ||
404 run.status === "queued"
405 ) {
406 retainedRunIds.add(String(run.id));
407 retainedMessageIds.add(String(run.userMessageId));
408 }
409 }
410
411 return projection.messages.filter(
412 (message) =>
413 retainedMessageIds.has(String(message.id)) ||
414 (message.runId !== null && retainedRunIds.has(String(message.runId))) ||
415 message.delegatedCompletion !== undefined,
416 );
417}
418
419/**
420 * Max local turn ordinal over the authoritative full projection turnItems.
421 * Used as a cheap partial-timeline watermark so old missing turn-item updates
422 * cannot append newest when the bounded window has no local rows.
423 */
424export function computeLatestLocalTurnOrdinal(
425 turnItems: ReadonlyArray<{ readonly ordinal: number }>,
426): number | null {
427 let latest: number | null = null;
428 for (const item of turnItems) {
429 if (latest === null || item.ordinal > latest) {
430 latest = item.ordinal;
431 }
432 }
433 return latest;
434}
435
436/**
437 * Encoded timeline contribution for a bounded snapshot: visible rows plus the
438 * duplicated local turnItems and any retained interrupt-request dependencies.
439 */
440export function boundedTimelineEncodedBytes(input: {
441 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
442 readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
443}): number {
444 let total = 0;
445 for (const row of input.visibleTurnItems) {
446 total += projectedRowEncodedBytes(row);
447 }
448 for (const item of input.turnItems) {
449 total += bytesOfJson(item);
450 }
451 return total;
452}
453
454/**
455 * Builds a partial thread projection with full control-plane arrays and a
456 * bounded recent timeline window plus matching local turnItems.
457 */
458export function buildBoundedThreadProjection(input: {
459 readonly projection: OrchestrationV2ThreadProjection;
460 readonly snapshotSequence: number;
461 readonly policy?: ThreadHistoryPagePolicy | undefined;
462}): BoundedProjectionResult {
463 const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;
464 const threadId = input.projection.thread.id;
465 const controlProjection = {
466 ...input.projection,
467 plans: input.projection.plans.filter((plan) => plan.status === "active"),
468 contextHandoffs: input.projection.contextHandoffs.filter(
469 (handoff) => handoff.status === "pending" || handoff.status === "ready",
470 ),
471 };
472 const latestLocalTurnOrdinal = computeLatestLocalTurnOrdinal(input.projection.turnItems);
473
474 // Reserve bytes for small interrupt-request dependencies that may sit outside
475 // the recent window but are required for visibility of results inside it.
476 const dependencyReserve = (() => {
477 // Upper bound: all request items in the full projection. Window selection
478 // uses this reserve so the final contribution stays under the cap.
479 let reserve = 0;
480 for (const item of controlProjection.turnItems) {
481 if (item.type === "run_interrupt_request") {
482 reserve += bytesOfJson(item);
483 }
484 }
485 return reserve;
486 })();
487 const controlBytes = bytesOfJson({
488 ...controlProjection,
489 messages: [],
490 turnItems: [],
491 visibleTurnItems: [],
492 });
493 const windowBudget = Math.max(
494 0,
495 policy.maxEncodedBytes - dependencyReserve - controlBytes - 1_024,
496 );
497 const windowPolicy: ThreadHistoryPagePolicy = {
498 maxUserTurns: policy.maxUserTurns,
499 maxItems: policy.maxItems,
500 // Zero still admits the first row via the at-least-one rule.
501 maxEncodedBytes: windowBudget,
502 };
503
504 const window = selectRecentTimelineWindow({
505 items: controlProjection.visibleTurnItems,
506 snapshotSequence: input.snapshotSequence,
507 policy: windowPolicy,
508 rowEncodedBytes: (row) => projectedRowBoundedSnapshotEncodedBytes(row, threadId),
509 });
510 const visibleTurnItems = renumberPositions(window.items);
511 const windowTurnItems = localTurnItemsForVisibleWindow(controlProjection, visibleTurnItems);
512 const dependencyTurnItems = retainedInterruptRequestTurnItems(
513 controlProjection,
514 visibleTurnItems,
515 );
516 const turnItemById = new Map<string, OrchestrationV2TurnItem>();
517 for (const item of windowTurnItems) {
518 turnItemById.set(String(item.id), item);
519 }
520 for (const item of dependencyTurnItems) {
521 turnItemById.set(String(item.id), item);
522 }
523 const turnItems = [...turnItemById.values()];
524
525 const visiblePlanIds = new Set(
526 turnItems.flatMap((item) =>
527 item.type === "proposed_plan" || item.type === "todo_list" ? [String(item.planId)] : [],
528 ),
529 );
530 const visibleHandoffIds = new Set(
531 turnItems.flatMap((item) => (item.type === "handoff" ? [String(item.contextHandoffId)] : [])),
532 );
533 const plans = input.projection.plans
534 .filter((plan) => plan.status === "active" || visiblePlanIds.has(String(plan.id)))
535 .map((plan) =>
536 plan.status === "active"
537 ? plan
538 : plan.kind === "proposed_plan"
539 ? { ...plan, markdown: "", detailInTurnItem: true as const }
540 : { ...plan, explanation: undefined, detailInTurnItem: true as const },
541 );
542 const contextHandoffs = input.projection.contextHandoffs
543 .filter(
544 (handoff) =>
545 handoff.status === "pending" ||
546 handoff.status === "ready" ||
547 visibleHandoffIds.has(String(handoff.id)),
548 )
549 .map((handoff) =>
550 handoff.status === "pending" || handoff.status === "ready"
551 ? handoff
552 : { ...handoff, summaryText: "", detailInTurnItem: true as const },
553 );
554
555 const projection = {
556 ...controlProjection,
557 plans,
558 contextHandoffs,
559 messages: messagesForBoundedProjection(controlProjection, turnItems),
560 turnItems,
561 visibleTurnItems,
562 };
563 return {
564 projection,
565 historyCursor: window.nextCursor,
566 hasMoreHistory: window.hasMoreHistory,
567 // Always from the full projection so inherited-only windows still carry a
568 // watermark for partial live reducers.
569 latestLocalTurnOrdinal,
570 payloadBudgetExceeded: bytesOfJson(projection) > policy.maxEncodedBytes,
571 };
572}