pi-tuck 1.1.2 → 1.2.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +7 -3
  3. package/dist/index.d.ts +2 -6
  4. package/dist/index.js +16 -111
  5. package/dist/src/build-id.d.ts +1 -1
  6. package/dist/src/build-id.js +1 -1
  7. package/dist/src/compaction.d.ts +2 -103
  8. package/dist/src/compaction.js +29 -146
  9. package/dist/src/diagnostic-replay.js +2 -2
  10. package/dist/src/diagnostics.d.ts +3 -2
  11. package/dist/src/diagnostics.js +30 -9
  12. package/dist/src/history-tools.js +3 -3
  13. package/dist/src/kept-reads.d.ts +2 -2
  14. package/dist/src/kept-reads.js +144 -8
  15. package/dist/src/ledger.d.ts +1 -1
  16. package/dist/src/ledger.js +5 -3
  17. package/dist/src/legacy-cleanup.d.ts +3 -0
  18. package/dist/src/legacy-cleanup.js +190 -0
  19. package/dist/src/notify.d.ts +3 -0
  20. package/dist/src/notify.js +13 -0
  21. package/dist/src/omissions.d.ts +1 -1
  22. package/dist/src/omissions.js +3 -3
  23. package/dist/src/path-key.d.ts +3 -0
  24. package/dist/src/path-key.js +8 -0
  25. package/dist/src/request-capacity.js +1 -1
  26. package/dist/src/run.d.ts +1 -3
  27. package/dist/src/run.js +3 -5
  28. package/dist/src/source-export.d.ts +1 -1
  29. package/dist/src/source-export.js +1 -1
  30. package/dist/src/status.d.ts +0 -6
  31. package/dist/src/status.js +1 -6
  32. package/dist/src/tuck/core/content.js +6 -9
  33. package/dist/src/tuck/core/keyword-query.d.ts +2 -2
  34. package/dist/src/tuck/core/keyword-query.js +1 -1
  35. package/dist/src/tuck/core/search-entries.js +5 -5
  36. package/dist/src/tuck/core/transcript.js +2 -1
  37. package/dist/src/tuck.js +390 -394
  38. package/dist/src/windows-private-storage.d.ts +9 -0
  39. package/dist/src/windows-private-storage.js +90 -0
  40. package/index.ts +18 -82
  41. package/package.json +5 -8
  42. package/src/build-id.ts +1 -1
  43. package/src/compaction.ts +28 -113
  44. package/src/diagnostic-replay.ts +2 -2
  45. package/src/diagnostics.ts +24 -9
  46. package/src/history-tools.ts +3 -3
  47. package/src/kept-reads.ts +78 -10
  48. package/src/ledger.ts +5 -3
  49. package/src/legacy-cleanup.ts +134 -0
  50. package/src/notify.ts +10 -0
  51. package/src/omissions.ts +3 -3
  52. package/src/path-key.ts +9 -0
  53. package/src/request-capacity.ts +1 -1
  54. package/src/run.ts +4 -6
  55. package/src/source-export.ts +1 -1
  56. package/src/status.ts +1 -10
  57. package/src/tuck/core/content.ts +5 -10
  58. package/src/tuck/core/keyword-query.ts +2 -2
  59. package/src/tuck/core/search-entries.ts +5 -5
  60. package/src/tuck/core/transcript.ts +2 -1
  61. package/src/tuck.ts +329 -335
  62. package/src/windows-private-storage.ts +94 -0
  63. package/dist/src/assets.d.ts +0 -58
  64. package/dist/src/assets.js +0 -80
  65. package/dist/src/eligibility-cache.d.ts +0 -19
  66. package/dist/src/eligibility-cache.js +0 -33
  67. package/dist/src/semantic-recall.d.ts +0 -422
  68. package/dist/src/semantic-recall.js +0 -1386
  69. package/dist/src/setup.d.ts +0 -3
  70. package/dist/src/setup.js +0 -191
  71. package/scripts/eg2-runtime.py +0 -307
  72. package/scripts/provision-eg2.py +0 -139
  73. package/scripts/semantic-worker.py +0 -234
  74. package/src/assets.ts +0 -92
  75. package/src/eligibility-cache.ts +0 -43
  76. package/src/semantic-recall.ts +0 -592
  77. package/src/setup.ts +0 -163
package/src/tuck.ts CHANGED
@@ -170,356 +170,350 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
170
170
  if (latestPosition >= 0 && (!latestTextOnly || latestPosition > lastResponse)) floorBoundary = Math.min(floorBoundary, latestPosition);
171
171
  // One fill owns the summary and the contiguous native suffix. Protocol/current-input
172
172
  // floors are representation constraints; every other source competes by rank.
