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