pi-tuck 1.3.3 → 1.4.1

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 (50) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +0 -59
  3. package/NOTICE +63 -0
  4. package/README.md +59 -189
  5. package/dist/index.d.ts +1 -4
  6. package/dist/index.js +49 -10
  7. package/dist/src/budget.d.ts +6 -15
  8. package/dist/src/budget.js +6 -11
  9. package/dist/src/build-id.d.ts +1 -1
  10. package/dist/src/build-id.js +1 -1
  11. package/dist/src/compaction.d.ts +12 -20
  12. package/dist/src/compaction.js +220 -202
  13. package/dist/src/content-observations.d.ts +24 -0
  14. package/dist/src/content-observations.js +122 -0
  15. package/dist/src/diagnostics.d.ts +1 -3
  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/omissions.d.ts +1 -5
  21. package/dist/src/omissions.js +8 -10
  22. package/dist/src/recall.js +8 -25
  23. package/dist/src/request-capacity.d.ts +11 -26
  24. package/dist/src/request-capacity.js +20 -57
  25. package/dist/src/run.d.ts +16 -7
  26. package/dist/src/run.js +53 -25
  27. package/dist/src/status.d.ts +2 -0
  28. package/dist/src/status.js +6 -5
  29. package/dist/src/tuck/core/format.js +1 -1
  30. package/dist/src/tuck/core/readable-content.d.ts +14 -0
  31. package/dist/src/tuck/core/readable-content.js +43 -0
  32. package/dist/src/tuck.d.ts +2 -1
  33. package/dist/src/tuck.js +92 -30
  34. package/index.ts +42 -10
  35. package/package.json +3 -2
  36. package/src/budget.ts +7 -12
  37. package/src/build-id.ts +1 -1
  38. package/src/compaction.ts +220 -193
  39. package/src/content-observations.ts +115 -0
  40. package/src/diagnostics.ts +1 -1
  41. package/src/ledger.ts +17 -10
  42. package/src/llama-continuation.ts +176 -0
  43. package/src/omissions.ts +8 -10
  44. package/src/recall.ts +8 -20
  45. package/src/request-capacity.ts +18 -57
  46. package/src/run.ts +48 -22
  47. package/src/status.ts +8 -5
  48. package/src/tuck/core/format.ts +1 -1
  49. package/src/tuck/core/readable-content.ts +44 -0
  50. 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,27 @@ 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.");
64
61
  /** 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
62
  export const CALIBRATION_CEILING = 1.5;
66
63
  /** How many recent paired replies (and overflow bounds, and the seed while it is among them) the calibration factor is the maximum of. */
67
64
  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
65
  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. */
66
+ /** Read the newest applicable calibration receipt on the branch for `key` ([provider, api, id]). A custom
67
+ * observation for another identity is skipped. A compaction receipt for another or missing identity resets
68
+ * the seed to [1]. A matching receipt supplies its recent ratios clamped to [0, CALIBRATION_CEILING],
69
+ * or its legacy factor clamped to [1, CALIBRATION_CEILING]. Without a usable seed, start at [1]. */
90
70
  export function seedWindow(branch, key) {
91
71
  for (let i = branch.length; i--;) {
92
72
  const entry = branch[i];
@@ -98,43 +78,34 @@ export function seedWindow(branch, key) {
98
78
  if (calibrationIdentity !== key) {
99
79
  if (entry.type === "custom")
100
80
  continue; // Another model's new observation does not hide this model's last saved seed.
101
- return initialWindow(key);
81
+ return [1];
102
82
  }
103
83
  if (Array.isArray(stored) && stored.length >= 1 && stored.length <= CALIBRATION_WINDOW && stored.every(n => typeof n === "number" && Number.isFinite(n)))
104
84
  return stored.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING));
105
85
  if (typeof calibrationFactor === "number" && Number.isFinite(calibrationFactor))
106
86
  return [Math.min(Math.max(calibrationFactor, 1), CALIBRATION_CEILING)];
107
- return initialWindow(key);
87
+ return [1];
108
88
  }
109
- return initialWindow(key);
89
+ return [1];
110
90
  }
111
91
  /** 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. */
