@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.
@@ -0,0 +1,1034 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type {
3
+ AssistantMessage,
4
+ ImageContent,
5
+ TextContent,
6
+ ToolCall,
7
+ ToolResultMessage,
8
+ UserMessage,
9
+ } from "@earendil-works/pi-ai";
10
+ import type {
11
+ BranchSummaryEntry,
12
+ CompactionEntry,
13
+ SessionEntry,
14
+ SessionMessageEntry,
15
+ } from "@earendil-works/pi-coding-agent";
16
+ import {
17
+ type BudgetInput,
18
+ type BudgetResult,
19
+ type ConversationRun,
20
+ DEFAULT_HANDOFF_TOKEN_CAP,
21
+ HANDOFF_BYTE_CAP,
22
+ HANDOFF_ENTRY_TYPE,
23
+ type HistoricalItem,
24
+ type LaneKey,
25
+ MAX_HANDOFF_TOKEN_CAP,
26
+ MAX_LISTED_OMITTED_ITEMS,
27
+ MIN_HANDOFF_TOKEN_CAP,
28
+ type SelectAndRenderHandoffInput,
29
+ type SelectionResult,
30
+ TOOL_NAME_HISTORY_READ,
31
+ } from "./types.ts";
32
+
33
+ const DEFAULT_WINDOW_TOKENS = 128_000;
34
+ const IMAGE_ATTACHMENT_TOKEN_COST = 8_192;
35
+ const OTHER_ATTACHMENT_TOKEN_COST = 4_096;
36
+ const MIN_WORK_RESERVE_TOKENS = 16_000;
37
+ const IMAGE_NOT_REPLAYED_NOTE = "[image attachment not replayed]";
38
+ const MAX_COMMAND_CHARS = 300;
39
+ const MAX_COMMAND_OUTPUT_CHARS = 1_200;
40
+ const MAX_ERROR_CHARS = 1_200;
41
+ const MIN_ANCHOR_TRUNCATE_BYTES = 160;
42
+
43
+ /** Build a canonical per-model lane key from provider and model ID. */
44
+ export function laneKeyFromModel(provider: string, modelId: string): LaneKey {
45
+ return `${provider.trim()}/${modelId.trim()}`;
46
+ }
47
+
48
+ /** Parse and clamp the handoff token cap from an explicit or environment value. */
49
+ export function resolveTokenCap(envCap?: string | number): number {
50
+ const raw = envCap ?? process.env.PI_MODEL_HANDOFF_TOKEN_CAP;
51
+ if (raw === undefined) {
52
+ return DEFAULT_HANDOFF_TOKEN_CAP;
53
+ }
54
+
55
+ let parsed: number;
56
+ if (typeof raw === "number") {
57
+ parsed = raw;
58
+ } else {
59
+ const trimmed = raw.trim();
60
+ if (trimmed.length === 0) {
61
+ return DEFAULT_HANDOFF_TOKEN_CAP;
62
+ }
63
+ parsed = Number(trimmed);
64
+ }
65
+
66
+ if (!Number.isFinite(parsed) || parsed <= 0) {
67
+ return DEFAULT_HANDOFF_TOKEN_CAP;
68
+ }
69
+
70
+ const floored = Math.floor(parsed);
71
+ return Math.min(MAX_HANDOFF_TOKEN_CAP, Math.max(MIN_HANDOFF_TOKEN_CAP, floored));
72
+ }
73
+
74
+ /** Conservatively estimate token count from text UTF-8 byte length (ceil(bytes / 4)). */
75
+ export function estimateTextTokens(text: string): number {
76
+ if (typeof text !== "string" || text.length === 0) {
77
+ return 0;
78
+ }
79
+ return Math.ceil(Buffer.byteLength(text, "utf8") / 4);
80
+ }
81
+
82
+ /** Compute the handoff byte budget and context reserve. */
83
+ export function computeHandoffBudget(input: BudgetInput): BudgetResult {
84
+ const windowTokens =
85
+ input.modelContextWindow !== undefined &&
86
+ Number.isFinite(input.modelContextWindow) &&
87
+ input.modelContextWindow > 0
88
+ ? Math.floor(input.modelContextWindow)
89
+ : DEFAULT_WINDOW_TOKENS;
90
+
91
+ const nativeTokens =
92
+ Number.isFinite(input.nativeTokens) && input.nativeTokens > 0
93
+ ? Math.floor(input.nativeTokens)
94
+ : 0;
95
+
96
+ const currentTextTokens = estimateTextTokens(
97
+ JSON.stringify(input.currentUserText ?? "") ?? "",
98
+ );
99
+ const imageCount =
100
+ input.currentImageCount !== undefined &&
101
+ Number.isFinite(input.currentImageCount) &&
102
+ input.currentImageCount > 0
103
+ ? Math.floor(input.currentImageCount)
104
+ : 0;
105
+ const otherAttachmentCount =
106
+ input.currentOtherAttachmentCount !== undefined &&
107
+ Number.isFinite(input.currentOtherAttachmentCount) &&
108
+ input.currentOtherAttachmentCount > 0
109
+ ? Math.floor(input.currentOtherAttachmentCount)
110
+ : 0;
111
+
112
+ const currentTokens =
113
+ currentTextTokens +
114
+ imageCount * IMAGE_ATTACHMENT_TOKEN_COST +
115
+ otherAttachmentCount * OTHER_ATTACHMENT_TOKEN_COST;
116
+
117
+ const workReserveTokens = Math.min(
118
+ Math.max(MIN_WORK_RESERVE_TOKENS, Math.ceil(windowTokens / 4)),
119
+ Math.ceil(windowTokens / 2),
120
+ );
121
+
122
+ const tokenCap =
123
+ Number.isFinite(input.tokenCap) && input.tokenCap > 0
124
+ ? Math.floor(input.tokenCap)
125
+ : 0;
126
+
127
+ const availableTokens = Math.max(
128
+ 0,
129
+ windowTokens - nativeTokens - currentTokens - workReserveTokens,
130
+ );
131
+ const budgetTokens = Math.max(0, Math.min(tokenCap, availableTokens));
132
+ const budgetBytes = Math.min(budgetTokens * 4, HANDOFF_BYTE_CAP);
133
+
134
+ return {
135
+ budgetBytes,
136
+ windowTokens,
137
+ workReserveTokens,
138
+ nativeTokens,
139
+ currentTokens,
140
+ };
141
+ }
142
+
143
+ function parseTimestamp(value: string | number | undefined): number {
144
+ if (typeof value === "number" && Number.isFinite(value)) {
145
+ return value;
146
+ }
147
+ if (typeof value === "string") {
148
+ const parsed = Date.parse(value);
149
+ if (Number.isFinite(parsed)) {
150
+ return parsed;
151
+ }
152
+ }
153
+ return 0;
154
+ }
155
+
156
+ function truncateMiddle(text: string, maxChars: number): string {
157
+ if (typeof text !== "string") {
158
+ return "";
159
+ }
160
+ const trimmed = text.trim();
161
+ if (trimmed.length <= maxChars) {
162
+ return trimmed;
163
+ }
164
+ if (maxChars <= 32) {
165
+ return trimmed.slice(0, Math.max(0, maxChars));
166
+ }
167
+ const marker = "\n... [truncated] ...\n";
168
+ const budget = maxChars - marker.length;
169
+ const headLen = Math.ceil(budget / 2);
170
+ const tailLen = Math.floor(budget / 2);
171
+ return `${trimmed.slice(0, headLen)}${marker}${trimmed.slice(trimmed.length - tailLen)}`;
172
+ }
173
+
174
+ function extractTextAndImageFlag(
175
+ content: string | readonly (TextContent | ImageContent)[] | null | undefined,
176
+ ): { text: string; hasImage: boolean } {
177
+ if (typeof content === "string") {
178
+ return { text: content.trim(), hasImage: false };
179
+ }
180
+ if (!Array.isArray(content)) {
181
+ return { text: "", hasImage: false };
182
+ }
183
+ const textParts: string[] = [];
184
+ let hasImage = false;
185
+ for (const block of content) {
186
+ if (!block || typeof block !== "object") {
187
+ continue;
188
+ }
189
+ if (block.type === "text") {
190
+ if (typeof block.text === "string" && block.text.trim().length > 0) {
191
+ textParts.push(block.text.trim());
192
+ }
193
+ } else if (block.type === "image") {
194
+ hasImage = true;
195
+ }
196
+ }
197
+ return {
198
+ text: textParts.join("\n"),
199
+ hasImage,
200
+ };
201
+ }
202
+
203
+ function formatUserLikeText(
204
+ content: string | readonly (TextContent | ImageContent)[] | null | undefined,
205
+ ): string {
206
+ const { text, hasImage } = extractTextAndImageFlag(content);
207
+ if (hasImage) {
208
+ return text.length > 0
209
+ ? `${text}\n${IMAGE_NOT_REPLAYED_NOTE}`
210
+ : IMAGE_NOT_REPLAYED_NOTE;
211
+ }
212
+ return text;
213
+ }
214
+
215
+ function extractToolResultText(msg: ToolResultMessage): string {
216
+ const { text, hasImage } = extractTextAndImageFlag(msg?.content);
217
+ if (hasImage) {
218
+ return text.length > 0
219
+ ? `${text}\n${IMAGE_NOT_REPLAYED_NOTE}`
220
+ : IMAGE_NOT_REPLAYED_NOTE;
221
+ }
222
+ return text;
223
+ }
224
+
225
+ function extractStringArg(call: ToolCall, key: string): string | null {
226
+ const args = call?.arguments as unknown;
227
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
228
+ return null;
229
+ }
230
+ const value = (args as Record<string, unknown>)[key];
231
+ if (typeof value === "string" && value.trim().length > 0) {
232
+ return value.trim();
233
+ }
234
+ return null;
235
+ }
236
+
237
+ function extractSummaryEntry(
238
+ entry: CompactionEntry | BranchSummaryEntry,
239
+ runOrdinal: number,
240
+ items: HistoricalItem[],
241
+ ): void {
242
+ const text = typeof entry.summary === "string" ? entry.summary.trim() : "";
243
+ if (text.length === 0) {
244
+ return;
245
+ }
246
+ const isCompaction = entry.type === "compaction";
247
+ items.push({
248
+ entryId: entry.id,
249
+ runOrdinal,
250
+ position: items.length,
251
+ role: "user",
252
+ kind: isCompaction ? "compaction_summary" : "branch_summary",
253
+ title: isCompaction ? "Compaction summary" : "Branch summary",
254
+ text,
255
+ timestamp: parseTimestamp(entry.timestamp),
256
+ });
257
+ }
258
+
259
+ function appendMessageItems(
260
+ entry: SessionMessageEntry,
261
+ runOrdinal: number,
262
+ toolResultsByCallId: ReadonlyMap<
263
+ string,
264
+ { entry: SessionMessageEntry; msg: ToolResultMessage }
265
+ >,
266
+ handledToolCallIds: Set<string>,
267
+ items: HistoricalItem[],
268
+ ): void {
269
+ const message = entry?.message as AgentMessage | null | undefined;
270
+ if (!message || typeof message !== "object") {
271
+ return;
272
+ }
273
+ const entryTs = parseTimestamp(entry.timestamp);
274
+
275
+ switch (message.role) {
276
+ case "user": {
277
+ const userMsg = message as UserMessage;
278
+ const text = formatUserLikeText(userMsg.content);
279
+ if (text.length > 0) {
280
+ items.push({
281
+ entryId: entry.id,
282
+ runOrdinal,
283
+ position: items.length,
284
+ role: "user",
285
+ kind: "user_message",
286
+ text,
287
+ timestamp: userMsg.timestamp > 0 ? userMsg.timestamp : entryTs,
288
+ });
289
+ }
290
+ return;
291
+ }
292
+
293
+ case "custom": {
294
+ if (message.customType === HANDOFF_ENTRY_TYPE) {
295
+ return;
296
+ }
297
+ const text = formatUserLikeText(message.content);
298
+ if (text.length > 0) {
299
+ items.push({
300
+ entryId: entry.id,
301
+ runOrdinal,
302
+ position: items.length,
303
+ role: "user",
304
+ kind: "user_message",
305
+ text,
306
+ timestamp: message.timestamp > 0 ? message.timestamp : entryTs,
307
+ });
308
+ }
309
+ return;
310
+ }
311
+
312
+ case "compactionSummary": {
313
+ const text = typeof message.summary === "string" ? message.summary.trim() : "";
314
+ if (text.length > 0) {
315
+ items.push({
316
+ entryId: entry.id,
317
+ runOrdinal,
318
+ position: items.length,
319
+ role: "user",
320
+ kind: "compaction_summary",
321
+ title: "Compaction summary",
322
+ text,
323
+ timestamp: message.timestamp > 0 ? message.timestamp : entryTs,
324
+ });
325
+ }
326
+ return;
327
+ }
328
+
329
+ case "branchSummary": {
330
+ const text = typeof message.summary === "string" ? message.summary.trim() : "";
331
+ if (text.length > 0) {
332
+ items.push({
333
+ entryId: entry.id,
334
+ runOrdinal,
335
+ position: items.length,
336
+ role: "user",
337
+ kind: "branch_summary",
338
+ title: "Branch summary",
339
+ text,
340
+ timestamp: message.timestamp > 0 ? message.timestamp : entryTs,
341
+ });
342
+ }
343
+ return;
344
+ }
345
+
346
+ case "bashExecution": {
347
+ if (message.excludeFromContext) {
348
+ return;
349
+ }
350
+ const command = truncateMiddle(message.command, MAX_COMMAND_CHARS);
351
+ const output = truncateMiddle(message.output, MAX_COMMAND_OUTPUT_CHARS);
352
+ const statusParts: string[] = [];
353
+ if (message.cancelled) {
354
+ statusParts.push("cancelled");
355
+ } else if (message.exitCode !== undefined && message.exitCode !== 0) {
356
+ statusParts.push(`exit ${message.exitCode}`);
357
+ }
358
+ const statusSuffix =
359
+ statusParts.length > 0 ? ` [${statusParts.join(", ")}]` : "";
360
+ const body = output.length > 0 ? `$ ${command}${statusSuffix}\n${output}` : `$ ${command}${statusSuffix}`;
361
+ items.push({
362
+ entryId: entry.id,
363
+ runOrdinal,
364
+ position: items.length,
365
+ role: "user",
366
+ kind: "command_execution",
367
+ title: command,
368
+ text: body,
369
+ timestamp: message.timestamp > 0 ? message.timestamp : entryTs,
370
+ });
371
+ return;
372
+ }
373
+
374
+ case "assistant": {
375
+ const assistantMsg = message as AssistantMessage;
376
+ const msgTs =
377
+ assistantMsg.timestamp > 0 ? assistantMsg.timestamp : entryTs;
378
+
379
+ const visibleTexts: string[] = [];
380
+ const fileChangeLines: string[] = [];
381
+ const seenFileChanges = new Set<string>();
382
+ const bashCalls: ToolCall[] = [];
383
+
384
+ const rawContent: unknown = assistantMsg.content;
385
+ if (typeof rawContent === "string") {
386
+ const trimmed = rawContent.trim();
387
+ if (trimmed.length > 0) {
388
+ visibleTexts.push(trimmed);
389
+ }
390
+ } else if (Array.isArray(rawContent)) {
391
+ for (const block of rawContent) {
392
+ if (!block || typeof block !== "object") {
393
+ continue;
394
+ }
395
+ if (block.type === "thinking") {
396
+ continue;
397
+ }
398
+ if (block.type === "text") {
399
+ if (typeof block.text === "string" && block.text.trim().length > 0) {
400
+ visibleTexts.push(block.text.trim());
401
+ }
402
+ continue;
403
+ }
404
+ if (block.type === "toolCall") {
405
+ if (block.name === "edit" || block.name === "write") {
406
+ const callId = typeof block.id === "string" ? block.id : "";
407
+ const paired = callId.length > 0 ? toolResultsByCallId.get(callId) : undefined;
408
+ if (paired?.msg.isError) {
409
+ continue;
410
+ }
411
+ const filePath = extractStringArg(block, "path");
412
+ if (filePath !== null) {
413
+ const line = `${block.name}: ${filePath}`;
414
+ if (!seenFileChanges.has(line)) {
415
+ seenFileChanges.add(line);
416
+ fileChangeLines.push(line);
417
+ }
418
+ }
419
+ } else if (block.name === "bash") {
420
+ bashCalls.push(block);
421
+ }
422
+ }
423
+ }
424
+ }
425
+
426
+ if (visibleTexts.length > 0) {
427
+ items.push({
428
+ entryId: entry.id,
429
+ runOrdinal,
430
+ position: items.length,
431
+ role: "assistant",
432
+ kind: "assistant_message",
433
+ text: visibleTexts.join("\n"),
434
+ timestamp: msgTs,
435
+ });
436
+ }
437
+
438
+ if (fileChangeLines.length > 0) {
439
+ items.push({
440
+ entryId: entry.id,
441
+ runOrdinal,
442
+ position: items.length,
443
+ role: "assistant",
444
+ kind: "file_change",
445
+ title: "Files modified",
446
+ text: fileChangeLines.join("\n"),
447
+ timestamp: msgTs,
448
+ });
449
+ }
450
+
451
+ for (const call of bashCalls) {
452
+ const command = truncateMiddle(
453
+ extractStringArg(call, "command") ?? "(empty command)",
454
+ MAX_COMMAND_CHARS,
455
+ );
456
+ const callId = typeof call.id === "string" ? call.id : "";
457
+ const paired = callId.length > 0 ? toolResultsByCallId.get(callId) : undefined;
458
+ if (paired) {
459
+ handledToolCallIds.add(callId);
460
+ const resultTs =
461
+ paired.msg.timestamp > 0 ? paired.msg.timestamp : parseTimestamp(paired.entry.timestamp);
462
+ const outputText = extractToolResultText(paired.msg);
463
+ if (paired.msg.isError) {
464
+ const errBody = truncateMiddle(
465
+ outputText.length > 0 ? `$ ${command}\n${outputText}` : `$ ${command}\n(command failed)`,
466
+ MAX_ERROR_CHARS,
467
+ );
468
+ items.push({
469
+ entryId: paired.entry.id,
470
+ runOrdinal,
471
+ position: items.length,
472
+ role: "assistant",
473
+ kind: "error",
474
+ title: `bash error: ${command}`,
475
+ text: errBody,
476
+ timestamp: resultTs,
477
+ });
478
+ } else {
479
+ const truncatedOutput = truncateMiddle(outputText, MAX_COMMAND_OUTPUT_CHARS);
480
+ const cmdBody =
481
+ truncatedOutput.length > 0
482
+ ? `$ ${command}\n${truncatedOutput}`
483
+ : `$ ${command}\n(no output)`;
484
+ items.push({
485
+ entryId: paired.entry.id,
486
+ runOrdinal,
487
+ position: items.length,
488
+ role: "assistant",
489
+ kind: "command_execution",
490
+ title: command,
491
+ text: cmdBody,
492
+ timestamp: resultTs,
493
+ });
494
+ }
495
+ } else {
496
+ items.push({
497
+ entryId: entry.id,
498
+ runOrdinal,
499
+ position: items.length,
500
+ role: "assistant",
501
+ kind: "command_execution",
502
+ title: command,
503
+ text: `$ ${command}\n(no tool result recorded)`,
504
+ timestamp: msgTs,
505
+ });
506
+ }
507
+ }
508
+
509
+ const rawErrorMsg =
510
+ typeof assistantMsg.errorMessage === "string"
511
+ ? assistantMsg.errorMessage.trim()
512
+ : "";
513
+ if (
514
+ rawErrorMsg.length > 0 ||
515
+ assistantMsg.stopReason === "error" ||
516
+ assistantMsg.stopReason === "aborted"
517
+ ) {
518
+ const errorText =
519
+ rawErrorMsg.length > 0
520
+ ? rawErrorMsg
521
+ : `Assistant stopped with reason: ${assistantMsg.stopReason}`;
522
+ items.push({
523
+ entryId: entry.id,
524
+ runOrdinal,
525
+ position: items.length,
526
+ role: "assistant",
527
+ kind: "error",
528
+ title: assistantMsg.stopReason === "aborted" ? "Aborted" : "Assistant error",
529
+ text: truncateMiddle(errorText, MAX_ERROR_CHARS),
530
+ timestamp: msgTs,
531
+ });
532
+ }
533
+ return;
534
+ }
535
+
536
+ case "toolResult": {
537
+ const toolResult = message as ToolResultMessage;
538
+ const toolCallId =
539
+ typeof toolResult.toolCallId === "string" ? toolResult.toolCallId : "";
540
+ if (toolCallId.length > 0 && handledToolCallIds.has(toolCallId)) {
541
+ return;
542
+ }
543
+ // Only emit failed tool results; successful read/grep/find/ls outputs are never inlined.
544
+ if (toolResult.isError) {
545
+ const toolName =
546
+ typeof toolResult.toolName === "string" && toolResult.toolName.length > 0
547
+ ? toolResult.toolName
548
+ : "tool";
549
+ const errText = extractToolResultText(toolResult);
550
+ const body = truncateMiddle(
551
+ errText.length > 0 ? errText : `${toolName} failed`,
552
+ MAX_ERROR_CHARS,
553
+ );
554
+ items.push({
555
+ entryId: entry.id,
556
+ runOrdinal,
557
+ position: items.length,
558
+ role: "assistant",
559
+ kind: "error",
560
+ title: `${toolName} error`,
561
+ text: body,
562
+ timestamp: toolResult.timestamp > 0 ? toolResult.timestamp : entryTs,
563
+ });
564
+ }
565
+ return;
566
+ }
567
+
568
+ default:
569
+ return;
570
+ }
571
+ }
572
+
573
+ function appendNonMessageEntry(
574
+ entry: SessionEntry,
575
+ runOrdinal: number,
576
+ items: HistoricalItem[],
577
+ ): void {
578
+ if (!entry || typeof entry !== "object") {
579
+ return;
580
+ }
581
+ if (entry.type === "compaction" || entry.type === "branch_summary") {
582
+ extractSummaryEntry(entry, runOrdinal, items);
583
+ return;
584
+ }
585
+ if (entry.type === "custom_message") {
586
+ if (entry.customType === HANDOFF_ENTRY_TYPE) {
587
+ return;
588
+ }
589
+ const text = formatUserLikeText(entry.content);
590
+ if (text.length > 0) {
591
+ items.push({
592
+ entryId: entry.id,
593
+ runOrdinal,
594
+ position: items.length,
595
+ role: "user",
596
+ kind: "user_message",
597
+ text,
598
+ timestamp: parseTimestamp(entry.timestamp),
599
+ });
600
+ }
601
+ }
602
+ }
603
+
604
+ /** Deterministically extract historical items from runs and optional pre-run summaries without any LLM calls. */
605
+ export function extractHistoricalItems(
606
+ runs: readonly ConversationRun[],
607
+ preRunSummaries?: readonly SessionEntry[],
608
+ ): HistoricalItem[] {
609
+ const items: HistoricalItem[] = [];
610
+
611
+ if (Array.isArray(preRunSummaries)) {
612
+ const preOrdinal = Array.isArray(runs) && runs.length > 0 ? Math.max(0, runs[0].ordinal - 1) : 0;
613
+ for (const entry of preRunSummaries) {
614
+ if (!entry || typeof entry !== "object") {
615
+ continue;
616
+ }
617
+ if (entry.type === "message") {
618
+ appendMessageItems(entry, preOrdinal, new Map(), new Set(), items);
619
+ } else {
620
+ appendNonMessageEntry(entry, preOrdinal, items);
621
+ }
622
+ }
623
+ }
624
+
625
+ if (!Array.isArray(runs)) {
626
+ return items;
627
+ }
628
+
629
+ for (const run of runs) {
630
+ if (!run || !Array.isArray(run.entries)) {
631
+ continue;
632
+ }
633
+ const toolResultsByCallId = new Map<
634
+ string,
635
+ { entry: SessionMessageEntry; msg: ToolResultMessage }
636
+ >();
637
+ for (const entry of run.entries) {
638
+ if (
639
+ entry &&
640
+ entry.type === "message" &&
641
+ entry.message &&
642
+ entry.message.role === "toolResult"
643
+ ) {
644
+ const toolResult = entry.message as ToolResultMessage;
645
+ if (typeof toolResult.toolCallId === "string" && toolResult.toolCallId.length > 0) {
646
+ toolResultsByCallId.set(toolResult.toolCallId, {
647
+ entry,
648
+ msg: toolResult,
649
+ });
650
+ }
651
+ }
652
+ }
653
+
654
+ const handledToolCallIds = new Set<string>();
655
+ for (const entry of run.entries) {
656
+ if (!entry || typeof entry !== "object") {
657
+ continue;
658
+ }
659
+ if (entry.type === "message") {
660
+ appendMessageItems(
661
+ entry,
662
+ run.ordinal,
663
+ toolResultsByCallId,
664
+ handledToolCallIds,
665
+ items,
666
+ );
667
+ } else {
668
+ appendNonMessageEntry(entry, run.ordinal, items);
669
+ }
670
+ }
671
+ }
672
+
673
+ return items;
674
+ }
675
+
676
+ function truncateToUtf8Bytes(text: string, maxBytes: number): string {
677
+ if (maxBytes <= 0 || text.length === 0) {
678
+ return "";
679
+ }
680
+ if (Buffer.byteLength(text, "utf8") <= maxBytes) {
681
+ return text;
682
+ }
683
+ let low = 0;
684
+ let high = text.length;
685
+ while (low < high) {
686
+ const mid = Math.ceil((low + high) / 2);
687
+ const slice = text.slice(0, mid);
688
+ if (Buffer.byteLength(slice, "utf8") <= maxBytes) {
689
+ low = mid;
690
+ } else {
691
+ high = mid - 1;
692
+ }
693
+ }
694
+ // Avoid splitting a UTF-16 surrogate pair at the boundary.
695
+ if (low > 0) {
696
+ const code = text.charCodeAt(low - 1);
697
+ if (code >= 0xd800 && code <= 0xdbff) {
698
+ low -= 1;
699
+ }
700
+ }
701
+ return text.slice(0, low);
702
+ }
703
+
704
+ function formatHistoricalItem(item: HistoricalItem): string {
705
+ const titleSuffix = item.title ? ` (${item.title})` : "";
706
+ return `### [run ${item.runOrdinal} | ${item.kind} | id: ${item.entryId}]${titleSuffix}\n${item.text}`;
707
+ }
708
+
709
+ function buildHeaderText(
710
+ input: SelectAndRenderHandoffInput,
711
+ items: readonly HistoricalItem[],
712
+ selectedCount: number,
713
+ ): string {
714
+ const laneFlow =
715
+ input.fromLane !== null
716
+ ? `from ${input.fromLane} to ${input.targetLane}`
717
+ : `target ${input.targetLane}`;
718
+ const resetNote = input.fallbackReset ? " [fallback_reset]" : "";
719
+ const entryRange =
720
+ items.length > 0
721
+ ? `${items[0].entryId}..${items[items.length - 1].entryId}`
722
+ : "none";
723
+
724
+ return [
725
+ "[Model Handoff Capsule]",
726
+ `strategy: ${input.strategy} (${laneFlow})${resetNote}`,
727
+ `covered_runs: ${input.coveredRunFrom}..${input.coveredRunTo} | items: ${selectedCount}/${items.length} (entries: ${entryRange})`,
728
+ "Notice: Attached files and native tool/reasoning state are not replayed.",
729
+ `To inspect omitted or truncated entries, call ${TOOL_NAME_HISTORY_READ}({ entryId, maxCharsPerItem: 4000 }).`,
730
+ ].join("\n");
731
+ }
732
+
733
+ function buildOmittedSection(
734
+ omittedEntryIds: readonly string[],
735
+ omittedCount: number,
736
+ omittedBudgetBytes: number,
737
+ ): { listedOmittedIds: string[]; sectionText: string } {
738
+ if (omittedCount === 0 || omittedBudgetBytes <= 0) {
739
+ return { listedOmittedIds: [], sectionText: "" };
740
+ }
741
+
742
+ const listedOmittedIds: string[] = [];
743
+ const capCount = Math.min(MAX_LISTED_OMITTED_ITEMS, omittedEntryIds.length);
744
+
745
+ for (let i = 0; i < capCount; i++) {
746
+ const candidateIds = [...listedOmittedIds, omittedEntryIds[i]];
747
+ const remaining = omittedEntryIds.length - candidateIds.length;
748
+ const moreSuffix = remaining > 0 ? ` ... (+${remaining} more)` : "";
749
+ const candidateLine = `Omitted entryIds (${candidateIds.length}/${omittedCount}): ${candidateIds.join(", ")}${moreSuffix}`;
750
+ if (Buffer.byteLength(candidateLine, "utf8") <= omittedBudgetBytes) {
751
+ listedOmittedIds.push(omittedEntryIds[i]);
752
+ } else {
753
+ break;
754
+ }
755
+ }
756
+
757
+ if (listedOmittedIds.length > 0) {
758
+ const remaining = omittedEntryIds.length - listedOmittedIds.length;
759
+ const moreSuffix = remaining > 0 ? ` ... (+${remaining} more)` : "";
760
+ return {
761
+ listedOmittedIds,
762
+ sectionText: `Omitted entryIds (${listedOmittedIds.length}/${omittedCount}): ${listedOmittedIds.join(", ")}${moreSuffix}`,
763
+ };
764
+ }
765
+
766
+ const fallbackLine = `Omitted entries: ${omittedCount}`;
767
+ if (Buffer.byteLength(fallbackLine, "utf8") <= omittedBudgetBytes) {
768
+ return { listedOmittedIds: [], sectionText: fallbackLine };
769
+ }
770
+
771
+ return { listedOmittedIds: [], sectionText: "" };
772
+ }
773
+
774
+ function findAnchorIndices(items: readonly HistoricalItem[]): number[] {
775
+ let lastUserIdx = -1;
776
+ let lastAssistantIdx = -1;
777
+ let firstUserIdx = -1;
778
+
779
+ for (let i = items.length - 1; i >= 0; i--) {
780
+ if (items[i].kind === "user_message") {
781
+ lastUserIdx = i;
782
+ break;
783
+ }
784
+ }
785
+ if (lastUserIdx === -1) {
786
+ for (let i = items.length - 1; i >= 0; i--) {
787
+ if (items[i].role === "user") {
788
+ lastUserIdx = i;
789
+ break;
790
+ }
791
+ }
792
+ }
793
+
794
+ for (let i = items.length - 1; i >= 0; i--) {
795
+ if (items[i].kind === "assistant_message") {
796
+ lastAssistantIdx = i;
797
+ break;
798
+ }
799
+ }
800
+ if (lastAssistantIdx === -1) {
801
+ for (let i = items.length - 1; i >= 0; i--) {
802
+ if (items[i].role === "assistant") {
803
+ lastAssistantIdx = i;
804
+ break;
805
+ }
806
+ }
807
+ }
808
+
809
+ for (let i = 0; i < items.length; i++) {
810
+ if (items[i].kind === "user_message") {
811
+ firstUserIdx = i;
812
+ break;
813
+ }
814
+ }
815
+ if (firstUserIdx === -1) {
816
+ for (let i = 0; i < items.length; i++) {
817
+ if (items[i].role === "user") {
818
+ firstUserIdx = i;
819
+ break;
820
+ }
821
+ }
822
+ }
823
+
824
+ const anchors: number[] = [];
825
+ for (const idx of [lastUserIdx, lastAssistantIdx, firstUserIdx]) {
826
+ if (idx !== -1 && !anchors.includes(idx)) {
827
+ anchors.push(idx);
828
+ }
829
+ }
830
+ return anchors;
831
+ }
832
+
833
+ function renderHandoffText(
834
+ headerText: string,
835
+ omittedSection: string,
836
+ formattedItems: readonly string[],
837
+ ): string {
838
+ const parts: string[] = [headerText];
839
+ if (omittedSection.length > 0) {
840
+ parts.push(omittedSection);
841
+ }
842
+ if (formattedItems.length > 0) {
843
+ parts.push(formattedItems.join("\n\n"));
844
+ }
845
+ return parts.join("\n\n");
846
+ }
847
+
848
+ /**
849
+ * Select historical items by anchor priority (last user -> last assistant -> first user -> reverse backfill)
850
+ * within the reserved budget and render them in chronological order.
851
+ */
852
+ export function selectAndRenderHandoff(
853
+ input: SelectAndRenderHandoffInput,
854
+ ): SelectionResult {
855
+ const rawBudgetBytes = Number.isFinite(input.budgetBytes)
856
+ ? Math.floor(input.budgetBytes)
857
+ : 0;
858
+ const budgetBytes = Math.max(0, Math.min(HANDOFF_BYTE_CAP, rawBudgetBytes));
859
+ const orderedItems = [...input.items].sort((a, b) => a.position - b.position);
860
+
861
+ if (budgetBytes === 0) {
862
+ const omittedEntryIds: string[] = [];
863
+ const seen = new Set<string>();
864
+ for (const item of orderedItems) {
865
+ if (!seen.has(item.entryId)) {
866
+ seen.add(item.entryId);
867
+ omittedEntryIds.push(item.entryId);
868
+ }
869
+ }
870
+ return {
871
+ selected: [],
872
+ omittedEntryIds,
873
+ omittedCount: orderedItems.length,
874
+ listedOmittedIds: [],
875
+ renderedText: "",
876
+ estimatedTokens: 0,
877
+ byteLength: 0,
878
+ };
879
+ }
880
+
881
+ // Reserve worst-case header size and omitted-ID list budget (<= budgetBytes / 8).
882
+ const worstCaseHeader = buildHeaderText(input, orderedItems, orderedItems.length);
883
+ const headerReserveBytes = Buffer.byteLength(worstCaseHeader, "utf8");
884
+ const omittedBudgetBytes = Math.floor(budgetBytes / 8);
885
+ const itemBudgetBytes = Math.max(
886
+ 0,
887
+ budgetBytes - headerReserveBytes - (orderedItems.length > 0 ? omittedBudgetBytes : 0) - 4,
888
+ );
889
+
890
+ const selectedIndexSet = new Set<number>();
891
+ const renderedItemByIndex = new Map<number, string>();
892
+ let usedItemBytes = 0;
893
+
894
+ const tryAddItem = (idx: number, allowTruncateAnchor: boolean): void => {
895
+ if (selectedIndexSet.has(idx)) {
896
+ return;
897
+ }
898
+ const item = orderedItems[idx];
899
+ const separatorBytes = selectedIndexSet.size > 0 ? 2 : 0; // "\n\n"
900
+ const formatted = formatHistoricalItem(item);
901
+ const fullBytes = Buffer.byteLength(formatted, "utf8");
902
+
903
+ if (usedItemBytes + separatorBytes + fullBytes <= itemBudgetBytes) {
904
+ selectedIndexSet.add(idx);
905
+ renderedItemByIndex.set(idx, formatted);
906
+ usedItemBytes += separatorBytes + fullBytes;
907
+ return;
908
+ }
909
+
910
+ if (allowTruncateAnchor) {
911
+ const availableForBlock = itemBudgetBytes - usedItemBytes - separatorBytes;
912
+ if (availableForBlock >= MIN_ANCHOR_TRUNCATE_BYTES) {
913
+ const prefix = `### [run ${item.runOrdinal} | ${item.kind} | id: ${item.entryId}]${item.title ? ` (${item.title})` : ""}\n`;
914
+ const suffix = `\n... [truncated; call ${TOOL_NAME_HISTORY_READ}({ entryId: "${item.entryId}", maxCharsPerItem: 4000 })]`;
915
+ const overheadBytes =
916
+ Buffer.byteLength(prefix, "utf8") + Buffer.byteLength(suffix, "utf8");
917
+ const bodyBudget = availableForBlock - overheadBytes;
918
+ if (bodyBudget > 32) {
919
+ const clippedBody = truncateToUtf8Bytes(item.text, bodyBudget);
920
+ if (clippedBody.length > 0) {
921
+ const clippedBlock = `${prefix}${clippedBody}${suffix}`;
922
+ selectedIndexSet.add(idx);
923
+ renderedItemByIndex.set(idx, clippedBlock);
924
+ usedItemBytes += separatorBytes + Buffer.byteLength(clippedBlock, "utf8");
925
+ }
926
+ }
927
+ }
928
+ }
929
+ };
930
+
931
+ // Priority phase 1: last user -> last assistant -> first user
932
+ const anchorIndices = findAnchorIndices(orderedItems);
933
+ for (const idx of anchorIndices) {
934
+ tryAddItem(idx, true);
935
+ }
936
+
937
+ // Priority phase 2: reverse backfill
938
+ for (let i = orderedItems.length - 1; i >= 0; i--) {
939
+ if (!selectedIndexSet.has(i)) {
940
+ tryAddItem(i, false);
941
+ }
942
+ }
943
+
944
+ // Chronological order output
945
+ const selectedIndices = Array.from(selectedIndexSet).sort((a, b) => a - b);
946
+
947
+ const buildResultForSelection = (indices: number[]): SelectionResult => {
948
+ const indexSet = new Set(indices);
949
+ const selected = indices.map((idx) => orderedItems[idx]);
950
+ const omittedCount = orderedItems.length - selected.length;
951
+ const omittedEntryIds: string[] = [];
952
+ const seenOmitted = new Set<string>();
953
+ for (let i = 0; i < orderedItems.length; i++) {
954
+ if (!indexSet.has(i)) {
955
+ const id = orderedItems[i].entryId;
956
+ if (!seenOmitted.has(id)) {
957
+ seenOmitted.add(id);
958
+ omittedEntryIds.push(id);
959
+ }
960
+ }
961
+ }
962
+
963
+ const headerText = buildHeaderText(input, orderedItems, selected.length);
964
+ const { listedOmittedIds, sectionText } = buildOmittedSection(
965
+ omittedEntryIds,
966
+ omittedCount,
967
+ omittedBudgetBytes,
968
+ );
969
+ const formattedItems = indices.map(
970
+ (idx) => renderedItemByIndex.get(idx) ?? formatHistoricalItem(orderedItems[idx]),
971
+ );
972
+ let renderedText = renderHandoffText(headerText, sectionText, formattedItems);
973
+ if (Buffer.byteLength(renderedText, "utf8") > budgetBytes) {
974
+ renderedText = truncateToUtf8Bytes(renderedText, budgetBytes);
975
+ }
976
+ const byteLength = Buffer.byteLength(renderedText, "utf8");
977
+
978
+ return {
979
+ selected,
980
+ omittedEntryIds,
981
+ omittedCount,
982
+ listedOmittedIds,
983
+ renderedText,
984
+ estimatedTokens: estimateTextTokens(renderedText),
985
+ byteLength,
986
+ };
987
+ };
988
+
989
+ // Ensure unclipped/exact fit within budgetBytes even if header shrunk or budget is very tight.
990
+ const activeIndices = [...selectedIndices];
991
+ let result = buildResultForSelection(activeIndices);
992
+ while (
993
+ activeIndices.length > 0 &&
994
+ Buffer.byteLength(
995
+ renderHandoffText(
996
+ buildHeaderText(input, orderedItems, activeIndices.length),
997
+ buildOmittedSection(
998
+ orderedItems
999
+ .filter((_, idx) => !activeIndices.includes(idx))
1000
+ .map((item) => item.entryId)
1001
+ .filter((id, i, arr) => arr.indexOf(id) === i),
1002
+ orderedItems.length - activeIndices.length,
1003
+ omittedBudgetBytes,
1004
+ ).sectionText,
1005
+ activeIndices.map(
1006
+ (idx) => renderedItemByIndex.get(idx) ?? formatHistoricalItem(orderedItems[idx]),
1007
+ ),
1008
+ ),
1009
+ "utf8",
1010
+ ) > budgetBytes
1011
+ ) {
1012
+ // Drop lowest-priority non-anchor first, then anchors in reverse priority.
1013
+ const dropCandidate = activeIndices.find((idx) => !anchorIndices.includes(idx));
1014
+ if (dropCandidate !== undefined) {
1015
+ activeIndices.splice(activeIndices.indexOf(dropCandidate), 1);
1016
+ } else {
1017
+ let dropped = false;
1018
+ for (let p = anchorIndices.length - 1; p >= 0; p--) {
1019
+ const pos = activeIndices.indexOf(anchorIndices[p]);
1020
+ if (pos !== -1) {
1021
+ activeIndices.splice(pos, 1);
1022
+ dropped = true;
1023
+ break;
1024
+ }
1025
+ }
1026
+ if (!dropped) {
1027
+ activeIndices.pop();
1028
+ }
1029
+ }
1030
+ result = buildResultForSelection(activeIndices);
1031
+ }
1032
+
1033
+ return result;
1034
+ }