@each1024/pi-model-handoff 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/package.json +51 -4
- package/src/handoff-budget.ts +1034 -0
- package/src/history-read-tool.ts +653 -0
- package/src/index.ts +393 -0
- package/src/lane-projection.ts +1039 -0
- package/src/types.ts +164 -0
- package/README.md +0 -3
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type {
|
|
3
|
+
BranchSummaryEntry,
|
|
4
|
+
CompactionEntry,
|
|
5
|
+
CustomMessageEntry,
|
|
6
|
+
SessionEntry,
|
|
7
|
+
SessionMessageEntry,
|
|
8
|
+
} from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import {
|
|
10
|
+
THREAD_READ_RESULT_MAX_BYTES,
|
|
11
|
+
type ThreadHistoryReadItem,
|
|
12
|
+
type ThreadHistoryReadParams,
|
|
13
|
+
type ThreadHistoryReadResult,
|
|
14
|
+
} from "./types.ts";
|
|
15
|
+
|
|
16
|
+
type UserMessage = Extract<AgentMessage, { role: "user" }>;
|
|
17
|
+
type AssistantMessage = Extract<AgentMessage, { role: "assistant" }>;
|
|
18
|
+
type ToolResultMessage = Extract<AgentMessage, { role: "toolResult" }>;
|
|
19
|
+
type BashExecutionMessage = Extract<AgentMessage, { role: "bashExecution" }>;
|
|
20
|
+
|
|
21
|
+
const DEFAULT_LIMIT = 10;
|
|
22
|
+
const MIN_LIMIT = 1;
|
|
23
|
+
const MAX_LIMIT = 50;
|
|
24
|
+
|
|
25
|
+
const DEFAULT_MAX_CHARS_PER_ITEM = 4_000;
|
|
26
|
+
const MIN_MAX_CHARS_PER_ITEM = 200;
|
|
27
|
+
const MAX_MAX_CHARS_PER_ITEM = 20_000;
|
|
28
|
+
|
|
29
|
+
const MESSAGE_VIEW_TYPES = new Set<string>([
|
|
30
|
+
"user_message",
|
|
31
|
+
"assistant_message",
|
|
32
|
+
"custom_message",
|
|
33
|
+
"compaction",
|
|
34
|
+
"branch_summary",
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
interface TimelineEntry {
|
|
38
|
+
position: number;
|
|
39
|
+
entryId: string;
|
|
40
|
+
runOrdinal: number;
|
|
41
|
+
type: string;
|
|
42
|
+
role: string;
|
|
43
|
+
title?: string;
|
|
44
|
+
fullText: string;
|
|
45
|
+
timestamp: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface SlicedTimelineEntry {
|
|
49
|
+
entry: TimelineEntry;
|
|
50
|
+
startOffset: number;
|
|
51
|
+
item: ThreadHistoryReadItem;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function clampInteger(
|
|
55
|
+
value: number | undefined,
|
|
56
|
+
fallback: number,
|
|
57
|
+
min: number,
|
|
58
|
+
max: number,
|
|
59
|
+
): number {
|
|
60
|
+
if (value === undefined || !Number.isFinite(value)) {
|
|
61
|
+
return fallback;
|
|
62
|
+
}
|
|
63
|
+
const intValue = Math.trunc(value);
|
|
64
|
+
return Math.min(max, Math.max(min, intValue));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function normalizeOffset(value: number | undefined): number {
|
|
68
|
+
if (value === undefined || !Number.isFinite(value)) {
|
|
69
|
+
return 0;
|
|
70
|
+
}
|
|
71
|
+
return Math.max(0, Math.trunc(value));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function parseEntryTimestamp(isoTimestamp: string, messageTimestamp?: number): number {
|
|
75
|
+
if (typeof messageTimestamp === "number" && Number.isFinite(messageTimestamp)) {
|
|
76
|
+
return messageTimestamp;
|
|
77
|
+
}
|
|
78
|
+
const parsed = Date.parse(isoTimestamp);
|
|
79
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function safeJsonStringify(value: unknown): string {
|
|
83
|
+
try {
|
|
84
|
+
return JSON.stringify(value);
|
|
85
|
+
} catch {
|
|
86
|
+
return String(value);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
91
|
+
return typeof value === "object" && value !== null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function extractContentText(content: unknown): string {
|
|
95
|
+
if (typeof content === "string") {
|
|
96
|
+
return content;
|
|
97
|
+
}
|
|
98
|
+
if (!Array.isArray(content)) {
|
|
99
|
+
return "";
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const parts: string[] = [];
|
|
103
|
+
for (const part of content) {
|
|
104
|
+
if (!isRecord(part) || typeof part.type !== "string") {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
108
|
+
if (part.text.length > 0) {
|
|
109
|
+
parts.push(part.text);
|
|
110
|
+
}
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (part.type === "image") {
|
|
114
|
+
const mime = typeof part.mimeType === "string" && part.mimeType.length > 0 ? part.mimeType : "image";
|
|
115
|
+
parts.push(`[image: ${mime}]`);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (part.type === "toolCall" && typeof part.name === "string") {
|
|
119
|
+
const args = "arguments" in part ? safeJsonStringify(part.arguments) : "{}";
|
|
120
|
+
const errSuffix =
|
|
121
|
+
typeof part.argumentsError === "string" && part.argumentsError.length > 0
|
|
122
|
+
? ` (argumentsError: ${part.argumentsError})`
|
|
123
|
+
: "";
|
|
124
|
+
parts.push(`[toolCall: ${part.name}] ${args}${errSuffix}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return parts.join("\n");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function formatAssistantText(msg: AssistantMessage): string {
|
|
131
|
+
const parts: string[] = [];
|
|
132
|
+
const body = extractContentText(msg.content);
|
|
133
|
+
if (body.length > 0) {
|
|
134
|
+
parts.push(body);
|
|
135
|
+
}
|
|
136
|
+
if (typeof msg.errorMessage === "string" && msg.errorMessage.length > 0) {
|
|
137
|
+
parts.push(`[error] ${msg.errorMessage}`);
|
|
138
|
+
} else if ((msg.stopReason === "error" || msg.stopReason === "aborted") && parts.length === 0) {
|
|
139
|
+
parts.push(`[${msg.stopReason}]`);
|
|
140
|
+
}
|
|
141
|
+
return parts.join("\n");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function formatBashExecutionText(msg: BashExecutionMessage): string {
|
|
145
|
+
let text = `Ran \`${msg.command}\`\n`;
|
|
146
|
+
if (msg.output) {
|
|
147
|
+
text += `\`\`\`\n${msg.output}\n\`\`\``;
|
|
148
|
+
} else {
|
|
149
|
+
text += "(no output)";
|
|
150
|
+
}
|
|
151
|
+
if (msg.cancelled) {
|
|
152
|
+
text += "\n\n(command cancelled)";
|
|
153
|
+
} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {
|
|
154
|
+
text += `\n\nCommand exited with code ${msg.exitCode}`;
|
|
155
|
+
}
|
|
156
|
+
if (msg.truncated) {
|
|
157
|
+
if (msg.fullOutputPath) {
|
|
158
|
+
text += `\n\n[Output truncated. Full output: ${msg.fullOutputPath}]`;
|
|
159
|
+
} else if (msg.fullOutputError) {
|
|
160
|
+
text += `\n\n[Output truncated. Could not save the full output: ${msg.fullOutputError}]`;
|
|
161
|
+
} else {
|
|
162
|
+
text += "\n\n[Output truncated]";
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (msg.excludeFromContext) {
|
|
166
|
+
text += "\n\n[Excluded from LLM context]";
|
|
167
|
+
}
|
|
168
|
+
return text;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function formatShortTitle(raw: string, maxLength = 120): string | undefined {
|
|
172
|
+
const firstLine = raw.split(/\r?\n/, 1)[0]?.trim() ?? "";
|
|
173
|
+
if (firstLine.length === 0) {
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
if (firstLine.length <= maxLength) {
|
|
177
|
+
return firstLine;
|
|
178
|
+
}
|
|
179
|
+
return `${firstLine.slice(0, maxLength - 3)}...`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function mapMessageEntry(
|
|
183
|
+
entry: SessionMessageEntry,
|
|
184
|
+
position: number,
|
|
185
|
+
runOrdinal: number,
|
|
186
|
+
): TimelineEntry | null {
|
|
187
|
+
const msg = entry.message;
|
|
188
|
+
|
|
189
|
+
switch (msg.role) {
|
|
190
|
+
case "user": {
|
|
191
|
+
const userMsg = msg as UserMessage;
|
|
192
|
+
return {
|
|
193
|
+
position,
|
|
194
|
+
entryId: entry.id,
|
|
195
|
+
runOrdinal,
|
|
196
|
+
type: "user_message",
|
|
197
|
+
role: "user",
|
|
198
|
+
fullText: extractContentText(userMsg.content),
|
|
199
|
+
timestamp: parseEntryTimestamp(entry.timestamp, userMsg.timestamp),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
case "assistant": {
|
|
203
|
+
const assistantMsg = msg as AssistantMessage;
|
|
204
|
+
const modelTitle =
|
|
205
|
+
typeof assistantMsg.model === "string" && assistantMsg.model.length > 0
|
|
206
|
+
? assistantMsg.provider
|
|
207
|
+
? `${assistantMsg.provider}/${assistantMsg.model}`
|
|
208
|
+
: assistantMsg.model
|
|
209
|
+
: undefined;
|
|
210
|
+
return {
|
|
211
|
+
position,
|
|
212
|
+
entryId: entry.id,
|
|
213
|
+
runOrdinal,
|
|
214
|
+
type: "assistant_message",
|
|
215
|
+
role: "assistant",
|
|
216
|
+
title: modelTitle,
|
|
217
|
+
fullText: formatAssistantText(assistantMsg),
|
|
218
|
+
timestamp: parseEntryTimestamp(entry.timestamp, assistantMsg.timestamp),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
case "toolResult": {
|
|
222
|
+
const toolMsg = msg as ToolResultMessage;
|
|
223
|
+
const body = extractContentText(toolMsg.content);
|
|
224
|
+
const fullText = toolMsg.isError
|
|
225
|
+
? body.length > 0
|
|
226
|
+
? `[error] ${body}`
|
|
227
|
+
: "[error]"
|
|
228
|
+
: body;
|
|
229
|
+
return {
|
|
230
|
+
position,
|
|
231
|
+
entryId: entry.id,
|
|
232
|
+
runOrdinal,
|
|
233
|
+
type: "tool_result",
|
|
234
|
+
role: "toolResult",
|
|
235
|
+
title: toolMsg.isError ? `${toolMsg.toolName} (error)` : toolMsg.toolName,
|
|
236
|
+
fullText,
|
|
237
|
+
timestamp: parseEntryTimestamp(entry.timestamp, toolMsg.timestamp),
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
case "bashExecution": {
|
|
241
|
+
const bashMsg = msg as BashExecutionMessage;
|
|
242
|
+
return {
|
|
243
|
+
position,
|
|
244
|
+
entryId: entry.id,
|
|
245
|
+
runOrdinal,
|
|
246
|
+
type: "bash_execution",
|
|
247
|
+
role: "bashExecution",
|
|
248
|
+
title: formatShortTitle(bashMsg.command),
|
|
249
|
+
fullText: formatBashExecutionText(bashMsg),
|
|
250
|
+
timestamp: parseEntryTimestamp(entry.timestamp, bashMsg.timestamp),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
default:
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function mapCustomMessageEntry(
|
|
259
|
+
entry: CustomMessageEntry,
|
|
260
|
+
position: number,
|
|
261
|
+
runOrdinal: number,
|
|
262
|
+
): TimelineEntry {
|
|
263
|
+
return {
|
|
264
|
+
position,
|
|
265
|
+
entryId: entry.id,
|
|
266
|
+
runOrdinal,
|
|
267
|
+
type: "custom_message",
|
|
268
|
+
role: "custom",
|
|
269
|
+
title: entry.customType,
|
|
270
|
+
fullText: extractContentText(entry.content),
|
|
271
|
+
timestamp: parseEntryTimestamp(entry.timestamp),
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function mapCompactionEntry(
|
|
276
|
+
entry: CompactionEntry,
|
|
277
|
+
position: number,
|
|
278
|
+
runOrdinal: number,
|
|
279
|
+
): TimelineEntry {
|
|
280
|
+
return {
|
|
281
|
+
position,
|
|
282
|
+
entryId: entry.id,
|
|
283
|
+
runOrdinal,
|
|
284
|
+
type: "compaction",
|
|
285
|
+
role: "system",
|
|
286
|
+
title: "Compaction summary",
|
|
287
|
+
fullText: entry.summary,
|
|
288
|
+
timestamp: parseEntryTimestamp(entry.timestamp),
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function mapBranchSummaryEntry(
|
|
293
|
+
entry: BranchSummaryEntry,
|
|
294
|
+
position: number,
|
|
295
|
+
runOrdinal: number,
|
|
296
|
+
): TimelineEntry {
|
|
297
|
+
return {
|
|
298
|
+
position,
|
|
299
|
+
entryId: entry.id,
|
|
300
|
+
runOrdinal,
|
|
301
|
+
type: "branch_summary",
|
|
302
|
+
role: "system",
|
|
303
|
+
title: "Branch summary",
|
|
304
|
+
fullText: entry.summary,
|
|
305
|
+
timestamp: parseEntryTimestamp(entry.timestamp),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Build a 0-based chronological timeline of all readable entries on a branch. */
|
|
310
|
+
function buildTimeline(branch: readonly SessionEntry[]): TimelineEntry[] {
|
|
311
|
+
const timeline: TimelineEntry[] = [];
|
|
312
|
+
let currentRunOrdinal = 0;
|
|
313
|
+
|
|
314
|
+
for (const entry of branch) {
|
|
315
|
+
if (entry.type === "message") {
|
|
316
|
+
if (entry.message.role === "user") {
|
|
317
|
+
currentRunOrdinal += 1;
|
|
318
|
+
}
|
|
319
|
+
const mapped = mapMessageEntry(entry, timeline.length, currentRunOrdinal);
|
|
320
|
+
if (mapped !== null) {
|
|
321
|
+
timeline.push(mapped);
|
|
322
|
+
}
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (entry.type === "custom_message") {
|
|
327
|
+
timeline.push(mapCustomMessageEntry(entry, timeline.length, currentRunOrdinal));
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
if (entry.type === "compaction") {
|
|
332
|
+
timeline.push(mapCompactionEntry(entry, timeline.length, currentRunOrdinal));
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (entry.type === "branch_summary") {
|
|
337
|
+
timeline.push(mapBranchSummaryEntry(entry, timeline.length, currentRunOrdinal));
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
return timeline;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function isHighSurrogate(code: number): boolean {
|
|
345
|
+
return code >= 0xd800 && code <= 0xdbff;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function isLowSurrogate(code: number): boolean {
|
|
349
|
+
return code >= 0xdc00 && code <= 0xdfff;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function adjustStartOffset(text: string, offset: number): number {
|
|
353
|
+
if (offset <= 0 || offset >= text.length) {
|
|
354
|
+
return offset;
|
|
355
|
+
}
|
|
356
|
+
if (isLowSurrogate(text.charCodeAt(offset)) && isHighSurrogate(text.charCodeAt(offset - 1))) {
|
|
357
|
+
return offset + 1;
|
|
358
|
+
}
|
|
359
|
+
return offset;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function adjustEndOffset(text: string, start: number, end: number): number {
|
|
363
|
+
if (end <= start || end >= text.length) {
|
|
364
|
+
return Math.min(text.length, Math.max(start, end));
|
|
365
|
+
}
|
|
366
|
+
if (isHighSurrogate(text.charCodeAt(end - 1)) && isLowSurrogate(text.charCodeAt(end))) {
|
|
367
|
+
return end - 1 > start ? end - 1 : end;
|
|
368
|
+
}
|
|
369
|
+
return end;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function sliceTimelineEntry(
|
|
373
|
+
entry: TimelineEntry,
|
|
374
|
+
rawOffset: number,
|
|
375
|
+
maxChars: number,
|
|
376
|
+
): SlicedTimelineEntry {
|
|
377
|
+
const fullText = entry.fullText;
|
|
378
|
+
const startOffset = adjustStartOffset(fullText, Math.max(0, rawOffset));
|
|
379
|
+
|
|
380
|
+
let text = "";
|
|
381
|
+
let textTruncated = false;
|
|
382
|
+
let nextTextOffset: number | null = null;
|
|
383
|
+
|
|
384
|
+
if (startOffset < fullText.length) {
|
|
385
|
+
const endOffset = adjustEndOffset(fullText, startOffset, startOffset + maxChars);
|
|
386
|
+
text = fullText.slice(startOffset, endOffset);
|
|
387
|
+
textTruncated = endOffset < fullText.length;
|
|
388
|
+
nextTextOffset = textTruncated ? endOffset : null;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const item: ThreadHistoryReadItem = {
|
|
392
|
+
position: entry.position,
|
|
393
|
+
entryId: entry.entryId,
|
|
394
|
+
runOrdinal: entry.runOrdinal,
|
|
395
|
+
type: entry.type,
|
|
396
|
+
role: entry.role,
|
|
397
|
+
...(entry.title !== undefined ? { title: entry.title } : {}),
|
|
398
|
+
text,
|
|
399
|
+
textTruncated,
|
|
400
|
+
nextTextOffset,
|
|
401
|
+
timestamp: entry.timestamp,
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
return { entry, startOffset, item };
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function utf8ByteLength(text: string): number {
|
|
408
|
+
return Buffer.byteLength(text, "utf8");
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function computePaginationState(
|
|
412
|
+
referenceList: readonly TimelineEntry[],
|
|
413
|
+
selectedItems: readonly ThreadHistoryReadItem[],
|
|
414
|
+
mode: "entry" | "forward" | "backward" | "latest",
|
|
415
|
+
): {
|
|
416
|
+
earlierPosition: number | null;
|
|
417
|
+
nextPosition: number | null;
|
|
418
|
+
hasMore: boolean;
|
|
419
|
+
} {
|
|
420
|
+
if (selectedItems.length === 0) {
|
|
421
|
+
return { earlierPosition: null, nextPosition: null, hasMore: false };
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const firstPos = selectedItems[0].position;
|
|
425
|
+
const lastPos = selectedItems[selectedItems.length - 1].position;
|
|
426
|
+
const hasEarlier = referenceList.some((entry) => entry.position < firstPos);
|
|
427
|
+
const hasLater = referenceList.some((entry) => entry.position > lastPos);
|
|
428
|
+
|
|
429
|
+
const earlierPosition = hasEarlier ? firstPos : null;
|
|
430
|
+
const nextPosition = hasLater ? lastPos : null;
|
|
431
|
+
|
|
432
|
+
let hasMore = false;
|
|
433
|
+
if (mode === "entry") {
|
|
434
|
+
hasMore = selectedItems[0].textTruncated;
|
|
435
|
+
} else if (mode === "forward") {
|
|
436
|
+
hasMore = hasLater;
|
|
437
|
+
} else {
|
|
438
|
+
hasMore = hasEarlier;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
return { earlierPosition, nextPosition, hasMore };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function measureResultBytes(result: ThreadHistoryReadResult): {
|
|
445
|
+
formattedBytes: number;
|
|
446
|
+
maxBytes: number;
|
|
447
|
+
} {
|
|
448
|
+
const formattedBytes = utf8ByteLength(formatHistoryReadText(result));
|
|
449
|
+
const withByteLength: ThreadHistoryReadResult = {
|
|
450
|
+
...result,
|
|
451
|
+
byteLength: formattedBytes,
|
|
452
|
+
};
|
|
453
|
+
const jsonBytes = utf8ByteLength(JSON.stringify(withByteLength));
|
|
454
|
+
return {
|
|
455
|
+
formattedBytes,
|
|
456
|
+
maxBytes: Math.max(formattedBytes, jsonBytes),
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function buildResultFromSlices(
|
|
461
|
+
totalItems: number,
|
|
462
|
+
referenceList: readonly TimelineEntry[],
|
|
463
|
+
slices: readonly SlicedTimelineEntry[],
|
|
464
|
+
mode: "entry" | "forward" | "backward" | "latest",
|
|
465
|
+
): ThreadHistoryReadResult {
|
|
466
|
+
const items = slices.map((slice) => slice.item);
|
|
467
|
+
const pagination = computePaginationState(referenceList, items, mode);
|
|
468
|
+
return {
|
|
469
|
+
totalItems,
|
|
470
|
+
items,
|
|
471
|
+
nextPosition: pagination.nextPosition,
|
|
472
|
+
earlierPosition: pagination.earlierPosition,
|
|
473
|
+
hasMore: pagination.hasMore,
|
|
474
|
+
byteLength: 0,
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function enforceByteLimit(
|
|
479
|
+
totalItems: number,
|
|
480
|
+
referenceList: readonly TimelineEntry[],
|
|
481
|
+
initialSlices: SlicedTimelineEntry[],
|
|
482
|
+
mode: "entry" | "forward" | "backward" | "latest",
|
|
483
|
+
): ThreadHistoryReadResult {
|
|
484
|
+
const slices = [...initialSlices];
|
|
485
|
+
let result = buildResultFromSlices(totalItems, referenceList, slices, mode);
|
|
486
|
+
let { formattedBytes, maxBytes } = measureResultBytes(result);
|
|
487
|
+
|
|
488
|
+
// Drop overflow items while keeping at least 1 item when non-empty.
|
|
489
|
+
while (slices.length > 1 && maxBytes > THREAD_READ_RESULT_MAX_BYTES) {
|
|
490
|
+
if (mode === "forward") {
|
|
491
|
+
slices.pop();
|
|
492
|
+
} else {
|
|
493
|
+
slices.shift();
|
|
494
|
+
}
|
|
495
|
+
result = buildResultFromSlices(totalItems, referenceList, slices, mode);
|
|
496
|
+
({ formattedBytes, maxBytes } = measureResultBytes(result));
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// Safely truncate the single remaining item if it still exceeds the 30,000-byte cap.
|
|
500
|
+
if (slices.length === 1 && maxBytes > THREAD_READ_RESULT_MAX_BYTES) {
|
|
501
|
+
const target = slices[0];
|
|
502
|
+
const fullText = target.entry.fullText;
|
|
503
|
+
const startOffset = target.startOffset;
|
|
504
|
+
|
|
505
|
+
let low = 0;
|
|
506
|
+
let high = target.item.text.length;
|
|
507
|
+
let bestEnd = startOffset;
|
|
508
|
+
|
|
509
|
+
while (low <= high) {
|
|
510
|
+
const mid = (low + high) >> 1;
|
|
511
|
+
const candidateEnd = adjustEndOffset(fullText, startOffset, startOffset + mid);
|
|
512
|
+
const candidateText = fullText.slice(startOffset, candidateEnd);
|
|
513
|
+
const candidateTruncated = candidateEnd < fullText.length;
|
|
514
|
+
const candidateItem: ThreadHistoryReadItem = {
|
|
515
|
+
...target.item,
|
|
516
|
+
text: candidateText,
|
|
517
|
+
textTruncated: candidateTruncated,
|
|
518
|
+
nextTextOffset: candidateTruncated ? candidateEnd : null,
|
|
519
|
+
};
|
|
520
|
+
const candidateResult = buildResultFromSlices(
|
|
521
|
+
totalItems,
|
|
522
|
+
referenceList,
|
|
523
|
+
[{ entry: target.entry, startOffset, item: candidateItem }],
|
|
524
|
+
mode,
|
|
525
|
+
);
|
|
526
|
+
const measured = measureResultBytes(candidateResult);
|
|
527
|
+
if (measured.maxBytes <= THREAD_READ_RESULT_MAX_BYTES) {
|
|
528
|
+
bestEnd = candidateEnd;
|
|
529
|
+
low = mid + 1;
|
|
530
|
+
} else {
|
|
531
|
+
high = mid - 1;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const finalText = fullText.slice(startOffset, bestEnd);
|
|
536
|
+
const finalTruncated = bestEnd < fullText.length;
|
|
537
|
+
slices[0] = {
|
|
538
|
+
entry: target.entry,
|
|
539
|
+
startOffset,
|
|
540
|
+
item: {
|
|
541
|
+
...target.item,
|
|
542
|
+
text: finalText,
|
|
543
|
+
textTruncated: finalTruncated,
|
|
544
|
+
nextTextOffset: finalTruncated ? bestEnd : null,
|
|
545
|
+
},
|
|
546
|
+
};
|
|
547
|
+
result = buildResultFromSlices(totalItems, referenceList, slices, mode);
|
|
548
|
+
({ formattedBytes } = measureResultBytes(result));
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
return {
|
|
552
|
+
...result,
|
|
553
|
+
byteLength: formattedBytes,
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Read and paginate readable history entries from a session branch.
|
|
559
|
+
*
|
|
560
|
+
* When `params.entryId` is specified, `view` is ignored and the matching entry
|
|
561
|
+
* is sliced by `textOffset` and `maxCharsPerItem`. Otherwise entries are
|
|
562
|
+
* filtered by `view` (`"messages"` by default, or `"activity"`) and paginated
|
|
563
|
+
* in chronological order.
|
|
564
|
+
*/
|
|
565
|
+
export function readBranchHistory(
|
|
566
|
+
branch: readonly SessionEntry[],
|
|
567
|
+
params: ThreadHistoryReadParams = {},
|
|
568
|
+
): ThreadHistoryReadResult {
|
|
569
|
+
const timeline = buildTimeline(branch);
|
|
570
|
+
const totalItems = timeline.length;
|
|
571
|
+
const maxCharsPerItem = clampInteger(
|
|
572
|
+
params.maxCharsPerItem,
|
|
573
|
+
DEFAULT_MAX_CHARS_PER_ITEM,
|
|
574
|
+
MIN_MAX_CHARS_PER_ITEM,
|
|
575
|
+
MAX_MAX_CHARS_PER_ITEM,
|
|
576
|
+
);
|
|
577
|
+
|
|
578
|
+
if (typeof params.entryId === "string" && params.entryId.length > 0) {
|
|
579
|
+
const matched = timeline.find((entry) => entry.entryId === params.entryId);
|
|
580
|
+
if (!matched) {
|
|
581
|
+
return enforceByteLimit(totalItems, timeline, [], "entry");
|
|
582
|
+
}
|
|
583
|
+
const textOffset = normalizeOffset(params.textOffset);
|
|
584
|
+
const sliced = sliceTimelineEntry(matched, textOffset, maxCharsPerItem);
|
|
585
|
+
return enforceByteLimit(totalItems, timeline, [sliced], "entry");
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const view = params.view === "activity" ? "activity" : "messages";
|
|
589
|
+
const filtered =
|
|
590
|
+
view === "activity"
|
|
591
|
+
? timeline
|
|
592
|
+
: timeline.filter((entry) => MESSAGE_VIEW_TYPES.has(entry.type));
|
|
593
|
+
|
|
594
|
+
const limit = clampInteger(params.limit, DEFAULT_LIMIT, MIN_LIMIT, MAX_LIMIT);
|
|
595
|
+
const hasAfter =
|
|
596
|
+
params.afterPosition !== undefined && Number.isFinite(params.afterPosition);
|
|
597
|
+
const hasBefore =
|
|
598
|
+
params.beforePosition !== undefined && Number.isFinite(params.beforePosition);
|
|
599
|
+
|
|
600
|
+
let candidates = filtered;
|
|
601
|
+
if (hasAfter) {
|
|
602
|
+
const afterPos = Math.trunc(params.afterPosition as number);
|
|
603
|
+
candidates = candidates.filter((entry) => entry.position > afterPos);
|
|
604
|
+
}
|
|
605
|
+
if (hasBefore) {
|
|
606
|
+
const beforePos = Math.trunc(params.beforePosition as number);
|
|
607
|
+
candidates = candidates.filter((entry) => entry.position < beforePos);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const mode: "forward" | "backward" | "latest" = hasAfter
|
|
611
|
+
? "forward"
|
|
612
|
+
: hasBefore
|
|
613
|
+
? "backward"
|
|
614
|
+
: "latest";
|
|
615
|
+
|
|
616
|
+
const selected =
|
|
617
|
+
mode === "forward" ? candidates.slice(0, limit) : candidates.slice(-limit);
|
|
618
|
+
const sliced = selected.map((entry) => sliceTimelineEntry(entry, 0, maxCharsPerItem));
|
|
619
|
+
|
|
620
|
+
return enforceByteLimit(totalItems, filtered, sliced, mode);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
function formatTimestamp(timestamp: number): string {
|
|
624
|
+
if (!Number.isFinite(timestamp) || timestamp <= 0) {
|
|
625
|
+
return "unknown";
|
|
626
|
+
}
|
|
627
|
+
return new Date(timestamp).toISOString();
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** Format a `ThreadHistoryReadResult` into a readable text block for model consumption. */
|
|
631
|
+
export function formatHistoryReadText(result: ThreadHistoryReadResult): string {
|
|
632
|
+
if (result.items.length === 0) {
|
|
633
|
+
return `No matching history entries (totalItems=${result.totalItems}).`;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const header = [
|
|
637
|
+
`History (${result.items.length} of ${result.totalItems} total items`,
|
|
638
|
+
`hasMore=${result.hasMore}`,
|
|
639
|
+
`earlierPosition=${result.earlierPosition ?? "null"}`,
|
|
640
|
+
`nextPosition=${result.nextPosition ?? "null"})`,
|
|
641
|
+
].join("; ");
|
|
642
|
+
|
|
643
|
+
const blocks = result.items.map((item) => {
|
|
644
|
+
const titlePart = item.title ? ` title=${JSON.stringify(item.title)}` : "";
|
|
645
|
+
const meta = `[${item.position}] entryId=${item.entryId} run=${item.runOrdinal} type=${item.type} role=${item.role}${titlePart} ts=${formatTimestamp(item.timestamp)}`;
|
|
646
|
+
const truncationNote = item.textTruncated
|
|
647
|
+
? `\n...[truncated; nextTextOffset=${item.nextTextOffset}]`
|
|
648
|
+
: "";
|
|
649
|
+
return `${meta}\n${item.text}${truncationNote}`;
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
return `${header}\n\n${blocks.join("\n\n")}`;
|
|
653
|
+
}
|