92
+ * tree moves load immediately. */
113
93
  class Calibration {
114
94
  identity = '';
115
95
  factor = 1;
116
96
  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
97
  pending;
122
98
  lastCeiling = null;
123
99
  estimatedTokens = 0;
124
100
  seededIdentity = '';
125
101
  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
102
  select(ctx) { this.identity = Calibration.key(ctx); }
128
- needsSeed(ctx) { return this.seededIdentity !== Calibration.key(ctx); }
103
+ needsSeed() { return this.seededIdentity !== this.identity; }
129
104
  reseed(ctx, reason) {
130
105
  this.identity = Calibration.key(ctx);
131
106
  this.pending = undefined;
132
- if (reason !== 'identity')
133
- this.windowObservation = undefined;
134
107
  if (reason === 'session') {
135
108
  this.factor = 1;
136
- this.learnedContextWindow = undefined;
137
- this.learnedCatalogue = undefined;
138
109
  this.estimatedTokens = 0;
139
110
  // Keep the old ratios/ceiling until their existing readers replace them, as in 1.1.1.
140
111
  this.seededIdentity = '';
@@ -146,8 +117,6 @@ class Calibration {
146
117
  const branch = ctx.sessionManager.getBranch();
147
118
  this.ratios = seedWindow(branch, this.identity);
148
119
  this.factor = Math.max(1, ...this.ratios);
149
- this.learnedCatalogue = ctx.model?.contextWindow;
150
- this.learnedContextWindow = seedContextWindow(branch, this.identity, this.learnedCatalogue);
151
120
  }
152
121
  learn(value, ctx, append) {
153
122
  this.ratios.push(value);
@@ -196,7 +165,7 @@ export async function installCompaction(pi, options = {}) {
196
165
  }
197
166
  });
198
167
  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 });
168
+ 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
169
  proposalId = receiptId(attached);
201
170
  if (recorder.enabled) {
202
171
  try {
@@ -226,7 +195,7 @@ export async function installCompaction(pi, options = {}) {
226
195
  pi.on("session_compact", (_event, ctx) => observe(ctx));
227
196
  pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
228
197
  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");
198
+ 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 }), "info");
230
199
  } });
231
200
  // Pi's native start/settled events bracket the run and its post-turn cuts.
232
201
  let run;
