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

threadHistoryPaging.ts

612 lines20.0 KB

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);
24export const THREAD_HISTORY_MAX_RAW_TURNS = 150;
25​
26export const THREAD_HISTORY_SNAPSHOT_ROW_LIMIT = THREAD_HISTORY_PAGE_POLICY.maxItems + 2;
27​
28const 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 }
77​
78function bytesOfJson(value: unknown): number {
79 return Buffer.byteLength(JSON.stringify(value), "utf8");
81​
82/**
83 * Proves overflow without serializing: a string's UTF-16 length never exceeds
84 * its UTF-8 JSON bytes, and local items are encoded once per array they sit in.
85 */
86function timelineTextExceedsBudget(
87 projection: OrchestrationV2ThreadProjection,
88 budget: number,
89): boolean {
90 let length = 0;
91 const exceeds = (item: OrchestrationV2TurnItem): boolean => {
92 if ("text" in item) {
93 length += item.text.length;
94 }
95 return length > budget;
96 };
97 return (
98 projection.visibleTurnItems.some((row) => exceeds(row.item)) ||
99 projection.turnItems.some(exceeds)
100 );
102​
103export function projectedRowEncodedBytes(row: HistoryRow): number {
104 return bytesOfJson(row);
106​
107/**
108 * Bounded-snapshot cost: local rows also land in `projection.turnItems`, so
109 * charge the nested item a second time. Inherited rows only appear in the
110 * visible list.
111 */
112export function projectedRowBoundedSnapshotEncodedBytes(
113 row: OrchestrationV2ProjectedTurnItem,
114 threadId: ThreadId | string,
115): number {
116 const rowBytes = projectedRowEncodedBytes(row);
117 if (row.visibility === "local" || String(row.sourceThreadId) === String(threadId)) {
118 return rowBytes + bytesOfJson(row.item);
119 }
120 return rowBytes;
122​
123function renumberPositions<Row extends HistoryRow>(items: ReadonlyArray<Row>): Row[] {
124 return items.map((row, position) => (row.position === position ? row : { ...row, position }));
126​
127function encodeCursorPayload(payload: ThreadHistoryCursorPayload): string {
128 return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
130​
131export function encodeThreadHistoryCursor(input: {
132 readonly snapshotSequence: number;
133 readonly sourceThreadId: ThreadId | string;
134 readonly sourceItemId: TurnItemId | string;
135 readonly position: number;
136}): string {
137 return encodeCursorPayload({
138 v: 1,
139 seq: input.snapshotSequence,
140 st: String(input.sourceThreadId),
141 si: String(input.sourceItemId),
142 p: input.position,
143 });
145​
146export function decodeThreadHistoryCursor(cursor: string): ThreadHistoryCursorPayload {
147 if (cursor.length === 0 || cursor.length > THREAD_HISTORY_CURSOR_MAX_LENGTH) {
148 throw new InvalidThreadHistoryCursorError();
149 }
150 let parsed: unknown;
151 try {
152 const json = Buffer.from(cursor, "base64url").toString("utf8");
153 parsed = JSON.parse(json) as unknown;
154 } catch {
155 throw new InvalidThreadHistoryCursorError();
156 }
157 if (
158 typeof parsed !== "object" ||
159 parsed === null ||
160 !("v" in parsed) ||
161 (parsed as { v: unknown }).v !== 1 ||
162 !("seq" in parsed) ||
163 typeof (parsed as { seq: unknown }).seq !== "number" ||
164 !Number.isInteger((parsed as { seq: number }).seq) ||
165 (parsed as { seq: number }).seq < 0 ||
166 !("st" in parsed) ||
167 typeof (parsed as { st: unknown }).st !== "string" ||
168 (parsed as { st: string }).st.length === 0 ||
169 !("si" in parsed) ||
170 typeof (parsed as { si: unknown }).si !== "string" ||
171 (parsed as { si: string }).si.length === 0 ||
172 !("p" in parsed) ||
173 typeof (parsed as { p: unknown }).p !== "number" ||
174 !Number.isInteger((parsed as { p: number }).p) ||
175 (parsed as { p: number }).p < 0
176 ) {
177 throw new InvalidThreadHistoryCursorError();
178 }
179 return parsed as ThreadHistoryCursorPayload;
181​
182function isThreadHistoryTurnStart(item: HistoryRow["item"]): boolean {
183 return (
184 item.type === "user_message" &&
185 (item.inputIntent === "turn_start" || item.inputIntent === "queued_turn")
186 );
188​
189/**
190 * A wake (PR watch, task completion) starts its run with a notification instead of a user message, so a
191 * notification starts a turn when it is its run's first input. ProjectionStore's `run_starts` window query
192 * applies the same rule.
193 */
194export function threadHistoryTurnStarts(
195 items: ReadonlyArray<HistoryRow["item"]>,
196): ReadonlyArray<boolean> {
197 const startedRuns = new Set<string>();
198 return items.map((item) => {
199 if (item.type !== "user_message" && item.type !== "notification") return false;
200 const firstInput = item.runId != null && !startedRuns.has(item.runId);
201 if (item.runId != null) startedRuns.add(item.runId);
202 return item.type === "notification" ? firstInput : isThreadHistoryTurnStart(item);
203 });
205​
206export function isThreadHistoryUserTurn(item: HistoryRow["item"]): boolean {
207 return (
208 isThreadHistoryTurnStart(item) && item.type === "user_message" && item.createdBy === "user"
209 );
211​
212/**
213 * Histories without turn starts use row budgets and always admit at least one
214 * row so oversized items cannot deadlock paging.
215 */
216function selectOlderTimelinePage<Row extends HistoryRow>(input: {
217 readonly items: ReadonlyArray<Row>;
218 readonly exclusiveEndIndex: number;
219 readonly snapshotSequence: number;
220 readonly policy?: ThreadHistoryPagePolicy | undefined;
221 readonly rowEncodedBytes?: ((row: Row) => number) | undefined;
222}): SelectTimelinePageResult<Row> {
223 const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;
224 const rowCost = input.rowEncodedBytes ?? projectedRowEncodedBytes;
225 const end = Math.min(Math.max(input.exclusiveEndIndex, 0), input.items.length);
226 if (end <= 0) {
227 return { items: [], nextCursor: null, hasMoreHistory: false };
228 }
229​
230 const selected: Row[] = [];
231 let encodedBytes = 0;
232 let userTurns = 0;
233 let rawTurns = 0;
234 const candidates = input.items.slice(0, end);
235 const turnStarts = threadHistoryTurnStarts(candidates.map((row) => row.item));
236 const turnLimit = candidates.some((row) => isThreadHistoryUserTurn(row.item))
237 ? policy.maxUserTurns
238 : undefined;
239 for (let index = end - 1; index >= 0; index -= 1) {
240 const row = input.items[index]!;
241 const rowBytes = turnLimit === undefined ? rowCost(row) : 0;
242 if (
243 selected.length > 0 &&
244 (turnLimit === undefined
245 ? selected.length >= policy.maxItems || encodedBytes + rowBytes > policy.maxEncodedBytes
246 : userTurns >= turnLimit || rawTurns >= THREAD_HISTORY_MAX_RAW_TURNS)
247 ) {
248 break;
249 }
250 selected.push(row);
251 encodedBytes += rowBytes;
252 if (isThreadHistoryUserTurn(row.item)) userTurns += 1;
253 if (turnStarts[index]) rawTurns += 1;
254 }
255 selected.reverse();
256​
257 const oldest = selected[0];
258 const oldestIndex = oldest
259 ? input.items.findIndex(
260 (row) =>
261 row.sourceThreadId === oldest.sourceThreadId && row.sourceItemId === oldest.sourceItemId,
262 )
263 : -1;
264 const hasMoreHistory = oldestIndex > 0;
265 const nextCursor =
266 hasMoreHistory && oldest
267 ? encodeThreadHistoryCursor({
268 snapshotSequence: input.snapshotSequence,
269 sourceThreadId: oldest.sourceThreadId,
270 sourceItemId: oldest.sourceItemId,
271 position: oldest.position,
272 })
273 : null;
274​
275 return {
276 items: renumberPositions(selected),
277 nextCursor,
278 hasMoreHistory,
279 };
281​
282export function selectRecentTimelineWindow(input: {
283 readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
284 readonly snapshotSequence: number;
285 readonly policy?: ThreadHistoryPagePolicy | undefined;
286 readonly rowEncodedBytes?: ((row: OrchestrationV2ProjectedTurnItem) => number) | undefined;
287}): SelectTimelinePageResult {
288 return selectOlderTimelinePage({
289 items: input.items,
290 exclusiveEndIndex: input.items.length,
291 snapshotSequence: input.snapshotSequence,
292 ...(input.policy === undefined ? {} : { policy: input.policy }),
293 ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }),
294 });
296​
297function findCursorIndex(
298 items: ReadonlyArray<Pick<HistoryRow, "sourceThreadId" | "sourceItemId">>,
299 cursor: ThreadHistoryCursorPayload,
300): number {
301 const byIdentity = items.findIndex(
302 (row) => String(row.sourceThreadId) === cursor.st && String(row.sourceItemId) === cursor.si,
303 );
304 if (byIdentity !== -1) {
305 return byIdentity;
306 }
307 return Math.min(cursor.p, items.length);
309​
310export function selectHistoryPageFromCursor<Row extends HistoryRow>(input: {
311 readonly items: ReadonlyArray<Row>;
312 readonly cursor: string;
313 readonly snapshotSequence: number;
314 readonly policy?: ThreadHistoryPagePolicy | undefined;
315 readonly rowEncodedBytes?: ((row: Row) => number) | undefined;
316 readonly throughEntryId?: string | undefined;
317}): SelectTimelinePageResult<Row> {
318 const decoded = decodeThreadHistoryCursor(input.cursor);
319 const anchorIndex = findCursorIndex(input.items, decoded);
320 let policy = input.policy ?? {
321 ...THREAD_HISTORY_PAGE_POLICY,
322 maxUserTurns: OLDER_THREAD_USER_TURN_LIMIT,
323 };
324 if (input.throughEntryId !== undefined) {
325 const targetIndex = input.items.findIndex(
326 (row) => (row.item.messageId ?? row.item.id) === input.throughEntryId,
327 );
328 if (targetIndex >= 0 && targetIndex < anchorIndex) {
329 const turns = input.items
330 .slice(targetIndex, anchorIndex)
331 .filter((row) => isThreadHistoryUserTurn(row.item)).length;
332 policy = {
333 ...policy,
334 maxUserTurns: Math.min(
335 OLDER_THREAD_USER_TURN_LIMIT * 2,
336 Math.max(
337 OLDER_THREAD_USER_TURN_LIMIT,
338 turns + (isThreadHistoryUserTurn(input.items[targetIndex]!.item) ? 0 : 1),
339 ),
340 ),
341 maxItems: policy.maxItems * 2,
342 };
343 }
344 }
345 return selectOlderTimelinePage({
346 items: input.items,
347 exclusiveEndIndex: anchorIndex,
348 snapshotSequence: input.snapshotSequence,
349 ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }),
350 policy,
351 });
353​
354function isLocalProjectedRow(
355 projection: OrchestrationV2ThreadProjection,
356 row: OrchestrationV2ProjectedTurnItem,
357): boolean {
358 return row.visibility === "local" || String(row.sourceThreadId) === String(projection.thread.id);
360​
361/**
362 * Keep every small request item from the full projection even when it sits
363 * outside the recent visible window, so a later history page that introduces
364 * the matching result still has the request available for live attempt/run
365 * reducers.
366 */
367function retainedInterruptRequestTurnItems(
368 projection: OrchestrationV2ThreadProjection,
369 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
370): OrchestrationV2TurnItem[] {
371 const visibleLocalIds = new Set<string>();
372 for (const row of visible) {
373 if (isLocalProjectedRow(projection, row)) {
374 visibleLocalIds.add(String(row.sourceItemId));
375 }
376 }
377​
378 const retained: OrchestrationV2TurnItem[] = [];
379 for (const item of projection.turnItems) {
380 if (item.type !== "run_interrupt_request") {
381 continue;
382 }
383 if (visibleLocalIds.has(String(item.id))) {
384 continue;
385 }
386 retained.push(item);
387 }
388 return retained;
390​
391function localTurnItemsForVisibleWindow(
392 projection: OrchestrationV2ThreadProjection,
393 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
394): OrchestrationV2TurnItem[] {
395 const localIds = new Set<string>();
396 for (const row of visible) {
397 if (isLocalProjectedRow(projection, row)) {
398 localIds.add(String(row.sourceItemId));
399 }
400 }
401 if (localIds.size === 0) {
402 return [];
403 }
404 return projection.turnItems.filter((item) => localIds.has(String(item.id)));
406​
407function messagesForBoundedProjection(
408 projection: OrchestrationV2ThreadProjection,
409 turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
410): OrchestrationV2ThreadProjection["messages"] {
411 const retainedMessageIds = new Set<string>();
412 for (const item of turnItems) {
413 if ("messageId" in item) {
414 retainedMessageIds.add(String(item.messageId));
415 }
416 }
417​
418 const latestRun = projection.runs.reduce<(typeof projection.runs)[number] | null>(
419 (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest),
420 null,
421 );
422 const retainedRunIds = new Set<string>();
423 for (const run of projection.runs) {
424 if (
425 run.id === latestRun?.id ||
426 run.status === "preparing" ||
427 run.status === "starting" ||
428 run.status === "running" ||
429 run.status === "waiting" ||
430 run.status === "queued"
431 ) {
432 retainedRunIds.add(String(run.id));
433 retainedMessageIds.add(String(run.userMessageId));
434 }
435 }
436​
437 return projection.messages.filter(
438 (message) =>
439 retainedMessageIds.has(String(message.id)) ||
440 (message.runId !== null && retainedRunIds.has(String(message.runId))) ||
441 message.delegatedCompletion !== undefined ||
442 // Clients open a workflow coordinator's thread from its script, however
443 // far back the history window starts. A thread has at most one.
444 message.workflowScript === true,
445 );
447​
448/**
449 * Used as a cheap partial-timeline watermark so old missing turn-item updates
450 * cannot append newest when the bounded window has no local rows.
451 */
452export function computeLatestLocalTurnOrdinal(
453 turnItems: ReadonlyArray<{ readonly ordinal: number }>,
454): number | null {
455 let latest: number | null = null;
456 for (const item of turnItems) {
457 if (latest === null || item.ordinal > latest) {
458 latest = item.ordinal;
459 }
460 }
461 return latest;
463​
464export function boundedTimelineEncodedBytes(input: {
465 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
466 readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
467}): number {
468 let total = 0;
469 for (const row of input.visibleTurnItems) {
470 total += projectedRowEncodedBytes(row);
471 }
472 for (const item of input.turnItems) {
473 total += bytesOfJson(item);
474 }
475 return total;
477​
478export function buildBoundedThreadProjection(input: {
479 readonly projection: OrchestrationV2ThreadProjection;
480 readonly snapshotSequence: number;
481 readonly policy?: ThreadHistoryPagePolicy | undefined;
482}): BoundedProjectionResult {
483 const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;
484 const threadId = input.projection.thread.id;
485 const runOrdinals = new Map(input.projection.runs.map((run) => [run.id, run.ordinal]));
486 let latestTodoList: (typeof input.projection.plans)[number] | undefined;
487 let latestTodoListOrdinal = -1;
488 for (const plan of input.projection.plans) {
489 const ordinal = plan.runId === null ? undefined : runOrdinals.get(plan.runId);
490 if (
491 plan.kind === "todo_list" &&
492 plan.status !== "superseded" &&
493 ordinal !== undefined &&
494 ordinal >= latestTodoListOrdinal
495 ) {
496 latestTodoList = plan;
497 latestTodoListOrdinal = ordinal;
498 }
499 }
500 const controlProjection = {
501 ...input.projection,
502 plans: input.projection.plans.filter(
503 (plan) => plan.status === "active" || plan.id === latestTodoList?.id,
504 ),
505 contextHandoffs: input.projection.contextHandoffs.filter(
506 (handoff) => handoff.status === "pending" || handoff.status === "ready",
507 ),
508 };
509 const latestLocalTurnOrdinal = computeLatestLocalTurnOrdinal(input.projection.turnItems);
510​
511 const dependencyReserve = (() => {
512 let reserve = 0;
513 for (const item of controlProjection.turnItems) {
514 if (item.type === "run_interrupt_request") {
515 reserve += bytesOfJson(item);
516 }
517 }
518 return reserve;
519 })();
520 const controlBytes = bytesOfJson({
521 ...controlProjection,
522 messages: [],
523 turnItems: [],
524 visibleTurnItems: [],
525 });
526 // Control state (checkpoint file lists, the latest task list) cannot be paged, so it may claim at most
527 // half the budget; past that the window would shrink to the one row every page admits.
528 const windowBudget = Math.max(
529 policy.maxEncodedBytes / 2,
530 policy.maxEncodedBytes - dependencyReserve - controlBytes - 1_024,
531 );
532 const windowPolicy: ThreadHistoryPagePolicy = {
533 maxUserTurns: policy.maxUserTurns,
534 maxItems: policy.maxItems,
535 maxEncodedBytes: windowBudget,
536 };
537​
538 const window = selectRecentTimelineWindow({
539 items: controlProjection.visibleTurnItems,
540 snapshotSequence: input.snapshotSequence,
541 policy: windowPolicy,
542 rowEncodedBytes: (row) => projectedRowBoundedSnapshotEncodedBytes(row, threadId),
543 });
544 const visibleTurnItems = renumberPositions(window.items);
545 const windowTurnItems = localTurnItemsForVisibleWindow(controlProjection, visibleTurnItems);
546 const dependencyTurnItems = retainedInterruptRequestTurnItems(
547 controlProjection,
548 visibleTurnItems,
549 );
550 const turnItemById = new Map<string, OrchestrationV2TurnItem>();
551 for (const item of windowTurnItems) {
552 turnItemById.set(String(item.id), item);
553 }
554 for (const item of dependencyTurnItems) {
555 turnItemById.set(String(item.id), item);
556 }
557 const turnItems = [...turnItemById.values()];
558​
559 const visiblePlanIds = new Set(
560 turnItems.flatMap((item) =>
561 item.type === "proposed_plan" || item.type === "todo_list" ? [String(item.planId)] : [],
562 ),
563 );
564 const visibleHandoffIds = new Set(
565 turnItems.flatMap((item) => (item.type === "handoff" ? [String(item.contextHandoffId)] : [])),
566 );
567 const plans = input.projection.plans
568 .filter(
569 (plan) =>
570 plan.status === "active" ||
571 plan.id === latestTodoList?.id ||
572 visiblePlanIds.has(String(plan.id)),
573 )
574 .map((plan) =>
575 plan.status === "active" || plan.id === latestTodoList?.id
576 ? plan
577 : plan.kind === "proposed_plan"
578 ? { ...plan, markdown: "", detailInTurnItem: true as const }
579 : { ...plan, explanation: undefined, detailInTurnItem: true as const },
580 );
581 const contextHandoffs = input.projection.contextHandoffs
582 .filter(
583 (handoff) =>
584 handoff.status === "pending" ||
585 handoff.status === "ready" ||
586 visibleHandoffIds.has(String(handoff.id)),
587 )
588 .map((handoff) =>
589 handoff.status === "pending" || handoff.status === "ready"
590 ? handoff
591 : { ...handoff, summaryText: "", detailInTurnItem: true as const },
592 );
593​
594 const projection = {
595 ...controlProjection,
596 plans,
597 contextHandoffs,
598 messages: messagesForBoundedProjection(controlProjection, turnItems),
599 turnItems,
600 visibleTurnItems,
601 };
602 return {
603 projection,
604 historyCursor: window.nextCursor,
605 hasMoreHistory: window.hasMoreHistory,
606 latestLocalTurnOrdinal,
607 payloadBudgetExceeded:
608 controlBytes > policy.maxEncodedBytes ||
609 timelineTextExceedsBudget(projection, policy.maxEncodedBytes) ||
610 bytesOfJson(projection) > policy.maxEncodedBytes,
611 };