@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,1039 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type {
3
+ AssistantMessage,
4
+ ImageContent,
5
+ TextContent,
6
+ ToolResultMessage,
7
+ UserMessage,
8
+ } from "@earendil-works/pi-ai";
9
+ import type {
10
+ CompactionEntry,
11
+ ContextEditEntry,
12
+ SessionEntry,
13
+ SessionMessageEntry,
14
+ } from "@earendil-works/pi-coding-agent";
15
+ import {
16
+ computeHandoffBudget,
17
+ estimateTextTokens,
18
+ extractHistoricalItems,
19
+ laneKeyFromModel,
20
+ selectAndRenderHandoff,
21
+ } from "./handoff-budget.ts";
22
+ import {
23
+ HANDOFF_ENTRY_TYPE,
24
+ MIN_DELTA_BUDGET_BYTES,
25
+ type ConversationRun,
26
+ type FrozenHandoffRecord,
27
+ type HandoffStrategy,
28
+ type LaneKey,
29
+ type ProjectMessagesInput,
30
+ type ProjectionResult,
31
+ } from "./types.ts";
32
+
33
+ const IMAGE_ESTIMATE_TOKENS = 256;
34
+
35
+ export function handoffRecordKey(
36
+ targetLane: LaneKey,
37
+ anchorUserEntryId: string,
38
+ ): string {
39
+ return `${targetLane}::${anchorUserEntryId}`;
40
+ }
41
+
42
+ /**
43
+ * Slice the session branch starting at the latest compaction checkpoint while
44
+ * preserving any pre-compaction entries kept via `firstKeptEntryId` so the
45
+ * resulting entry list aligns with Pi's `buildContextEntries`.
46
+ */
47
+ export function sliceActiveBranchAfterCompaction(
48
+ branch: SessionEntry[],
49
+ ): SessionEntry[] {
50
+ let compactionIdx = -1;
51
+ for (let i = branch.length - 1; i >= 0; i--) {
52
+ if (branch[i].type === "compaction") {
53
+ compactionIdx = i;
54
+ break;
55
+ }
56
+ }
57
+ if (compactionIdx < 0) {
58
+ return branch.slice();
59
+ }
60
+
61
+ const compaction = branch[compactionIdx] as CompactionEntry;
62
+ const active: SessionEntry[] = [compaction];
63
+
64
+ if (compaction.firstKeptEntryId && compaction.firstKeptEntryId !== compaction.id) {
65
+ let foundFirstKept = false;
66
+ for (let i = 0; i < compactionIdx; i++) {
67
+ const entry = branch[i];
68
+ if (entry.id === compaction.firstKeptEntryId) {
69
+ foundFirstKept = true;
70
+ }
71
+ if (
72
+ foundFirstKept &&
73
+ entry.type !== "compaction" &&
74
+ !(entry.type === "message" && entry.message.role === "system")
75
+ ) {
76
+ active.push(entry);
77
+ }
78
+ }
79
+ }
80
+
81
+ for (let i = compactionIdx + 1; i < branch.length; i++) {
82
+ active.push(branch[i]);
83
+ }
84
+ return active;
85
+ }
86
+
87
+ function isUserMessageEntry(
88
+ entry: SessionEntry,
89
+ ): entry is SessionMessageEntry & { message: UserMessage } {
90
+ return entry.type === "message" && entry.message?.role === "user";
91
+ }
92
+
93
+ function collectContextEditsByTarget(
94
+ entries: readonly SessionEntry[],
95
+ ): Map<string, ContextEditEntry> {
96
+ const editsByTarget = new Map<string, ContextEditEntry>();
97
+ for (const entry of entries) {
98
+ if (entry.type === "context_edit") {
99
+ editsByTarget.set(entry.targetId, entry);
100
+ }
101
+ }
102
+ return editsByTarget;
103
+ }
104
+
105
+ function isValidAssistantMessage(msg: AssistantMessage): boolean {
106
+ return (
107
+ msg.stopReason !== "error" &&
108
+ msg.stopReason !== "aborted" &&
109
+ msg.stopReason !== "pending" &&
110
+ msg.stopReason !== "deferred"
111
+ );
112
+ }
113
+
114
+ function extractUsageInputTokens(msg: AssistantMessage): number | undefined {
115
+ const usage = msg.usage;
116
+ if (!usage) return undefined;
117
+ const inputSum =
118
+ (usage.input ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
119
+ if (inputSum > 0) return inputSum;
120
+ return usage.totalTokens > 0 ? usage.totalTokens : undefined;
121
+ }
122
+
123
+ /**
124
+ * Segment active branch entries into user-turn runs. Each run's `ownerLane` is
125
+ * determined by its last valid assistant message; `error`/`aborted` empty runs
126
+ * are not counted as delivered, and the current unfinished run belongs to `currentLane`.
127
+ */
128
+ export function segmentBranchIntoRuns(
129
+ activeEntries: SessionEntry[],
130
+ currentLane: LaneKey,
131
+ ): ConversationRun[] {
132
+ const editsByTarget = collectContextEditsByTarget(activeEntries);
133
+ const userIndices: number[] = [];
134
+ for (let i = 0; i < activeEntries.length; i++) {
135
+ if (isUserMessageEntry(activeEntries[i])) {
136
+ userIndices.push(i);
137
+ }
138
+ }
139
+
140
+ const runs: ConversationRun[] = [];
141
+ for (let r = 0; r < userIndices.length; r++) {
142
+ const startIndex = userIndices[r];
143
+ const endIndex =
144
+ r + 1 < userIndices.length
145
+ ? userIndices[r + 1] - 1
146
+ : activeEntries.length - 1;
147
+ const entries = activeEntries.slice(startIndex, endIndex + 1);
148
+ const userEntry = activeEntries[startIndex] as SessionMessageEntry;
149
+
150
+ let lastValidAssistant: AssistantMessage | null = null;
151
+ let hasError = false;
152
+
153
+ for (const entry of entries) {
154
+ if (entry.type !== "message" || entry.message?.role !== "assistant") {
155
+ continue;
156
+ }
157
+ if (editsByTarget.get(entry.id)?.replacement === null) {
158
+ continue;
159
+ }
160
+ const assistant = entry.message as AssistantMessage;
161
+ if (
162
+ assistant.stopReason === "error" ||
163
+ assistant.stopReason === "aborted"
164
+ ) {
165
+ hasError = true;
166
+ }
167
+ if (isValidAssistantMessage(assistant)) {
168
+ lastValidAssistant = assistant;
169
+ }
170
+ }
171
+
172
+ const isLastRun = r === userIndices.length - 1;
173
+ let ownerLane: LaneKey | null = null;
174
+ let delivered = false;
175
+ let lastUsageInputTokens: number | undefined;
176
+
177
+ if (lastValidAssistant) {
178
+ ownerLane =
179
+ lastValidAssistant.provider && lastValidAssistant.model
180
+ ? laneKeyFromModel(lastValidAssistant.provider, lastValidAssistant.model)
181
+ : currentLane;
182
+ delivered = true;
183
+ lastUsageInputTokens = extractUsageInputTokens(lastValidAssistant);
184
+ } else if (isLastRun && !hasError) {
185
+ ownerLane = currentLane;
186
+ delivered = false;
187
+ }
188
+
189
+ runs.push({
190
+ ordinal: r + 1,
191
+ userEntryId: userEntry.id,
192
+ startIndex,
193
+ endIndex,
194
+ ownerLane,
195
+ delivered,
196
+ hasError,
197
+ entries,
198
+ ...(lastUsageInputTokens !== undefined ? { lastUsageInputTokens } : {}),
199
+ });
200
+ }
201
+
202
+ return runs;
203
+ }
204
+
205
+ function isFrozenHandoffRecord(value: unknown): value is FrozenHandoffRecord {
206
+ if (!value || typeof value !== "object") return false;
207
+ const candidate = value as Partial<FrozenHandoffRecord>;
208
+ return (
209
+ candidate.version === 1 &&
210
+ typeof candidate.targetLane === "string" &&
211
+ typeof candidate.anchorUserEntryId === "string" &&
212
+ typeof candidate.renderedText === "string" &&
213
+ (candidate.strategy === "full_thread_summary" ||
214
+ candidate.strategy === "delta_since_target_last_seen")
215
+ );
216
+ }
217
+
218
+ /**
219
+ * Collect frozen handoff records from active entries (and optional in-memory extras).
220
+ * Always preserves the first record per `(targetLane, anchorUserEntryId)` to keep
221
+ * prompt-cache prefixes stable.
222
+ */
223
+ export function collectFrozenRecords(
224
+ activeEntries: SessionEntry[],
225
+ extraRecords?: ReadonlyMap<string, FrozenHandoffRecord>,
226
+ ): Map<string, FrozenHandoffRecord> {
227
+ const records = new Map<string, FrozenHandoffRecord>();
228
+
229
+ for (const entry of activeEntries) {
230
+ if (entry.type !== "custom" || entry.customType !== HANDOFF_ENTRY_TYPE) {
231
+ continue;
232
+ }
233
+ if (!isFrozenHandoffRecord(entry.data)) {
234
+ continue;
235
+ }
236
+ const key = handoffRecordKey(
237
+ entry.data.targetLane,
238
+ entry.data.anchorUserEntryId,
239
+ );
240
+ if (!records.has(key)) {
241
+ records.set(key, entry.data);
242
+ }
243
+ }
244
+
245
+ if (extraRecords) {
246
+ for (const record of extraRecords.values()) {
247
+ if (!isFrozenHandoffRecord(record)) {
248
+ continue;
249
+ }
250
+ const key = handoffRecordKey(record.targetLane, record.anchorUserEntryId);
251
+ if (!records.has(key)) {
252
+ records.set(key, record);
253
+ }
254
+ }
255
+ }
256
+
257
+ return records;
258
+ }
259
+
260
+ function extractUserContentSummary(
261
+ content: UserMessage["content"] | null | undefined,
262
+ ): { text: string; imageCount: number; otherAttachmentCount: number } {
263
+ if (typeof content === "string") {
264
+ return { text: content, imageCount: 0, otherAttachmentCount: 0 };
265
+ }
266
+ if (!Array.isArray(content)) {
267
+ return { text: "", imageCount: 0, otherAttachmentCount: 0 };
268
+ }
269
+ const textParts: string[] = [];
270
+ let imageCount = 0;
271
+ let otherAttachmentCount = 0;
272
+ for (const block of content) {
273
+ if (!block || typeof block !== "object") {
274
+ continue;
275
+ }
276
+ if (block.type === "text") {
277
+ if (typeof block.text === "string") {
278
+ textParts.push(block.text);
279
+ }
280
+ } else if (block.type === "image") {
281
+ imageCount += 1;
282
+ } else {
283
+ otherAttachmentCount += 1;
284
+ }
285
+ }
286
+ return {
287
+ text: textParts.join("\n"),
288
+ imageCount,
289
+ otherAttachmentCount,
290
+ };
291
+ }
292
+
293
+ function normalizeText(text: string): string {
294
+ return text.trim().replace(/\s+/g, " ");
295
+ }
296
+
297
+ function estimateContentBlocksTokens(
298
+ content:
299
+ | string
300
+ | readonly (
301
+ | TextContent
302
+ | ImageContent
303
+ | { type: string; text?: string; name?: string; arguments?: unknown }
304
+ )[]
305
+ | null
306
+ | undefined,
307
+ ): number {
308
+ if (typeof content === "string") {
309
+ return estimateTextTokens(content);
310
+ }
311
+ if (!Array.isArray(content)) {
312
+ return 0;
313
+ }
314
+ let tokens = 0;
315
+ for (const block of content) {
316
+ if (!block || typeof block !== "object") {
317
+ continue;
318
+ }
319
+ if (block.type === "text" && typeof block.text === "string") {
320
+ tokens += estimateTextTokens(block.text);
321
+ } else if (block.type === "image") {
322
+ tokens += IMAGE_ESTIMATE_TOKENS;
323
+ } else if (block.type === "thinking") {
324
+ const thinkingText = (block as { thinking?: unknown }).thinking;
325
+ if (typeof thinkingText === "string") {
326
+ tokens += estimateTextTokens(thinkingText);
327
+ }
328
+ } else if (block.type === "toolCall") {
329
+ const call = block as { name?: string; arguments?: unknown };
330
+ tokens += estimateTextTokens(
331
+ `${call.name ?? ""}${JSON.stringify(call.arguments ?? {})}`,
332
+ );
333
+ }
334
+ }
335
+ return tokens;
336
+ }
337
+
338
+ function estimateAgentMessageTokens(msg: AgentMessage): number {
339
+ if (!msg || typeof msg !== "object") {
340
+ return 0;
341
+ }
342
+ switch (msg.role) {
343
+ case "user":
344
+ case "assistant":
345
+ case "toolResult":
346
+ case "custom":
347
+ return estimateContentBlocksTokens(msg.content);
348
+ case "compactionSummary":
349
+ case "branchSummary":
350
+ return typeof msg.summary === "string" ? estimateTextTokens(msg.summary) : 0;
351
+ case "bashExecution":
352
+ return estimateTextTokens(
353
+ `${typeof msg.command === "string" ? msg.command : ""}\n${typeof msg.output === "string" ? msg.output : ""}`,
354
+ );
355
+ default:
356
+ return 0;
357
+ }
358
+ }
359
+
360
+ function buildItemsWithOptionalPreRun(
361
+ activeEntries: SessionEntry[],
362
+ targetRuns: ConversationRun[],
363
+ includePreRun: boolean,
364
+ ) {
365
+ if (!includePreRun) {
366
+ return extractHistoricalItems(targetRuns);
367
+ }
368
+ const firstRunStart = targetRuns[0]?.startIndex ?? activeEntries.length;
369
+ const preRunEntries = activeEntries.slice(0, firstRunStart);
370
+ return extractHistoricalItems(targetRuns, preRunEntries);
371
+ }
372
+
373
+ interface AlignedMessageSlice {
374
+ run: ConversationRun | null;
375
+ messages: AgentMessage[];
376
+ }
377
+
378
+ /**
379
+ * Align `eventMessages` (which may have string or ContentBlock[] user contents,
380
+ * context edits, or trailing unsaved messages) against branch `runs`.
381
+ */
382
+ function alignEventMessagesToRuns(
383
+ eventMessages: AgentMessage[],
384
+ activeEntries: SessionEntry[],
385
+ runs: ConversationRun[],
386
+ ): {
387
+ preRunMessages: AgentMessage[];
388
+ slices: AlignedMessageSlice[];
389
+ runIndexByOrdinal: Map<number, number>;
390
+ } {
391
+ const editsByTarget = collectContextEditsByTarget(activeEntries);
392
+
393
+ const expectedRuns = runs.filter((run) => {
394
+ const edit = editsByTarget.get(run.userEntryId);
395
+ return !edit || edit.replacement !== null;
396
+ });
397
+
398
+ const userMsgPositions: number[] = [];
399
+ for (let i = 0; i < eventMessages.length; i++) {
400
+ if (eventMessages[i]?.role === "user") {
401
+ userMsgPositions.push(i);
402
+ }
403
+ }
404
+
405
+ const preRunMessages =
406
+ userMsgPositions.length > 0
407
+ ? eventMessages.slice(0, userMsgPositions[0])
408
+ : eventMessages.slice();
409
+
410
+ const matchedRunForUserMsg = new Array<ConversationRun | null>(
411
+ userMsgPositions.length,
412
+ ).fill(null);
413
+
414
+ if (userMsgPositions.length === expectedRuns.length) {
415
+ for (let i = 0; i < userMsgPositions.length; i++) {
416
+ matchedRunForUserMsg[i] = expectedRuns[i];
417
+ }
418
+ } else if (userMsgPositions.length > 0 && expectedRuns.length > 0) {
419
+ // Monotonic DP alignment scored by timestamp + normalized user text match.
420
+ const m = userMsgPositions.length;
421
+ const n = expectedRuns.length;
422
+
423
+ const msgMeta = userMsgPositions.map((pos) => {
424
+ const userMsg = eventMessages[pos] as UserMessage;
425
+ return {
426
+ timestamp: userMsg.timestamp,
427
+ text: normalizeText(extractUserContentSummary(userMsg.content).text),
428
+ };
429
+ });
430
+
431
+ const runMeta = expectedRuns.map((run) => {
432
+ const userEntry = activeEntries[run.startIndex] as SessionMessageEntry & {
433
+ message: UserMessage;
434
+ };
435
+ const edit = editsByTarget.get(run.userEntryId);
436
+ const effectiveContent =
437
+ edit?.replacement && typeof edit.replacement.content !== "undefined"
438
+ ? (edit.replacement.content as UserMessage["content"])
439
+ : userEntry.message?.content;
440
+ return {
441
+ timestamp: userEntry.message.timestamp,
442
+ text: normalizeText(extractUserContentSummary(effectiveContent).text),
443
+ };
444
+ });
445
+
446
+ const dp: number[][] = Array.from({ length: m + 1 }, () =>
447
+ new Array<number>(n + 1).fill(0),
448
+ );
449
+ const choice: number[][] = Array.from({ length: m + 1 }, () =>
450
+ new Array<number>(n + 1).fill(0),
451
+ );
452
+
453
+ for (let i = m - 1; i >= 0; i--) {
454
+ for (let j = n - 1; j >= 0; j--) {
455
+ let pairScore = 0;
456
+ if (msgMeta[i].timestamp === runMeta[j].timestamp) {
457
+ pairScore += 4;
458
+ }
459
+ if (msgMeta[i].text === runMeta[j].text) {
460
+ pairScore += 2;
461
+ }
462
+
463
+ const matchVal = pairScore > 0 ? pairScore + dp[i + 1][j + 1] : -1;
464
+ const skipMsgVal = dp[i + 1][j];
465
+ const skipRunVal = dp[i][j + 1];
466
+
467
+ if (matchVal >= skipMsgVal && matchVal >= skipRunVal && pairScore > 0) {
468
+ dp[i][j] = matchVal;
469
+ choice[i][j] = 1;
470
+ } else if (skipMsgVal >= skipRunVal) {
471
+ dp[i][j] = skipMsgVal;
472
+ choice[i][j] = 2;
473
+ } else {
474
+ dp[i][j] = skipRunVal;
475
+ choice[i][j] = 3;
476
+ }
477
+ }
478
+ }
479
+
480
+ let i = 0;
481
+ let j = 0;
482
+ while (i < m && j < n) {
483
+ if (choice[i][j] === 1) {
484
+ matchedRunForUserMsg[i] = expectedRuns[j];
485
+ i += 1;
486
+ j += 1;
487
+ } else if (choice[i][j] === 2) {
488
+ i += 1;
489
+ } else {
490
+ j += 1;
491
+ }
492
+ }
493
+ }
494
+
495
+ const slices: AlignedMessageSlice[] = [];
496
+ const runIndexByOrdinal = new Map<number, number>();
497
+ for (let u = 0; u < userMsgPositions.length; u++) {
498
+ const start = userMsgPositions[u];
499
+ const end =
500
+ u + 1 < userMsgPositions.length
501
+ ? userMsgPositions[u + 1]
502
+ : eventMessages.length;
503
+ const run = matchedRunForUserMsg[u];
504
+ const sliceIdx = slices.length;
505
+ slices.push({
506
+ run,
507
+ messages: eventMessages.slice(start, end),
508
+ });
509
+ if (run) {
510
+ runIndexByOrdinal.set(run.ordinal, sliceIdx);
511
+ }
512
+ }
513
+
514
+ return { preRunMessages, slices, runIndexByOrdinal };
515
+ }
516
+
517
+ function inlineHandoffIntoUserMessage(
518
+ msg: UserMessage,
519
+ renderedText: string,
520
+ ): { message: UserMessage; changed: boolean } {
521
+ if (!renderedText) {
522
+ return { message: msg, changed: false };
523
+ }
524
+
525
+ if (typeof msg.content === "string") {
526
+ if (msg.content.startsWith(renderedText)) {
527
+ return { message: msg, changed: false };
528
+ }
529
+ const nextContent = msg.content
530
+ ? `${renderedText}\n\n${msg.content}`
531
+ : renderedText;
532
+ return {
533
+ message: {
534
+ ...msg,
535
+ content: nextContent,
536
+ },
537
+ changed: true,
538
+ };
539
+ }
540
+
541
+ const handoffBlock: TextContent = {
542
+ type: "text",
543
+ text: renderedText,
544
+ };
545
+
546
+ if (!Array.isArray(msg.content)) {
547
+ return {
548
+ message: {
549
+ ...msg,
550
+ content: [handoffBlock],
551
+ },
552
+ changed: true,
553
+ };
554
+ }
555
+
556
+ const first = msg.content[0];
557
+ if (
558
+ first?.type === "text" &&
559
+ typeof first.text === "string" &&
560
+ first.text.startsWith(renderedText)
561
+ ) {
562
+ return { message: msg, changed: false };
563
+ }
564
+
565
+ return {
566
+ message: {
567
+ ...msg,
568
+ content: [handoffBlock, ...msg.content],
569
+ },
570
+ changed: true,
571
+ };
572
+ }
573
+
574
+ function dropOrphanedToolResults(
575
+ messages: AgentMessage[],
576
+ ): { messages: AgentMessage[]; dropped: boolean } {
577
+ const result: AgentMessage[] = [];
578
+ const activeToolCallIds = new Set<string>();
579
+ let dropped = false;
580
+
581
+ for (const msg of messages) {
582
+ if (!msg || typeof msg !== "object") {
583
+ continue;
584
+ }
585
+ if (msg.role === "assistant") {
586
+ activeToolCallIds.clear();
587
+ if (Array.isArray(msg.content)) {
588
+ for (const block of msg.content) {
589
+ if (
590
+ block &&
591
+ typeof block === "object" &&
592
+ block.type === "toolCall" &&
593
+ typeof block.id === "string"
594
+ ) {
595
+ activeToolCallIds.add(block.id);
596
+ }
597
+ }
598
+ }
599
+ result.push(msg);
600
+ continue;
601
+ }
602
+
603
+ if (msg.role === "toolResult") {
604
+ const toolResult = msg as ToolResultMessage;
605
+ if (
606
+ typeof toolResult.toolCallId === "string" &&
607
+ activeToolCallIds.has(toolResult.toolCallId)
608
+ ) {
609
+ result.push(msg);
610
+ } else {
611
+ dropped = true;
612
+ }
613
+ continue;
614
+ }
615
+
616
+ activeToolCallIds.clear();
617
+ result.push(msg);
618
+ }
619
+
620
+ return { messages: result, dropped };
621
+ }
622
+
623
+ function computeKeepSetAndEffectiveRecords(
624
+ runs: ConversationRun[],
625
+ anchorRun: ConversationRun,
626
+ targetLane: LaneKey,
627
+ frozenRecords: ReadonlyMap<string, FrozenHandoffRecord>,
628
+ ): {
629
+ effectiveStartOrdinal: number;
630
+ omittedOrdinals: Set<number>;
631
+ recordByRunOrdinal: Map<number, FrozenHandoffRecord>;
632
+ } {
633
+ const recordByRunOrdinal = new Map<number, FrozenHandoffRecord>();
634
+ let effectiveStartOrdinal = 1;
635
+ let fallbackResetOrdinal = 1;
636
+
637
+ for (const run of runs) {
638
+ const rec = frozenRecords.get(handoffRecordKey(targetLane, run.userEntryId));
639
+ if (!rec) continue;
640
+ recordByRunOrdinal.set(run.ordinal, rec);
641
+ if (run.ordinal <= anchorRun.ordinal) {
642
+ if (rec.strategy === "full_thread_summary" || rec.fallbackReset) {
643
+ effectiveStartOrdinal = Math.max(effectiveStartOrdinal, run.ordinal);
644
+ }
645
+ if (rec.fallbackReset) {
646
+ fallbackResetOrdinal = Math.max(fallbackResetOrdinal, run.ordinal);
647
+ }
648
+ }
649
+ }
650
+
651
+ const omittedOrdinals = new Set<number>();
652
+ // Any ordinal-based filtering is strictly bounded before anchorRun.ordinal;
653
+ // do not use stale pre-compaction coveredRunFrom..coveredRunTo ranges.
654
+ for (const run of runs) {
655
+ if (run.ordinal >= anchorRun.ordinal) {
656
+ continue;
657
+ }
658
+ if (run.ordinal < fallbackResetOrdinal) {
659
+ omittedOrdinals.add(run.ordinal);
660
+ continue;
661
+ }
662
+ if (
663
+ run.delivered &&
664
+ run.ownerLane !== null &&
665
+ run.ownerLane !== targetLane
666
+ ) {
667
+ omittedOrdinals.add(run.ordinal);
668
+ }
669
+ }
670
+
671
+ return { effectiveStartOrdinal, omittedOrdinals, recordByRunOrdinal };
672
+ }
673
+
674
+ function estimateNativePrefixTokens(
675
+ runs: ConversationRun[],
676
+ preRunMessages: AgentMessage[],
677
+ slices: AlignedMessageSlice[],
678
+ runIndexByOrdinal: Map<number, number>,
679
+ omittedOrdinals: Set<number>,
680
+ recordByRunOrdinal: Map<number, FrozenHandoffRecord>,
681
+ upToOrdinal: number,
682
+ effectiveStartOrdinal: number,
683
+ ): number {
684
+ const keptPrefixRuns = runs.filter(
685
+ (run) => run.ordinal <= upToOrdinal && !omittedOrdinals.has(run.ordinal),
686
+ );
687
+ if (keptPrefixRuns.length === 0) {
688
+ return 0;
689
+ }
690
+
691
+ // If the last kept native run has real provider input token usage, reuse it
692
+ // and only add estimates for any trailing kept runs without usage.
693
+ let lastUsageIdx = -1;
694
+ for (let i = keptPrefixRuns.length - 1; i >= 0; i--) {
695
+ if (
696
+ keptPrefixRuns[i].lastUsageInputTokens !== undefined &&
697
+ keptPrefixRuns[i].lastUsageInputTokens! > 0
698
+ ) {
699
+ lastUsageIdx = i;
700
+ break;
701
+ }
702
+ }
703
+
704
+ let total = 0;
705
+ let estimateFromIdx = 0;
706
+ if (lastUsageIdx >= 0) {
707
+ total = keptPrefixRuns[lastUsageIdx].lastUsageInputTokens!;
708
+ estimateFromIdx = lastUsageIdx + 1;
709
+ } else if (effectiveStartOrdinal === 1) {
710
+ for (const msg of preRunMessages) {
711
+ total += estimateAgentMessageTokens(msg);
712
+ }
713
+ }
714
+
715
+ for (let i = estimateFromIdx; i < keptPrefixRuns.length; i++) {
716
+ const run = keptPrefixRuns[i];
717
+ const sliceIdx = runIndexByOrdinal.get(run.ordinal);
718
+ if (sliceIdx === undefined) continue;
719
+ const rec = recordByRunOrdinal.get(run.ordinal);
720
+ const msgs = slices[sliceIdx].messages;
721
+ for (let m = 0; m < msgs.length; m++) {
722
+ let msg = msgs[m];
723
+ if (m === 0 && msg.role === "user" && rec) {
724
+ msg = inlineHandoffIntoUserMessage(msg, rec.renderedText).message;
725
+ }
726
+ total += estimateAgentMessageTokens(msg);
727
+ }
728
+ }
729
+
730
+ return total;
731
+ }
732
+
733
+ function createHandoffRecord(params: {
734
+ activeEntries: SessionEntry[];
735
+ coveredRuns: ConversationRun[];
736
+ strategy: HandoffStrategy;
737
+ fallbackReset: boolean;
738
+ targetLane: LaneKey;
739
+ fromLane: LaneKey | null;
740
+ anchorUserEntryId: string;
741
+ budgetBytes: number;
742
+ includeCompaction: boolean;
743
+ }): FrozenHandoffRecord | null {
744
+ const items = buildItemsWithOptionalPreRun(
745
+ params.activeEntries,
746
+ params.coveredRuns,
747
+ params.includeCompaction,
748
+ );
749
+ if (items.length === 0) {
750
+ return null;
751
+ }
752
+
753
+ const coveredRunFrom = params.coveredRuns[0]?.ordinal ?? 0;
754
+ const coveredRunTo =
755
+ params.coveredRuns[params.coveredRuns.length - 1]?.ordinal ?? 0;
756
+
757
+ const selection = selectAndRenderHandoff({
758
+ items,
759
+ strategy: params.strategy,
760
+ targetLane: params.targetLane,
761
+ fromLane: params.fromLane,
762
+ coveredRunFrom,
763
+ coveredRunTo,
764
+ budgetBytes: params.budgetBytes,
765
+ fallbackReset: params.fallbackReset,
766
+ });
767
+
768
+ return {
769
+ version: 1,
770
+ targetLane: params.targetLane,
771
+ fromLane: params.fromLane,
772
+ anchorUserEntryId: params.anchorUserEntryId,
773
+ strategy: params.strategy,
774
+ fallbackReset: params.fallbackReset,
775
+ coveredRunFrom,
776
+ coveredRunTo,
777
+ sourceEntryFrom: items[0]?.entryId ?? null,
778
+ sourceEntryTo: items[items.length - 1]?.entryId ?? null,
779
+ includedCount: selection.selected.length,
780
+ omittedCount: selection.omittedCount,
781
+ omittedEntryIds: selection.omittedEntryIds,
782
+ estimatedTokens: selection.estimatedTokens,
783
+ byteLength: selection.byteLength,
784
+ renderedText: selection.renderedText,
785
+ createdAt: Date.now(),
786
+ };
787
+ }
788
+
789
+ /**
790
+ * Project conversation `eventMessages` onto `targetLane` using frozen or newly
791
+ * computed handoff records, without mutating input messages or creating orphaned
792
+ * `toolResult` messages.
793
+ */
794
+ export function projectMessagesForLane(
795
+ input: ProjectMessagesInput,
796
+ ): ProjectionResult {
797
+ const activeEntries = sliceActiveBranchAfterCompaction(input.branch);
798
+ const runs = segmentBranchIntoRuns(activeEntries, input.targetLane);
799
+ const totalRuns = runs.length;
800
+
801
+ if (input.bypass || totalRuns === 0) {
802
+ return {
803
+ messages: input.eventMessages,
804
+ modified: false,
805
+ activeLane: input.targetLane,
806
+ newRecord: null,
807
+ appliedRecords: [],
808
+ keptNativeRuns: totalRuns,
809
+ totalRuns,
810
+ };
811
+ }
812
+
813
+ const frozenRecords = collectFrozenRecords(activeEntries, input.extraRecords);
814
+ const anchorRun = runs[runs.length - 1];
815
+ const priorRuns = runs.slice(0, runs.length - 1);
816
+
817
+ const hasForeignDelivered = priorRuns.some(
818
+ (run) =>
819
+ run.delivered &&
820
+ run.ownerLane !== null &&
821
+ run.ownerLane !== input.targetLane,
822
+ );
823
+ const hasForeignInAnchor =
824
+ anchorRun.delivered &&
825
+ anchorRun.ownerLane !== null &&
826
+ anchorRun.ownerLane !== input.targetLane;
827
+ const hasFrozenForTarget = runs.some((run) =>
828
+ frozenRecords.has(handoffRecordKey(input.targetLane, run.userEntryId)),
829
+ );
830
+
831
+ // Rule 4: Single-lane thread with no foreign history and no frozen records passes through unchanged.
832
+ if (!hasForeignDelivered && !hasForeignInAnchor && !hasFrozenForTarget) {
833
+ return {
834
+ messages: input.eventMessages,
835
+ modified: false,
836
+ activeLane: input.targetLane,
837
+ newRecord: null,
838
+ appliedRecords: [],
839
+ keptNativeRuns: totalRuns,
840
+ totalRuns,
841
+ };
842
+ }
843
+
844
+ const aligned = alignEventMessagesToRuns(
845
+ input.eventMessages,
846
+ activeEntries,
847
+ runs,
848
+ );
849
+
850
+ const workingFrozenRecords = new Map(frozenRecords);
851
+ const anchorKey = handoffRecordKey(input.targetLane, anchorRun.userEntryId);
852
+ let newRecord: FrozenHandoffRecord | null = null;
853
+
854
+ // Rule 3 & 5: Reuse existing frozen record for (targetLane, anchorUserEntryId);
855
+ // otherwise create one only when switching from a foreign delivered run.
856
+ if (!workingFrozenRecords.has(anchorKey)) {
857
+ let lastDeliveredRun: ConversationRun | null = null;
858
+ for (let i = priorRuns.length - 1; i >= 0; i--) {
859
+ if (priorRuns[i].delivered && priorRuns[i].ownerLane !== null) {
860
+ lastDeliveredRun = priorRuns[i];
861
+ break;
862
+ }
863
+ }
864
+
865
+ if (lastDeliveredRun && lastDeliveredRun.ownerLane !== input.targetLane) {
866
+ let lastTargetIdx = -1;
867
+ for (let i = priorRuns.length - 1; i >= 0; i--) {
868
+ if (
869
+ priorRuns[i].delivered &&
870
+ priorRuns[i].ownerLane === input.targetLane
871
+ ) {
872
+ lastTargetIdx = i;
873
+ break;
874
+ }
875
+ }
876
+
877
+ const anchorSliceIdx = aligned.runIndexByOrdinal.get(anchorRun.ordinal);
878
+ const anchorUserMsg =
879
+ anchorSliceIdx !== undefined
880
+ ? (aligned.slices[anchorSliceIdx].messages[0] as UserMessage)
881
+ : (
882
+ activeEntries[anchorRun.startIndex] as SessionMessageEntry & {
883
+ message: UserMessage;
884
+ }
885
+ ).message;
886
+ const anchorSummary = extractUserContentSummary(anchorUserMsg?.content);
887
+
888
+ if (lastTargetIdx >= 0) {
889
+ const lastTargetRun = priorRuns[lastTargetIdx];
890
+ const deltaRuns = priorRuns.slice(lastTargetIdx + 1);
891
+ const prefixPlan = computeKeepSetAndEffectiveRecords(
892
+ runs,
893
+ anchorRun,
894
+ input.targetLane,
895
+ workingFrozenRecords,
896
+ );
897
+ const nativeTokens = estimateNativePrefixTokens(
898
+ runs,
899
+ aligned.preRunMessages,
900
+ aligned.slices,
901
+ aligned.runIndexByOrdinal,
902
+ prefixPlan.omittedOrdinals,
903
+ prefixPlan.recordByRunOrdinal,
904
+ lastTargetRun.ordinal,
905
+ prefixPlan.effectiveStartOrdinal,
906
+ );
907
+
908
+ const deltaBudget = computeHandoffBudget({
909
+ tokenCap: input.tokenCap,
910
+ modelContextWindow: input.modelContextWindow,
911
+ nativeTokens,
912
+ currentUserText: anchorSummary.text,
913
+ currentImageCount: anchorSummary.imageCount,
914
+ currentOtherAttachmentCount: anchorSummary.otherAttachmentCount,
915
+ });
916
+
917
+ if (deltaBudget.budgetBytes < MIN_DELTA_BUDGET_BYTES) {
918
+ const fullBudget = computeHandoffBudget({
919
+ tokenCap: input.tokenCap,
920
+ modelContextWindow: input.modelContextWindow,
921
+ nativeTokens: 0,
922
+ currentUserText: anchorSummary.text,
923
+ currentImageCount: anchorSummary.imageCount,
924
+ currentOtherAttachmentCount: anchorSummary.otherAttachmentCount,
925
+ });
926
+ newRecord = createHandoffRecord({
927
+ activeEntries,
928
+ coveredRuns: priorRuns,
929
+ strategy: "full_thread_summary",
930
+ fallbackReset: true,
931
+ targetLane: input.targetLane,
932
+ fromLane: lastDeliveredRun.ownerLane,
933
+ anchorUserEntryId: anchorRun.userEntryId,
934
+ budgetBytes: fullBudget.budgetBytes,
935
+ includeCompaction: true,
936
+ });
937
+ } else {
938
+ newRecord = createHandoffRecord({
939
+ activeEntries,
940
+ coveredRuns: deltaRuns,
941
+ strategy: "delta_since_target_last_seen",
942
+ fallbackReset: false,
943
+ targetLane: input.targetLane,
944
+ fromLane: lastDeliveredRun.ownerLane,
945
+ anchorUserEntryId: anchorRun.userEntryId,
946
+ budgetBytes: deltaBudget.budgetBytes,
947
+ includeCompaction: false,
948
+ });
949
+ }
950
+ } else {
951
+ const fullBudget = computeHandoffBudget({
952
+ tokenCap: input.tokenCap,
953
+ modelContextWindow: input.modelContextWindow,
954
+ nativeTokens: 0,
955
+ currentUserText: anchorSummary.text,
956
+ currentImageCount: anchorSummary.imageCount,
957
+ currentOtherAttachmentCount: anchorSummary.otherAttachmentCount,
958
+ });
959
+ newRecord = createHandoffRecord({
960
+ activeEntries,
961
+ coveredRuns: priorRuns,
962
+ strategy: "full_thread_summary",
963
+ fallbackReset: false,
964
+ targetLane: input.targetLane,
965
+ fromLane: lastDeliveredRun.ownerLane,
966
+ anchorUserEntryId: anchorRun.userEntryId,
967
+ budgetBytes: fullBudget.budgetBytes,
968
+ includeCompaction: true,
969
+ });
970
+ }
971
+
972
+ if (newRecord) {
973
+ workingFrozenRecords.set(anchorKey, newRecord);
974
+ }
975
+ }
976
+ }
977
+
978
+ const plan = computeKeepSetAndEffectiveRecords(
979
+ runs,
980
+ anchorRun,
981
+ input.targetLane,
982
+ workingFrozenRecords,
983
+ );
984
+
985
+ const projectedMessages: AgentMessage[] = [];
986
+ const appliedRecords: FrozenHandoffRecord[] = [];
987
+ let keptNativeRuns = 0;
988
+ let hasContentModification = newRecord !== null;
989
+
990
+ if (plan.effectiveStartOrdinal === 1) {
991
+ projectedMessages.push(...aligned.preRunMessages);
992
+ } else if (aligned.preRunMessages.length > 0) {
993
+ hasContentModification = true;
994
+ }
995
+
996
+ for (const slice of aligned.slices) {
997
+ if (!slice.run) {
998
+ projectedMessages.push(...slice.messages);
999
+ continue;
1000
+ }
1001
+
1002
+ if (plan.omittedOrdinals.has(slice.run.ordinal)) {
1003
+ hasContentModification = true;
1004
+ continue;
1005
+ }
1006
+
1007
+ keptNativeRuns += 1;
1008
+ const rec = plan.recordByRunOrdinal.get(slice.run.ordinal);
1009
+ if (!rec) {
1010
+ projectedMessages.push(...slice.messages);
1011
+ continue;
1012
+ }
1013
+
1014
+ appliedRecords.push(rec);
1015
+ const [firstMsg, ...restMsgs] = slice.messages;
1016
+ if (firstMsg && firstMsg.role === "user") {
1017
+ const inlined = inlineHandoffIntoUserMessage(firstMsg, rec.renderedText);
1018
+ if (inlined.changed) {
1019
+ hasContentModification = true;
1020
+ }
1021
+ projectedMessages.push(inlined.message, ...restMsgs);
1022
+ } else {
1023
+ projectedMessages.push(...slice.messages);
1024
+ }
1025
+ }
1026
+
1027
+ const sanitized = dropOrphanedToolResults(projectedMessages);
1028
+ const modified = hasContentModification || sanitized.dropped;
1029
+
1030
+ return {
1031
+ messages: modified ? sanitized.messages : input.eventMessages,
1032
+ modified,
1033
+ activeLane: input.targetLane,
1034
+ newRecord,
1035
+ appliedRecords,
1036
+ keptNativeRuns,
1037
+ totalRuns,
1038
+ };
1039
+ }