@@ -235,6 +204,12 @@ export async function installCompaction(pi, options = {}) {
235
204
  const protectedPrompt = (ctx) => run?.prompt?.id(ctx.sessionManager.getBranch());
236
205
  const clips = () => run?.clips ?? emptyClips;
237
206
  const emptyClips = new Map();
207
+ const restoreClips = (snapshot) => {
208
+ const current = clips();
209
+ current.clear();
210
+ for (const [id, clip] of snapshot)
211
+ current.set(id, clip);
212
+ };
238
213
  const resetRun = (session = false) => {
239
214
  if (!session && run?.phase === "commit-failed")
240
215
  run.clear();
@@ -254,38 +229,23 @@ export async function installCompaction(pi, options = {}) {
254
229
  if (stateFor(ctx).kind === "active")
255
230
  return false;
256
231
  resetRun();
257
- calibration.windowObservation = undefined;
258
- lengthStop = false;
232
+ lengthStop = undefined;
259
233
  return true;
260
234
  };
261
235
  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
236
  const calibration = new Calibration();
263
- const serverClipped = new WeakSet();
264
237
  const identityFor = (ctx) => {
265
238
  calibration.select(ctx);
266
- if (calibration.needsSeed(ctx))
239
+ if (calibration.needsSeed())
267
240
  calibration.reseed(ctx, "identity");
268
241
  return calibration.identity;
269
242
  };
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
- };
243
+ pi.on("model_select", (_event, ctx) => {
244
+ calibration.select(ctx);
245
+ if (run)
246
+ run.rejectedBudget = undefined;
288
247
  });
248
+ const contextWindow = (ctx) => ctx.model?.contextWindow ?? 0;
289
249
  // 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
250
  const learn = (value, ctx) => calibration.learn(value, ctx, (kind, data) => pi.appendEntry(kind, data));
291
251
  const corrected = (tokens, ctx) => { identityFor(ctx); return Math.ceil(tokens * calibration.factor); };
@@ -296,7 +256,6 @@ export async function installCompaction(pi, options = {}) {
296
256
  // The cut planner's raw reserve for the target limit, on the same factor as every other consumer.
297
257
  const planReserve = (target, room, band, mandatory, ctx) => {
298
258
  identityFor(ctx);
299
- // The compiler subtracts this reserve from the catalogue window. Targets already use the learned window.
300
259
  return planningReserve(ctx.model?.contextWindow ?? 0, target === "band" ? band : room, calibration.factor, mandatory);
301
260
  };
302
261
  pi.on("message_end", (event, ctx) => {
@@ -322,11 +281,14 @@ export async function installCompaction(pi, options = {}) {
322
281
  (!overflow && !["stop", "toolUse", "length"].includes(message.stopReason)) ||
323
282
  !isDeepStrictEqual(convertToLlm(paired.messages), paired.snapshot))
324
283
  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.
284
+ // The error alone does not report the server's window or whether it counted input plus output. Use the configured
285
+ // input limit as a planning assumption and keep that assumption explicit in the notice.
329
286
  if (overflow) {
287
+ if (run?.phase === "admitted" && !options.requestReserve && piClamp) {
288
+ const { estimate, cap } = requestClamp(paired.messages, ctx);
289
+ if (cap !== undefined)
290
+ run.rejectedBudget = { input: estimate, output: cap };
291
+ }
330
292
  const window = contextWindow(ctx), bound = (window + 1) / paired.tokens;
331
293
  const learned = bound <= CALIBRATION_CEILING;
332
294
  notify(ctx, overflowNotice(window, bound, learned), "warning");
@@ -341,49 +303,44 @@ export async function installCompaction(pi, options = {}) {
341
303
  if (!counts.every(n => Number.isSafeInteger(n) && n >= 0))
342
304
  return;
343
305
  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.
306
+ // Reject usage above the configured window for calibration. Learning from a reported 60,000-token
307
+ // cache read with a 32,768-token window once made a subsequent 6,000-token prompt refuse.
359
308
  if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio))
360
309
  learn(ratio, ctx);
361
310
  });
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
311
  // 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
312
  // 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;
313
+ let lengthStop;
375
314
  pi.on("agent_start", (_event, ctx) => { if (standDown(ctx))
376
315
  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"; });
316
+ run.transition("admitted"); lengthStop = undefined; calibration.pending = undefined; });
317
+ // Pi's overflow-recovery rule: a new user message or a good reply grants another recovery.
318
+ const rearmLengthRetry = (ctx) => {
319
+ if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel)
320
+ run?.rearmLengthRetry();
321
+ };
322
+ pi.on("message_start", (event, ctx) => { if (event.message.role === "user")
323
+ rearmLengthRetry(ctx); });
324
+ pi.on("message_end", (event, ctx) => {
325
+ if (event.message.role !== "assistant")
326
+ return;
327
+ if (event.message.stopReason !== "error" && event.message.stopReason !== "length")
328
+ rearmLengthRetry(ctx);
329
+ lengthStop = event.message.stopReason === "length" ? {
330
+ kind: event.message.content && thinkingOnlyLength(event.message) ? "thinking" : "output",
331
+ cacheMiss: event.message.errorMessage === CONTINUATION_CACHE_MISS,
332
+ } : undefined;
333
+ });
380
334
  pi.on("agent_settled", (_event, ctx) => {
381
335
  try {
382
336
  if (standDown(ctx) || !lengthStop || !active())
383
337
  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");
338
+ const { kind, cacheMiss } = lengthStop;
339
+ const message = kind === "thinking"
340
+ ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
341
+ : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
342
+ lengthStop = undefined;
343
+ notify(ctx, kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message, "warning");
387
344
  }
388
345
  finally {
389
346
  resetRun();
@@ -391,18 +348,14 @@ export async function installCompaction(pi, options = {}) {
391
348
  });
392
349
  const active = () => options.active?.() ?? true;
393
350
  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) => {
351
+ // Pi’s configured reserve is the standalone cut target, separate from the output cap.
352
+ const responseReserve = (ctx) => {
400
353
  const host = options.requestReserve?.(ctx);
401
354
  const budget = host ?? { response: settingsFor().getCompactionSettings(ctx.model).reserveTokens };
402
355
  if (!Number.isSafeInteger(budget.response) || budget.response < 0)
403
356
  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 };
357
+ const floor = host && host.responseExact !== true;
358
+ return floor ? Math.max(budget.response, ctx.model?.maxTokens ?? 0) : budget.response;
406
359
  };
407
360
  const inputRoom = (response, ctx) => {
408
361
  const configured = options.activeInputTokens;
@@ -413,18 +366,16 @@ export async function installCompaction(pi, options = {}) {
413
366
  return Math.min(contextWindow(ctx) - response, ceiling ?? Infinity);
414
367
  };
415
368
  // Room still owns every existing cut/clip attempt. Only final capacity admission uses the hard line.
369
+ let floorMinimum = 1;
416
370
  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);
371
+ const response = responseReserve(ctx), room = inputRoom(response, ctx);
372
+ const floor = options.requestReserve || !ctx.model ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model, floorMinimum);
419
373
  const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
420
374
  return { response, room, hardLine, replyFloor: floor };
421
375
  };
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);
427
- };
376
+ const preservePrefix = (ctx) => ctx.model !== undefined &&
377
+ options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
378
+ const decisionBand = (ctx, room) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
428
379
  const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
