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