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