429
380
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
430
381
  const measureFor = (ctx) => (messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
@@ -449,10 +400,33 @@ export async function installCompaction(pi, options = {}) {
449
400
  // whereas our hard line is in corrected units; fitting that line alone need not leave the branch's reply floor.
450
401
  const requestClamp = (messages, ctx) => {
451
402
  const context = normalizeContext({ messages: convertToLlm(messages) });
452
- const cap = piClamp?.({ ...ctx.model, contextWindow: contextWindow(ctx) }, context, ctx.model.maxTokens);
403
+ const cap = piClamp?.(ctx.model, context, ctx.model.maxTokens);
453
404
  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) };
405
+ const fitsWindow = cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx);
406
+ // The native clamp bottoms out at one even when the estimate leaves no room.
407
+ return { cap, leavesFloor: cap === undefined || fitsWindow && cap >= limits(ctx).replyFloor, estimate, fitsWindow };
408
+ };
409
+ // 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
410
+ // did not exist, so it never refuses a request.
411
+ const planAboveRoom = (plan, ctx) => {
412
+ const { replyFloor, room } = limits(ctx);
413
+ if (!options.requestReserve) {
414
+ const previousClips = new Map(clips());
415
+ floorMinimum = CUT_REPLY_FLOOR;
416
+ try {
417
+ const shaped = limits(ctx);
418
+ if (shaped.replyFloor > replyFloor && shaped.hardLine > room) {
419
+ const decision = plan(shaped.hardLine);
420
+ if (decision.kind === "cut" || decision.kind === "none")
421
+ return decision;
422
+ }
423
+ }
424
+ finally {
425
+ floorMinimum = 1;
426
+ }
427
+ restoreClips(previousClips);
428
+ }
429
+ return plan(limits(ctx).hardLine);
456
430
  };
