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
package/src/compaction.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { textOf } from "./tuck/core/content.js";
2
2
  import { PendingCut, StartingPrompt, Run, type CutEntry } from "./run.js";
3
- import { requestReplyFloor, replyFit, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath, seedContextWindow, WINDOW_RECEIPT, type WindowReceipt } 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, type Receipt, type RecorderOptions } from "./diagnostics.js";
6
6
  import { createHash } from "node:crypto";
@@ -20,7 +20,7 @@ import type { RecallPolicy } from "./recall.js";
20
20
  import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY_CHARACTERS } from "./recall.js";
21
21
 
22
22
  import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
23
- import { LOADED_VERSION, statusText } from "./status.js";
23
+ import { CONTINUATION_CACHE_MISS, LOADED_VERSION, statusText } from "./status.js";
24
24
  import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
25
25
  import { notify } from "./notify.js";
26
26
  import { applyHistoryTools, historyToolDeclarations, historyToolNames, stageHistoryTools } from "./history-tools.js";
@@ -49,41 +49,29 @@ const reply = (value: unknown) => ({ content: [{ type: "text" as const, text: JS
49
49
  /** The compactor's verdict that this attempt cannot be made: the cut it needs cannot be made, or the request cannot fit. Like every failure but
50
50
  * a `CommitFault`, it ends with its attempt (`resetRun`), and the next attempt plans afresh from the session as it is. */
51
51
  class Refusal extends Error {}
52
- /** 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
53
- * 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. */
52
+ /** 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. */
54
53
  class CommitFault extends Error {}
55
54
  /** A refusal for want of room, which the user can remedy: it carries advice. */
56
55
  class CapacityError extends Refusal {}
57
- /** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
58
- * likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
56
+ /** Explain a high planning factor, which can come from reported usage or an overflow estimate. */
59
57
  export const refusalNotice = (message: string, factor: number): string =>
60
58
  message + "; shorten the input, use a model with a larger window, or lower Pi's compaction.reserveTokens, then retry." +
61
- (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.` : "");
62
- /** 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
63
- * 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. */
59
+ (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.` : "");
60
+ /** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
64
61
  export const overflowNotice = (contextWindow: number, bound: number, learned: boolean): string =>
65
- `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` +
66
- (learned ? "; the next request is planned at that." : "; too far out to be a low estimate, so the factor is unchanged.");
62
+ `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.` +
63
+ (learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
64
+ /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
65
+ export const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
67
66
  /** 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. */
68
67
  export const CALIBRATION_CEILING = 1.5;
69
68
  /** How many recent paired replies (and overflow bounds, and the seed while it is among them) the calibration factor is the maximum of. */
70
69
  export const CALIBRATION_WINDOW = 32;
71
- /** 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
72
- * 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
73
- * was replayed reasoning, which the estimate now counts; with it counted, the first 32 requests of a real session measured at most 0.97. */
74
- export const MEASURED_CALIBRATION: Readonly<Record<string, number>> = {};
75
- /** 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
76
- * `identityFor`'s [provider, api, id]. */
77
- function initialWindow(key: string): number[] {
78
- try { const [provider, , id] = JSON.parse(key) as [string, string, string]; return [Math.min(MEASURED_CALIBRATION[`${provider}/${id}`] ?? 1, CALIBRATION_CEILING)]; } catch { return [1]; }
79
- }
80
70
  export const CALIBRATION_RECEIPT = 'pi-tuck-calibration';
81
- /** 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
82
- * receipt decides, and no older receipt is consulted. A receipt without the identity field (written before it existed) or from another identity gives `initialWindow`.
83
- * Otherwise its `calibrationWindow` (an array of 1..CALIBRATION_WINDOW finite numbers, oldest first) is the window, each entry clamped to
84
- * [0, CALIBRATION_CEILING]; without a valid one, the window is its `calibrationFactor` clamped to [1, CALIBRATION_CEILING] as one entry, else
85
- * `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
86
- * 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. */
71
+ /** Read the newest applicable calibration receipt on the branch for `key` ([provider, api, id]). A custom
72
+ * observation for another identity is skipped. A compaction receipt for another or missing identity resets
73
+ * the seed to [1]. A matching receipt supplies its recent ratios clamped to [0, CALIBRATION_CEILING],
74
+ * or its legacy factor clamped to [1, CALIBRATION_CEILING]. Without a usable seed, start at [1]. */
87
75
  export function seedWindow(branch: readonly SessionEntry[], key: string): number[] {
88
76
  for (let i = branch.length; i--;) {
89
77
  const entry = branch[i]!;
@@ -93,39 +81,33 @@ export function seedWindow(branch: readonly SessionEntry[], key: string): number
93
81
  const { calibrationIdentity, calibrationFactor, calibrationWindow } = receipt?.settings ?? {}, stored: unknown = calibrationWindow;
94
82
  if (calibrationIdentity !== key) {
95
83
  if (entry.type === "custom") continue; // Another model's new observation does not hide this model's last saved seed.
96
- return initialWindow(key);
84
+ return [1];
97
85
  }
98
86
  if (Array.isArray(stored) && stored.length >= 1 && stored.length <= CALIBRATION_WINDOW && stored.every(n => typeof n === "number" && Number.isFinite(n)))
99
87
  return stored.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING));
100
88
  if (typeof calibrationFactor === "number" && Number.isFinite(calibrationFactor)) return [Math.min(Math.max(calibrationFactor, 1), CALIBRATION_CEILING)];
101
- return initialWindow(key);
89
+ return [1];
102
90
  }
103
- return initialWindow(key);
91
+ return [1];
104
92
  }
105
93
  /** One accounting owner. Session start still defers receipt loading until the first budget read;
106
- * tree moves load immediately, and identity changes keep any uncommitted window observation. */
94
+ * tree moves load immediately. */
107
95
  class Calibration {
108
96
  identity = '';
109
97
  factor = 1;
110
98
  ratios: number[] = [];
111
- learnedContextWindow: number | undefined;
112
- /** The configured window the learned window was learned under; the learned window applies only while the model still has it. */
113
- learnedCatalogue: number | undefined;
114
- windowObservation: { message: AgentMessage; identity: string; window: number; catalogue: number } | undefined;
115
- pending: { identity: string; tokens: number; messages: Parameters<typeof convertToLlm>[0]; snapshot: ReturnType<typeof convertToLlm>; requestedMaxTokens?: () => number | undefined } | undefined;
99
+ pending: { identity: string; tokens: number; messages: Parameters<typeof convertToLlm>[0]; snapshot: ReturnType<typeof convertToLlm> } | undefined;
116
100
  lastCeiling: number | null = null;
117
101
  estimatedTokens = 0;
118
102
  private seededIdentity = '';
119
103
  static key(ctx: ExtensionContext) { return ctx.model ? JSON.stringify([ctx.model.provider, ctx.model.api, ctx.model.id]) : ''; }
120
- /** Model selection itself never reloads receipts: switching away and back without a request keeps the learned window. */
121
104
  select(ctx: ExtensionContext) { this.identity = Calibration.key(ctx); }
122
- needsSeed(ctx: ExtensionContext) { return this.seededIdentity !== Calibration.key(ctx); }
105
+ needsSeed() { return this.seededIdentity !== this.identity; }
123
106
  reseed(ctx: ExtensionContext, reason: 'identity' | 'session' | 'tree') {
124
107
  this.identity = Calibration.key(ctx);
125
108
  this.pending = undefined;
126
- if (reason !== 'identity') this.windowObservation = undefined;
127
109
  if (reason === 'session') {
128
- this.factor = 1; this.learnedContextWindow = undefined; this.learnedCatalogue = undefined; this.estimatedTokens = 0;
110
+ this.factor = 1; this.estimatedTokens = 0;
129
111
  // Keep the old ratios/ceiling until their existing readers replace them, as in 1.1.1.
130
112
  this.seededIdentity = '';
131
113
  return;
@@ -135,8 +117,6 @@ class Calibration {
135
117
  const branch = ctx.sessionManager.getBranch();
136
118
  this.ratios = seedWindow(branch, this.identity);
137
119
  this.factor = Math.max(1, ...this.ratios);
138
- this.learnedCatalogue = ctx.model?.contextWindow;
139
- this.learnedContextWindow = seedContextWindow(branch, this.identity, this.learnedCatalogue);
140
120
  }
141
121
  learn(value: number, ctx: ExtensionContext, append: (kind: string, data: unknown) => void) {
142
122
  this.ratios.push(value); if (this.ratios.length > CALIBRATION_WINDOW) this.ratios.shift(); this.factor = Math.max(1, ...this.ratios);
@@ -165,12 +145,12 @@ export interface CompactionOptions {
165
145
  * which is the room less 2% of it, or this fraction of the room when that is lower; a lower value cuts earlier and leaves less. The room
166
146
  * owns cut targets; standalone final capacity admission uses the branch reply floor. If omitted, the band adapts to the last cut. */
167
147
  cutAt?: number;
168
- /** A host's response reserve: without `responseExact: true`, the catalogue maximum output stays its floor; with it, `response` is exact.
169
- * Standalone cuts against Pi's reserveTokens, then admits up to the window less Pi's safety margin and max(3,584, largest branch output), capped at that reserve.
170
- * After a genuine length stop with text/tool output or context overflow it holds the full reserve, also raised to the catalogue maximum.
171
- * Server clipping below the sent reply cap instead learns the smaller window and preserves the normal reply floor.
172
- * Thinking-only exhaustion keeps Pi's reserve and requires the branch's largest observed reply instead.
173
- * Resume, fork and /tree follow that branch's history; a new session has no inherited fallback. */
148
+ /** Models where a usable cached prefix is more valuable than an early cut. */
149
+ cacheSensitiveModels?: readonly string[];
150
+ /** provider/model with provider-native continuation; it keeps one length recovery per run, and only where a cut adds reply room. */
151
+ continuationModel?: string;
152
+ /** Host response reserve. `responseExact: true` uses it as declared. Otherwise the SDK
153
+ * keeps the catalogue maximum as a floor for existing callers. Standalone uses Pi’s soft reserve. */
174
154
  requestReserve?: (ctx: ExtensionContext) => { response: number; responseExact?: true };
175
155
  /** The exact messages the host's `context` hook adds to every final request beyond the saved conversation (for example a role
176
156
  * view), in the form the hook injects them. Cut triggers, the cut planner and the post-cut checks count them with the same
@@ -206,7 +186,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
206
186
  if (found) { recorder.capture("observed-entry", "current-native-branch-memory-not-durable", { entryId: found.id, diagnosticReceiptId: proposalId, details: found.type === "compaction" ? found.details : undefined }); recorder.cut(); proposalId = undefined; }
207
187
  });
208
188
  const captureDraft = (draft: NonNullable<ReturnType<typeof tuckDraft>["compaction"]>, ctx: ExtensionContext, reserve: number, reason: string, tokensBefore: number, retainCurrentInput: boolean, operatorManual: boolean, previousSummary?: string, budget?: { response: number; host: number; mandatory: number; target: Target; margin: number }) => recorder.measureInline(() => {
209
- 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 });
189
+ 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 });
210
190
  proposalId = receiptId(attached);
211
191
  if (recorder.enabled) { try {
212
192
  const filtered = permittedEntries(ctx.sessionManager.getEntries(), options.recallPolicy);
@@ -225,7 +205,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
225
205
  pi.on("session_compact", (_event, ctx) => observe(ctx));
226
206
  pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
227
207
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
228
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, pending: view(ctx).pending }), "info");
208
+ 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");
229
209
  } });
230
210
  // Pi's native start/settled events bracket the run and its post-turn cuts.
231
211
  let run: Run | undefined;
@@ -234,6 +214,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
234
214
  const protectedPrompt = (ctx: ExtensionContext) => run?.prompt?.id(ctx.sessionManager.getBranch());
235
215
  const clips = () => run?.clips ?? emptyClips;
236
216
  const emptyClips = new Map<string, Clip>();
217
+ const restoreClips = (snapshot: ReadonlyMap<string, Clip>) => {
218
+ const current = clips();
219
+ current.clear();
220
+ for (const [id, clip] of snapshot) current.set(id, clip);
221
+ };
237
222
  const resetRun = (session = false) => {
238
223
  if (!session && run?.phase === "commit-failed") run.clear(); else run = undefined;
239
224
  calibration.pending = undefined;
@@ -246,36 +231,21 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
246
231
  const standDown = (ctx: ExtensionContext) => {
247
232
  if (stateFor(ctx).kind === "active") return false;
248
233
  resetRun();
249
- calibration.windowObservation = undefined;
250
- lengthStop = false;
234
+ lengthStop = undefined;
251
235
  return true;
252
236
  };
253
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");
254
238
  const calibration = new Calibration();
255
- const serverClipped = new WeakSet<object>();
256
239
  const identityFor = (ctx: ExtensionContext) => {
257
240
  calibration.select(ctx);
258
- if (calibration.needsSeed(ctx)) calibration.reseed(ctx, "identity");
241
+ if (calibration.needsSeed()) calibration.reseed(ctx, "identity");
259
242
  return calibration.identity;
260
243
  };
261
- pi.on("model_select", (_event, ctx) => { calibration.select(ctx); });
262
- const contextWindow = (ctx: ExtensionContext) => {
263
- identityFor(ctx);
264
- const model = ctx.model?.contextWindow ?? 0;
265
- const learned = calibration.learnedCatalogue === ctx.model?.contextWindow ? calibration.learnedContextWindow : undefined;
266
- return Math.min(model, learned ?? Infinity);
267
- };
268
- // This is the cap in Pi's built provider payload, including its context clamp and thinking adjustments.
269
- // An API with no explicit cap supplies no clipping evidence; never substitute the catalogue maximum.
270
- pi.on("before_provider_request", event => {
271
- if (!calibration.pending || !event.payload || typeof event.payload !== "object") return;
272
- const payload = event.payload as Record<string, unknown>;
273
- // Read at reply time so later in-place payload edits are included too.
274
- calibration.pending.requestedMaxTokens = () => {
275
- const cap = payload.max_tokens ?? payload.max_completion_tokens ?? payload.max_output_tokens;
276
- return typeof cap === "number" && Number.isSafeInteger(cap) && cap > 0 ? cap : undefined;
277
- };
244
+ pi.on("model_select", (_event, ctx) => {
245
+ calibration.select(ctx);
246
+ if (run) run.rejectedBudget = undefined;
278
247
  });
248
+ const contextWindow = (ctx: ExtensionContext) => ctx.model?.contextWindow ?? 0;
279
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.
280
250
  const learn = (value: number, ctx: ExtensionContext) => calibration.learn(value, ctx, (kind, data) => pi.appendEntry(kind, data));
281
251
  const corrected = (tokens: number, ctx: ExtensionContext) => { identityFor(ctx); return Math.ceil(tokens * calibration.factor); };
@@ -285,7 +255,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
285
255
  // The cut planner's raw reserve for the target limit, on the same factor as every other consumer.
286
256
  const planReserve = (target: Target, room: number, band: number, mandatory: number, ctx: ExtensionContext) => {
287
257
  identityFor(ctx);
288
- // The compiler subtracts this reserve from the catalogue window. Targets already use the learned window.
289
258
  return planningReserve(ctx.model?.contextWindow ?? 0, target === "band" ? band : room, calibration.factor, mandatory);
290
259
  };
291
260
  pi.on("message_end", (event, ctx) => {
@@ -304,11 +273,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
304
273
  message.provider !== ctx.model?.provider || message.model !== ctx.model.id || message.api !== ctx.model.api ||
305
274
  (!overflow && !["stop", "toolUse", "length"].includes(message.stopReason)) ||
306
275
  !isDeepStrictEqual(convertToLlm(paired.messages), paired.snapshot)) return;
307
- // 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
308
- // 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.
309
- // 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
310
- // with no word from pi-tuck read as a hang: every other refusal says why, and this is the path that skipped it.
276
+ // The error alone does not report the server's window or whether it counted input plus output. Use the configured
277
+ // input limit as a planning assumption and keep that assumption explicit in the notice.
311
278
  if (overflow) {
279
+ if (run?.phase === "admitted" && !options.requestReserve && piClamp) {
280
+ const { estimate, cap } = requestClamp(paired.messages, ctx);
281
+ if (cap !== undefined) run.rejectedBudget = { input: estimate, output: cap };
282
+ }
312
283
  const window = contextWindow(ctx), bound = (window + 1) / paired.tokens;
313
284
  const learned = bound <= CALIBRATION_CEILING;
314
285
  notify(ctx, overflowNotice(window, bound, learned), "warning");
@@ -320,56 +291,48 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
320
291
  const counts = [usage.input, usage.cacheRead, usage.cacheWrite];
321
292
  if (!counts.every(n => Number.isSafeInteger(n) && n >= 0)) return;
322
293
  const input = counts.reduce((a, b) => a + b, 0), ratio = input / paired.tokens;
323
- const output = usage.output, bound = usage.input + usage.cacheRead + output, requested = paired.requestedMaxTokens?.();
324
- if (message.stopReason === "length" && requested !== undefined &&
325
- Number.isSafeInteger(output) && output >= 0 && output < requested &&
326
- Number.isSafeInteger(bound) && bound > 0 && bound <= ctx.model.contextWindow) {
327
- // A learned window from another configured window no longer bounds this one.
328
- if (calibration.learnedCatalogue !== ctx.model.contextWindow) calibration.learnedContextWindow = undefined;
329
- calibration.learnedCatalogue = ctx.model.contextWindow;
330
- calibration.learnedContextWindow = Math.min(calibration.learnedContextWindow ?? Infinity, bound);
331
- serverClipped.add(message);
332
- calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow, catalogue: ctx.model.contextWindow };
333
- }
334
- // A request that was answered cannot have held more than the model's window, so a report above it describes something that never happened.
335
- // 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
336
- // 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.
294
+ // Reject usage above the configured window for calibration. Learning from a reported 60,000-token
295
+ // cache read with a 32,768-token window once made a subsequent 6,000-token prompt refuse.
337
296
  if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio)) learn(ratio, ctx);
338
297
  });
339
- pi.on("turn_end", (event, ctx) => {
340
- if (standDown(ctx)) return;
341
- if (calibration.windowObservation?.message !== event.message) return;
342
- const observation = calibration.windowObservation; calibration.windowObservation = undefined;
343
- pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window, catalogueContextWindow: observation.catalogue,
344
- serverClippedReplyId: event.messageEntryId } satisfies WindowReceipt);
345
- });
346
298
  // 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
347
299
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
348
- let lengthStop = false;
349
- pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= new Run("starting"); if (!failure()) run.transition("admitted", ctx); run.thinkingRetryPending = false; lengthStop = false; calibration.pending = undefined; });
350
- pi.on("message_end", event => { if (event.message.role === "assistant") lengthStop = event.message.stopReason === "length"; });
300
+ let lengthStop: { kind: "thinking" | "output"; cacheMiss: boolean } | undefined;
301
+ pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= new Run("starting"); if (!failure()) run.transition("admitted"); lengthStop = undefined; calibration.pending = undefined; });
302
+ // Pi's overflow-recovery rule: a new user message or a good reply grants another recovery.
303
+ const rearmLengthRetry = (ctx: ExtensionContext) => {
304
+ if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel) run?.rearmLengthRetry();
305
+ };
306
+ pi.on("message_start", (event, ctx) => { if (event.message.role === "user") rearmLengthRetry(ctx); });
307
+ pi.on("message_end", (event, ctx) => {
308
+ if (event.message.role !== "assistant") return;
309
+ if (event.message.stopReason !== "error" && event.message.stopReason !== "length") rearmLengthRetry(ctx);
310
+ lengthStop = event.message.stopReason === "length" ? {
311
+ kind: event.message.content && thinkingOnlyLength(event.message) ? "thinking" : "output",
312
+ cacheMiss: event.message.errorMessage === CONTINUATION_CACHE_MISS,
313
+ } : undefined;
314
+ });
351
315
  pi.on("agent_settled", (_event, ctx) => {
352
316
  try {
353
317
  if (standDown(ctx) || !lengthStop || !active()) return;
354
- lengthStop = false;
355
- const message = "pi-tuck: the last reply stopped at the model's output limit and may be cut off. Ask the agent to continue.";
356
- notify(ctx, message, "warning");
318
+ const { kind, cacheMiss } = lengthStop;
319
+ const message = kind === "thinking"
320
+ ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
321
+ : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
322
+ lengthStop = undefined;
323
+ notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + INCIDENT_HINT, "warning");
357
324
  } finally { resetRun(); }
358
325
  });
359
326
  const active = () => options.active?.() ?? true;
360
327
  const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings?.());
361
- // The one reserve decision; every consumer takes its room from limits. Standalone starts at Pi's native cut point. Once a reply did
362
- // 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
363
- // length stop uses branchReplyFloor's observed output instead; reserving the catalogue maximum would strand setups above the room.
364
- // 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,
365
- // fork, /tree or a new session.
366
- const requestReserve = (ctx: ExtensionContext) => {
328
+ // Pi’s configured reserve is the standalone cut target, separate from the output cap.
329
+ const responseReserve = (ctx: ExtensionContext) => {
367
330
  const host = options.requestReserve?.(ctx);
368
331
  const budget = host ?? { response: settingsFor().getCompactionSettings(ctx.model).reserveTokens };
369
332
  if (!Number.isSafeInteger(budget.response) || budget.response < 0)
370
333
  throw new Error("Invalid host request reserve");
371
- const floor = host ? host.responseExact !== true : replyFit(ctx.sessionManager.getBranch()).failed;
372
- return { response: floor ? Math.max(budget.response, ctx.model?.maxTokens ?? 0) : budget.response };
334
+ const floor = host && host.responseExact !== true;
335
+ return floor ? Math.max(budget.response, ctx.model?.maxTokens ?? 0) : budget.response;
373
336
  };
374
337
  const inputRoom = (response: number, ctx: ExtensionContext) => {
375
338
  const configured = options.activeInputTokens;
@@ -380,17 +343,20 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
380
343
  return Math.min(contextWindow(ctx) - response, ceiling ?? Infinity);
381
344
  };
382
345
  // Room still owns every existing cut/clip attempt. Only final capacity admission uses the hard line.
346
+ let floorMinimum = 1;
383
347
  const limits = (ctx: ExtensionContext) => {
384
- const { response } = requestReserve(ctx), room = inputRoom(response, ctx);
385
- const floor = options.requestReserve ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model?.maxTokens);
348
+ const response = responseReserve(ctx), room = inputRoom(response, ctx);
349
+ const floor = options.requestReserve || !ctx.model ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model, floorMinimum);
386
350
  const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
387
351
  return { response, room, hardLine, replyFloor: floor };
388
352
  };
389
- const decisionBand = (ctx: ExtensionContext, room: number, system: number, current = view(ctx)) => {
390
- const last = current.session.getBranch().findLast(entry => entry.type === "compaction");
391
- const after = last?.type === "compaction" ? (last.details as { tokensAfter?: unknown } | undefined)?.tokensAfter : undefined;
392
- return bandOf(room, cutAt, options.cutAt === undefined && typeof after === "number" && Number.isFinite(after) && after >= 0
393
- ? { system, tokensAfter: after, factor: calibration.factor } : undefined);
353
+ const preservePrefix = (ctx: ExtensionContext) => ctx.model !== undefined &&
354
+ options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
355
+ const decisionBand = (ctx: ExtensionContext, room: number) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
356
+ /** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
357
+ const cutPoint = (ctx: ExtensionContext): number | undefined => {
358
+ if (!active() || !ctx.model || stateFor(ctx).kind !== "active") return undefined;
359
+ try { const band = decisionBand(ctx, limits(ctx).room); return band > 0 ? band : undefined; } catch { return undefined; }
394
360
  };
395
361
  const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
396
362
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
@@ -418,10 +384,29 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
418
384
  // whereas our hard line is in corrected units; fitting that line alone need not leave the branch's reply floor.
419
385
  const requestClamp = (messages: Messages, ctx: ExtensionContext) => {
420
386
  const context = normalizeContext({ messages: convertToLlm(messages) });
421
- const cap = piClamp?.({ ...ctx.model!, contextWindow: contextWindow(ctx) }, context, ctx.model!.maxTokens);
387
+ const cap = piClamp?.(ctx.model!, context, ctx.model!.maxTokens);
422
388
  const estimate = piMath ? piMath.estimateContextTokens(context).tokens : 0;
423
- return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor, estimate,
424
- fitsWindow: cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx) };
389
+ const fitsWindow = cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx);
390
+ // The native clamp bottoms out at one even when the estimate leaves no room.
391
+ return { cap, leavesFloor: cap === undefined || fitsWindow && cap >= limits(ctx).replyFloor, estimate, fitsWindow };
392
+ };
393
+ // 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
394
+ // did not exist, so it never refuses a request.
395
+ const planAboveRoom = (plan: (hardLine: number) => Decision<CutPlan>, ctx: ExtensionContext): Decision<CutPlan> => {
396
+ const { replyFloor, room } = limits(ctx);
397
+ if (!options.requestReserve) {
398
+ const previousClips = new Map(clips());
399
+ floorMinimum = CUT_REPLY_FLOOR;
400
+ try {
401
+ const shaped = limits(ctx);
402
+ if (shaped.replyFloor > replyFloor && shaped.hardLine > room) {
403
+ const decision = plan(shaped.hardLine);
404
+ if (decision.kind === "cut" || decision.kind === "none") return decision;
405
+ }
406
+ } finally { floorMinimum = 1; }
407
+ restoreClips(previousClips);
408
+ }
409
+ return plan(limits(ctx).hardLine);
425
410
  };
426
411
  const projectedRequest = (messages: Messages, ctx: ExtensionContext, host: Messages, incoming: Messages, prompt: string, tools: readonly string[], cut: boolean) => {
427
412
  const enabled = cut || historyToolsEnabled(ctx), shapes = toolShapes(historyToolNames(pi, tools, enabled));
@@ -438,7 +423,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
438
423
  const candidate = deepest();
439
424
  if (candidate.kind === "cut" && fits(total(candidate), limits(ctx).hardLine, ctx) && requestClamp(project(candidate), ctx).leavesFloor)
440
425
  return candidate;
441
- clips().clear(); for (const [id, clip] of previousClips) clips().set(id, clip);
426
+ restoreClips(previousClips);
442
427
  return { kind: "fault", capacity: true, message: clampMessage };
443
428
  };
444
429
  for (let retry = 0; ; retry++) {
@@ -469,21 +454,21 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
469
454
  recorder.stop("native-attempt-failed");
470
455
  // 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
471
456
  // means for the session, anything else as it is (an attempt that ended with no word looked like a hang).
472
- const previous = failure(), shouldNotify = !previous;
457
+ const previous = failure();
473
458
  const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
474
459
  const receipted = run?.refusalReceipted;
475
460
  calibration.pending = undefined;
476
461
  // Keep the same terminal run until Pi settles; later start hooks cannot admit it.
477
462
  run ??= new Run("starting"); run.clear();
478
- run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", ctx, fault);
463
+ run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", fault);
479
464
  run.refusalReceipted = true;
480
465
  try {
481
466
  if (!receipted) receipt("refusal", fault.message, ctx);
482
467
  options.fail?.(error);
483
468
  } finally {
484
- try { if (shouldNotify) notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
469
+ try { if (!receipted) notify(ctx, (fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
485
470
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
486
- : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error"); }
471
+ : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`) + INCIDENT_HINT, "error"); }
487
472
  finally { ctx.abort(); }
488
473
  }
489
474
  };
@@ -501,12 +486,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
501
486
  catch (error) { fail(error, ctx); }
502
487
  // Pi normally reaches its pre-run threshold check within microtasks. Auth I/O or a later extension's input I/O can make a
503
488
  // real prompt expire too; safely fall back to carrying its cut in the request and saving it at the first boundary.
504
- setImmediate(() => { if (run === decision && decision.phase === "decided") decision.transition("expired", ctx); });
489
+ setImmediate(() => { if (run === decision && decision.phase === "decided") decision.transition("expired"); });
505
490
  });
506
491
 
507
492
  pi.registerTool({
508
493
  name: "tuck_recall", label: "pi-tuck history", parameters: RecallInput,
509
- 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.",
494
+ 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.",
510
495
  async execute(_id, raw, signal, _update, ctx) {
511
496
  access();
512
497
  const input = checkedInput(raw);
@@ -538,13 +523,16 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
538
523
  // Pi checks its own threshold after a prompt's input and before the run starts: the prompt's cut, planned with the prompt counted,
539
524
  // is the answer, and it is saved before the first request.
540
525
  if ((run?.phase === "decided" || run?.phase === "claimed") && event.reason === "threshold") {
541
- run.transition("claimed", ctx);
526
+ run.transition("claimed");
542
527
  if (view(ctx).pending) {
543
528
  access();
544
- const current = view(ctx), { type: _, ...compaction } = run.cut.take()!;
529
+ const current = view(ctx), { type: _, ...compaction } = run.cut.take(ctx)!;
545
530
  return { compaction: { ...compaction, firstKeptEntryId: current.keptFromId! } };
546
531
  }
547
532
  }
533
+ // Capacity is decided when there is another request to send. A threshold
534
+ // notification after exhausted reasoning must not put that response away.
535
+ if (event.reason === "threshold" && lengthStop?.kind === "thinking") return { cancel: true };
548
536
  const operatorManual = event.reason === "manual";
549
537
  if (operatorManual && run?.phase !== "admitted") resetRun();
550
538
  access();
@@ -557,8 +545,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
557
545
  // cut: the system part and the host input. A prompt's cut is pi-tuck's own and never comes here.
558
546
  const saved = ctx.sessionManager.buildSessionProjection().messages;
559
547
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
560
- const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), saved, ctx.getSystemPrompt());
561
- const mandatory = system + host, band = decisionBand(ctx, room, system, view(ctx, event.reason === "threshold"));
548
+ const systemPrompt = ctx.getSystemPrompt(), tools = pi.getActiveTools();
549
+ const system = requestSystemPart(systemPrompt, tools, saved, systemPrompt);
550
+ const project = (messages: Messages, cut: boolean) => projectedRequest(messages, ctx, hostInput, [], systemPrompt, tools, cut);
551
+ const mandatory = system + host, band = decisionBand(ctx, room);
562
552
  const before = plannerMeasureFor(ctx)(saved);
563
553
  observeBudget(before + mandatory, ctx);
564
554
  // Pi's own usage threshold (reason "threshold") counts the last reply's output tokens, reasoning included, plus the messages after
@@ -580,7 +570,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
580
570
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
581
571
  // 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
582
572
  // from any run that ended. A retry is inside its run.
583
- const draft = tuckDraft(tuck, event, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, retain, operatorManual, operatorManual || run?.phase !== "admitted", run?.phase === "admitted" ? protectedPrompt(ctx) : undefined);
573
+ 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);
584
574
  return draft.compaction ? { draft: true, after: draft.after, compaction: draft.compaction, reserve,
585
575
  messages: plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages }
586
576
  : { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
@@ -590,12 +580,35 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
590
580
  let decision: Decision<CutPlan> = decide();
591
581
  const { hardLine } = limits(ctx);
592
582
  if (!operatorManual && hardLine > room && decision.kind === "fault") {
593
- decision = fits(before + mandatory, hardLine, ctx) ? { kind: "none" } : decide(hardLine, hardLine);
594
- decision = clampAboveRoom(decision, ctx, room, hardLine,
583
+ decision = planAboveRoom(hardLine => clampAboveRoom(fits(before + mandatory, hardLine, ctx) ? { kind: "none" } : decide(hardLine, hardLine), ctx, room, hardLine,
595
584
  candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory,
596
- candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, [], ctx.getSystemPrompt(), pi.getActiveTools(), candidate.kind === "cut"),
585
+ candidate => project(candidate.kind === "cut" ? candidate.plan.messages : saved, candidate.kind === "cut"),
597
586
  target => target <= room ? decide() : decide(target, target),
598
- () => deepestDecision(ctx, operatorManual || run?.phase !== "admitted", retain));
587
+ () => deepestDecision(ctx, operatorManual || run?.phase !== "admitted", retain)), ctx);
588
+ }
589
+ const rejected = event.reason === "overflow" && event.willRetry ? run?.rejectedBudget : undefined;
590
+ if (rejected && decision.kind === "cut") {
591
+ const prompt = run?.prompt;
592
+ const canRetry = (candidate: CutPlan) => {
593
+ const messages = project(candidate.messages, true);
594
+ const { estimate, cap, leavesFloor } = requestClamp(messages, ctx);
595
+ const improves = leavesFloor && cap !== undefined && estimate < rejected.input &&
596
+ estimate + cap < rejected.input + rejected.output &&
597
+ fits(requestSystemPart(systemPrompt, tools, messages, systemPrompt) + conversationTokens(messages), hardLine, ctx) &&
598
+ (!prompt || carriesPrompt(messages, prompt.text(ctx.sessionManager.getBranch()), prompt.role));
599
+ recorder.capture("overflow-recovery", "estimated-before-provider-transforms", { rejected, input: estimate, output: cap, improves });
600
+ return improves;
601
+ };
602
+ if (!canRetry(decision.plan)) {
603
+ const previousClips = new Map(clips());
604
+ const deepest = deepestDecision(ctx, false, retain);
605
+ if (deepest.kind !== "cut" || !canRetry(deepest.plan)) {
606
+ restoreClips(previousClips);
607
+ recorder.stop("no-capacity-gain");
608
+ return { cancel: true };
609
+ }
610
+ decision = deepest;
611
+ }
599
612
  }
600
613
  if (decision.kind === "cut") { return { compaction: captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, event.reason, event.preparation.tokensBefore,
601
614
  retain, operatorManual, event.preparation.previousSummary, { response, host, mandatory, target: decision.target, margin: room - band }) }; }
@@ -623,7 +636,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
623
636
  pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
624
637
  const plannedView = (ctx: ExtensionContext, cut: CutEntry) => {
625
638
  const preview = new PendingCut();
626
- preview.plan(cut, ctx.sessionManager.getBranch().length);
639
+ preview.plan(cut, ctx);
627
640
  return preview.view(ctx);
628
641
  };
629
642
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
@@ -647,7 +660,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
647
660
  }
648
661
  }
649
662
  const before = measureFor(ctx)(saved);
650
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before,
663
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before,
651
664
  previousSummary: saved.find(message => message.role === "compactionSummary")?.summary, newPrompt, reRenderSummary: true,
652
665
  protectedPromptEntryId: newPrompt ? undefined : protectedPrompt(ctx), deepest: true }, ctx, 0, plannerMeasureFor(ctx), options.recallPolicy, retain);
653
666
  if (!draft.compaction) return { kind: "fault", capacity: Boolean(draft.capacityRejected), message: draft.unavailable };
@@ -662,7 +675,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
662
675
  // and its pending retry cannot use this escape. No fresh content is clipped or edited by this admission attempt.
663
676
  const nativeFloorDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean,
664
677
  project: (candidate: Decision<CutPlan>) => Messages): Extract<Decision<CutPlan>, { kind: "cut" }> | undefined => {
665
- if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.thinkingRetryPending) return;
678
+ if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.lengthRetryPending) return;
666
679
  const candidate = deepestDecision(ctx, newPrompt, retain, false);
667
680
  if (candidate.kind !== "cut") return;
668
681
  const messages = project(candidate);
@@ -678,7 +691,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
678
691
  if (standDown(ctx)) return;
679
692
  run!.cut.clear();
680
693
  run!.nativeFloorPending = false;
681
- const branchLength = ctx.sessionManager.getBranch().length;
682
694
  if (!active()) return;
683
695
  access();
684
696
  if (!settingsFor().getCompactionSettings(ctx.model).enabled) return;
@@ -687,7 +699,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
687
699
  // Public early view only: later handlers, image normalization and tool-loop growth remain the complete-context guard's responsibility.
688
700
  const saved = ctx.sessionManager.buildSessionProjection().messages;
689
701
  const system = requestSystemPart(observedPrompt, tools, saved, ctx.getSystemPrompt());
690
- const band = decisionBand(ctx, room, system);
702
+ const band = decisionBand(ctx, room);
691
703
  const hostInput = hostSnapshot ?? hostMessages(ctx), host = conversationTokens(hostInput), measure = measureFor(ctx), before = measure(saved);
692
704
  const incoming = incomingPart + system, mandatory = incoming + host;
693
705
  observeBudget(before + mandatory, ctx);
@@ -707,11 +719,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
707
719
  // 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
708
720
  // there buys nothing the request needed and costs history the next recall would have found.
709
721
  // A steer joins the admitted run: keep its starting prompt and the unexposed tool round, just as at a tool boundary.
710
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
722
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
711
723
  newPrompt: !protectedId, protectedPromptEntryId: protectedId, reRenderSummary: !opportunistic }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, Boolean(protectedId));
712
724
  if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
713
725
  const candidate = new PendingCut();
714
- candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, branchLength);
726
+ candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, ctx);
715
727
  const messages = candidate.view(ctx).session.buildSessionProjection().messages;
716
728
  assertNativeToolRounds(messages);
717
729
  return { draft: true, after: measure(messages), compaction: draft.compaction, reserve, messages };
@@ -720,13 +732,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
720
732
  let decision: Decision<CutPlan> = gate.kind === "plan" ? decide(room, band, gate.opportunistic) : { kind: "defer" };
721
733
  const { hardLine } = limits(ctx);
722
734
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
723
- decision = fits(before + mandatory, hardLine, ctx) ? { kind: "none" } :
724
- fits(mandatory, hardLine, ctx) ? decide(hardLine, hardLine, false) : { kind: "defer" };
725
- decision = clampAboveRoom(decision, ctx, room, hardLine,
735
+ decision = planAboveRoom(hardLine => clampAboveRoom(fits(before + mandatory, hardLine, ctx) ? { kind: "none" } :
736
+ fits(mandatory, hardLine, ctx) ? decide(hardLine, hardLine, false) : { kind: "defer" }, ctx, room, hardLine,
726
737
  candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory,
727
738
  candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, candidate.kind === "cut"),
728
739
  target => decide(target, target <= room ? band : target, false),
729
- () => deepestDecision(ctx, !protectedId, Boolean(protectedId)));
740
+ () => deepestDecision(ctx, !protectedId, Boolean(protectedId))), ctx);
730
741
  }
731
742
  if (decision.kind === "defer") return;
732
743
  // An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
@@ -739,7 +750,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
739
750
  if (decision.kind === "fault") throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
740
751
  const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, Boolean(protectedId), false, previousSummary,
741
752
  { response, host, mandatory, target: decision.target, margin: room - band });
742
- run!.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, branchLength);
753
+ run!.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, ctx);
743
754
  };
744
755
  pi.on("before_agent_start", async (event, ctx) => {
745
756
  if (standDown(ctx)) return;
@@ -748,7 +759,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
748
759
  const prompted = run && ["decided", "claimed", "expired"].includes(run.phase) && event.messageType !== "custom";
749
760
  if (!prompted && !failure()) beginRun("starting");
750
761
  run ??= new Run("starting");
751
- if (!failure() && run.phase !== "starting") run.transition("starting", ctx);
762
+ if (!failure() && run.phase !== "starting") run.transition("starting");
752
763
  const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
753
764
  run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
754
765
  try {
@@ -803,7 +814,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
803
814
  // saved conversation. Pi's peek returns the steering queue, else the follow-up queue; a follow-up is not in the very next
804
815
  // request while tools still run, so it can be counted early: conservative, and nothing else would cut at that later boundary.
805
816
  const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), saved, ctx.getSystemPrompt());
806
- const band = decisionBand(ctx, room, system);
817
+ const band = decisionBand(ctx, room);
807
818
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
808
819
  const queued = event.context.pendingMessages.length ? conversationTokens(event.context.pendingMessages as Messages) : 0;
809
820
  const mandatory = system + host + queued;
@@ -841,7 +852,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
841
852
  unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
842
853
  plan: (target): Plan<CutPlan> => {
843
854
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
844
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
855
+ 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);
845
856
  if (!draft.compaction) {
846
857
  // The planner's own floor, so a clip's second budget is measured against what the smallest cut really keeps.
847
858
  if (draft.floorMessages && event.toolResults) {
@@ -888,17 +899,19 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
888
899
  calibration.estimatedTokens = corrected(before + mandatory, ctx);
889
900
  const { hardLine } = limits(ctx);
890
901
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
891
- if (fits(before + mandatory, hardLine, ctx)) decision = { kind: "none" };
892
- else { decision = decide(hardLine, hardLine); tryClips(hardLine, hardLine); }
893
- decision = clampAboveRoom(decision, ctx, room, hardLine,
894
- candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory,
895
- candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, event.context.pendingMessages as Messages, ctx.getSystemPrompt(), pi.getActiveTools(), candidate.kind === "cut"),
896
- target => {
897
- const targetBand = target <= room ? band : target;
898
- decision = decide(target, targetBand, target > room);
899
- tryClips(target, targetBand, target > room);
900
- return decision;
901
- }, () => deepestDecision(ctx, false, true));
902
+ decision = planAboveRoom(hardLine => {
903
+ if (fits(before + mandatory, hardLine, ctx)) decision = { kind: "none" };
904
+ else { decision = decide(hardLine, hardLine); tryClips(hardLine, hardLine); }
905
+ return clampAboveRoom(decision, ctx, room, hardLine,
906
+ candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory,
907
+ candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, event.context.pendingMessages as Messages, ctx.getSystemPrompt(), pi.getActiveTools(), candidate.kind === "cut"),
908
+ target => {
909
+ const targetBand = target <= room ? band : target;
910
+ decision = decide(target, targetBand, target > room);
911
+ tryClips(target, targetBand, target > room);
912
+ return decision;
913
+ }, () => deepestDecision(ctx, false, true));
914
+ }, ctx);
902
915
  }
903
916
  if (decision.kind === "fault" && reason === "tool-loop") {
904
917
  if (decision.capacity) decision = nativeFloorDecision(ctx, false, true,
@@ -934,7 +947,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
934
947
  const atBoundary = (event: Boundary, ctx: ExtensionContext, reason: "tool-loop" | "run-end", decide: boolean) => {
935
948
  const current = view(ctx);
936
949
  if (!current.pending) return decide ? boundaryCut(event, ctx, reason) : undefined;
937
- const entry = run!.cut.take()!;
950
+ const entry = run!.cut.take(ctx)!;
938
951
  const preview = current.session, context: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
939
952
  const more = decide && !event.entries.length
940
953
  ? boundaryCut({ ...event, context: { ...event.context, contextMessages: preview.buildSessionProjection().messages } }, context, reason) : undefined;
@@ -943,47 +956,66 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
943
956
  return { entries: [...event.entries as CutEntry[], saved, ...(more?.entries ?? [])] };
944
957
  };
945
958
  const retryLength = (event: TurnEndEvent, ctx: ExtensionContext) => {
959
+ // Exhausting the full per-request allowance is not evidence that input is too large.
960
+ // Preserve the unfinished response; provider-native continuation owns this case.
961
+ // Native Pi does not compact-and-retry output that reached the catalogue cap.
962
+ if (event.message.role !== "assistant" || !ctx.model) return;
963
+ const stoppedOutput = event.message.usage?.output;
964
+ if (stoppedOutput >= ctx.model.maxTokens) {
965
+ return { entries: event.entries, continue: false };
966
+ }
946
967
  // Pi's supported boundary drafts commit before finishTurn honors `continue`. Omitting the selected failed response also prevents
947
968
  // Pi's later native length recovery from retrying it independently. The stored message and its output usage stay on the branch.
948
969
  const entries: SessionBoundaryDraft[] = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries),
949
970
  { type: "context_edit", targetId: event.messageEntryId, replacement: null }];
950
- if (run!.thinkingRetryPending) { markBoundary(entries); return { entries, continue: false }; }
971
+ if (!run!.canRetryLength) { markBoundary(entries); return { entries, continue: false }; }
951
972
  const preview = liveCut.view(ctx, entries).session;
952
973
  const view: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
953
974
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
954
- // 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
955
- // as large as the deepest cut's, the turn is retried uncut, and no history is given up for nothing.
956
975
  const asIs = projectedRequest(preview.buildSessionProjection().messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), false);
957
976
  const asIsCheck = requestClamp(asIs, view);
958
977
  const previousClips = new Map(clips());
959
978
  const decision = deepestDecision(view, false, true);
960
- if (!serverClipped.has(event.message) && decision.kind === "cut" && asIsCheck.cap !== undefined && asIsCheck.leavesFloor &&
961
- requestClamp(projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true), view).cap! <= asIsCheck.cap) {
962
- clips().clear(); for (const [id, clip] of previousClips) clips().set(id, clip);
979
+ const cut = decision.kind === "cut" ? {
980
+ ...decision,
981
+ messages: projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true),
982
+ } : undefined;
983
+ const check = cut && requestClamp(cut.messages, view);
984
+ const continuation = `${ctx.model.provider}/${ctx.model.id}` === options.continuationModel;
985
+ // A cut that adds no reply room gives up history for nothing: retry the request uncut.
986
+ if (!continuation && asIsCheck.cap !== undefined && asIsCheck.leavesFloor && (check?.cap === undefined || check.cap <= asIsCheck.cap)) {
987
+ restoreClips(previousClips);
963
988
  const { room, hardLine } = limits(view);
964
- run!.thinkingRetryPending = true;
989
+ run!.requestLengthRetry();
965
990
  const drafts = [...entries, { type: "custom" as const, customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
966
- stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: false,
991
+ stoppedOutputTokens: stoppedOutput ?? 0, cut: false,
967
992
  piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }];
968
993
  markBoundary(drafts);
969
994
  return { entries: drafts, continue: true };
970
995
  }
971
- if (decision.kind !== "cut") throw new CapacityError(clampMessage);
972
- const messages = projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true);
996
+ // With a continuation model an unchanged allowance would repeat the same failed generation. If the
997
+ // planner found no history to cut, there is no capacity diagnosis to make.
998
+ if (!cut || check?.cap === undefined || asIsCheck.cap === undefined || check.cap <= (continuation ? Math.max(asIsCheck.cap, stoppedOutput ?? 0) : asIsCheck.cap)) {
999
+ restoreClips(previousClips);
1000
+ if (!asIsCheck.leavesFloor) {
1001
+ if (check && !check.leavesFloor) throw new CapacityError(clampMessage);
1002
+ if (decision.kind === "fault" && decision.capacity) throw new CapacityError(decision.message);
1003
+ }
1004
+ markBoundary(entries);
1005
+ return { entries, continue: false };
1006
+ }
1007
+ const { messages } = cut;
973
1008
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role)) throw promptRefusal();
974
1009
  const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
975
- const tokens = system + conversationTokens(messages), check = requestClamp(messages, view);
1010
+ const tokens = system + conversationTokens(messages);
976
1011
  const { response, room, hardLine } = limits(view);
977
- // A learned server boundary uses the same admission rule as the guard: below the room the whole reserve fits in provider units.
978
- // Keep the thinking-only rule's unconditional native-clamp floor unchanged.
979
- const needsClampFloor = !serverClipped.has(event.message) || corrected(tokens, view) > room;
980
- if (!fits(tokens, hardLine, view) || check.cap === undefined || needsClampFloor && !check.leavesFloor) throw new CapacityError(clampMessage);
981
- const compaction = captureDraft(decision.plan.compaction, view, decision.plan.reserve, "length-retry", tokens, true, false, undefined,
982
- { response, host, mandatory: system + host + conversationTokens(event.context.pendingMessages), target: decision.target, margin: room - decisionBand(view, room, system) });
983
- run!.thinkingRetryPending = true;
1012
+ if (!fits(tokens, hardLine, view) || !check.leavesFloor) throw new CapacityError(clampMessage);
1013
+ const compaction = captureDraft(cut.plan.compaction, view, cut.plan.reserve, "length-retry", tokens, true, false, undefined,
1014
+ { response, host, mandatory: system + host + conversationTokens(event.context.pendingMessages), target: cut.target, margin: room - decisionBand(view, room) });
1015
+ run!.requestLengthRetry();
984
1016
  const drafts = [...entries, { type: "compaction" as const, summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId || null, details: compaction.details },
985
1017
  { type: "custom" as const, customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
986
- stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: true,
1018
+ stoppedOutputTokens: stoppedOutput ?? 0, cut: true,
987
1019
  estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
988
1020
  markBoundary(drafts);
989
1021
  return { entries: drafts, continue: true };
@@ -992,9 +1024,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
992
1024
  try {
993
1025
  if (standDown(ctx)) return;
994
1026
  if (!active() || run?.phase !== "admitted") return;
995
- if ((thinkingOnlyLength(event.message) || serverClipped.has(event.message)) && !failure() && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
1027
+ if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
996
1028
  return retryLength(event, ctx);
997
- run.thinkingRetryPending = false;
1029
+ run.finishLengthRetry();
998
1030
  const decide = event.outcome === "completed" && !ctx.signal?.aborted && event.context.canContinue && event.toolResults.length > 0 &&
999
1031
  settingsFor().getCompactionSettings(ctx.model).enabled;
1000
1032
  if (!view(ctx).pending && !decide) return;
@@ -1034,7 +1066,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1034
1066
  const guardCut = (messages: Messages, tokens: number, system: number, ctx: ExtensionContext): { messages: Messages; native?: boolean } => {
1035
1067
  const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
1036
1068
  const before = conversationTokens(source), mandatory = tokens - before;
1037
- const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room, system);
1069
+ const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room);
1038
1070
  const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
1039
1071
  const previousClips = new Map(clips());
1040
1072
  const measure = measureFor(ctx);
@@ -1043,7 +1075,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1043
1075
  unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
1044
1076
  plan: (target): Plan<CutPlan> => {
1045
1077
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
1046
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
1078
+ const draft = tuckObservedDraft(tuck, { keepRecentTokens: settingsFor().getCompactionSettings(ctx.model).keepRecentTokens, branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
1047
1079
  protectedPromptEntryId: protectedPrompt(ctx) }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
1048
1080
  if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
1049
1081
  const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
@@ -1057,9 +1089,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1057
1089
  const total = (candidate: Decision<CutPlan>) => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory;
1058
1090
  let decision = decide(room, band);
1059
1091
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
1060
- decision = decide(hardLine, hardLine);
1061
- decision = clampAboveRoom(decision, ctx, room, hardLine, total, project,
1062
- target => decide(target, target <= room ? band : target), () => deepestDecision(ctx, false, true));
1092
+ decision = planAboveRoom(hardLine => clampAboveRoom(decide(hardLine, hardLine), ctx, room, hardLine, total, project,
1093
+ target => decide(target, target <= room ? band : target), () => deepestDecision(ctx, false, true)), ctx);
1063
1094
  }
1064
1095
  const accepts = (candidate: Decision<CutPlan>) => {
1065
1096
  if (candidate.kind !== "cut" || candidate.plan.after >= before) return false;
@@ -1070,7 +1101,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1070
1101
  if (!accepts(decision)) decision = deepestDecision(ctx, false, true);
1071
1102
  let native = false;
1072
1103
  if (decision.kind !== "cut" || !accepts(decision)) {
1073
- clips().clear(); for (const [id, clip] of previousClips) clips().set(id, clip);
1104
+ restoreClips(previousClips);
1074
1105
  const floor = nativeFloorDecision(ctx, false, true, project);
1075
1106
  if (!floor) return { messages };
1076
1107
  decision = floor;
@@ -1079,7 +1110,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1079
1110
  if (decision.kind !== "cut") return { messages };
1080
1111
  const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary,
1081
1112
  { response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
1082
- run!.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx.sessionManager.getBranch().length);
1113
+ run!.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx);
1083
1114
  run!.nativeFloorPending = native;
1084
1115
  syncHistoryTools(ctx);
1085
1116
  return { messages: historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)),
@@ -1123,7 +1154,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1123
1154
  // Pi commits these entries before the run settles.
1124
1155
  try {
1125
1156
  if (!active() || run?.phase !== "admitted" || failure() || !settingsFor().getCompactionSettings(ctx.model).enabled) return;
1126
- const decide = event.outcome === "completed" && !ctx.signal?.aborted;
1157
+ const decide = event.outcome === "completed" && !ctx.signal?.aborted && lengthStop?.kind !== "thinking";
1127
1158
  if (view(ctx).pending ? event.outcome === "error" : !decide) return;
1128
1159
  return atBoundary(event, ctx, "run-end", decide);
1129
1160
  } catch (error) { fail(error, ctx); }
@@ -1131,7 +1162,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1131
1162
  pi.on("context_with_system", (event, ctx) => {
1132
1163
  if (standDown(ctx)) return;
1133
1164
  // Reaching the next request boundary proves native commit returned, not durable storage.
1134
- if (run) { run.pendingBoundaryReceipts = []; }
1165
+ if (run) {
1166
+ run.pendingBoundaryReceipts = [];
1167
+ run.rejectedBudget = undefined;
1168
+ }
1135
1169
  calibration.pending = undefined;
1136
1170
  try {
1137
1171
  if (!active()) return;
@@ -1187,7 +1221,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1187
1221
 
1188
1222
  } catch (error) { fail(error, ctx); }
1189
1223
  });
1190
- return {close:async()=>{recorder.stop("caller-close");}, state: stateFor, inspectState: (ctx: ExtensionContext) => ({ run: run as Readonly<Run> | undefined, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending })};
1224
+ return {close:async()=>{recorder.stop("caller-close");}, state: stateFor, cutPoint, inspectState: (ctx: ExtensionContext) => ({ run: run as Readonly<Run> | undefined, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending })};
1191
1225
  }
1192
1226
 
1193
1227
  function checkedInput(raw: unknown) { if (!Check(RecallInput, raw)) throw new Error("Invalid recall input"); return structuredClone(raw); }