pi-tuck 1.3.4 → 1.5.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 (48) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +67 -122
  3. package/dist/index.d.ts +1 -4
  4. package/dist/index.js +56 -10
  5. package/dist/src/budget.d.ts +6 -15
  6. package/dist/src/budget.js +6 -11
  7. package/dist/src/build-id.d.ts +1 -1
  8. package/dist/src/build-id.js +1 -1
  9. package/dist/src/compaction.d.ts +15 -20
  10. package/dist/src/compaction.js +236 -204
  11. package/dist/src/content-observations.d.ts +24 -0
  12. package/dist/src/content-observations.js +122 -0
  13. package/dist/src/diagnostics.d.ts +1 -3
  14. package/dist/src/footer.d.ts +37 -0
  15. package/dist/src/footer.js +91 -0
  16. package/dist/src/ledger.d.ts +6 -3
  17. package/dist/src/ledger.js +14 -7
  18. package/dist/src/llama-continuation.d.ts +8 -0
  19. package/dist/src/llama-continuation.js +179 -0
  20. package/dist/src/recall.js +8 -25
  21. package/dist/src/request-capacity.d.ts +11 -26
  22. package/dist/src/request-capacity.js +20 -57
  23. package/dist/src/run.d.ts +16 -7
  24. package/dist/src/run.js +53 -25
  25. package/dist/src/status.d.ts +9 -0
  26. package/dist/src/status.js +14 -9
  27. package/dist/src/tuck/core/format.js +1 -1
  28. package/dist/src/tuck/core/readable-content.d.ts +14 -0
  29. package/dist/src/tuck/core/readable-content.js +43 -0
  30. package/dist/src/tuck.d.ts +2 -1
  31. package/dist/src/tuck.js +92 -30
  32. package/index.ts +46 -10
  33. package/package.json +3 -1
  34. package/src/budget.ts +7 -12
  35. package/src/build-id.ts +1 -1
  36. package/src/compaction.ts +228 -194
  37. package/src/content-observations.ts +115 -0
  38. package/src/diagnostics.ts +1 -1
  39. package/src/footer.ts +111 -0
  40. package/src/ledger.ts +17 -10
  41. package/src/llama-continuation.ts +176 -0
  42. package/src/recall.ts +8 -20
  43. package/src/request-capacity.ts +18 -57
  44. package/src/run.ts +48 -22
  45. package/src/status.ts +20 -9
  46. package/src/tuck/core/format.ts +1 -1
  47. package/src/tuck/core/readable-content.ts +44 -0
  48. package/src/tuck.ts +79 -28
@@ -1,6 +1,6 @@
1
1
  import { textOf } from "./tuck/core/content.js";
2
2
  import { PendingCut, StartingPrompt, Run } from "./run.js";
