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