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

threadHistoryPaging.ts

567 lines18.7 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​
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 }
77​
78function bytesOfJson(value: unknown): number {
79 return Buffer.byteLength(JSON.stringify(value), "utf8");
81​
82export function projectedRowEncodedBytes(row: HistoryRow): number {
83 return bytesOfJson(row);
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;
101​
102function renumberPositions<Row extends HistoryRow>(items: ReadonlyArray<Row>): Row[] {
103 return items.map((row, position) => (row.position === position ? row : { ...row, position }));
105​
106function encodeCursorPayload(payload: ThreadHistoryCursorPayload): string {
107 return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
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 });
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;
160​
161function isThreadHistoryTurnStart(item: HistoryRow["item"]): boolean {
162 return (
163 item.type === "user_message" &&
164 (item.inputIntent === "turn_start" || item.inputIntent === "queued_turn")
165 );
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 });
184​
185export function isThreadHistoryUserTurn(item: HistoryRow["item"]): boolean {
186 return (
187 isThreadHistoryTurnStart(item) && item.type === "user_message" && item.createdBy === "user"
188 );
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 };
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 });
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);
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 });
332​
333function isLocalProjectedRow(
334 projection: OrchestrationV2ThreadProjection,
335 row: OrchestrationV2ProjectedTurnItem,
336): boolean {
337 return row.visibility === "local" || String(row.sourceThreadId) === String(projection.thread.id);
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;
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)));
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 // Clients open a workflow coordinator's thread from its script, however
422 // far back the history window starts. A thread has at most one.
423 message.workflowScript === true,
424 );
426​
427/**
428 * Used as a cheap partial-timeline watermark so old missing turn-item updates
429 * cannot append newest when the bounded window has no local rows.
430 */
431export function computeLatestLocalTurnOrdinal(
432 turnItems: ReadonlyArray<{ readonly ordinal: number }>,
433): number | null {
434 let latest: number | null = null;
435 for (const item of turnItems) {
436 if (latest === null || item.ordinal > latest) {
437 latest = item.ordinal;
438 }
439 }
440 return latest;
442​
443export function boundedTimelineEncodedBytes(input: {
444 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
445 readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
446}): number {
447 let total = 0;
448 for (const row of input.visibleTurnItems) {
449 total += projectedRowEncodedBytes(row);
450 }
451 for (const item of input.turnItems) {
452 total += bytesOfJson(item);
453 }
454 return total;
456​
457export function buildBoundedThreadProjection(input: {
458 readonly projection: OrchestrationV2ThreadProjection;
459 readonly snapshotSequence: number;
460 readonly policy?: ThreadHistoryPagePolicy | undefined;
461}): BoundedProjectionResult {
462 const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;
463 const threadId = input.projection.thread.id;
464 const controlProjection = {
465 ...input.projection,
466 plans: input.projection.plans.filter((plan) => plan.status === "active"),
467 contextHandoffs: input.projection.contextHandoffs.filter(
468 (handoff) => handoff.status === "pending" || handoff.status === "ready",
469 ),
470 };
471 const latestLocalTurnOrdinal = computeLatestLocalTurnOrdinal(input.projection.turnItems);
472​
473 const dependencyReserve = (() => {
474 let reserve = 0;
475 for (const item of controlProjection.turnItems) {
476 if (item.type === "run_interrupt_request") {
477 reserve += bytesOfJson(item);
478 }
479 }
480 return reserve;
481 })();
482 const controlBytes = bytesOfJson({
483 ...controlProjection,
484 messages: [],
485 turnItems: [],
486 visibleTurnItems: [],
487 });
488 // Control state (checkpoint file lists, an active plan) cannot be paged, so it may claim at most
489 // half the budget; past that the window would shrink to the one row every page admits.
490 const windowBudget = Math.max(
491 policy.maxEncodedBytes / 2,
492 policy.maxEncodedBytes - dependencyReserve - controlBytes - 1_024,
493 );
494 const windowPolicy: ThreadHistoryPagePolicy = {
495 maxUserTurns: policy.maxUserTurns,
496 maxItems: policy.maxItems,
497 maxEncodedBytes: windowBudget,
498 };
499​
500 const window = selectRecentTimelineWindow({
501 items: controlProjection.visibleTurnItems,
502 snapshotSequence: input.snapshotSequence,
503 policy: windowPolicy,
504 rowEncodedBytes: (row) => projectedRowBoundedSnapshotEncodedBytes(row, threadId),
505 });
506 const visibleTurnItems = renumberPositions(window.items);
507 const windowTurnItems = localTurnItemsForVisibleWindow(controlProjection, visibleTurnItems);
508 const dependencyTurnItems = retainedInterruptRequestTurnItems(
509 controlProjection,
510 visibleTurnItems,
511 );
512 const turnItemById = new Map<string, OrchestrationV2TurnItem>();
513 for (const item of windowTurnItems) {
514 turnItemById.set(String(item.id), item);
515 }
516 for (const item of dependencyTurnItems) {
517 turnItemById.set(String(item.id), item);
518 }
519 const turnItems = [...turnItemById.values()];
520​
521 const visiblePlanIds = new Set(
522 turnItems.flatMap((item) =>
523 item.type === "proposed_plan" || item.type === "todo_list" ? [String(item.planId)] : [],
524 ),
525 );
526 const visibleHandoffIds = new Set(
527 turnItems.flatMap((item) => (item.type === "handoff" ? [String(item.contextHandoffId)] : [])),
528 );
529 const plans = input.projection.plans
530 .filter((plan) => plan.status === "active" || visiblePlanIds.has(String(plan.id)))
531 .map((plan) =>
532 plan.status === "active"
533 ? plan
534 : plan.kind === "proposed_plan"
535 ? { ...plan, markdown: "", detailInTurnItem: true as const }
536 : { ...plan, explanation: undefined, detailInTurnItem: true as const },
537 );
538 const contextHandoffs = input.projection.contextHandoffs
539 .filter(
540 (handoff) =>
541 handoff.status === "pending" ||
542 handoff.status === "ready" ||
543 visibleHandoffIds.has(String(handoff.id)),
544 )
545 .map((handoff) =>
546 handoff.status === "pending" || handoff.status === "ready"
547 ? handoff
548 : { ...handoff, summaryText: "", detailInTurnItem: true as const },
549 );
550​
551 const projection = {
552 ...controlProjection,
553 plans,
554 contextHandoffs,
555 messages: messagesForBoundedProjection(controlProjection, turnItems),
556 turnItems,
557 visibleTurnItems,
558 };
559 return {
560 projection,
561 historyCursor: window.nextCursor,
562 hasMoreHistory: window.hasMoreHistory,
563 latestLocalTurnOrdinal,
564 payloadBudgetExceeded:
565 controlBytes > policy.maxEncodedBytes || bytesOfJson(projection) > policy.maxEncodedBytes,
566 };