3
- import { requestReplyFloor, replyFit, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath, seedContextWindow, WINDOW_RECEIPT } from "./request-capacity.js";
3
+ import { CUT_REPLY_FLOOR, requestReplyFloor, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
4
4
  import { BUILD_ID } from "./build-id.js";
5
5
  import { DIAGNOSTIC_BUILD, IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry } from "./diagnostics.js";
6
6
  import { createHash } from "node:crypto";
@@ -17,7 +17,7 @@ import { Type } from "typebox";
17
17
  import { Check } from "typebox/value";
18
18
  import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
19
19
  import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
20
- import { LOADED_VERSION, statusText } from "./status.js";
20
+ import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
21
21
  import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
22
22
  import { notify } from "./notify.js";
23
23
  import { applyHistoryTools, historyToolDeclarations, historyToolNames, stageHistoryTools } from "./history-tools.js";
@@ -46,47 +46,29 @@ const reply = (value) => ({ content: [{ type: "text", text: JSON.stringify(value
46
46
  * a `CommitFault`, it ends with its attempt (`resetRun`), and the next attempt plans afresh from the session as it is. */
47
47
  class Refusal extends Error {
48
48
  }
49
- /** A cut this compactor supplied that Pi then failed to commit. Pi appends a cut to the session in memory before it writes the file, so the
50
- * session may hold a cut its file lacks; what is written after would build on it. The one failure that stays until the session restarts. */
49
+ /** Pi could not confirm a pi-tuck cut on disk. Keep this fault until restart because a failed boundary may leave memory and disk out of sync. */
51
50
  class CommitFault extends Error {
52
51
  }
53
52
  /** A refusal for want of room, which the user can remedy: it carries advice. */
54
53
  class CapacityError extends Refusal {
55
54
  }
56
- /** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
57
- * likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
55
+ /** Explain a high planning factor, which can come from reported usage or an overflow estimate. */
58
56
  export const refusalNotice = (message, factor) => message + "; shorten the input, use a model with a larger window, or lower Pi's compaction.reserveTokens, then retry." +
59
- (factor >= 1.5 ? ` This provider has counted up to ${factor.toFixed(1)}x the input pi-tuck estimates; through a router such as OpenRouter, a different upstream may count less.` : "");
60
- /** What the operator hears when the provider refuses a request pi-tuck admitted as over its window: the bound that reply puts on the counting, and
61
- * what pi-tuck did with it. A bound pi-tuck cannot carry (above the ceiling) says so rather than implying the next request is planned at it. */
62
- export const overflowNotice = (contextWindow, bound, learned) => `pi-tuck: the provider refused this request as over its ${contextWindow}-token window, so the input counted at least ${bound.toFixed(2)}x what pi-tuck estimated` +
63
- (learned ? "; the next request is planned at that." : "; too far out to be a low estimate, so the factor is unchanged.");
57
+ (factor >= 1.5 ? ` pi-tuck is planning with ${factor.toFixed(1)}x its base input estimate. Through a router such as OpenRouter, a different upstream may count less.` : "");
58
+ /** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
59
+ export const overflowNotice = (contextWindow, bound, learned) => `pi-tuck: the provider refused this request for context overflow. Using the configured ${contextWindow}-token window as the input limit gives a planning factor of ${bound.toFixed(2)}x.` +
60
+ (learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
61
+ /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
62
+ export const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
64
63
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
65
64
  export const CALIBRATION_CEILING = 1.5;
66
65
  /** How many recent paired replies (and overflow bounds, and the seed while it is among them) the calibration factor is the maximum of. */
67
66
  export const CALIBRATION_WINDOW = 32;
68
- /** Measured provider-input undercount by model, as "provider/id". An identity with no usable receipt of its own starts its window with this entry, which
69
- * ages out after CALIBRATION_WINDOW later entries; every other model starts at 1. Empty: an undercount of 1.18 once measured for openai/gpt-6.1-sol
70
- * was replayed reasoning, which the estimate now counts; with it counted, the first 32 requests of a real session measured at most 0.97. */
71
- export const MEASURED_CALIBRATION = {};
72
- /** The window of an identity with no usable receipt of its own: the model's measured undercount (at most CALIBRATION_CEILING), else 1. `key` is
73
- * `identityFor`'s [provider, api, id]. */
74
- function initialWindow(key) {
75
- try {
76
- const [provider, , id] = JSON.parse(key);
77
- return [Math.min(MEASURED_CALIBRATION[`${provider}/${id}`] ?? 1, CALIBRATION_CEILING)];
78
- }
79
- catch {
80
- return [1];
81
- }
82
- }
83
67
  export const CALIBRATION_RECEIPT = 'pi-tuck-calibration';
84
- /** The calibration window a session starts with under accounting identity `key`: the newest calibration entry or compaction on the branch that carries this package's
85
- * receipt decides, and no older receipt is consulted. A receipt without the identity field (written before it existed) or from another identity gives `initialWindow`.
86
- * Otherwise its `calibrationWindow` (an array of 1..CALIBRATION_WINDOW finite numbers, oldest first) is the window, each entry clamped to
87
- * [0, CALIBRATION_CEILING]; without a valid one, the window is its `calibrationFactor` clamped to [1, CALIBRATION_CEILING] as one entry, else
88
- * `initialWindow`. A usable receipt of the identity's own wins over the measured seed, as a learned window replaces it: a Resume from a receipt
89
- * written before the seed existed, or after it aged out, starts at that receipt's window (as low as 1). Reads only; a malformed receipt never throws. */
68
+ /** Read the newest applicable calibration receipt on the branch for `key` ([provider, api, id]). A custom
69
+ * observation for another identity is skipped. A compaction receipt for another or missing identity resets
70
+ * the seed to [1]. A matching receipt supplies its recent ratios clamped to [0, CALIBRATION_CEILING],
71
+ * or its legacy factor clamped to [1, CALIBRATION_CEILING]. Without a usable seed, start at [1]. */
90
72
  export function seedWindow(branch, key) {
91
73
  for (let i = branch.length; i--;) {
92
74
  const entry = branch[i];
@@ -98,43 +80,34 @@ export function seedWindow(branch, key) {
98
80
  if (calibrationIdentity !== key) {
99
81
  if (entry.type === "custom")
100
82
  continue; // Another model's new observation does not hide this model's last saved seed.
101
- return initialWindow(key);
83
+ return [1];
102
84
  }
103
85
  if (Array.isArray(stored) && stored.length >= 1 && stored.length <= CALIBRATION_WINDOW && stored.every(n => typeof n === "number" && Number.isFinite(n)))
104
86
  return stored.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING));
105
87
  if (typeof calibrationFactor === "number" && Number.isFinite(calibrationFactor))
106
88
  return [Math.min(Math.max(calibrationFactor, 1), CALIBRATION_CEILING)];
107
- return initialWindow(key);
89
+ return [1];
108
90
  }
109
- return initialWindow(key);
91
+ return [1];
110
92
  }
111
93
  /** One accounting owner. Session start still defers receipt loading until the first budget read;
112
- * tree moves load immediately, and identity changes keep any uncommitted window observation. */
94
+ * tree moves load immediately. */
113
95
  class Calibration {
114
96
  identity = '';
115
97
  factor = 1;
116
98
  ratios = [];
117
- learnedContextWindow;
118
- /** The configured window the learned window was learned under; the learned window applies only while the model still has it. */
119
- learnedCatalogue;
120
- windowObservation;
121
99
  pending;
122
100
  lastCeiling = null;
123
101
  estimatedTokens = 0;
124
102
  seededIdentity = '';
125
103
  static key(ctx) { return ctx.model ? JSON.stringify([ctx.model.provider, ctx.model.api, ctx.model.id]) : ''; }
126
- /** Model selection itself never reloads receipts: switching away and back without a request keeps the learned window. */
127
104
  select(ctx) { this.identity = Calibration.key(ctx); }
128
- needsSeed(ctx) { return this.seededIdentity !== Calibration.key(ctx); }
105
+ needsSeed() { return this.seededIdentity !== this.identity; }
129
106
  reseed(ctx, reason) {
130
107
  this.identity = Calibration.key(ctx);
131
108
  this.pending = undefined;
132
- if (reason !== 'identity')
133
- this.windowObservation = undefined;
134
109
  if (reason === 'session') {
135
110
  this.factor = 1;
136
- this.learnedContextWindow = undefined;
137
- this.learnedCatalogue = undefined;
138
111
  this.estimatedTokens = 0;
139
112
  // Keep the old ratios/ceiling until their existing readers replace them, as in 1.1.1.
140
113
  this.seededIdentity = '';
@@ -146,8 +119,6 @@ class Calibration {
146
119
  const branch = ctx.sessionManager.getBranch();
147
120
  this.ratios = seedWindow(branch, this.identity);
148
121
  this.factor = Math.max(1, ...this.ratios);
149
- this.learnedCatalogue = ctx.model?.contextWindow;
150
- this.learnedContextWindow = seedContextWindow(branch, this.identity, this.learnedCatalogue);
151
122
  }
152
123
  learn(value, ctx, append) {
153
124
  this.ratios.push(value);
@@ -196,7 +167,7 @@ export async function installCompaction(pi, options = {}) {
196
167
  }
197
168
  });
198
169
  const captureDraft = (draft, ctx, reserve, reason, tokensBefore, retainCurrentInput, operatorManual, previousSummary, budget) => recorder.measureInline(() => {
199
- const attached = attachReceipt(draft, reason, reserve, contextWindow(ctx), { responseReserveTokens: budget?.response, hostInputTokens: budget?.host, mandatoryInputTokens: budget?.mandatory, target: budget?.target, triggerMarginTokens: budget?.margin, ...(cutAt === 1 ? {} : { cutAt }), calibrationFactor: calibration.factor, calibrationWindow: [...calibration.ratios], calibrationIdentity: calibration.identity, learnedContextWindow: calibration.learnedContextWindow, ...(calibration.learnedContextWindow !== undefined && calibration.learnedCatalogue !== undefined ? { catalogueContextWindow: calibration.learnedCatalogue } : {}), activeInputCeilingTokens: calibration.lastCeiling });
170
+ const attached = attachReceipt(draft, reason, reserve, contextWindow(ctx), { responseReserveTokens: budget?.response, hostInputTokens: budget?.host, mandatoryInputTokens: budget?.mandatory, target: budget?.target, triggerMarginTokens: budget?.margin, ...(cutAt === 1 ? {} : { cutAt }), calibrationFactor: calibration.factor, calibrationWindow: [...calibration.ratios], calibrationIdentity: calibration.identity, activeInputCeilingTokens: calibration.lastCeiling });
200
171
  proposalId = receiptId(attached);
201
172
  if (recorder.enabled) {
202
173
  try {
@@ -226,7 +197,7 @@ export async function installCompaction(pi, options = {}) {
226
197
  pi.on("session_compact", (_event, ctx) => observe(ctx));
227
198
  pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
228
199
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
229
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, pending: view(ctx).pending }), "info");
200
+ ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx) }), "info");
230
201
  } });
231
202
  // Pi's native start/settled events bracket the run and its post-turn cuts.
232
203
  let run;
@@ -235,6 +206,12 @@ export async function installCompaction(pi, options = {}) {
235
206
  const protectedPrompt = (ctx) => run?.prompt?.id(ctx.sessionManager.getBranch());
236
207
  const clips = () => run?.clips ?? emptyClips;
237
208
  const emptyClips = new Map();
209
+ const restoreClips = (snapshot) => {
210
+ const current = clips();
211
+ current.clear();
212
+ for (const [id, clip] of snapshot)
213
+ current.set(id, clip);
214
+ };
238
215
  const resetRun = (session = false) => {
239
216
  if (!session && run?.phase === "commit-failed")
240
217
  run.clear();
@@ -254,38 +231,23 @@ export async function installCompaction(pi, options = {}) {
254
231
  if (stateFor(ctx).kind === "active")
255
232
  return false;
256
233
  resetRun();
257
- calibration.windowObservation = undefined;
258
- lengthStop = false;
234
+ lengthStop = undefined;
259
235
  return true;
260
236
  };
261
237
  const promptRefusal = () => new Refusal("Prompt check failed: the whole starting prompt cannot fit after cutting to the band and room, shrinking the summary and clipping fresh results. Shorten the prompt or choose a model with a larger context window, then retry");
262
238
  const calibration = new Calibration();
263
- const serverClipped = new WeakSet();
264
239
  const identityFor = (ctx) => {
265
240
  calibration.select(ctx);
266
- if (calibration.needsSeed(ctx))
241
+ if (calibration.needsSeed())
267
242
  calibration.reseed(ctx, "identity");
268
243
  return calibration.identity;
269
244
  };
270
- pi.on("model_select", (_event, ctx) => { calibration.select(ctx); });
271
- const contextWindow = (ctx) => {
272
- identityFor(ctx);
273
- const model = ctx.model?.contextWindow ?? 0;
274
- const learned = calibration.learnedCatalogue === ctx.model?.contextWindow ? calibration.learnedContextWindow : undefined;
275
- return Math.min(model, learned ?? Infinity);
276
- };
277
- // This is the cap in Pi's built provider payload, including its context clamp and thinking adjustments.
278
- // An API with no explicit cap supplies no clipping evidence; never substitute the catalogue maximum.
279
- pi.on("before_provider_request", event => {
280
- if (!calibration.pending || !event.payload || typeof event.payload !== "object")
281
- return;
282
- const payload = event.payload;
283
- // Read at reply time so later in-place payload edits are included too.
284
- calibration.pending.requestedMaxTokens = () => {
285
- const cap = payload.max_tokens ?? payload.max_completion_tokens ?? payload.max_output_tokens;
286
- return typeof cap === "number" && Number.isSafeInteger(cap) && cap > 0 ? cap : undefined;
287
- };
245
+ pi.on("model_select", (_event, ctx) => {
246
+ calibration.select(ctx);
247
+ if (run)
248
+ run.rejectedBudget = undefined;
288
249
  });
250
+ const contextWindow = (ctx) => ctx.model?.contextWindow ?? 0;
289
251
  // The factor is max(1, the last CALIBRATION_WINDOW paired ratios, overflow bounds and seed): it rises at once and a stale high ratio ages out.
290
252
  const learn = (value, ctx) => calibration.learn(value, ctx, (kind, data) => pi.appendEntry(kind, data));
291
253
  const corrected = (tokens, ctx) => { identityFor(ctx); return Math.ceil(tokens * calibration.factor); };
@@ -296,7 +258,6 @@ export async function installCompaction(pi, options = {}) {
296
258
  // The cut planner's raw reserve for the target limit, on the same factor as every other consumer.
297
259
  const planReserve = (target, room, band, mandatory, ctx) => {
298
260
  identityFor(ctx);
299
- // The compiler subtracts this reserve from the catalogue window. Targets already use the learned window.
300
261
  return planningReserve(ctx.model?.contextWindow ?? 0, target === "band" ? band : room, calibration.factor, mandatory);
301
262
  };
302
263
  pi.on("message_end", (event, ctx) => {
@@ -322,11 +283,14 @@ export async function installCompaction(pi, options = {}) {
322
283
  (!overflow && !["stop", "toolUse", "length"].includes(message.stopReason)) ||
323
284
  !isDeepStrictEqual(convertToLlm(paired.messages), paired.snapshot))
324
285
  return;
325
- // The provider refused this exact request for exceeding the window: its true count was at least window + 1, a lower bound on the ratio. A
326
- // bound above the ceiling says the estimate is not merely low, so it is not learned: the overflow ends the attempt as it does without it.
327
- // Either way the operator hears it from pi-tuck. The estimate is what admitted the request, and a turn that ended in the provider's error
328
- // with no word from pi-tuck read as a hang: every other refusal says why, and this is the path that skipped it.
286
+ // The error alone does not report the server's window or whether it counted input plus output. Use the configured
287
+ // input limit as a planning assumption and keep that assumption explicit in the notice.
329
288
  if (overflow) {
289
+ if (run?.phase === "admitted" && !options.requestReserve && piClamp) {
290
+ const { estimate, cap } = requestClamp(paired.messages, ctx);
291
+ if (cap !== undefined)
292
+ run.rejectedBudget = { input: estimate, output: cap };
293
+ }
330
294
  const window = contextWindow(ctx), bound = (window + 1) / paired.tokens;
331
295
  const learned = bound <= CALIBRATION_CEILING;
332
296
  notify(ctx, overflowNotice(window, bound, learned), "warning");
@@ -341,49 +305,44 @@ export async function installCompaction(pi, options = {}) {
341
305
  if (!counts.every(n => Number.isSafeInteger(n) && n >= 0))
342
306
  return;
343
307
  const input = counts.reduce((a, b) => a + b, 0), ratio = input / paired.tokens;
344
- const output = usage.output, bound = usage.input + usage.cacheRead + output, requested = paired.requestedMaxTokens?.();
345
- if (message.stopReason === "length" && requested !== undefined &&
346
- Number.isSafeInteger(output) && output >= 0 && output < requested &&
347
- Number.isSafeInteger(bound) && bound > 0 && bound <= ctx.model.contextWindow) {
348
- // A learned window from another configured window no longer bounds this one.
349
- if (calibration.learnedCatalogue !== ctx.model.contextWindow)
350
- calibration.learnedContextWindow = undefined;
351
- calibration.learnedCatalogue = ctx.model.contextWindow;
352
- calibration.learnedContextWindow = Math.min(calibration.learnedContextWindow ?? Infinity, bound);
353
- serverClipped.add(message);
354
- calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow, catalogue: ctx.model.contextWindow };
355
- }
356
- // A request that was answered cannot have held more than the model's window, so a report above it describes something that never happened.
357
- // Learning from one sets the factor for the requests after it: a 60,000-token cache read reported in a 32,768-token window made a
358
- // 6,000-token prompt refuse. The overflow branch above learns from a refusal, where the count is a lower bound, and the ceiling is unchanged.
308
+ // Reject usage above the configured window for calibration. Learning from a reported 60,000-token
309
+ // cache read with a 32,768-token window once made a subsequent 6,000-token prompt refuse.
359
310
  if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio))
360
311
  learn(ratio, ctx);
361
312
  });
362
- pi.on("turn_end", (event, ctx) => {
363
- if (standDown(ctx))
364
- return;
365
- if (calibration.windowObservation?.message !== event.message)
366
- return;
367
- const observation = calibration.windowObservation;
368
- calibration.windowObservation = undefined;
369
- pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window, catalogueContextWindow: observation.catalogue,
370
- serverClippedReplyId: event.messageEntryId });
371
- });
372
313
  // The operator's length-stop notice is decided at settle and is not attempt state: a run reset before then (a tree move inside another
373
314
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
374
- let lengthStop = false;
315
+ let lengthStop;
375
316
  pi.on("agent_start", (_event, ctx) => { if (standDown(ctx))
376
317
  return; run ??= new Run("starting"); if (!failure())
377
- run.transition("admitted", ctx); run.thinkingRetryPending = false; lengthStop = false; calibration.pending = undefined; });
378
- pi.on("message_end", event => { if (event.message.role === "assistant")
379
- lengthStop = event.message.stopReason === "length"; });
318
+ run.transition("admitted"); lengthStop = undefined; calibration.pending = undefined; });
319
+ // Pi's overflow-recovery rule: a new user message or a good reply grants another recovery.
320
+ const rearmLengthRetry = (ctx) => {
321
+ if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel)
322
+ run?.rearmLengthRetry();
323
+ };
324
+ pi.on("message_start", (event, ctx) => { if (event.message.role === "user")
325
+ rearmLengthRetry(ctx); });
326
+ pi.on("message_end", (event, ctx) => {
327
+ if (event.message.role !== "assistant")
328
+ return;
329
+ if (event.message.stopReason !== "error" && event.message.stopReason !== "length")
330
+ rearmLengthRetry(ctx);
331
+ lengthStop = event.message.stopReason === "length" ? {
332
+ kind: event.message.content && thinkingOnlyLength(event.message) ? "thinking" : "output",
333
+ cacheMiss: event.message.errorMessage === CONTINUATION_CACHE_MISS,
334
+ } : undefined;
335
+ });
380
336
  pi.on("agent_settled", (_event, ctx) => {
381
337
  try {
382
338
  if (standDown(ctx) || !lengthStop || !active())
383
339
  return;
384
- lengthStop = false;
385
- const message = "pi-tuck: the last reply stopped at the model's output limit and may be cut off. Ask the agent to continue.";
386
- notify(ctx, message, "warning");
340
+ const { kind, cacheMiss } = lengthStop;
341
+ const message = kind === "thinking"
342
+ ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
343
+ : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
344
+ lengthStop = undefined;
345
+ notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + INCIDENT_HINT, "warning");
387
346
  }
388
347
  finally {
389
348
  resetRun();
@@ -391,18 +350,14 @@ export async function installCompaction(pi, options = {}) {
391
350
  });
392
351
  const active = () => options.active?.() ?? true;
393
352
  const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings?.());
394
- // The one reserve decision; every consumer takes its room from limits. Standalone starts at Pi's native cut point. Once a reply did
395
- // not fit (a length stop with text/tools, or a refusal pi-ai classes as a context overflow), hold the catalogue maximum too. A thinking-only
396
- // length stop uses branchReplyFloor's observed output instead; reserving the catalogue maximum would strand setups above the room.
397
- // Other errors, such as a 503, keep native's room. Read the whole branch, including history before compactions, each time: no flag to persist or reset on resume,
398
- // fork, /tree or a new session.
399
- const requestReserve = (ctx) => {
353
+ // Pi’s configured reserve is the standalone cut target, separate from the output cap.
354
+ const responseReserve = (ctx) => {
400
355
  const host = options.requestReserve?.(ctx);
401
356
  const budget = host ?? { response: settingsFor().getCompactionSettings(ctx.model).reserveTokens };
402
357
  if (!Number.isSafeInteger(budget.response) || budget.response < 0)
403
358
  throw new Error("Invalid host request reserve");
404
- const floor = host ? host.responseExact !== true : replyFit(ctx.sessionManager.getBranch()).failed;
405
- return { response: floor ? Math.max(budget.response, ctx.model?.maxTokens ?? 0) : budget.response };
359
+ const floor = host && host.responseExact !== true;
360
+ return floor ? Math.max(budget.response, ctx.model?.maxTokens ?? 0) : budget.response;
406
361
  };
407
362
  const inputRoom = (response, ctx) => {
408
363
  const configured = options.activeInputTokens;
@@ -413,17 +368,27 @@ export async function installCompaction(pi, options = {}) {
413
368
  return Math.min(contextWindow(ctx) - response, ceiling ?? Infinity);
414
369
  };
415
370
  // Room still owns every existing cut/clip attempt. Only final capacity admission uses the hard line.
371
+ let floorMinimum = 1;
416
372
  const limits = (ctx) => {
417
- const { response } = requestReserve(ctx), room = inputRoom(response, ctx);
418
- const floor = options.requestReserve ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model?.maxTokens);
373
+ const response = responseReserve(ctx), room = inputRoom(response, ctx);
374
+ const floor = options.requestReserve || !ctx.model ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model, floorMinimum);
419
375
  const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
420
376
  return { response, room, hardLine, replyFloor: floor };
421
377
  };
422
- const decisionBand = (ctx, room, system, current = view(ctx)) => {
423
- const last = current.session.getBranch().findLast(entry => entry.type === "compaction");
424
- const after = last?.type === "compaction" ? last.details?.tokensAfter : undefined;
425
- return bandOf(room, cutAt, options.cutAt === undefined && typeof after === "number" && Number.isFinite(after) && after >= 0
426
- ? { system, tokensAfter: after, factor: calibration.factor } : undefined);
378
+ const preservePrefix = (ctx) => ctx.model !== undefined &&
379
+ options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
380
+ const decisionBand = (ctx, room) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
381
+ /** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
382
+ const cutPoint = (ctx) => {
383
+ if (!active() || !ctx.model || stateFor(ctx).kind !== "active")
384
+ return undefined;
385
+ try {
386
+ const band = decisionBand(ctx, limits(ctx).room);
387
+ return band > 0 ? band : undefined;
388
+ }
389
+ catch {
390
+ return undefined;
391
+ }
427
392
  };
428
393
  const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
429
394
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
@@ -449,10 +414,33 @@ export async function installCompaction(pi, options = {}) {
449
414
  // whereas our hard line is in corrected units; fitting that line alone need not leave the branch's reply floor.
450
415
  const requestClamp = (messages, ctx) => {
451
416
  const context = normalizeContext({ messages: convertToLlm(messages) });
452
- const cap = piClamp?.({ ...ctx.model, contextWindow: contextWindow(ctx) }, context, ctx.model.maxTokens);
417
+ const cap = piClamp?.(ctx.model, context, ctx.model.maxTokens);
453
418
  const estimate = piMath ? piMath.estimateContextTokens(context).tokens : 0;
454
- return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor, estimate,
455
- fitsWindow: cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx) };
419
+ const fitsWindow = cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx);
420
+ // The native clamp bottoms out at one even when the estimate leaves no room.
421
+ return { cap, leavesFloor: cap === undefined || fitsWindow && cap >= limits(ctx).replyFloor, estimate, fitsWindow };
422
+ };
423
+ // Plan a cut above the room for the cut floor first. The floor only shapes cuts: where no plan reaches it, the admission floor plans as if it
424
+ // did not exist, so it never refuses a request.
425
+ const planAboveRoom = (plan, ctx) => {
426
+ const { replyFloor, room } = limits(ctx);
427
+ if (!options.requestReserve) {
428
+ const previousClips = new Map(clips());
429
+ floorMinimum = CUT_REPLY_FLOOR;
430
+ try {
431
+ const shaped = limits(ctx);
432
+ if (shaped.replyFloor > replyFloor && shaped.hardLine > room) {
433
+ const decision = plan(shaped.hardLine);
434
+ if (decision.kind === "cut" || decision.kind === "none")
435
+ return decision;
436
+ }
437
+ }
438
+ finally {
439
+ floorMinimum = 1;
440
+ }
441
+ restoreClips(previousClips);
442
+ }
443
+ return plan(limits(ctx).hardLine);
456
444
  };
457
445
  const projectedRequest = (messages, ctx, host, incoming, prompt, tools, cut) => {
458
446
  const enabled = cut || historyToolsEnabled(ctx), shapes = toolShapes(historyToolNames(pi, tools, enabled));
@@ -469,9 +457,7 @@ export async function installCompaction(pi, options = {}) {
469
457
  const candidate = deepest();
470
458
  if (candidate.kind === "cut" && fits(total(candidate), limits(ctx).hardLine, ctx) && requestClamp(project(candidate), ctx).leavesFloor)
471
459
  return candidate;
472
- clips().clear();
473
- for (const [id, clip] of previousClips)
474
- clips().set(id, clip);
460
+ restoreClips(previousClips);
475
461
  return { kind: "fault", capacity: true, message: clampMessage };
476
462
  };
477
463
  for (let retry = 0;; retry++) {
@@ -509,14 +495,14 @@ export async function installCompaction(pi, options = {}) {
509
495
  recorder.stop("native-attempt-failed");
510
496
  // Every refusal says why, once per attempt: a capacity error with what the user can change, a cut Pi failed to commit with what that
511
497
  // means for the session, anything else as it is (an attempt that ended with no word looked like a hang).
512
- const previous = failure(), shouldNotify = !previous;
498
+ const previous = failure();
513
499
  const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
514
500
  const receipted = run?.refusalReceipted;
515
501
  calibration.pending = undefined;
516
502
  // Keep the same terminal run until Pi settles; later start hooks cannot admit it.
517
503
  run ??= new Run("starting");
518
504
  run.clear();
519
- run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", ctx, fault);
505
+ run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", fault);
520
506
  run.refusalReceipted = true;
521
507
  try {
522
508
  if (!receipted)
@@ -525,10 +511,10 @@ export async function installCompaction(pi, options = {}) {
525
511
  }
526
512
  finally {
527
513
  try {
528
- if (shouldNotify)
529
- notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
514
+ if (!receipted)
515
+ notify(ctx, (fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
530
516
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
531
- : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error");
517
+ : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`) + INCIDENT_HINT, "error");
532
518
  }
533
519
  finally {
534
520
  ctx.abort();
@@ -556,11 +542,11 @@ export async function installCompaction(pi, options = {}) {
556
542
  // Pi normally reaches its pre-run threshold check within microtasks. Auth I/O or a later extension's input I/O can make a
557
543
  // real prompt expire too; safely fall back to carrying its cut in the request and saving it at the first boundary.
558
544
  setImmediate(() => { if (run === decision && decision.phase === "decided")
559
- decision.transition("expired", ctx); });
545
+ decision.transition("expired"); });
560
546
  });
561
547
  pi.registerTool({
562
548
  name: "tuck_recall", label: "pi-tuck history", parameters: RecallInput,
563
- description: "Keyword lookup locates particular text in your current branch. {query} returns ranked passages with read coordinates; punctuation separates words. Pass the returned next as {continuation} unchanged. Knowing an identifier does not itself justify narrowing discovery. {entryId} or {index} (a summary sourceIndex or #N) reads one source, optionally with query, offset and limit in UTF-16 characters (limit defaults to 8000). {} browses history; {around} expands neighbors; {entryId,image} reads an image; outputPath writes an original to a file with the native write tool. Hidden reasoning and system records are excluded.",
549
+ description: "Keyword lookup locates particular text in your current branch. {query} returns ranked passages with read coordinates; punctuation separates words. Pass the returned next as {continuation} unchanged. Knowing an identifier does not itself justify narrowing discovery. {entryId} or {index} (a summary sourceIndex or #N) reads one source, optionally with query, offset and limit in UTF-16 characters (limit defaults to 8000). {} browses history; {around} expands neighbors; {entryId,image} reads an image; outputPath writes an original to a file with the native write tool. Plain thinking is readable; signed, redacted or encrypted reasoning and system records are excluded.",
564
550
  async execute(_id, raw, signal, _update, ctx) {
565
551
  access();
566
552
  const input = checkedInput(raw);
@@ -600,13 +586,17 @@ export async function installCompaction(pi, options = {}) {
600
586
  // Pi checks its own threshold after a prompt's input and before the run starts: the prompt's cut, planned with the prompt counted,
601
587
  // is the answer, and it is saved before the first request.
602
588
  if ((run?.phase === "decided" || run?.phase === "claimed") && event.reason === "threshold") {
603
- run.transition("claimed", ctx);
589
+ run.transition("claimed");
604
590
  if (view(ctx).pending) {
605
591
  access();
606
- const current = view(ctx), { type: _, ...compaction } = run.cut.take();
592
+ const current = view(ctx), { type: _, ...compaction } = run.cut.take(ctx);
607
593
  return { compaction: { ...compaction, firstKeptEntryId: current.keptFromId } };
608
594
  }
609
595
  }
596
+ // Capacity is decided when there is another request to send. A threshold
597
+ // notification after exhausted reasoning must not put that response away.
598
+ if (event.reason === "threshold" && lengthStop?.kind === "thinking")
599
+ return { cancel: true };
610
600
  const operatorManual = event.reason === "manual";
611
601
  if (operatorManual && run?.phase !== "admitted")
612
602
  resetRun();
@@ -621,8 +611,10 @@ export async function installCompaction(pi, options = {}) {
621
611
  // cut: the system part and the host input. A prompt's cut is pi-tuck's own and never comes here.
622
612
  const saved = ctx.sessionManager.buildSessionProjection().messages;
623
613
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
624
- const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), saved, ctx.getSystemPrompt());
625
- const mandatory = system + host, band = decisionBand(ctx, room, system, view(ctx, event.reason === "threshold"));
614
+ const systemPrompt = ctx.getSystemPrompt(), tools = pi.getActiveTools();
615
+ const system = requestSystemPart(systemPrompt, tools, saved, systemPrompt);
616
+ const project = (messages, cut) => projectedRequest(messages, ctx, hostInput, [], systemPrompt, tools, cut);
617
+ const mandatory = system + host, band = decisionBand(ctx, room);
626
618
  const before = plannerMeasureFor(ctx)(saved);
627
619
  observeBudget(before + mandatory, ctx);
628
620
  // Pi's own usage threshold (reason "threshold") counts the last reply's output tokens, reasoning included, plus the messages after
@@ -645,7 +637,7 @@ export async function installCompaction(pi, options = {}) {
645
637
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
646
638
  // Every cut asked while no run is admitted (an operator's cut) is planned for a run that has not begun: the session has moved on
647
639
  // from any run that ended. A retry is inside its run.
648
- const draft = tuckDraft(tuck, event, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, retain, operatorManual, operatorManual || run?.phase !== "admitted", run?.phase === "admitted" ? protectedPrompt(ctx) : undefined);
640
+ const draft = tuckDraft(tuck, event, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, retain, operatorManual, operatorManual || run?.phase !== "admitted", run?.phase === "admitted" ? protectedPrompt(ctx) : undefined, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
649
641
  return draft.compaction ? { draft: true, after: draft.after, compaction: draft.compaction, reserve,
650
642
  messages: plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages }
651
643
  : { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
@@ -655,8 +647,31 @@ export async function installCompaction(pi, options = {}) {
655
647
  let decision = decide();
656
648
  const { hardLine } = limits(ctx);
657
649
  if (!operatorManual && hardLine > room && decision.kind === "fault") {
658
- decision = fits(before + mandatory, hardLine, ctx) ? { kind: "none" } : decide(hardLine, hardLine);
659
- decision = clampAboveRoom(decision, ctx, room, hardLine, candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory, candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, [], ctx.getSystemPrompt(), pi.getActiveTools(), candidate.kind === "cut"), target => target <= room ? decide() : decide(target, target), () => deepestDecision(ctx, operatorManual || run?.phase !== "admitted", retain));
650
+ decision = planAboveRoom(hardLine => clampAboveRoom(fits(before + mandatory, hardLine, ctx) ? { kind: "none" } : decide(hardLine, hardLine), ctx, room, hardLine, candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory, candidate => project(candidate.kind === "cut" ? candidate.plan.messages : saved, candidate.kind === "cut"), target => target <= room ? decide() : decide(target, target), () => deepestDecision(ctx, operatorManual || run?.phase !== "admitted", retain)), ctx);
651
+ }
652
+ const rejected = event.reason === "overflow" && event.willRetry ? run?.rejectedBudget : undefined;
653
+ if (rejected && decision.kind === "cut") {
654
+ const prompt = run?.prompt;
655
+ const canRetry = (candidate) => {
656
+ const messages = project(candidate.messages, true);
657
+ const { estimate, cap, leavesFloor } = requestClamp(messages, ctx);
658
+ const improves = leavesFloor && cap !== undefined && estimate < rejected.input &&
659
+ estimate + cap < rejected.input + rejected.output &&
660
+ fits(requestSystemPart(systemPrompt, tools, messages, systemPrompt) + conversationTokens(messages), hardLine, ctx) &&
661
+ (!prompt || carriesPrompt(messages, prompt.text(ctx.sessionManager.getBranch()), prompt.role));
662
+ recorder.capture("overflow-recovery", "estimated-before-provider-transforms", { rejected, input: estimate, output: cap, improves });
663
+ return improves;
664
+ };
665
+ if (!canRetry(decision.plan)) {
666
+ const previousClips = new Map(clips());
667
+ const deepest = deepestDecision(ctx, false, retain);
668
+ if (deepest.kind !== "cut" || !canRetry(deepest.plan)) {
669
+ restoreClips(previousClips);
670
+ recorder.stop("no-capacity-gain");
671
+ return { cancel: true };
672
+ }
673
+ decision = deepest;
674
+ }
660
675
  }
661
676
  if (decision.kind === "cut") {
662
677
  return { compaction: captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, event.reason, event.preparation.tokensBefore, retain, operatorManual, event.preparation.previousSummary, { response, host, mandatory, target: decision.target, margin: room - band }) };
@@ -696,7 +711,7 @@ export async function installCompaction(pi, options = {}) {
696
711
  pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
697
712
  const plannedView = (ctx, cut) => {
698
713
  const preview = new PendingCut();
699
- preview.plan(cut, ctx.sessionManager.getBranch().length);
714
+ preview.plan(cut, ctx);
700
715
  return preview.view(ctx);
701
716
  };
702
717
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
@@ -725,7 +740,7 @@ export async function installCompaction(pi, options = {}) {
725
740
  }
726
741
  }
727
742
  const before = measureFor(ctx)(saved);
728
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before,
743
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before,
729
744
  previousSummary: saved.find(message => message.role === "compactionSummary")?.summary, newPrompt, reRenderSummary: true,
730
745
  protectedPromptEntryId: newPrompt ? undefined : protectedPrompt(ctx), deepest: true }, ctx, 0, plannerMeasureFor(ctx), options.recallPolicy, retain);
731
746
  if (!draft.compaction)
@@ -740,7 +755,7 @@ export async function installCompaction(pi, options = {}) {
740
755
  // This does not relax thinking-only length recovery: retryLength still requires the observed reply floor before continuing,
741
756
  // and its pending retry cannot use this escape. No fresh content is clipped or edited by this admission attempt.
742
757
  const nativeFloorDecision = (ctx, newPrompt, retain, project) => {
743
- if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.thinkingRetryPending)
758
+ if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.lengthRetryPending)
744
759
  return;
745
760
  const candidate = deepestDecision(ctx, newPrompt, retain, false);
746
761
  if (candidate.kind !== "cut")
@@ -761,7 +776,6 @@ export async function installCompaction(pi, options = {}) {
761
776
  return;
762
777
  run.cut.clear();
763
778
  run.nativeFloorPending = false;
764
- const branchLength = ctx.sessionManager.getBranch().length;
765
779
  if (!active())
766
780
  return;
767
781
  access();
@@ -773,7 +787,7 @@ export async function installCompaction(pi, options = {}) {
773
787
  // Public early view only: later handlers, image normalization and tool-loop growth remain the complete-context guard's responsibility.
774
788
  const saved = ctx.sessionManager.buildSessionProjection().messages;
775
789
  const system = requestSystemPart(observedPrompt, tools, saved, ctx.getSystemPrompt());
776
- const band = decisionBand(ctx, room, system);
790
+ const band = decisionBand(ctx, room);
777
791
  const hostInput = hostSnapshot ?? hostMessages(ctx), host = conversationTokens(hostInput), measure = measureFor(ctx), before = measure(saved);
778
792
  const incoming = incomingPart + system, mandatory = incoming + host;
779
793
  observeBudget(before + mandatory, ctx);
@@ -794,12 +808,12 @@ export async function installCompaction(pi, options = {}) {
794
808
  // Only a due cut re-renders a summary that sits alone in the session: inside the band a cut is opportunistic, and a smaller summary
795
809
  // there buys nothing the request needed and costs history the next recall would have found.
796
810
  // A steer joins the admitted run: keep its starting prompt and the unexposed tool round, just as at a tool boundary.
797
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
811
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
798
812
  newPrompt: !protectedId, protectedPromptEntryId: protectedId, reRenderSummary: !opportunistic }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, Boolean(protectedId));
799
813
  if (!draft.compaction)
800
814
  return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
801
815
  const candidate = new PendingCut();
802
- candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, branchLength);
816
+ candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, ctx);
803
817
  const messages = candidate.view(ctx).session.buildSessionProjection().messages;
804
818
  assertNativeToolRounds(messages);
805
819
  return { draft: true, after: measure(messages), compaction: draft.compaction, reserve, messages };
@@ -808,9 +822,8 @@ export async function installCompaction(pi, options = {}) {
808
822
  let decision = gate.kind === "plan" ? decide(room, band, gate.opportunistic) : { kind: "defer" };
809
823
  const { hardLine } = limits(ctx);
810
824
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
811
- decision = fits(before + mandatory, hardLine, ctx) ? { kind: "none" } :
812
- fits(mandatory, hardLine, ctx) ? decide(hardLine, hardLine, false) : { kind: "defer" };
813
- decision = clampAboveRoom(decision, ctx, room, hardLine, candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory, candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, candidate.kind === "cut"), target => decide(target, target <= room ? band : target, false), () => deepestDecision(ctx, !protectedId, Boolean(protectedId)));
825
+ decision = planAboveRoom(hardLine => clampAboveRoom(fits(before + mandatory, hardLine, ctx) ? { kind: "none" } :
826
+ fits(mandatory, hardLine, ctx) ? decide(hardLine, hardLine, false) : { kind: "defer" }, ctx, room, hardLine, candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory, candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, candidate.kind === "cut"), target => decide(target, target <= room ? band : target, false), () => deepestDecision(ctx, !protectedId, Boolean(protectedId))), ctx);
814
827
  }
815
828
  if (decision.kind === "defer")
816
829
  return;
@@ -827,7 +840,7 @@ export async function installCompaction(pi, options = {}) {
827
840
  if (decision.kind === "fault")
828
841
  throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
829
842
  const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, Boolean(protectedId), false, previousSummary, { response, host, mandatory, target: decision.target, margin: room - band });
830
- run.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, branchLength);
843
+ run.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, ctx);
831
844
  };
832
845
  pi.on("before_agent_start", async (event, ctx) => {
833
846
  if (standDown(ctx))
@@ -839,7 +852,7 @@ export async function installCompaction(pi, options = {}) {
839
852
  beginRun("starting");
840
853
  run ??= new Run("starting");
841
854
  if (!failure() && run.phase !== "starting")
842
- run.transition("starting", ctx);
855
+ run.transition("starting");
843
856
  const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
844
857
  run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
845
858
  try {
@@ -906,7 +919,7 @@ export async function installCompaction(pi, options = {}) {
906
919
  // saved conversation. Pi's peek returns the steering queue, else the follow-up queue; a follow-up is not in the very next
907
920
  // request while tools still run, so it can be counted early: conservative, and nothing else would cut at that later boundary.
908
921
  const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), saved, ctx.getSystemPrompt());
909
- const band = decisionBand(ctx, room, system);
922
+ const band = decisionBand(ctx, room);
910
923
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
911
924
  const queued = event.context.pendingMessages.length ? conversationTokens(event.context.pendingMessages) : 0;
912
925
  const mandatory = system + host + queued;
@@ -946,7 +959,7 @@ export async function installCompaction(pi, options = {}) {
946
959
  unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
947
960
  plan: (target) => {
948
961
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
949
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
962
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
950
963
  if (!draft.compaction) {
951
964
  // The planner's own floor, so a clip's second budget is measured against what the smallest cut really keeps.
952
965
  if (draft.floorMessages && event.toolResults) {
@@ -999,18 +1012,20 @@ export async function installCompaction(pi, options = {}) {
999
1012
  calibration.estimatedTokens = corrected(before + mandatory, ctx);
1000
1013
  const { hardLine } = limits(ctx);
1001
1014
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
1002
- if (fits(before + mandatory, hardLine, ctx))
1003
- decision = { kind: "none" };
1004
- else {
1005
- decision = decide(hardLine, hardLine);
1006
- tryClips(hardLine, hardLine);
1007
- }
1008
- decision = clampAboveRoom(decision, ctx, room, hardLine, candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory, candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), candidate.kind === "cut"), target => {
1009
- const targetBand = target <= room ? band : target;
1010
- decision = decide(target, targetBand, target > room);
1011
- tryClips(target, targetBand, target > room);
1012
- return decision;
1013
- }, () => deepestDecision(ctx, false, true));
1015
+ decision = planAboveRoom(hardLine => {
1016
+ if (fits(before + mandatory, hardLine, ctx))
1017
+ decision = { kind: "none" };
1018
+ else {
1019
+ decision = decide(hardLine, hardLine);
1020
+ tryClips(hardLine, hardLine);
1021
+ }
1022
+ return clampAboveRoom(decision, ctx, room, hardLine, candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory, candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), candidate.kind === "cut"), target => {
1023
+ const targetBand = target <= room ? band : target;
1024
+ decision = decide(target, targetBand, target > room);
1025
+ tryClips(target, targetBand, target > room);
1026
+ return decision;
1027
+ }, () => deepestDecision(ctx, false, true));
1028
+ }, ctx);
1014
1029
  }
1015
1030
  if (decision.kind === "fault" && reason === "tool-loop") {
1016
1031
  if (decision.capacity)
@@ -1046,7 +1061,7 @@ export async function installCompaction(pi, options = {}) {
1046
1061
  const current = view(ctx);
1047
1062
  if (!current.pending)
1048
1063
  return decide ? boundaryCut(event, ctx, reason) : undefined;
1049
- const entry = run.cut.take();
1064
+ const entry = run.cut.take(ctx);
1050
1065
  const preview = current.session, context = Object.create(ctx, { sessionManager: { value: preview } });
1051
1066
  const more = decide && !event.entries.length
1052
1067
  ? boundaryCut({ ...event, context: { ...event.context, contextMessages: preview.buildSessionProjection().messages } }, context, reason) : undefined;
@@ -1055,54 +1070,73 @@ export async function installCompaction(pi, options = {}) {
1055
1070
  return { entries: [...event.entries, saved, ...(more?.entries ?? [])] };
1056
1071
  };
1057
1072
  const retryLength = (event, ctx) => {
1073
+ // Exhausting the full per-request allowance is not evidence that input is too large.
1074
+ // Preserve the unfinished response; provider-native continuation owns this case.
1075
+ // Native Pi does not compact-and-retry output that reached the catalogue cap.
1076
+ if (event.message.role !== "assistant" || !ctx.model)
1077
+ return;
1078
+ const stoppedOutput = event.message.usage?.output;
1079
+ if (stoppedOutput >= ctx.model.maxTokens) {
1080
+ return { entries: event.entries, continue: false };
1081
+ }
1058
1082
  // Pi's supported boundary drafts commit before finishTurn honors `continue`. Omitting the selected failed response also prevents
1059
1083
  // Pi's later native length recovery from retrying it independently. The stored message and its output usage stay on the branch.
1060
1084
  const entries = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries),
1061
1085
  { type: "context_edit", targetId: event.messageEntryId, replacement: null }];
1062
- if (run.thinkingRetryPending) {
1086
+ if (!run.canRetryLength) {
1063
1087
  markBoundary(entries);
1064
1088
  return { entries, continue: false };
1065
1089
  }
1066
1090
  const preview = liveCut.view(ctx, entries).session;
1067
1091
  const view = Object.create(ctx, { sessionManager: { value: preview } });
1068
1092
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
1069
- // The deepest cut only when it buys reply room: where Pi's cap on the request as it stands (the stopped reply left out) is already
1070
- // as large as the deepest cut's, the turn is retried uncut, and no history is given up for nothing.
1071
1093
  const asIs = projectedRequest(preview.buildSessionProjection().messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), false);
1072
1094
  const asIsCheck = requestClamp(asIs, view);
1073
1095
  const previousClips = new Map(clips());
1074
1096
  const decision = deepestDecision(view, false, true);
1075
- if (!serverClipped.has(event.message) && decision.kind === "cut" && asIsCheck.cap !== undefined && asIsCheck.leavesFloor &&
1076
- requestClamp(projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true), view).cap <= asIsCheck.cap) {
1077
- clips().clear();
1078
- for (const [id, clip] of previousClips)
1079
- clips().set(id, clip);
1097
+ const cut = decision.kind === "cut" ? {
1098
+ ...decision,
1099
+ messages: projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true),
1100
+ } : undefined;
1101
+ const check = cut && requestClamp(cut.messages, view);
1102
+ const continuation = `${ctx.model.provider}/${ctx.model.id}` === options.continuationModel;
1103
+ // A cut that adds no reply room gives up history for nothing: retry the request uncut.
1104
+ if (!continuation && asIsCheck.cap !== undefined && asIsCheck.leavesFloor && (check?.cap === undefined || check.cap <= asIsCheck.cap)) {
1105
+ restoreClips(previousClips);
1080
1106
  const { room, hardLine } = limits(view);
1081
- run.thinkingRetryPending = true;
1107
+ run.requestLengthRetry();
1082
1108
  const drafts = [...entries, { type: "custom", customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
1083
- stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: false,
1109
+ stoppedOutputTokens: stoppedOutput ?? 0, cut: false,
1084
1110
  piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }];
1085
1111
  markBoundary(drafts);
1086
1112
  return { entries: drafts, continue: true };
1087
1113
  }
1088
- if (decision.kind !== "cut")
1089
- throw new CapacityError(clampMessage);
1090
- const messages = projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true);
1114
+ // With a continuation model an unchanged allowance would repeat the same failed generation. If the
1115
+ // planner found no history to cut, there is no capacity diagnosis to make.
1116
+ if (!cut || check?.cap === undefined || asIsCheck.cap === undefined || check.cap <= (continuation ? Math.max(asIsCheck.cap, stoppedOutput ?? 0) : asIsCheck.cap)) {
1117
+ restoreClips(previousClips);
1118
+ if (!asIsCheck.leavesFloor) {
1119
+ if (check && !check.leavesFloor)
1120
+ throw new CapacityError(clampMessage);
1121
+ if (decision.kind === "fault" && decision.capacity)
1122
+ throw new CapacityError(decision.message);
1123
+ }
1124
+ markBoundary(entries);
1125
+ return { entries, continue: false };
1126
+ }
1127
+ const { messages } = cut;
1091
1128
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1092
1129
  throw promptRefusal();
1093
1130
  const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1094
- const tokens = system + conversationTokens(messages), check = requestClamp(messages, view);
1131
+ const tokens = system + conversationTokens(messages);
1095
1132
  const { response, room, hardLine } = limits(view);
1096
- // A learned server boundary uses the same admission rule as the guard: below the room the whole reserve fits in provider units.
1097
- // Keep the thinking-only rule's unconditional native-clamp floor unchanged.
1098
- const needsClampFloor = !serverClipped.has(event.message) || corrected(tokens, view) > room;
1099
- if (!fits(tokens, hardLine, view) || check.cap === undefined || needsClampFloor && !check.leavesFloor)
1133
+ if (!fits(tokens, hardLine, view) || !check.leavesFloor)
1100
1134
  throw new CapacityError(clampMessage);
1101
- const compaction = captureDraft(decision.plan.compaction, view, decision.plan.reserve, "length-retry", tokens, true, false, undefined, { response, host, mandatory: system + host + conversationTokens(event.context.pendingMessages), target: decision.target, margin: room - decisionBand(view, room, system) });
1102
- run.thinkingRetryPending = true;
1135
+ const compaction = captureDraft(cut.plan.compaction, view, cut.plan.reserve, "length-retry", tokens, true, false, undefined, { response, host, mandatory: system + host + conversationTokens(event.context.pendingMessages), target: cut.target, margin: room - decisionBand(view, room) });
1136
+ run.requestLengthRetry();
1103
1137
  const drafts = [...entries, { type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId || null, details: compaction.details },
1104
1138
  { type: "custom", customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
1105
- stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: true,
1139
+ stoppedOutputTokens: stoppedOutput ?? 0, cut: true,
1106
1140
  estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
1107
1141
  markBoundary(drafts);
1108
1142
  return { entries: drafts, continue: true };
@@ -1113,9 +1147,9 @@ export async function installCompaction(pi, options = {}) {
1113
1147
  return;
1114
1148
  if (!active() || run?.phase !== "admitted")
1115
1149
  return;
1116
- if ((thinkingOnlyLength(event.message) || serverClipped.has(event.message)) && !failure() && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
1150
+ if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
1117
1151
  return retryLength(event, ctx);
1118
- run.thinkingRetryPending = false;
1152
+ run.finishLengthRetry();
1119
1153
  const decide = event.outcome === "completed" && !ctx.signal?.aborted && event.context.canContinue && event.toolResults.length > 0 &&
1120
1154
  settingsFor().getCompactionSettings(ctx.model).enabled;
1121
1155
  if (!view(ctx).pending && !decide)
@@ -1159,7 +1193,7 @@ export async function installCompaction(pi, options = {}) {
1159
1193
  const guardCut = (messages, tokens, system, ctx) => {
1160
1194
  const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
1161
1195
  const before = conversationTokens(source), mandatory = tokens - before;
1162
- const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room, system);
1196
+ const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room);
1163
1197
  const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
1164
1198
  const previousClips = new Map(clips());
1165
1199
  const measure = measureFor(ctx);
@@ -1168,7 +1202,7 @@ export async function installCompaction(pi, options = {}) {
1168
1202
  unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
1169
1203
  plan: (target) => {
1170
1204
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
1171
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
1205
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
1172
1206
  protectedPromptEntryId: protectedPrompt(ctx) }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
1173
1207
  if (!draft.compaction)
1174
1208
  return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
@@ -1182,8 +1216,7 @@ export async function installCompaction(pi, options = {}) {
1182
1216
  const total = (candidate) => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory;
1183
1217
  let decision = decide(room, band);
1184
1218
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
1185
- decision = decide(hardLine, hardLine);
1186
- decision = clampAboveRoom(decision, ctx, room, hardLine, total, project, target => decide(target, target <= room ? band : target), () => deepestDecision(ctx, false, true));
1219
+ decision = planAboveRoom(hardLine => clampAboveRoom(decide(hardLine, hardLine), ctx, room, hardLine, total, project, target => decide(target, target <= room ? band : target), () => deepestDecision(ctx, false, true)), ctx);
1187
1220
  }
1188
1221
  const accepts = (candidate) => {
1189
1222
  if (candidate.kind !== "cut" || candidate.plan.after >= before)
@@ -1196,9 +1229,7 @@ export async function installCompaction(pi, options = {}) {
1196
1229
  decision = deepestDecision(ctx, false, true);
1197
1230
  let native = false;
1198
1231
  if (decision.kind !== "cut" || !accepts(decision)) {
1199
- clips().clear();
1200
- for (const [id, clip] of previousClips)
1201
- clips().set(id, clip);
1232
+ restoreClips(previousClips);
1202
1233
  const floor = nativeFloorDecision(ctx, false, true, project);
1203
1234
  if (!floor)
1204
1235
  return { messages };
@@ -1208,7 +1239,7 @@ export async function installCompaction(pi, options = {}) {
1208
1239
  if (decision.kind !== "cut")
1209
1240
  return { messages };
1210
1241
  const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary, { response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
1211
- run.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx.sessionManager.getBranch().length);
1242
+ run.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx);
1212
1243
  run.nativeFloorPending = native;
1213
1244
  syncHistoryTools(ctx);
1214
1245
  return { messages: historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)), toolShapes(pi.getActiveTools()), true), native };
@@ -1277,7 +1308,7 @@ export async function installCompaction(pi, options = {}) {
1277
1308
  try {
1278
1309
  if (!active() || run?.phase !== "admitted" || failure() || !settingsFor().getCompactionSettings(ctx.model).enabled)
1279
1310
  return;
1280
- const decide = event.outcome === "completed" && !ctx.signal?.aborted;
1311
+ const decide = event.outcome === "completed" && !ctx.signal?.aborted && lengthStop?.kind !== "thinking";
1281
1312
  if (view(ctx).pending ? event.outcome === "error" : !decide)
1282
1313
  return;
1283
1314
  return atBoundary(event, ctx, "run-end", decide);
@@ -1292,6 +1323,7 @@ export async function installCompaction(pi, options = {}) {
1292
1323
  // Reaching the next request boundary proves native commit returned, not durable storage.
1293
1324
  if (run) {
1294
1325
  run.pendingBoundaryReceipts = [];
1326
+ run.rejectedBudget = undefined;
1295
1327
  }
1296
1328
  calibration.pending = undefined;
1297
1329
  try {
@@ -1357,7 +1389,7 @@ export async function installCompaction(pi, options = {}) {
1357
1389
  fail(error, ctx);
1358
1390
  }
1359
1391
  });
1360
- return { close: async () => { recorder.stop("caller-close"); }, state: stateFor, inspectState: (ctx) => ({ run: run, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending }) };
1392
+ return { close: async () => { recorder.stop("caller-close"); }, state: stateFor, cutPoint, inspectState: (ctx) => ({ run: run, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending }) };
1361
1393
  }
1362
1394
  function checkedInput(raw) { if (!Check(RecallInput, raw))
1363
1395
  throw new Error("Invalid recall input"); return structuredClone(raw); }