457
431
  const projectedRequest = (messages, ctx, host, incoming, prompt, tools, cut) => {
458
432
  const enabled = cut || historyToolsEnabled(ctx), shapes = toolShapes(historyToolNames(pi, tools, enabled));
@@ -469,9 +443,7 @@ export async function installCompaction(pi, options = {}) {
469
443
  const candidate = deepest();
470
444
  if (candidate.kind === "cut" && fits(total(candidate), limits(ctx).hardLine, ctx) && requestClamp(project(candidate), ctx).leavesFloor)
471
445
  return candidate;
472
- clips().clear();
473
- for (const [id, clip] of previousClips)
474
- clips().set(id, clip);
446
+ restoreClips(previousClips);
475
447
  return { kind: "fault", capacity: true, message: clampMessage };
476
448
  };
477
449
  for (let retry = 0;; retry++) {
@@ -509,14 +481,14 @@ export async function installCompaction(pi, options = {}) {
509
481
  recorder.stop("native-attempt-failed");
510
482
  // 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
483
  // 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;
484
+ const previous = failure();
513
485
  const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
514
486
  const receipted = run?.refusalReceipted;
515
487
  calibration.pending = undefined;
516
488
  // Keep the same terminal run until Pi settles; later start hooks cannot admit it.
517
489
  run ??= new Run("starting");
518
490
  run.clear();
519
- run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", ctx, fault);
491
+ run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", fault);
520
492
  run.refusalReceipted = true;
521
493
  try {
522
494
  if (!receipted)
@@ -525,7 +497,7 @@ export async function installCompaction(pi, options = {}) {
525
497
  }
526
498
  finally {
527
499
  try {
528
- if (shouldNotify)
500
+ if (!receipted)
529
501
  notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
530
502
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
531
503
  : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error");
@@ -556,11 +528,11 @@ export async function installCompaction(pi, options = {}) {
556
528
  // 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
529
  // real prompt expire too; safely fall back to carrying its cut in the request and saving it at the first boundary.
558
530
  setImmediate(() => { if (run === decision && decision.phase === "decided")
559
- decision.transition("expired", ctx); });
531
+ decision.transition("expired"); });
560
532
  });
561
533
  pi.registerTool({
562
534
  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.",
535
+ 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
536
  async execute(_id, raw, signal, _update, ctx) {
565
537
  access();
566
538
  const input = checkedInput(raw);
@@ -600,13 +572,17 @@ export async function installCompaction(pi, options = {}) {
600
572
  // 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
573
  // is the answer, and it is saved before the first request.
602
574
  if ((run?.phase === "decided" || run?.phase === "claimed") && event.reason === "threshold") {
603
- run.transition("claimed", ctx);
575
+ run.transition("claimed");
604
576
  if (view(ctx).pending) {
605
577
  access();
606
- const current = view(ctx), { type: _, ...compaction } = run.cut.take();
578
+ const current = view(ctx), { type: _, ...compaction } = run.cut.take(ctx);
607
579
  return { compaction: { ...compaction, firstKeptEntryId: current.keptFromId } };
608
580
  }
609
581
  }
582
+ // Capacity is decided when there is another request to send. A threshold
583
+ // notification after exhausted reasoning must not put that response away.
584
+ if (event.reason === "threshold" && lengthStop?.kind === "thinking")
585
+ return { cancel: true };
610
586
  const operatorManual = event.reason === "manual";
611
587
  if (operatorManual && run?.phase !== "admitted")
612
588
  resetRun();
@@ -621,8 +597,10 @@ export async function installCompaction(pi, options = {}) {
621
597
  // cut: the system part and the host input. A prompt's cut is pi-tuck's own and never comes here.
622
598
  const saved = ctx.sessionManager.buildSessionProjection().messages;
623
599
  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"));
600
+ const systemPrompt = ctx.getSystemPrompt(), tools = pi.getActiveTools();
601
+ const system = requestSystemPart(systemPrompt, tools, saved, systemPrompt);
602
+ const project = (messages, cut) => projectedRequest(messages, ctx, hostInput, [], systemPrompt, tools, cut);
603
+ const mandatory = system + host, band = decisionBand(ctx, room);
626
604
  const before = plannerMeasureFor(ctx)(saved);
627
605
  observeBudget(before + mandatory, ctx);
628
606
  // Pi's own usage threshold (reason "threshold") counts the last reply's output tokens, reasoning included, plus the messages after
@@ -645,7 +623,7 @@ export async function installCompaction(pi, options = {}) {
645
623
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
646
624
  // 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
625
  // 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);
626
+ 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
627
  return draft.compaction ? { draft: true, after: draft.after, compaction: draft.compaction, reserve,
650
628
  messages: plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages }
651
629
  : { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
@@ -655,8 +633,31 @@ export async function installCompaction(pi, options = {}) {
655
633
  let decision = decide();
656
634
  const { hardLine } = limits(ctx);
657
635
  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));
636
+ 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);
637
+ }
638
+ const rejected = event.reason === "overflow" && event.willRetry ? run?.rejectedBudget : undefined;
639
+ if (rejected && decision.kind === "cut") {
640
+ const prompt = run?.prompt;
641
+ const canRetry = (candidate) => {
642
+ const messages = project(candidate.messages, true);
643
+ const { estimate, cap, leavesFloor } = requestClamp(messages, ctx);
644
+ const improves = leavesFloor && cap !== undefined && estimate < rejected.input &&
645
+ estimate + cap < rejected.input + rejected.output &&
646
+ fits(requestSystemPart(systemPrompt, tools, messages, systemPrompt) + conversationTokens(messages), hardLine, ctx) &&
647
+ (!prompt || carriesPrompt(messages, prompt.text(ctx.sessionManager.getBranch()), prompt.role));
648
+ recorder.capture("overflow-recovery", "estimated-before-provider-transforms", { rejected, input: estimate, output: cap, improves });
649
+ return improves;
650
+ };
651
+ if (!canRetry(decision.plan)) {
652
+ const previousClips = new Map(clips());
653
+ const deepest = deepestDecision(ctx, false, retain);
654
+ if (deepest.kind !== "cut" || !canRetry(deepest.plan)) {
655
+ restoreClips(previousClips);
656
+ recorder.stop("no-capacity-gain");
657
+ return { cancel: true };
658
+ }
659
+ decision = deepest;
660
+ }
660
661
  }
661
662
  if (decision.kind === "cut") {
662
663
  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 +697,7 @@ export async function installCompaction(pi, options = {}) {
696
697
  pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
697
698
  const plannedView = (ctx, cut) => {
698
699
  const preview = new PendingCut();
699
- preview.plan(cut, ctx.sessionManager.getBranch().length);
700
+ preview.plan(cut, ctx);
700
701
  return preview.view(ctx);
701
702
  };
702
703
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
@@ -725,7 +726,7 @@ export async function installCompaction(pi, options = {}) {
725
726
  }
726
727
  }
727
728
  const before = measureFor(ctx)(saved);
728
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before,
729
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before,
729
730
  previousSummary: saved.find(message => message.role === "compactionSummary")?.summary, newPrompt, reRenderSummary: true,
730
731
  protectedPromptEntryId: newPrompt ? undefined : protectedPrompt(ctx), deepest: true }, ctx, 0, plannerMeasureFor(ctx), options.recallPolicy, retain);
731
732
  if (!draft.compaction)
@@ -740,7 +741,7 @@ export async function installCompaction(pi, options = {}) {
740
741
  // This does not relax thinking-only length recovery: retryLength still requires the observed reply floor before continuing,
741
742
  // and its pending retry cannot use this escape. No fresh content is clipped or edited by this admission attempt.
742
743
  const nativeFloorDecision = (ctx, newPrompt, retain, project) => {
743
- if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.thinkingRetryPending)
744
+ if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.lengthRetryPending)
744
745
  return;
745
746
  const candidate = deepestDecision(ctx, newPrompt, retain, false);
746
747
  if (candidate.kind !== "cut")
@@ -761,7 +762,6 @@ export async function installCompaction(pi, options = {}) {
761
762
  return;
762
763
  run.cut.clear();
763
764
  run.nativeFloorPending = false;
764
- const branchLength = ctx.sessionManager.getBranch().length;
765
765
  if (!active())
766
766
  return;
767
767
  access();
@@ -773,7 +773,7 @@ export async function installCompaction(pi, options = {}) {
773
773
  // Public early view only: later handlers, image normalization and tool-loop growth remain the complete-context guard's responsibility.
774
774
  const saved = ctx.sessionManager.buildSessionProjection().messages;
775
775
  const system = requestSystemPart(observedPrompt, tools, saved, ctx.getSystemPrompt());
776
- const band = decisionBand(ctx, room, system);
776
+ const band = decisionBand(ctx, room);
777
777
  const hostInput = hostSnapshot ?? hostMessages(ctx), host = conversationTokens(hostInput), measure = measureFor(ctx), before = measure(saved);
778
778
  const incoming = incomingPart + system, mandatory = incoming + host;
779
779
  observeBudget(before + mandatory, ctx);
@@ -794,12 +794,12 @@ export async function installCompaction(pi, options = {}) {
794
794
  // 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
795
  // there buys nothing the request needed and costs history the next recall would have found.
796
796
  // 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,
797
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
798
798
  newPrompt: !protectedId, protectedPromptEntryId: protectedId, reRenderSummary: !opportunistic }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, Boolean(protectedId));
799
799
  if (!draft.compaction)
800
800
  return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
801
801
  const candidate = new PendingCut();
802
- candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, branchLength);
802
+ candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, ctx);
803
803
  const messages = candidate.view(ctx).session.buildSessionProjection().messages;
804
804
  assertNativeToolRounds(messages);
805
805
  return { draft: true, after: measure(messages), compaction: draft.compaction, reserve, messages };
@@ -808,9 +808,8 @@ export async function installCompaction(pi, options = {}) {
808
808
  let decision = gate.kind === "plan" ? decide(room, band, gate.opportunistic) : { kind: "defer" };
809
809
  const { hardLine } = limits(ctx);
810
810
  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)));
811
+ decision = planAboveRoom(hardLine => clampAboveRoom(fits(before + mandatory, hardLine, ctx) ? { kind: "none" } :
812
+ 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
813
  }
815
814
  if (decision.kind === "defer")
816
815
  return;
@@ -827,7 +826,7 @@ export async function installCompaction(pi, options = {}) {
827
826
  if (decision.kind === "fault")
828
827
  throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
829
828
  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);
829
+ run.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, ctx);
831
830
  };
832
831
  pi.on("before_agent_start", async (event, ctx) => {
833
832
  if (standDown(ctx))
@@ -839,7 +838,7 @@ export async function installCompaction(pi, options = {}) {
839
838
  beginRun("starting");
840
839
  run ??= new Run("starting");
841
840
  if (!failure() && run.phase !== "starting")
842
- run.transition("starting", ctx);
841
+ run.transition("starting");
843
842
  const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
844
843
  run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
845
844
  try {
@@ -906,7 +905,7 @@ export async function installCompaction(pi, options = {}) {
906
905
  // saved conversation. Pi's peek returns the steering queue, else the follow-up queue; a follow-up is not in the very next
907
906
  // request while tools still run, so it can be counted early: conservative, and nothing else would cut at that later boundary.
908
907
  const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), saved, ctx.getSystemPrompt());
909
- const band = decisionBand(ctx, room, system);
908
+ const band = decisionBand(ctx, room);
910
909
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
911
910
  const queued = event.context.pendingMessages.length ? conversationTokens(event.context.pendingMessages) : 0;
912
911
  const mandatory = system + host + queued;
@@ -946,7 +945,7 @@ export async function installCompaction(pi, options = {}) {
946
945
  unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
947
946
  plan: (target) => {
948
947
  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);
948
+ 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
949
  if (!draft.compaction) {
951
950
  // The planner's own floor, so a clip's second budget is measured against what the smallest cut really keeps.
952
951
  if (draft.floorMessages && event.toolResults) {
@@ -999,18 +998,20 @@ export async function installCompaction(pi, options = {}) {
999
998
  calibration.estimatedTokens = corrected(before + mandatory, ctx);
1000
999
  const { hardLine } = limits(ctx);
1001
1000
  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));
1001
+ decision = planAboveRoom(hardLine => {
1002
+ if (fits(before + mandatory, hardLine, ctx))
1003
+ decision = { kind: "none" };
1004
+ else {
1005
+ decision = decide(hardLine, hardLine);
1006
+ tryClips(hardLine, hardLine);
1007
+ }
1008
+ 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 => {
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));
1014
+ }, ctx);
1014
1015
  }
1015
1016
  if (decision.kind === "fault" && reason === "tool-loop") {
1016
1017
  if (decision.capacity)
@@ -1046,7 +1047,7 @@ export async function installCompaction(pi, options = {}) {
1046
1047
  const current = view(ctx);
1047
1048
  if (!current.pending)
1048
1049
  return decide ? boundaryCut(event, ctx, reason) : undefined;
1049
- const entry = run.cut.take();
1050
+ const entry = run.cut.take(ctx);
1050
1051
  const preview = current.session, context = Object.create(ctx, { sessionManager: { value: preview } });
1051
1052
  const more = decide && !event.entries.length
1052
1053
  ? boundaryCut({ ...event, context: { ...event.context, contextMessages: preview.buildSessionProjection().messages } }, context, reason) : undefined;
@@ -1055,54 +1056,73 @@ export async function installCompaction(pi, options = {}) {
1055
1056
  return { entries: [...event.entries, saved, ...(more?.entries ?? [])] };
1056
1057
  };
1057
1058
  const retryLength = (event, ctx) => {
1059
+ // Exhausting the full per-request allowance is not evidence that input is too large.
1060
+ // Preserve the unfinished response; provider-native continuation owns this case.
1061
+ // Native Pi does not compact-and-retry output that reached the catalogue cap.
1062
+ if (event.message.role !== "assistant" || !ctx.model)
1063
+ return;
1064
+ const stoppedOutput = event.message.usage?.output;
1065
+ if (stoppedOutput >= ctx.model.maxTokens) {
1066
+ return { entries: event.entries, continue: false };
1067
+ }
1058
1068
  // Pi's supported boundary drafts commit before finishTurn honors `continue`. Omitting the selected failed response also prevents
1059
1069
  // Pi's later native length recovery from retrying it independently. The stored message and its output usage stay on the branch.
1060
1070
  const entries = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries),
1061
1071
  { type: "context_edit", targetId: event.messageEntryId, replacement: null }];
1062
- if (run.thinkingRetryPending) {
1072
+ if (!run.canRetryLength) {
1063
1073
  markBoundary(entries);
1064
1074
  return { entries, continue: false };
1065
1075
  }
1066
1076
  const preview = liveCut.view(ctx, entries).session;
1067
1077
  const view = Object.create(ctx, { sessionManager: { value: preview } });
1068
1078
  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
1079
  const asIs = projectedRequest(preview.buildSessionProjection().messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), false);
1072
1080
  const asIsCheck = requestClamp(asIs, view);
1073
1081
  const previousClips = new Map(clips());
1074
1082
  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);
1083
+ const cut = decision.kind === "cut" ? {
1084
+ ...decision,
1085
+ messages: projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true),
1086
+ } : undefined;
1087
+ const check = cut && requestClamp(cut.messages, view);
1088
+ const continuation = `${ctx.model.provider}/${ctx.model.id}` === options.continuationModel;
1089
+ // A cut that adds no reply room gives up history for nothing: retry the request uncut.
1090
+ if (!continuation && asIsCheck.cap !== undefined && asIsCheck.leavesFloor && (check?.cap === undefined || check.cap <= asIsCheck.cap)) {
1091
+ restoreClips(previousClips);
1080
1092
  const { room, hardLine } = limits(view);
1081
- run.thinkingRetryPending = true;
1093
+ run.requestLengthRetry();
1082
1094
  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,
1095
+ stoppedOutputTokens: stoppedOutput ?? 0, cut: false,
1084
1096
  piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }];
1085
1097
  markBoundary(drafts);
1086
1098
  return { entries: drafts, continue: true };
1087
1099
  }
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);
1100
+ // With a continuation model an unchanged allowance would repeat the same failed generation. If the
1101
+ // planner found no history to cut, there is no capacity diagnosis to make.
1102
+ if (!cut || check?.cap === undefined || asIsCheck.cap === undefined || check.cap <= (continuation ? Math.max(asIsCheck.cap, stoppedOutput ?? 0) : asIsCheck.cap)) {
1103
+ restoreClips(previousClips);
1104
+ if (!asIsCheck.leavesFloor) {
1105
+ if (check && !check.leavesFloor)
1106
+ throw new CapacityError(clampMessage);
1107
+ if (decision.kind === "fault" && decision.capacity)
1108
+ throw new CapacityError(decision.message);
1109
+ }
1110
+ markBoundary(entries);
1111
+ return { entries, continue: false };
1112
+ }
1113
+ const { messages } = cut;
1091
1114
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1092
1115
  throw promptRefusal();
1093
1116
  const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1094
- const tokens = system + conversationTokens(messages), check = requestClamp(messages, view);
1117
+ const tokens = system + conversationTokens(messages);
1095
1118
  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)