173
- return rankedFill();
174
-
175
- function rankedFill(): Draft {
176
- const model = ctx.model;
177
- if (!model) return { unavailable: "pi-tuck needs a model to measure the cut" };
178
- const indices = tuck.buildGlobalIndexById(ctx.sessionManager.getEntries());
179
- const header = ctx.sessionManager.getHeader();
180
- if (!header) throw new Error("Missing native session header");
181
- const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
182
- const minimumOpeningLength = 80, openingLength = Math.max(80, Math.floor(Math.sqrt(room * 4)));
183
- const positions = new Map(entries.map((entry, at) => [entry.id, at]));
184
- const originals = tuck.buildOwnCut(entries.filter(entry => entry.type !== "compaction"), 0);
185
- if (!originals.ok) return { unavailable: "No eligible original prefix to compile" };
186
- const byId = new Map(entries.map(entry => [entry.id, entry]));
187
- const sourceIndices = originals.selectedIds.map(id => indices.get(id));
188
- const rows = originals.selectedIds.map((id, at) => ({ id, position: positions.get(id)!, index: sourceIndices[at], message: originals.messages[at] as AgentMessage }));
189
- const users = rows.filter(row => row.message.role === "user");
190
- const userTexts = new Map(users.map(row => [row.index, textOf((row.message as Extract<AgentMessage, { role: "user" }>).content)]));
191
- let replied = false;
192
- const answered: SessionEntry[] = [];
193
- for (let at = entries.length - 1; at >= 0; at--) {
194
- const entry = entries[at]!;
195
- if (entry.type !== "message") continue;
196
- if (entry.message.role === "assistant" && !isDiscardedResponse(entry.message) && entry.message.content.length) { replied = true; continue; }
197
- if (entry.message.role !== "user") continue;
198
- if (replied && textOf(entry.message.content).length) answered.push(entry);
199
- replied = false;
200
- }
201
- const anchors = [...new Map([...answered.slice(0, 8), ...(firstUserPosition >= 0 ? [entries[firstUserPosition]!] : [])].map(entry => [entry.id, entry])).values()];
202
- const failedCalls = new Set(entries.flatMap(entry => entry.type === "message" && entry.message.role === "toolResult" && entry.message.isError ? [entry.message.toolCallId] : []));
203
- const detailsAt = (boundary: number) => ({ compactor: "pi-tuck", version: 2, adapter: "standalone",
204
- keptUserTurns: users.reduce((n, row) => n + Number(row.position >= boundary), 0),
205
- ...(boundary === preferredBoundary && budgetCut ? { budgetCut } : {}) });
206
- const preview = (summary: string, boundary: number) => {
207
- const manager = SessionManager.inMemory(ctx.cwd, undefined, [header, ...branch]);
208
- manager.appendCompaction(summary, entries[boundary]?.id ?? "", input.tokensBefore, detailsAt(boundary), true);
209
- return manager.buildSessionProjection().messages;
210
- };
211
- // Price the native suffix once. The measure's additive offset and Pi's
212
- // summary envelope are calibrated once, rather than replaying a session
213
- // for each opening, ledger line or tail boundary considered by the fill.
214
- const rawPositions = new Map(branch.map((entry, at) => [entry.id, at]));
215
- const native = new Float64Array(branch.length + 1);
216
- for (const entry of projected.entries) {
217
- if (entry.sourceEntry.type === "compaction") continue;
218
- const at = rawPositions.get(entry.sourceEntry.id);
219
- if (at !== undefined) for (const message of entry.messages)
220
- native[at] += measure.messageTokens ? measure.messageTokens(message) : conversationTokens([message]);
221
- }
222
- for (let at = branch.length - 1; at >= 0; at--) native[at] += native[at + 1]!;
223
- const nativeAt = (boundary: number) => boundary === entries.length ? 0 : native[rawPositions.get(entries[boundary]!.id)!]!;
224
- const tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
225
- // Move only the older end, to the newest whole protocol-safe entries
226
- // within the shared tail size. Required current/fresh native sources
227
- // stay whole even when their floor exceeds that preferred amount.
228
- while (preferredBoundary < floorBoundary && nativeAt(preferredBoundary) > tailTokens) {
173
+ const model = ctx.model;
174
+ if (!model) return { unavailable: "pi-tuck needs a model to measure the cut" };
175
+ const indices = tuck.buildGlobalIndexById(ctx.sessionManager.getEntries());
176
+ const header = ctx.sessionManager.getHeader();
177
+ if (!header) throw new Error("Missing native session header");
178
+ const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
179
+ const minimumOpeningLength = 80, openingLength = Math.max(80, Math.floor(Math.sqrt(room * 4)));
180
+ const positions = new Map(entries.map((entry, at) => [entry.id, at]));
181
+ const originals = tuck.buildOwnCut(entries.filter(entry => entry.type !== "compaction"), 0);
182
+ if (!originals.ok) return { unavailable: "No eligible original prefix to compile" };
183
+ const sourceIndices = originals.selectedIds.map(id => indices.get(id));
184
+ const rows = originals.selectedIds.map((id, at) => ({ id, position: positions.get(id)!, index: sourceIndices[at], message: originals.messages[at] as AgentMessage }));
185
+ const users = rows.filter(row => row.message.role === "user");
186
+ const userTexts = new Map(users.map(row => [row.index, textOf((row.message as Extract<AgentMessage, { role: "user" }>).content)]));
187
+ let replied = false;
188
+ const answered: SessionEntry[] = [];
189
+ for (let at = entries.length - 1; at >= 0; at--) {
190
+ const entry = entries[at]!;
191
+ if (entry.type !== "message") continue;
192
+ if (entry.message.role === "assistant" && !isDiscardedResponse(entry.message) && entry.message.content.length) { replied = true; continue; }
193
+ if (entry.message.role !== "user") continue;
194
+ if (replied && textOf(entry.message.content).length) answered.push(entry);
195
+ replied = false;
196
+ }
197
+ const anchors = [...new Map([...answered.slice(0, 8), ...(firstUserPosition >= 0 ? [entries[firstUserPosition]!] : [])].map(entry => [entry.id, entry])).values()];
198
+ const failedCalls = new Set(entries.flatMap(entry => entry.type === "message" && entry.message.role === "toolResult" && entry.message.isError ? [entry.message.toolCallId] : []));
199
+ const detailsAt = (boundary: number) => ({ compactor: "pi-tuck", version: 2, adapter: "standalone",
200
+ keptUserTurns: users.reduce((n, row) => n + Number(row.position >= boundary), 0),
201
+ ...(boundary === preferredBoundary && budgetCut ? { budgetCut } : {}) });
202
+ const preview = (summary: string, boundary: number) => {
203
+ const manager = SessionManager.inMemory(ctx.cwd, undefined, [header, ...branch]);
204
+ manager.appendCompaction(summary, entries[boundary]?.id ?? "", input.tokensBefore, detailsAt(boundary), true);
205
+ return manager.buildSessionProjection().messages;
206
+ };
207
+ // Price the native suffix once. The measure's additive offset and Pi's
208
+ // summary envelope are calibrated once, rather than replaying a session
209
+ // for each opening, ledger line or tail boundary considered by the fill.
210
+ const rawPositions = new Map(branch.map((entry, at) => [entry.id, at]));
211
+ const native = new Float64Array(branch.length + 1);
212
+ for (const entry of projected.entries) {
213
+ if (entry.sourceEntry.type === "compaction") continue;
214
+ const at = rawPositions.get(entry.sourceEntry.id);
215
+ if (at !== undefined) for (const message of entry.messages)
216
+ native[at] += measure.messageTokens ? measure.messageTokens(message) : conversationTokens([message]);
217
+ }
218
+ for (let at = branch.length - 1; at >= 0; at--) native[at] += native[at + 1]!;
219
+ const nativeAt = (boundary: number) => boundary === entries.length ? 0 : native[rawPositions.get(entries[boundary]!.id)!]!;
220
+ const tailTokens = carriedTailTokens(nativeAt(preferredBoundary));
221
+ // Move only the older end, to the newest whole protocol-safe entries
222
+ // within the shared tail size. Required current/fresh native sources
223
+ // stay whole even when their floor exceeds that preferred amount.
224
+ while (preferredBoundary < floorBoundary && nativeAt(preferredBoundary) > tailTokens) {
225
+ preferredBoundary++;
226
+ while (preferredBoundary < floorBoundary) {
227
+ const entry = entries[preferredBoundary]!;
228
+ if ((entry.type === "message" && entry.message.role !== "toolResult") || entry.type === "custom_message" || entry.type === "branch_summary") break;
229
229
  preferredBoundary++;
230
- while (preferredBoundary < floorBoundary) {
231
- const entry = entries[preferredBoundary]!;
232
- if ((entry.type === "message" && entry.message.role !== "toolResult") || entry.type === "custom_message" || entry.type === "branch_summary") break;
233
- preferredBoundary++;
234
- }
235
230
  }
236
- const envelope = convertToLlm([{ role: "compactionSummary", summary: "", tokensBefore: 0, timestamp: 0 }]);
237
- const wrapperCharacters = envelope.reduce((n, message) => n + textOf(message.content).length, 0);
238
- const summaryTokens = (characters: number) => Math.ceil((characters + wrapperCharacters) / 4);
239
- const lineCost = (records: readonly TranscriptRecord[]) => records.reduce((n, record) => n + serializeRecord(record).length + 1, 0);
240
- const frameLength = (cost: number, count: number) => TRANSCRIPT_HEADER.length + DIALOGUE_SUFFIX.length + cost + (count ? 0 : 1);
241
- const render = (records: TranscriptRecord[]) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + DIALOGUE_SUFFIX;
242
- type Unit = { position: number; index: number; count: number };
243
- const units: Record<"user" | "assistant" | "toolResult", Unit[]> = { user: [], assistant: [], toolResult: [] };
244
- for (const row of rows) {
245
- if (row.index === undefined) continue;
246
- const message = row.message;
247
- if (message.role === "user" && textOf(message.content).length) units.user.push({ position: row.position, index: row.index, count: 1 });
248
- else if (message.role === "toolResult") units.toolResult.push({ position: row.position, index: row.index, count: 1 });
249
- else if (message.role === "assistant" && !isDiscardedResponse(message)) {
250
- const count = message.content.filter(part => part.type === "text" && part.text.trim()).length;
251
- if (count) units.assistant.push({ position: row.position, index: row.index, count });
252
- }
231
+ }
232
+ const envelope = convertToLlm([{ role: "compactionSummary", summary: "", tokensBefore: 0, timestamp: 0 }]);
233
+ const wrapperCharacters = envelope.reduce((n, message) => n + textOf(message.content).length, 0);
234
+ const summaryTokens = (characters: number) => Math.ceil((characters + wrapperCharacters) / 4);
235
+ const lineCost = (records: readonly TranscriptRecord[]) => records.reduce((n, record) => n + serializeRecord(record).length + 1, 0);
236
+ const frameLength = (cost: number, count: number) => TRANSCRIPT_HEADER.length + DIALOGUE_SUFFIX.length + cost + (count ? 0 : 1);
237
+ const render = (records: TranscriptRecord[]) => (serializeTranscript(records) || TRANSCRIPT_HEADER + "\n") + DIALOGUE_SUFFIX;
238
+ type Unit = { position: number; index: number; count: number };
239
+ const units: Record<"user" | "assistant" | "toolResult", Unit[]> = { user: [], assistant: [], toolResult: [] };
240
+ for (const row of rows) {
241
+ if (row.index === undefined) continue;
242
+ const message = row.message;
243
+ if (message.role === "user" && textOf(message.content).length) units.user.push({ position: row.position, index: row.index, count: 1 });
244
+ else if (message.role === "toolResult") units.toolResult.push({ position: row.position, index: row.index, count: 1 });
245
+ else if (message.role === "assistant" && !isDiscardedResponse(message)) {
246
+ const count = message.content.filter(part => part.type === "text" && part.text.trim()).length;
247
+ if (count) units.assistant.push({ position: row.position, index: row.index, count });
253
248
  }
254
- const prefixes = Object.fromEntries(Object.entries(units).map(([role, list]) => {
255
- const end = new Int32Array(entries.length + 1), count = new Int32Array(list.length + 1);
256
- let seen = 0;
257
- for (let at = 0; at <= entries.length; at++) {
258
- while (seen < list.length && list[seen]!.position < at) seen++;
259
- end[at] = seen;
260
- }
261
- list.forEach((unit, at) => count[at + 1] = count[at]! + unit.count);
262
- return [role, { end, count }];
263
- })) as Record<keyof typeof units, { end: Int32Array; count: Int32Array }>;
264
- const quoteCache = new Map<string, { records: TranscriptRecord[]; cost: number; whole: boolean }>();
265
- const quote = (entry: SessionEntry, take: number) => {
266
- const key = `${entry.id}:${take}`;
267
- let cached = quoteCache.get(key);
268
- if (cached) return cached;
269
- const index = indices.get(entry.id);
270
- const text = entry.type === "custom_message" ? textOf(entry.content) : entry.type === "message" && entry.message.role === "user" ? textOf(entry.message.content) : "";
271
- const sourceTimes = index === undefined ? undefined : [{ sourceIndex: index, ...resolveSourceTime(entry) }];
272
- // Custom entries have a native identity but no global message index.
273
- const records: TranscriptRecord[] = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity
274
- ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }), text, sourceTimes,
275
- ...(entry.type === "custom_message" ? { sourceEntryId: entry.id } : {}) }]
276
- : userPrefixRecords({ kind: "user", text, originalText: text, startsSource: true, sourceIndex: index }, undefined, take).map(record => ({ ...record, sourceTimes }));
277
- cached = { records, cost: lineCost(records), whole: take >= text.length };
278
- quoteCache.set(key, cached);
279
- return cached;
280
- };
281
- const highAt = (boundary: number, length: number) => {
282
- const kept: TranscriptRecord[] = [], selected = new Set<number>(), whole = new Set<number>();
283
- let cost = 0;
284
- const add = (entry: SessionEntry, take: number) => {
285
- const quoted = quote(entry, take), index = indices.get(entry.id);
286
- kept.push(...quoted.records); cost += quoted.cost;
287
- if (index !== undefined && quoted.records.length) { selected.add(index); if (quoted.whole) whole.add(index); }
288
- };
289
- if (latestPosition >= 0 && latestPosition < boundary && latestTextOnly) add(latest!, Infinity);
290
- if (currentPosition >= 0 && currentPosition < boundary && current?.id !== latest?.id) add(current!, Infinity);
291
- for (const entry of anchors) if (entry.id !== latest?.id && entry.id !== current?.id && positions.get(entry.id)! < boundary) add(entry, length);
292
- const omissions: TranscriptRecord[] = [];
293
- for (const role of ["user", "assistant", "toolResult"] as const) {
294
- const list = units[role], prefix = prefixes[role];
295
- let first = 0, last = prefix.end[boundary]! - 1;
296
- if (role === "user") {
297
- while (first <= last && selected.has(list[first]!.index)) first++;
298
- while (last >= first && selected.has(list[last]!.index)) last--;
299
- }
300
- if (last < first) continue;
301
- const a = list[first]!, b = list[last]!;
302
- let count = prefix.count[last + 1]! - prefix.count[first]!;
303
- if (role === "user") for (const index of whole) if (index >= a.index && index <= b.index) count--;
304
- if (count) omissions.push(omissionRecord(role, count, [a.index, b.index], false));
305
- }
306
- const rows = [...kept, ...omissions], totalCost = cost + lineCost(omissions);
307
- return { kept, whole, omissions, rows, cost: totalCost, length: frameLength(totalCost, rows.length) };
308
- };
309
- const calibrationHigh = highAt(floorBoundary, minimumOpeningLength);
310
- const floorSummary = render(calibrationHigh.rows), floorProjection = preview(floorSummary, floorBoundary);
311
- // The last admission attempt and thinking-only retry share this exact floor: whole protected prompts, the smallest
312
- // existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
313
- if (input.deepest) {
314
- assertNativeToolRounds(floorProjection);
315
- const after = measure(floorProjection);
316
- return { compaction: { summary: floorSummary, firstKeptEntryId: entries[floorBoundary]?.id ?? "", tokensBefore: input.tokensBefore,
317
- details: { ...detailsAt(floorBoundary), tokensAfter: after, carriedTarget: after, view: "shrunk-dialogue", mode: "shrunk", deepest: true } }, after, mode: "shrunk" };
249
+ }
250
+ const prefixes = Object.fromEntries(Object.entries(units).map(([role, list]) => {
251
+ const end = new Int32Array(entries.length + 1), count = new Int32Array(list.length + 1);
252
+ let seen = 0;
253
+ for (let at = 0; at <= entries.length; at++) {
254
+ while (seen < list.length && list[seen]!.position < at) seen++;
255
+ end[at] = seen;
318
256
  }
319
- const offset = measure(floorProjection) - nativeAt(floorBoundary) - summaryTokens(floorSummary.length);
320
- const price = (characters: number, boundary: number) => offset + nativeAt(boundary) + summaryTokens(characters);
321
- const listCache = new Map<number, { files: ReturnType<typeof ledgerItems>; actions: ReturnType<typeof actionItems>; records: TranscriptRecord[] }>();
322
- const listsAt = (boundary: number) => {
323
- const cached = listCache.get(boundary);
324
- if (cached) return cached;
325
- const compacted = entries.slice(0, boundary), resolves = (entry: SessionEntry) => readable(entry) !== undefined;
326
- const files = ledgerItems(compacted, indices, resolves, failedCalls), actions = actionItems(compacted, indices, resolves, failedCalls);
327
- const lists = { files, actions, records: [...actionRecords(actions), ...ledgerRecords(files)] };
328
- listCache.set(boundary, lists);
329
- return lists;
257
+ list.forEach((unit, at) => count[at + 1] = count[at]! + unit.count);
258
+ return [role, { end, count }];
259
+ })) as Record<keyof typeof units, { end: Int32Array; count: Int32Array }>;
260
+ const quoteCache = new Map<string, { records: TranscriptRecord[]; cost: number; whole: boolean }>();
261
+ const quote = (entry: SessionEntry, take: number) => {
262
+ const key = `${entry.id}:${take}`;
263
+ let cached = quoteCache.get(key);
264
+ if (cached) return cached;
265
+ const index = indices.get(entry.id);
266
+ const text = entry.type === "custom_message" ? textOf(entry.content) : entry.type === "message" && entry.message.role === "user" ? textOf(entry.message.content) : "";
267
+ const sourceTimes = index === undefined ? undefined : [{ sourceIndex: index, ...resolveSourceTime(entry) }];
268
+ // Custom entries have a native identity but no global message index.
269
+ const records: TranscriptRecord[] = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity
270
+ ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }), text, sourceTimes,
271
+ ...(entry.type === "custom_message" ? { sourceEntryId: entry.id } : {}) }]
272
+ : userPrefixRecords({ kind: "user", text, originalText: text, startsSource: true, sourceIndex: index }, undefined, take).map(record => ({ ...record, sourceTimes }));
273
+ cached = { records, cost: lineCost(records), whole: take >= text.length };
274
+ quoteCache.set(key, cached);
275
+ return cached;
276
+ };
277
+ const highAt = (boundary: number, length: number) => {
278
+ const kept: TranscriptRecord[] = [], selected = new Set<number>(), whole = new Set<number>();
279
+ let cost = 0;
280
+ const add = (entry: SessionEntry, take: number) => {
281
+ const quoted = quote(entry, take), index = indices.get(entry.id);
282
+ kept.push(...quoted.records); cost += quoted.cost;
283
+ if (index !== undefined && quoted.records.length) { selected.add(index); if (quoted.whole) whole.add(index); }
330
284
  };
331
- const preferredHigh = highAt(preferredBoundary, openingLength), preferredLists = listsAt(preferredBoundary);
332
- const fixedRowsCost = preferredHigh.cost + lineCost(preferredLists.records);
333
- const baseCharacters = frameLength(fixedRowsCost, preferredHigh.rows.length + preferredLists.records.length);
334
- const base = price(baseCharacters, preferredBoundary);
335
- const target = carriedTarget(model.contextWindow, reserveTokens, base, before);
336
- // The old tail rule supplies an ordering boundary only. Its recent
337
- // suffix follows the openings, and is charged to the same total grant.
338
- const boundaries = [floorBoundary];
339
- for (let at = floorBoundary - 1; at >= preferredBoundary; at--) {
340
- const entry = entries[at]!;
341
- if ((entry.type === "message" && entry.message.role !== "toolResult") || entry.type === "custom_message" || entry.type === "branch_summary") boundaries.push(at);
342
- }
343
- boundaries.reverse();
344
- const tailFor = (length: number) => {
345
- // Longest suffix first: the first fit is the preferred rank. Most
346
- // cuts keep that entire suffix, so no other boundaries need pricing.
347
- for (const boundary of boundaries) {
348
- const high = highAt(boundary, length);
349
- if (price(high.length, boundary) <= target) return { boundary, high };
285
+ if (latestPosition >= 0 && latestPosition < boundary && latestTextOnly) add(latest!, Infinity);
286
+ if (currentPosition >= 0 && currentPosition < boundary && current?.id !== latest?.id) add(current!, Infinity);
287
+ for (const entry of anchors) if (entry.id !== latest?.id && entry.id !== current?.id && positions.get(entry.id)! < boundary) add(entry, length);
288
+ const omissions: TranscriptRecord[] = [];
289
+ for (const role of ["user", "assistant", "toolResult"] as const) {
290
+ const list = units[role], prefix = prefixes[role];
291
+ let first = 0, last = prefix.end[boundary]! - 1;
292
+ if (role === "user") {
293
+ while (first <= last && selected.has(list[first]!.index)) first++;
294
+ while (last >= first && selected.has(list[last]!.index)) last--;
350
295
  }
351
- return undefined;
352
- };
353
- let selected = tailFor(minimumOpeningLength);
354
- if (!selected) return { unavailable: "pi-tuck's mandatory context cannot fit or reduce the request budget",
355
- capacityRejected: price(calibrationHigh.length, floorBoundary) + reserveTokens >= model.contextWindow,
356
- floorMessages: floorProjection };
357
- let low = minimumOpeningLength, high = openingLength;
358
- while (low < high) {
359
- const middle = Math.ceil((low + high) / 2);
360
- if (tailFor(middle)) low = middle; else high = middle - 1;
296
+ if (last < first) continue;
297
+ const a = list[first]!, b = list[last]!;
298
+ let count = prefix.count[last + 1]! - prefix.count[first]!;
299
+ if (role === "user") for (const index of whole) if (index >= a.index && index <= b.index) count--;
300
+ if (count) omissions.push(omissionRecord(role, count, [a.index, b.index], false));
361
301
  }
362
- selected = tailFor(low)!;
363
- let { boundary, high: protectedView } = selected;
364
- const sourceRows = rows.filter(row => row.position < boundary);
365
- const lists = listsAt(boundary);
366
- const maxSummaryCharactersAt = (at: number) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
367
- const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
368
- let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
369
- const keptReads: TranscriptRecord[] = [];
370
- for (const record of keptReadCandidates(entries.slice(0, boundary), indices, entry => readable(entry) !== undefined)) {
371
- const cost = lineCost([record]);
372
- if (cost > allowance) continue;
373
- keptReads.push(record); allowance -= cost;
374
- if (keptReads.length === 4) break;
302
+ const rows = [...kept, ...omissions], totalCost = cost + lineCost(omissions);
303
+ return { kept, whole, omissions, rows, cost: totalCost, length: frameLength(totalCost, rows.length) };
304
+ };
305
+ const calibrationHigh = highAt(floorBoundary, minimumOpeningLength);
306
+ const floorSummary = render(calibrationHigh.rows), floorProjection = preview(floorSummary, floorBoundary);
307
+ // The last admission attempt and thinking-only retry share this exact floor: whole protected prompts, the smallest
308
+ // existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
309
+ if (input.deepest) {
310
+ assertNativeToolRounds(floorProjection);
311
+ const after = measure(floorProjection);
312
+ return { compaction: { summary: floorSummary, firstKeptEntryId: entries[floorBoundary]?.id ?? "", tokensBefore: input.tokensBefore,
313
+ details: { ...detailsAt(floorBoundary), tokensAfter: after, carriedTarget: after, view: "shrunk-dialogue", mode: "shrunk", deepest: true } }, after, mode: "shrunk" };
314
+ }
315
+ const offset = measure(floorProjection) - nativeAt(floorBoundary) - summaryTokens(floorSummary.length);
316
+ const price = (characters: number, boundary: number) => offset + nativeAt(boundary) + summaryTokens(characters);
317
+ const listCache = new Map<number, { files: ReturnType<typeof ledgerItems>; actions: ReturnType<typeof actionItems>; records: TranscriptRecord[] }>();
318
+ const listsAt = (boundary: number) => {
319
+ const cached = listCache.get(boundary);
320
+ if (cached) return cached;
321
+ const compacted = entries.slice(0, boundary), resolves = (entry: SessionEntry) => readable(entry) !== undefined;
322
+ const files = ledgerItems(compacted, indices, resolves, failedCalls, header.cwd), actions = actionItems(compacted, indices, resolves, failedCalls);
323
+ const lists = { files, actions, records: [...actionRecords(actions), ...ledgerRecords(files)] };
324
+ listCache.set(boundary, lists);
325
+ return lists;
326
+ };
327
+ const preferredHigh = highAt(preferredBoundary, openingLength), preferredLists = listsAt(preferredBoundary);
328
+ const fixedRowsCost = preferredHigh.cost + lineCost(preferredLists.records);
329
+ const baseCharacters = frameLength(fixedRowsCost, preferredHigh.rows.length + preferredLists.records.length);
330
+ const base = price(baseCharacters, preferredBoundary);
331
+ const target = carriedTarget(model.contextWindow, reserveTokens, base, before);
332
+ // The old tail rule supplies an ordering boundary only. Its recent
333
+ // suffix follows the openings, and is charged to the same total grant.
334
+ const boundaries = [floorBoundary];
335
+ for (let at = floorBoundary - 1; at >= preferredBoundary; at--) {
336
+ const entry = entries[at]!;
337
+ if ((entry.type === "message" && entry.message.role !== "toolResult") || entry.type === "custom_message" || entry.type === "branch_summary") boundaries.push(at);
338
+ }
339
+ boundaries.reverse();
340
+ const tailFor = (length: number) => {
341
+ // Longest suffix first: the first fit is the preferred rank. Most
342
+ // cuts keep that entire suffix, so no other boundaries need pricing.
343
+ for (const boundary of boundaries) {
344
+ const high = highAt(boundary, length);
345
+ if (price(high.length, boundary) <= target) return { boundary, high };
375
346
  }
376
- let ledger: TranscriptRecord[] = [...lists.records, ...keptReads];
377
- // List caps are existing ranking policy; only the carried target is a
378
- // spending limit. Candidate list sizes have fixed, cached line prices.
379
- while (keptReads.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
380
- keptReads.pop();
381
- ledger = [...lists.records, ...keptReads];
347
+ return undefined;
348
+ };
349
+ let selected = tailFor(minimumOpeningLength);
350
+ if (!selected) return { unavailable: "pi-tuck's mandatory context cannot fit or reduce the request budget",
351
+ capacityRejected: price(calibrationHigh.length, floorBoundary) + reserveTokens >= model.contextWindow,
352
+ floorMessages: floorProjection };
353
+ let low = minimumOpeningLength, high = openingLength;
354
+ while (low < high) {
355
+ const middle = Math.ceil((low + high) / 2);
356
+ if (tailFor(middle)) low = middle; else high = middle - 1;
357
+ }
358
+ selected = tailFor(low)!;
359
+ let { boundary, high: protectedView } = selected;
360
+ const sourceRows = rows.filter(row => row.position < boundary);
361
+ const lists = listsAt(boundary);
362
+ const maxSummaryCharactersAt = (at: number) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
363
+ const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
364
+ let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
365
+ const keptReads: TranscriptRecord[] = [];
366
+ for (const record of keptReadCandidates([header, ...entries.slice(0, boundary)], indices, entry => readable(entry) !== undefined)) {
367
+ const cost = lineCost([record]);
368
+ if (cost > allowance) continue;
369
+ keptReads.push(record); allowance -= cost;
370
+ if (keptReads.length === 4) break;
371
+ }
372
+ let ledger: TranscriptRecord[] = [...lists.records, ...keptReads];
373
+ // List caps are existing ranking policy; only the carried target is a
374
+ // spending limit. Candidate list sizes have fixed, cached line prices.
375
+ while (keptReads.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
376
+ keptReads.pop();
377
+ ledger = [...lists.records, ...keptReads];
378
+ }
379
+ if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
380
+ ledger = [];
381
+ for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
382
+ const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
383
+ if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target) ledger = candidate;
384
+ }
385
+ }
386
+ const mandatory = new Set([...protectedView.whole].filter(index => {
387
+ const row = users.find(row => row.index === index);
388
+ return row?.message.role === "user" && isTextOnly(row.message.content);
389
+ }));
390
+ const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
391
+ const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
392
+ const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
393
+ sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position]!)),
394
+ ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
395
+ const imageLabels = new Map<number | undefined, Set<string>>();
396
+ for (const row of sourceRows) if (row.message.role === "user" && Array.isArray(row.message.content))
397
+ imageLabels.set(row.index, new Set(row.message.content.flatMap(part => part.type === "image" ? [`[image: ${part.mimeType}]`] : [])));
398
+ const compiledBoundary = boundary;
399
+ // A protected custom prompt uses its native entry ID in the same anchoring/movement path as indexed user prompts.
400
+ const sourceKey = (record: TranscriptRecord) => current?.type === "custom_message" && record.sourceEntryId === current.id ? current.id : record.sourceIndex;
401
+ const assemble = (compiled: string, at = compiledBoundary) => {
402
+ const split = compiled ? splitSummary(compiled) : undefined;
403
+ if (compiled && !split) throw new Error("pi-tuck returned an invalid summary");
404
+ const inputRecords = split ? parseRecords(split.body, split.version) : protectedView.omissions;
405
+ const expanded = new Set(protectedView.kept.filter(record => record.kind === "excerpt" && inputRecords.some(row =>
406
+ row.kind === "excerpt" && row.role === record.role && sourceKey(row) === sourceKey(record) && row.text.startsWith(record.text!) && row.text.length >= record.text!.length)).map(sourceKey));
407
+ const anchored = new Set(protectedView.kept.map(sourceKey));
408
+ const moved = new Set(rows.filter(row => row.position >= at && row.position < compiledBoundary).map(row =>
409
+ current?.type === "custom_message" && row.id === current.id ? row.id : row.index));
410
+ const records = [...inputRecords.filter(record => {
411
+ const key = sourceKey(record);
412
+ if (key !== undefined && moved.has(key)) return false;
413
+ if (record.kind === "excerpt" && record.role === "user" && imageLabels.get(record.sourceIndex)?.has(record.text)) return true;
414
+ return record.role !== "user" && record.role !== "custom" || key === undefined || !anchored.has(key) || expanded.has(key);
415
+ }), ...protectedView.kept.filter(record => !expanded.has(sourceKey(record)) && !moved.has(sourceKey(record)))];
416
+ // Mixed user turns keep their text opening, while their image
417
+ // metadata remains in the ordinary lower-ranked dialogue lane.
418
+ const wholeUser = new Set(records.filter(record => record.kind === "excerpt" && record.role === "user" && record.text === userTexts.get(record.sourceIndex)).map(record => record.sourceIndex));
419
+ const wholeAssistant = new Map<number, number>();
420
+ for (const record of records) if (record.kind === "excerpt" && record.role === "assistant" && !record.span && record.sourceIndex !== undefined)
421
+ wholeAssistant.set(record.sourceIndex, (wholeAssistant.get(record.sourceIndex) ?? 0) + 1);
422
+ for (let pos = records.length - 1; pos >= 0; pos--) {
423
+ const record = records[pos]!;
424
+ if (record.kind !== "omission" || !record.sourceRange) continue;
425
+ if (record.role === "user") {
426
+ const missing = units.user.filter(unit => unit.position < at && unit.index >= record.sourceRange!.start && unit.index <= record.sourceRange!.end && !wholeUser.has(unit.index));
427
+ if (!missing.length) records.splice(pos, 1);
428
+ else records[pos] = omissionRecord("user", missing.length, [missing[0]!.index, missing.at(-1)!.index], false);
429
+ } else if (at !== compiledBoundary) {
430
+ const role = record.role;
431
+ if (role === "assistant" || role === "toolResult") {
432
+ const missing = units[role].filter(unit => unit.position < at && unit.index >= record.sourceRange!.start && unit.index <= record.sourceRange!.end &&
433
+ (role === "toolResult" || unit.count > (wholeAssistant.get(unit.index) ?? 0)));
434
+ const count = missing.reduce((n, unit) => n + unit.count - (role === "assistant" ? wholeAssistant.get(unit.index) ?? 0 : 0), 0);
435
+ if (!count) records.splice(pos, 1);
436
+ else records[pos] = omissionRecord(role, count, [missing[0]!.index, missing.at(-1)!.index], false);
437
+ }
438
+ }
382
439
  }
383
- if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
384
- ledger = [];
385
- for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
386
- const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
387
- if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target) ledger = candidate;
440
+ orderByOriginalSource(records, sourceIndices, originals.selectedIds);
441
+ const summary = render([...records, ...ledger]);
442
+ return { summary, records };
443
+ };
444
+ const compiled = tuck.compileDialogue(compileInput);
445
+ let offer = assemble(compiled.text);
446
+ // Only capacity left after all higher ranks can extend the native tail
447
+ // beyond its preferred rank boundary. No old allocator is consulted.
448
+ const liveStartId = calibration.ok ? calibration.selectedIds[0] : undefined;
449
+ const liveStart = liveStartId === undefined ? preferredBoundary : positions.get(liveStartId)!;
450
+ if (boundary > liveStart) {
451
+ const recordCosts = new Float64Array(entries.length + 1), recordCounts = new Int32Array(entries.length + 1);
452
+ const sourcePositions = new Map(rows.map(row => [row.index, row.position]));
453
+ const wholeUsers = new Set(offer.records.filter(record => record.kind === "excerpt" && record.role === "user" &&
454
+ record.text === userTexts.get(record.sourceIndex)).map(record => record.sourceIndex));
455
+ const wholeAssistants = new Map<number, number>();
456
+ for (const record of offer.records) {
457
+ const at = record.sourceIndex === undefined ? undefined : sourcePositions.get(record.sourceIndex);
458
+ if (at !== undefined) { recordCosts[at + 1] += lineCost([record]); recordCounts[at + 1]++; }
459
+ if (record.kind === "excerpt" && record.role === "assistant" && !record.span && record.sourceIndex !== undefined)
460
+ wholeAssistants.set(record.sourceIndex, (wholeAssistants.get(record.sourceIndex) ?? 0) + 1);
388
461
  }
462
+ for (let at = 1; at <= entries.length; at++) {
463
+ recordCosts[at] += recordCosts[at - 1]!; recordCounts[at] += recordCounts[at - 1]!;
389
464
  }
390
- const mandatory = new Set([...protectedView.whole].filter(index => {
391
- const row = users.find(row => row.index === index);
392
- return row?.message.role === "user" && isTextOnly(row.message.content);
393
- }));
394
- const fixed = [...protectedView.kept, ...ledger], fixedCost = lineCost(fixed);
395
- const maxBriefChars = Math.max(0, maxSummaryCharacters - fixedCost);
396
- const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
397
- sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(byId.get(row.id)!)),
398
- ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
399
- const imageLabels = new Map<number | undefined, Set<string>>();
400
- for (const row of sourceRows) if (row.message.role === "user" && Array.isArray(row.message.content))
401
- imageLabels.set(row.index, new Set(row.message.content.flatMap(part => part.type === "image" ? [`[image: ${part.mimeType}]`] : [])));
402
- const compiledBoundary = boundary;
403
- // A protected custom prompt uses its native entry ID in the same anchoring/movement path as indexed user prompts.
404
- const sourceKey = (record: TranscriptRecord) => current?.type === "custom_message" && record.sourceEntryId === current.id ? current.id : record.sourceIndex;
405
- const assemble = (compiled: string, at = compiledBoundary) => {
406
- const split = compiled ? splitSummary(compiled) : undefined;
407
- if (compiled && !split) throw new Error("pi-tuck returned an invalid summary");
408
- const inputRecords = split ? parseRecords(split.body, split.version) : protectedView.omissions;
409
- const expanded = new Set(protectedView.kept.filter(record => record.kind === "excerpt" && inputRecords.some(row =>
410
- row.kind === "excerpt" && row.role === record.role && sourceKey(row) === sourceKey(record) && row.text.startsWith(record.text!) && row.text.length >= record.text!.length)).map(sourceKey));
411
- const anchored = new Set(protectedView.kept.map(sourceKey));
412
- const moved = new Set(rows.filter(row => row.position >= at && row.position < compiledBoundary).map(row =>
413
- current?.type === "custom_message" && row.id === current.id ? row.id : row.index));
414
- const records = [...inputRecords.filter(record => {
415
- const key = sourceKey(record);
416
- if (key !== undefined && moved.has(key)) return false;
417
- if (record.kind === "excerpt" && record.role === "user" && imageLabels.get(record.sourceIndex)?.has(record.text)) return true;
418
- return record.role !== "user" && record.role !== "custom" || key === undefined || !anchored.has(key) || expanded.has(key);
419
- }), ...protectedView.kept.filter(record => !expanded.has(sourceKey(record)) && !moved.has(sourceKey(record)))];
420
- // Mixed user turns keep their text opening, while their image
421
- // metadata remains in the ordinary lower-ranked dialogue lane.
422
- const wholeUser = new Set(records.filter(record => record.kind === "excerpt" && record.role === "user" && record.text === userTexts.get(record.sourceIndex)).map(record => record.sourceIndex));
423
- const wholeAssistant = new Map<number, number>();
424
- for (const record of records) if (record.kind === "excerpt" && record.role === "assistant" && !record.span && record.sourceIndex !== undefined)
425
- wholeAssistant.set(record.sourceIndex, (wholeAssistant.get(record.sourceIndex) ?? 0) + 1);
426
- for (let pos = records.length - 1; pos >= 0; pos--) {
427
- const record = records[pos]!;
428
- if (record.kind !== "omission" || !record.sourceRange) continue;
429
- if (record.role === "user") {
430
- const missing = units.user.filter(unit => unit.position < at && unit.index >= record.sourceRange!.start && unit.index <= record.sourceRange!.end && !wholeUser.has(unit.index));
431
- if (!missing.length) records.splice(pos, 1);
432
- else records[pos] = omissionRecord("user", missing.length, [missing[0]!.index, missing.at(-1)!.index], false);
433
- } else if (at !== compiledBoundary) {
434
- const role = record.role;
435
- if (role === "assistant" || role === "toolResult") {
436
- const missing = units[role].filter(unit => unit.position < at && unit.index >= record.sourceRange!.start && unit.index <= record.sourceRange!.end &&
437
- (role === "toolResult" || unit.count > (wholeAssistant.get(unit.index) ?? 0)));
438
- const count = missing.reduce((n, unit) => n + unit.count - (role === "assistant" ? wholeAssistant.get(unit.index) ?? 0 : 0), 0);
439
- if (!count) records.splice(pos, 1);
440
- else records[pos] = omissionRecord(role, count, [missing[0]!.index, missing.at(-1)!.index], false);
441
- }
442
- }
443
- }
444
- orderByOriginalSource(records, sourceIndices, originals.selectedIds);
445
- const summary = render([...records, ...ledger]);
446
- return { summary, after: price(summary.length, at), records };
447
- };
448
- const compiled = tuck.compileDialogue(compileInput);
449
- let offer = assemble(compiled.text);
450
- // Only capacity left after all higher ranks can extend the native tail
451
- // beyond its preferred rank boundary. No old allocator is consulted.
452
- const liveStartId = calibration.ok ? calibration.selectedIds[0] : undefined;
453
- const liveStart = liveStartId === undefined ? preferredBoundary : positions.get(liveStartId)!;
454
- if (boundary > liveStart) {
455
- const recordCosts = new Float64Array(entries.length + 1), recordCounts = new Int32Array(entries.length + 1);
456
- const sourcePositions = new Map(rows.map(row => [row.index, row.position]));
457
- const wholeUsers = new Set(offer.records.filter(record => record.kind === "excerpt" && record.role === "user" &&
458
- record.text === userTexts.get(record.sourceIndex)).map(record => record.sourceIndex));
459
- const wholeAssistants = new Map<number, number>();
460
- for (const record of offer.records) {
461
- const at = record.sourceIndex === undefined ? undefined : sourcePositions.get(record.sourceIndex);
462
- if (at !== undefined) { recordCosts[at + 1] += lineCost([record]); recordCounts[at + 1]++; }
463
- if (record.kind === "excerpt" && record.role === "assistant" && !record.span && record.sourceIndex !== undefined)
464
- wholeAssistants.set(record.sourceIndex, (wholeAssistants.get(record.sourceIndex) ?? 0) + 1);
465
- }
466
- for (let at = 1; at <= entries.length; at++) {
467
- recordCosts[at] += recordCosts[at - 1]!; recordCounts[at] += recordCounts[at - 1]!;
468
- }
469
- // A tail extension removes source records and shortens at most three
470
- // counted ranges. Price those changes from prefix sums; render only the
471
- // winning suffix, rather than parsing/serializing the dialogue per step.
472
- const ranges = offer.records.flatMap(record => {
473
- if (record.kind !== "omission" || !record.sourceRange || !["user", "assistant", "toolResult"].includes(record.role ?? "")) return [];
474
- const role = record.role as keyof typeof units;
475
- const missing = units[role].flatMap(unit => {
476
- const count = role === "user" ? Number(!wholeUsers.has(unit.index)) : unit.count - (role === "assistant" ? wholeAssistants.get(unit.index) ?? 0 : 0);
477
- return count && unit.position < compiledBoundary && unit.index >= record.sourceRange!.start && unit.index <= record.sourceRange!.end ? [{ ...unit, count }] : [];
478
- });
479
- const ends = new Int32Array(entries.length + 1), counts = new Int32Array(missing.length + 1);
480
- let seen = 0;
481
- for (let at = 0; at <= entries.length; at++) {
482
- while (seen < missing.length && missing[seen]!.position < at) seen++;
483
- ends[at] = seen;
484
- }
485
- missing.forEach((unit, at) => counts[at + 1] = counts[at]! + unit.count);
486
- return [{ role, missing, ends, counts, cost: lineCost([record]) }];
465
+ // A tail extension removes source records and shortens at most three
466
+ // counted ranges. Price those changes from prefix sums; render only the
467
+ // winning suffix, rather than parsing/serializing the dialogue per step.
468
+ const ranges = offer.records.flatMap(record => {
469
+ if (record.kind !== "omission" || !record.sourceRange || !["user", "assistant", "toolResult"].includes(record.role ?? "")) return [];
470
+ const role = record.role as keyof typeof units;
471
+ const missing = units[role].flatMap(unit => {
472
+ const count = role === "user" ? Number(!wholeUsers.has(unit.index)) : unit.count - (role === "assistant" ? wholeAssistants.get(unit.index) ?? 0 : 0);
473
+ return count && unit.position < compiledBoundary && unit.index >= record.sourceRange!.start && unit.index <= record.sourceRange!.end ? [{ ...unit, count }] : [];
487
474
  });
488
- const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
489
- const keptReadCost = lineCost(keptReads), keptReadIndices = new Set(keptReads.map(record => record.sourceIndex));
490
- const lastKeptReadPosition = entries.findLastIndex(entry => keptReadIndices.has(indices.get(entry.id)));
491
- const extensionPrice = (at: number) => {
492
- // Fixed kept reads outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
493
- if (keptReads.length && (at <= lastKeptReadPosition || keptReadCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000))) return Infinity;
494
- let cost = baseCost - (recordCosts[compiledBoundary]! - recordCosts[at]!);
495
- let count = baseCount - (recordCounts[compiledBoundary]! - recordCounts[at]!);
496
- for (const range of ranges) {
497
- const end = range.ends[at]!;
498
- cost -= range.cost;
499
- if (end) cost += lineCost([omissionRecord(range.role, range.counts[end]!, [range.missing[0]!.index, range.missing[end - 1]!.index], false)]);
500
- else count--;
501
- }
502
- return price(frameLength(cost, count), at);
503
- };
504
- for (let at = boundary - 1; at >= liveStart; at--) {
505
- const entry = entries[at]!;
506
- if (entry.type !== "message" && entry.type !== "custom_message" && entry.type !== "branch_summary") continue;
507
- if (entry.type === "message" && entry.message.role === "toolResult") continue;
508
- if (extensionPrice(at) <= target) boundary = at;
509
- else break;
475
+ const ends = new Int32Array(entries.length + 1), counts = new Int32Array(missing.length + 1);
476
+ let seen = 0;
477
+ for (let at = 0; at <= entries.length; at++) {
478
+ while (seen < missing.length && missing[seen]!.position < at) seen++;
479
+ ends[at] = seen;
480
+ }
481
+ missing.forEach((unit, at) => counts[at + 1] = counts[at]! + unit.count);
482
+ return [{ role, missing, ends, counts, cost: lineCost([record]) }];
483
+ });
484
+ const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
485
+ const keptReadCost = lineCost(keptReads), keptReadIndices = new Set(keptReads.map(record => record.sourceIndex));
486
+ const lastKeptReadPosition = entries.findLastIndex(entry => keptReadIndices.has(indices.get(entry.id)));
487
+ const extensionPrice = (at: number) => {
488
+ // Fixed kept reads outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
489
+ if (keptReads.length && (at <= lastKeptReadPosition || keptReadCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000))) return Infinity;
490
+ let cost = baseCost - (recordCosts[compiledBoundary]! - recordCosts[at]!);
491
+ let count = baseCount - (recordCounts[compiledBoundary]! - recordCounts[at]!);
492
+ for (const range of ranges) {
493
+ const end = range.ends[at]!;
494
+ cost -= range.cost;
495
+ if (end) cost += lineCost([omissionRecord(range.role, range.counts[end]!, [range.missing[0]!.index, range.missing[end - 1]!.index], false)]);
496
+ else count--;
510
497
  }
511
- if (boundary !== compiledBoundary) offer = assemble(compiled.text, boundary);
498
+ return price(frameLength(cost, count), at);
499
+ };
500
+ for (let at = boundary - 1; at >= liveStart; at--) {
501
+ const entry = entries[at]!;
502
+ if (entry.type !== "message" && entry.type !== "custom_message" && entry.type !== "branch_summary") continue;
503
+ if (entry.type === "message" && entry.message.role === "toolResult") continue;
504
+ if (extensionPrice(at) <= target) boundary = at;
505
+ else break;
512
506
  }
513
- const projection = preview(offer.summary, boundary);
514
- assertNativeToolRounds(projection);
515
- const after = measure(projection);
516
- if (after + reserveTokens >= model.contextWindow || after >= before)
517
- return { unavailable: "pi-tuck's draft does not reduce context within the request budget", capacityRejected: after + reserveTokens >= model.contextWindow, floorMessages: floorProjection };
518
- const mode: DraftMode = compiled.step === "whole" ? "dialogue" : "shrunk";
519
- return { compaction: { summary: offer.summary, firstKeptEntryId: entries[boundary]?.id ?? "", tokensBefore: input.tokensBefore,
520
- details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode } }, after, mode };
507
+ if (boundary !== compiledBoundary) offer = assemble(compiled.text, boundary);
521
508
  }
522
-
509
+ const projection = preview(offer.summary, boundary);
510
+ assertNativeToolRounds(projection);
511
+ const after = measure(projection);
512
+ if (after + reserveTokens >= model.contextWindow || after >= before)
513
+ return { unavailable: "pi-tuck's draft does not reduce context within the request budget", capacityRejected: after + reserveTokens >= model.contextWindow, floorMessages: floorProjection };
514
+ const mode: DraftMode = compiled.step === "whole" ? "dialogue" : "shrunk";
515
+ return { compaction: { summary: offer.summary, firstKeptEntryId: entries[boundary]?.id ?? "", tokensBefore: input.tokensBefore,
516
+ details: { ...detailsAt(boundary), tokensAfter: after, carriedTarget: target, view: mode === "dialogue" ? "complete-dialogue" : "shrunk-dialogue", mode } }, after, mode };
523
517
  }
524
518
 
525
519
  /** Numeric references use the original session index, then intersect with readable current-branch entries. */