1119
+ if (!fits(tokens, hardLine, view) || !check.leavesFloor)
1100
1120
  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;
1121
+ 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) });
1122
+ run.requestLengthRetry();
1103
1123
  const drafts = [...entries, { type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId || null, details: compaction.details },
1104
1124
  { 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,
1125
+ stoppedOutputTokens: stoppedOutput ?? 0, cut: true,
1106
1126
  estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
1107
1127
  markBoundary(drafts);
1108
1128
  return { entries: drafts, continue: true };
@@ -1113,9 +1133,9 @@ export async function installCompaction(pi, options = {}) {
1113
1133
  return;
1114
1134
  if (!active() || run?.phase !== "admitted")
1115
1135
  return;
1116
- if ((thinkingOnlyLength(event.message) || serverClipped.has(event.message)) && !failure() && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
1136
+ if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
1117
1137
  return retryLength(event, ctx);
1118
- run.thinkingRetryPending = false;
1138
+ run.finishLengthRetry();
1119
1139
  const decide = event.outcome === "completed" && !ctx.signal?.aborted && event.context.canContinue && event.toolResults.length > 0 &&
1120
1140
  settingsFor().getCompactionSettings(ctx.model).enabled;
1121
1141
  if (!view(ctx).pending && !decide)
@@ -1159,7 +1179,7 @@ export async function installCompaction(pi, options = {}) {
1159
1179
  const guardCut = (messages, tokens, system, ctx) => {
1160
1180
  const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
1161
1181
  const before = conversationTokens(source), mandatory = tokens - before;
1162
- const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room, system);
1182
+ const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room);
1163
1183
  const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
1164
1184
  const previousClips = new Map(clips());
1165
1185
  const measure = measureFor(ctx);
@@ -1168,7 +1188,7 @@ export async function installCompaction(pi, options = {}) {
1168
1188
  unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
1169
1189
  plan: (target) => {
1170
1190
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
1171
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
1191
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
1172
1192
  protectedPromptEntryId: protectedPrompt(ctx) }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
1173
1193
  if (!draft.compaction)
1174
1194
  return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
@@ -1182,8 +1202,7 @@ export async function installCompaction(pi, options = {}) {
1182
1202
  const total = (candidate) => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory;
1183
1203
  let decision = decide(room, band);
1184
1204
  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));
1205
+ 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
1206
  }
1188
1207
  const accepts = (candidate) => {
1189
1208
  if (candidate.kind !== "cut" || candidate.plan.after >= before)
@@ -1196,9 +1215,7 @@ export async function installCompaction(pi, options = {}) {
1196
1215
  decision = deepestDecision(ctx, false, true);
1197
1216
  let native = false;
1198
1217
  if (decision.kind !== "cut" || !accepts(decision)) {
1199
- clips().clear();
1200
- for (const [id, clip] of previousClips)
1201
- clips().set(id, clip);
1218
+ restoreClips(previousClips);
1202
1219
  const floor = nativeFloorDecision(ctx, false, true, project);
1203
1220
  if (!floor)
1204
1221
  return { messages };
@@ -1208,7 +1225,7 @@ export async function installCompaction(pi, options = {}) {
1208
1225
  if (decision.kind !== "cut")
1209
1226
  return { messages };
1210
1227
  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);
1228
+ run.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx);
1212
1229
  run.nativeFloorPending = native;
1213
1230
  syncHistoryTools(ctx);
1214
1231
  return { messages: historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)), toolShapes(pi.getActiveTools()), true), native };
@@ -1277,7 +1294,7 @@ export async function installCompaction(pi, options = {}) {
1277
1294
  try {
1278
1295
  if (!active() || run?.phase !== "admitted" || failure() || !settingsFor().getCompactionSettings(ctx.model).enabled)
1279
1296
  return;
1280
- const decide = event.outcome === "completed" && !ctx.signal?.aborted;
1297
+ const decide = event.outcome === "completed" && !ctx.signal?.aborted && lengthStop?.kind !== "thinking";
1281
1298
  if (view(ctx).pending ? event.outcome === "error" : !decide)
1282
1299
  return;
1283
1300
  return atBoundary(event, ctx, "run-end", decide);
@@ -1292,6 +1309,7 @@ export async function installCompaction(pi, options = {}) {
1292
1309
  // Reaching the next request boundary proves native commit returned, not durable storage.
1293
1310
  if (run) {
1294
1311
  run.pendingBoundaryReceipts = [];
1312
+ run.rejectedBudget = undefined;
1295
1313
  }
1296
1314
  calibration.pending = undefined;
1297
1315
  try {