pi-tuck 1.1.1 → 1.1.3

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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,41 @@
3
3
  All notable changes to pi-tuck. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [1.1.3] - 2026-11-15
7
+
8
+ ### Fixed
9
+
10
+ - **A steering message after a very large tool round could end the run with a false refusal.** When the user or a harness sent a message
11
+ while the agent was working, right after a round of tool results too large for the window, pi-tuck planned that cut as if a new run
12
+ were starting. The summary could then leave out the prompt that started the run, and pi-tuck's own prompt check refused with "the
13
+ request is missing the whole text of the prompt that started this run". The cut now keeps the running task's prompt and the fresh tool
14
+ round, as a cut at a tool boundary does. Cuts without a steering message are unchanged.
15
+
16
+ ### Release gates
17
+
18
+ - **Shipped without a live gate: replay matches 1.1.2 byte for byte.** 29 recordings, 13,946 of 13,946 requests identical, 0 lost or
19
+ dead tasks; none of them contains a mid-run steer.
20
+ - **The defect is pinned by two tests that fail on 1.1.2 and pass here:** a scripted large parallel round followed by a steer, and a
21
+ replay of the recorded session where it was found (a public benchmark task, paths scrubbed).
22
+ - **Strict stress:** 322 cells, including 4 new steer cells, and the resumed-session and stand-down suites; 0 findings. Lifecycle with 40
23
+ seeds. Tests and CI. The packed tarball loaded in the real installed Pi.
24
+
25
+ ## [1.1.2] - 2026-11-14
26
+
27
+ ### Changed
28
+
29
+ - **Internal: pi-tuck's run and calibration state each have one owner.** A run's failure is now its phase alone, changed only through a
30
+ fixed table of allowed moves, so a failed run can no longer be treated as admitted. The calibration values that three events used to
31
+ reset separately are one object reseeded in one place. Nothing the model sees changes. The lifecycle test now also resumes sessions
32
+ cold, switches models mid-session and back, and checks after every event that no impossible state appears.
33
+
34
+ ### Release gates
35
+
36
+ - **Shipped without a live gate: replay matches 1.1.1 byte for byte.** 29 recordings, 13,946 of 13,946 requests identical, the same
37
+ 1,971 cuts, 0 lost or dead tasks.
38
+ - **Strict stress:** 318 cells and the resumed-session suite, 0 findings. Lifecycle with 40 seeds. Tests and CI. The packed tarball loaded
39
+ in the real installed Pi.
40
+
6
41
  ## [1.1.1] - 2026-11-14
7
42
 
8
43
  ### Fixed
package/README.md CHANGED
@@ -64,8 +64,8 @@ Then start a new Pi session. That is all. pi-tuck takes over Pi's compaction, bo
64
64
 
65
65
  - Needs Pi 1.2.0 or later (tested on 1.2.0 and 1.4.0), on macOS or Linux. On an older Pi, pi-tuck stays off, Pi's own compaction runs, and pi-tuck says so once. Full features on macOS with Apple silicon; elsewhere, compaction and word recall.
66
66
  - On macOS with Apple silicon, the first session also downloads a local search model in the background (about 390 MB, once), and says once when it is set up. Until it is ready, search works by keyword. See [Semantic search](#semantic-search).
67
- - Prefer GitHub? `pi install git:github.com/galyavin/pi-tuck@v1.1.0`.
68
- - To pin a version, add it: `pi install npm:pi-tuck@1.1.0`.
67
+ - Prefer GitHub? `pi install git:github.com/galyavin/pi-tuck@v1.1.2`.
68
+ - To pin a version, add it: `pi install npm:pi-tuck@1.1.2`.
69
69
 
70
70
  ## Uninstall
71
71
 
@@ -103,10 +103,12 @@ pi-tuck's tools appear only after its first cut. Before that there is nothing ou
103
103
 
104
104
  | Command | Does |
105
105
  |---|---|
106
- | `/tuck` | Says in words what pi-tuck is doing in this session: the version this session loaded (an open session keeps it until Pi restarts), how many cuts and retries pi-tuck made and the last cut's size before and after, whether the cut point adapts or is fixed by `cutAt`, and how search works here. It is for you; the model sees nothing new. |
106
+ | `/tuck` | Says in words what pi-tuck is doing in this session: the version this session loaded (an open session keeps it until Pi restarts), how many cuts and retries pi-tuck made and the last cut's size before and after, whether the cut point adapts or is fixed by `cutAt`, how search works here, and, since 1.1.1, `standing down:` with the reason when pi-tuck is not acting. It is for you; the model sees nothing new. |
107
107
  | `/tuck-semantic on\|off\|status` | Turns semantic search on or off for this session, or shows its state. |
108
108
  | `/tuck-incident on\|next\|off\|status` | Records this session's compaction decisions to a file you can attach to a bug report. |
109
109
 
110
+ Since 1.1.1, pi-tuck stands down to native Pi when it cannot do its job safely: with an unknown context window (0, missing or not a number), with a Pi virtual model, or with Pi's auto-compaction turned off. It then does exactly what native Pi does, and `/tuck` says `standing down:` with the reason. Refusal, overflow and manual-cut notices also reach stderr when there is no UI (`pi -p`, JSON runs), as the output-limit notice already did.
111
+
110
112
  `/compact` works as usual. Text after it does not steer the summary, because pi-tuck builds the summary from the session itself: since 1.0.19 it cuts as plain `/compact` does and says the text was not used. Pi's own setting `"compaction": { "enabled": false }` turns compaction off.
111
113
 
112
114
  ## What is proven, and what is not
@@ -136,6 +138,8 @@ Known limits today:
136
138
  - A request above the room could be admitted and then refused, leaving the session stuck where native Pi would have sent (1.0.22 to 1.0.24; fixed in 1.0.25). pi-tuck checked its line in its own corrected token count, while Pi's reply cap uses Pi's own estimate, which is higher when the provider counts fewer tokens than pi-tuck's raw measure ([`CHANGELOG.md`](CHANGELOG.md) 1.0.25).
137
139
  - Near the 1.0.22 refusal line, replies were cut to a few hundred tokens (1.0.22; fixed in 1.0.23). 1.0.22 left only its reply floor and did not count Pi's 4,096-token margin on the reply cap ([`CHANGELOG.md`](CHANGELOG.md) 1.0.23).
138
140
  - Cost of the 1.0.22 change: between the room and the window, the reply reserve no longer cushions a wrong count. At a cold start an undercount can reach the provider. A provider that errors is caught and learned from; a server that truncates silently truncates, as it does for native Pi. With a setup above the room, cuts are forced and frequent, each freeing little, which beats a stranded session ([`CHANGELOG.md`](CHANGELOG.md) 1.0.22).
141
+ - Fixed in 1.1.1: a resumed session forgot what pi-tuck had learned about the provider's token counts. pi-tuck saved its calibration only inside a cut, so after quitting and resuming Pi before the next cut it counted at 1x again and could send a request the provider truncated or refused, where native Pi succeeded. pi-tuck now saves a small private entry in the session when what a resume would learn changes, not every turn, and reads it back on resume. The entry never reaches the model ([`CHANGELOG.md`](CHANGELOG.md) 1.1.1).
142
+ - Fixed in 1.1.1: pi-tuck refused prompts that native Pi would have sent when the context window was unknown, the model was a Pi virtual model, or Pi's auto-compaction was turned off. It now stands down to native in those cases. Also fixed in 1.1.1: refusal, overflow and manual-cut notices were silent without a UI, so a run in `pi -p` or JSON mode could end with no word; the semantic search status could claim "ready" when it was turned off or had failed; and a retry after a reply hit the output limit skipped a check that a pending cut had really been saved in the session ([`CHANGELOG.md`](CHANGELOG.md) 1.1.1).
139
143
  - Fixed in 1.0.33: a file read's recall number pointed at the read call, not at what the read returned. The summary lists each file the session read with a `tuck_recall` number, and that number brought back the call's arguments instead of the file's contents, so recalling a read cost a turn and showed nothing useful. It now brings back the read's output ([`CHANGELOG.md`](CHANGELOG.md) 1.0.33).
140
144
  - Fixed in 1.0.32: background indexing never started at the cuts pi-tuck makes itself. Pi announces only its own compactions, so cuts pi-tuck saved after a tool round, at the end of a run, or before retrying a reply that hit the output limit started no indexing ([`CHANGELOG.md`](CHANGELOG.md) 1.0.32).
141
145
  - Fixed in 1.0.31: input that arrived after a tool round had been checked, such as another extension's context or a newly enabled tool, could push the next request past the hard line, and the final check refused a request that pi-tuck could still cut. It now cuts at that check, carries the cut in that request, saves it at the next boundary, and refuses only when no cut can fit ([`CHANGELOG.md`](CHANGELOG.md) 1.0.31).
@@ -1 +1 @@
1
- export declare const BUILD_ID = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
1
+ export declare const BUILD_ID = "d3c9d03a4fd2a19793701c4c043b680a24b0a5f219c4c3ab6f7c3a232feb333e";
@@ -1 +1 @@
1
- export const BUILD_ID = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
1
+ export const BUILD_ID = "d3c9d03a4fd2a19793701c4c043b680a24b0a5f219c4c3ab6f7c3a232feb333e";
@@ -1,3 +1,4 @@
1
+ import { type Run } from "./run.js";
1
2
  import { type SemanticRecallController } from "./semantic-recall.js";
2
3
  import { type RecorderOptions } from "./diagnostics.js";
3
4
  import { type AgentMessage } from "./budget.js";
@@ -180,4 +181,10 @@ export declare function installCompaction(pi: ExtensionAPI, options?: Compaction
180
181
  };
181
182
  };
182
183
  state: (ctx: ExtensionContext) => CompactionState;
184
+ inspectState: (ctx: ExtensionContext) => {
185
+ run: Readonly<Run> | undefined;
186
+ phase: "starting" | "failed" | "decided" | "claimed" | "expired" | "admitted" | "commit-failed" | undefined;
187
+ calibrationIdentity: string;
188
+ pendingCut: boolean;
189
+ };
183
190
  }>;
@@ -119,6 +119,53 @@ export function seedWindow(branch, key) {
119
119
  }
120
120
  return initialWindow(key);
121
121
  }
122
+ /** One accounting owner. Session start still defers receipt loading until the first budget read;
123
+ * tree moves load immediately, and identity changes keep any uncommitted window observation. */
124
+ class Calibration {
125
+ identity = '';
126
+ factor = 1;
127
+ ratios = [];
128
+ learnedContextWindow;
129
+ windowObservation;
130
+ pending;
131
+ lastCeiling = null;
132
+ estimatedTokens = 0;
133
+ seededIdentity = '';
134
+ static key(ctx) { return ctx.model ? JSON.stringify([ctx.model.provider, ctx.model.api, ctx.model.id]) : ''; }
135
+ /** Model selection itself never reloads receipts: switching away and back without a request keeps the learned window. */
136
+ select(ctx) { this.identity = Calibration.key(ctx); }
137
+ needsSeed(ctx) { return this.seededIdentity !== Calibration.key(ctx); }
138
+ reseed(ctx, reason) {
139
+ this.identity = Calibration.key(ctx);
140
+ this.pending = undefined;
141
+ if (reason !== 'identity')
142
+ this.windowObservation = undefined;
143
+ if (reason === 'session') {
144
+ this.factor = 1;
145
+ this.learnedContextWindow = undefined;
146
+ this.estimatedTokens = 0;
147
+ // Keep the old ratios/ceiling until their existing readers replace them, as in 1.1.1.
148
+ this.seededIdentity = '';
149
+ return;
150
+ }
151
+ this.seededIdentity = this.identity;
152
+ if (reason === 'tree' && !this.identity)
153
+ return;
154
+ const branch = ctx.sessionManager.getBranch();
155
+ this.ratios = seedWindow(branch, this.identity);
156
+ this.factor = Math.max(1, ...this.ratios);
157
+ this.learnedContextWindow = seedContextWindow(branch, this.identity);
158
+ }
159
+ learn(value, ctx, append) {
160
+ this.ratios.push(value);
161
+ if (this.ratios.length > CALIBRATION_WINDOW)
162
+ this.ratios.shift();
163
+ this.factor = Math.max(1, ...this.ratios);
164
+ // D7: compare what a cold instance would seed, including the existing clamps.
165
+ if (!isDeepStrictEqual(seedWindow(ctx.sessionManager.getBranch(), this.identity), this.ratios.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING))))
166
+ append(CALIBRATION_RECEIPT, { calibrationIdentity: this.identity, calibrationWindow: [...this.ratios] });
167
+ }
168
+ }
122
169
  /** Only evidenced prerequisites disable our request/summary transforms. A missing model keeps the existing explicit error. */
123
170
  export function compactionState(model, enabled) {
124
171
  const reason = !enabled ? "compaction is disabled" : model?.api === "pi-virtual" ? "pi-virtual model" : !model ? undefined
@@ -167,7 +214,7 @@ export async function installCompaction(pi, options = {}) {
167
214
  }
168
215
  });
169
216
  const captureDraft = (draft, ctx, reserve, reason, tokensBefore, retainCurrentInput, operatorManual, previousSummary, budget) => recorder.measureInline(() => {
170
- const attached = attachReceipt(draft, reason, reserve, contextWindow(ctx), { responseReserveTokens: budget?.response, hostInputTokens: budget?.host, mandatoryInputTokens: budget?.mandatory, target: budget?.target, triggerMarginTokens: budget?.margin, ...(cutAt === 1 ? {} : { cutAt }), calibrationFactor: factor, calibrationWindow: [...ratios], calibrationIdentity: identity, learnedContextWindow, activeInputCeilingTokens: lastCeiling });
217
+ 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, activeInputCeilingTokens: calibration.lastCeiling });
171
218
  proposalId = receiptId(attached);
172
219
  if (recorder.enabled) {
173
220
  try {
@@ -253,80 +300,72 @@ export async function installCompaction(pi, options = {}) {
253
300
  } });
254
301
  // Pi's native start/settled events bracket the run and its post-turn cuts.
255
302
  let run;
256
- // A native append may have mutated memory before its disk write failed. This session fault outlives the run.
257
- let commitFault;
258
- const failure = () => commitFault ?? run?.failure;
303
+ // A commit-failed phase survives attempts/tree moves until session_start: native memory may be ahead of disk.
304
+ const failure = () => run?.phase === "failed" || run?.phase === "commit-failed" ? run.error : undefined;
259
305
  const protectedPrompt = (ctx) => run?.prompt?.id(ctx.sessionManager.getBranch());
260
306
  const clips = () => run?.clips ?? emptyClips;
261
307
  const emptyClips = new Map();
262
- const resetRun = () => { run = undefined; pending = undefined; };
308
+ const resetRun = (session = false) => {
309
+ if (!session && run?.phase === "commit-failed")
310
+ run.clear();
311
+ else
312
+ run = undefined;
313
+ calibration.pending = undefined;
314
+ };
315
+ const beginRun = (phase) => {
316
+ if (run?.phase === "commit-failed")
317
+ run.clear();
318
+ else
319
+ run = createRun(phase);
320
+ };
263
321
  const stateFor = (ctx) => compactionState(ctx.model, settingsFor().getCompactionSettings(ctx.model).enabled);
264
322
  // A prerequisite can change with the model/settings; discard the old plan before returning control to native.
265
323
  const standDown = (ctx) => {
266
324
  if (stateFor(ctx).kind === "active")
267
325
  return false;
268
326
  resetRun();
269
- windowObservation = undefined;
327
+ calibration.windowObservation = undefined;
270
328
  lengthStop = false;
271
329
  return true;
272
330
  };
273
331
  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");
274
- let estimatedTokens = 0;
275
- // One serial request, one accounting identity; observations never certify new content. A new identity (the first request after a session
276
- // start, or a model switch) starts with the window its branch's newest receipt recorded for that identity, else that receipt's factor, else the model's measured undercount or 1 (`seedWindow`).
277
- let identity = "", factor = 1, ratios = [];
278
- let learnedContextWindow;
332
+ const calibration = new Calibration();
279
333
  const serverClipped = new WeakSet();
280
- let windowObservation;
281
- let lastCeiling = null;
282
- let pending;
283
334
  const identityFor = (ctx) => {
284
- const key = ctx.model ? JSON.stringify([ctx.model.provider, ctx.model.api, ctx.model.id]) : "";
285
- if (key !== identity) {
286
- identity = key;
287
- ratios = seedWindow(ctx.sessionManager.getBranch(), key);
288
- factor = Math.max(1, ...ratios);
289
- learnedContextWindow = seedContextWindow(ctx.sessionManager.getBranch(), key);
290
- pending = undefined;
291
- }
292
- return key;
335
+ calibration.select(ctx);
336
+ if (calibration.needsSeed(ctx))
337
+ calibration.reseed(ctx, "identity");
338
+ return calibration.identity;
293
339
  };
340
+ pi.on("model_select", (_event, ctx) => { calibration.select(ctx); });
294
341
  const contextWindow = (ctx) => {
295
342
  identityFor(ctx);
296
- return Math.min(ctx.model?.contextWindow ?? 0, learnedContextWindow ?? Infinity);
343
+ return Math.min(ctx.model?.contextWindow ?? 0, calibration.learnedContextWindow ?? Infinity);
297
344
  };
298
345
  // This is the cap in Pi's built provider payload, including its context clamp and thinking adjustments.
299
346
  // An API with no explicit cap supplies no clipping evidence; never substitute the catalogue maximum.
300
347
  pi.on("before_provider_request", event => {
301
- if (!pending || !event.payload || typeof event.payload !== "object")
348
+ if (!calibration.pending || !event.payload || typeof event.payload !== "object")
302
349
  return;
303
350
  const payload = event.payload;
304
351
  // Read at reply time so later in-place payload edits are included too.
305
- pending.requestedMaxTokens = () => {
352
+ calibration.pending.requestedMaxTokens = () => {
306
353
  const cap = payload.max_tokens ?? payload.max_completion_tokens ?? payload.max_output_tokens;
307
354
  return typeof cap === "number" && Number.isSafeInteger(cap) && cap > 0 ? cap : undefined;
308
355
  };
309
356
  });
310
357
  // 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.
311
- const learn = (value, ctx) => {
312
- ratios.push(value);
313
- if (ratios.length > CALIBRATION_WINDOW)
314
- ratios.shift();
315
- factor = Math.max(1, ...ratios);
316
- // Compare what a cold instance would seed (including the existing clamps). Stable windows write nothing.
317
- if (!isDeepStrictEqual(seedWindow(ctx.sessionManager.getBranch(), identity), ratios.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING))))
318
- pi.appendEntry(CALIBRATION_RECEIPT, { calibrationIdentity: identity, calibrationWindow: [...ratios] });
319
- };
320
- const corrected = (tokens, ctx) => { identityFor(ctx); return Math.ceil(tokens * factor); };
358
+ const learn = (value, ctx) => calibration.learn(value, ctx, (kind, data) => pi.appendEntry(kind, data));
359
+ const corrected = (tokens, ctx) => { identityFor(ctx); return Math.ceil(tokens * calibration.factor); };
321
360
  const observeBudget = (rawTokens, ctx) => {
322
361
  if (options.observeBudget)
323
- options.observeBudget({ rawTokens, tokens: corrected(rawTokens, ctx), factor, ...limits(ctx), context: ctx });
362
+ options.observeBudget({ rawTokens, tokens: corrected(rawTokens, ctx), factor: calibration.factor, ...limits(ctx), context: ctx });
324
363
  };
325
364
  // The cut planner's raw reserve for the target limit, on the same factor as every other consumer.
326
365
  const planReserve = (target, room, band, mandatory, ctx) => {
327
366
  identityFor(ctx);
328
367
  // The compiler subtracts this reserve from the catalogue window. Targets already use the learned window.
329
- return planningReserve(ctx.model?.contextWindow ?? 0, target === "band" ? band : room, factor, mandatory);
368
+ return planningReserve(ctx.model?.contextWindow ?? 0, target === "band" ? band : room, calibration.factor, mandatory);
330
369
  };
331
370
  pi.on("message_end", (event, ctx) => {
332
371
  if (event.message.role !== "assistant")
@@ -342,8 +381,8 @@ export async function installCompaction(pi, options = {}) {
342
381
  recorder.capture("response-actions", "hidden-material-excluded", { stopReason: responseMessage.stopReason }, true);
343
382
  recorder.responded(responseMessage.stopReason);
344
383
  });
345
- const paired = pending;
346
- pending = undefined;
384
+ const paired = calibration.pending;
385
+ calibration.pending = undefined;
347
386
  const key = identityFor(ctx), message = event.message;
348
387
  const overflow = message.stopReason === "error" && isContextOverflow(message);
349
388
  if (!paired || !key || paired.identity !== key || !active() || failure() || ctx.signal?.aborted || (message.errorMessage && !overflow) ||
@@ -374,9 +413,9 @@ export async function installCompaction(pi, options = {}) {
374
413
  if (message.stopReason === "length" && requested !== undefined &&
375
414
  Number.isSafeInteger(output) && output >= 0 && output < requested &&
376
415
  Number.isSafeInteger(bound) && bound > 0 && bound <= ctx.model.contextWindow) {
377
- learnedContextWindow = Math.min(learnedContextWindow ?? Infinity, bound);
416
+ calibration.learnedContextWindow = Math.min(calibration.learnedContextWindow ?? Infinity, bound);
378
417
  serverClipped.add(message);
379
- windowObservation = { message, identity: key, window: learnedContextWindow };
418
+ calibration.windowObservation = { message, identity: key, window: calibration.learnedContextWindow };
380
419
  }
381
420
  // A request that was answered cannot have held more than the model's window, so a report above it describes something that never happened.
382
421
  // 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
@@ -387,10 +426,10 @@ export async function installCompaction(pi, options = {}) {
387
426
  pi.on("turn_end", (event, ctx) => {
388
427
  if (standDown(ctx))
389
428
  return;
390
- if (windowObservation?.message !== event.message)
429
+ if (calibration.windowObservation?.message !== event.message)
391
430
  return;
392
- const observation = windowObservation;
393
- windowObservation = undefined;
431
+ const observation = calibration.windowObservation;
432
+ calibration.windowObservation = undefined;
394
433
  pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window,
395
434
  serverClippedReplyId: event.messageEntryId });
396
435
  });
@@ -398,7 +437,8 @@ export async function installCompaction(pi, options = {}) {
398
437
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
399
438
  let lengthStop = false;
400
439
  pi.on("agent_start", (_event, ctx) => { if (standDown(ctx))
401
- return; run ??= createRun("admitted"); run.phase = "admitted"; run.thinkingRetryPending = false; lengthStop = false; pending = undefined; });
440
+ return; run ??= createRun("starting"); if (!failure())
441
+ run.transition("admitted", ctx); run.thinkingRetryPending = false; lengthStop = false; calibration.pending = undefined; });
402
442
  pi.on("message_end", event => { if (event.message.role === "assistant")
403
443
  lengthStop = event.message.stopReason === "length"; });
404
444
  pi.on("agent_settled", (_event, ctx) => {
@@ -431,7 +471,7 @@ export async function installCompaction(pi, options = {}) {
431
471
  const inputRoom = (response, ctx) => {
432
472
  const configured = options.activeInputTokens;
433
473
  const ceiling = typeof configured === "function" ? configured(ctx) : configured;
434
- lastCeiling = ceiling ?? null;
474
+ calibration.lastCeiling = ceiling ?? null;
435
475
  if (ceiling !== undefined && (!Number.isSafeInteger(ceiling) || ceiling <= 0))
436
476
  throw new Error("Invalid active-input token ceiling");
437
477
  return Math.min(contextWindow(ctx) - response, ceiling ?? Infinity);
@@ -440,14 +480,14 @@ export async function installCompaction(pi, options = {}) {
440
480
  const limits = (ctx) => {
441
481
  const { response } = requestReserve(ctx), room = inputRoom(response, ctx);
442
482
  const floor = options.requestReserve ? response : requestReplyFloor(ctx.sessionManager.getBranch(), response, ctx.model?.maxTokens);
443
- const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), lastCeiling ?? Infinity);
483
+ const hardLine = Math.min(Math.max(room, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
444
484
  return { response, room, hardLine, replyFloor: floor };
445
485
  };
446
486
  const decisionBand = (ctx, room, system, current = view(ctx)) => {
447
487
  const last = current.session.getBranch().findLast(entry => entry.type === "compaction");
448
488
  const after = last?.type === "compaction" ? last.details?.tokensAfter : undefined;
449
489
  return bandOf(room, cutAt, options.cutAt === undefined && typeof after === "number" && Number.isFinite(after) && after >= 0
450
- ? { system, tokensAfter: after, factor } : undefined);
490
+ ? { system, tokensAfter: after, factor: calibration.factor } : undefined);
451
491
  };
452
492
  const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
453
493
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
@@ -525,7 +565,7 @@ export async function installCompaction(pi, options = {}) {
525
565
  ({ room, hardLine } = limits(ctx));
526
566
  }
527
567
  catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
528
- pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens, room, hardLine, buildId: BUILD_ID });
568
+ pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID });
529
569
  };
530
570
  const fail = (error, ctx) => {
531
571
  recorder.stop("native-attempt-failed");
@@ -534,13 +574,12 @@ export async function installCompaction(pi, options = {}) {
534
574
  const previous = failure(), shouldNotify = !previous;
535
575
  const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
536
576
  const receipted = run?.refusalReceipted;
537
- resetRun();
538
- // Keep only a terminal attempt record until Pi settles: its fresh abort controller must still see the refusal.
539
- run = createRun("failed");
540
- run.failure = fault;
577
+ calibration.pending = undefined;
578
+ // Keep the same terminal run until Pi settles; later start hooks cannot admit it.
579
+ run ??= createRun("starting");
580
+ run.clear();
581
+ run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", ctx, fault);
541
582
  run.refusalReceipted = true;
542
- if (fault instanceof CommitFault)
543
- commitFault = fault;
544
583
  try {
545
584
  if (!receipted)
546
585
  receipt("refusal", fault.message, ctx);
@@ -549,7 +588,7 @@ export async function installCompaction(pi, options = {}) {
549
588
  finally {
550
589
  try {
551
590
  if (shouldNotify)
552
- notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, factor) : fault instanceof CommitFault
591
+ notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
553
592
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
554
593
  : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error");
555
594
  }
@@ -566,7 +605,7 @@ export async function installCompaction(pi, options = {}) {
566
605
  pi.on("input", async (event, ctx) => {
567
606
  if (!ctx.isIdle() || run?.phase === "starting")
568
607
  return; // steering joins the existing run
569
- run = createRun("decided");
608
+ beginRun("decided");
570
609
  const decision = run;
571
610
  try {
572
611
  syncHistoryTools(ctx);
@@ -578,8 +617,8 @@ export async function installCompaction(pi, options = {}) {
578
617
  }
579
618
  // Pi normally reaches its pre-run threshold check within microtasks. Auth I/O or a later extension's input I/O can make a
580
619
  // real prompt expire too; safely fall back to carrying its cut in the request and saving it at the first boundary.
581
- setImmediate(() => { if (run === decision && !decision.claimed)
582
- decision.expired = true; });
620
+ setImmediate(() => { if (run === decision && decision.phase === "decided")
621
+ decision.transition("expired", ctx); });
583
622
  });
584
623
  pi.registerTool({
585
624
  name: "tuck_recall", label: "pi-tuck history", parameters: RecallInput,
@@ -659,8 +698,8 @@ export async function installCompaction(pi, options = {}) {
659
698
  }
660
699
  // Pi checks its own threshold after a prompt's input and before the run starts: the prompt's cut, planned with the prompt counted,
661
700
  // is the answer, and it is saved before the first request.
662
- if (run?.phase === "decided" && !run.expired && event.reason === "threshold") {
663
- run.claimed = true;
701
+ if ((run?.phase === "decided" || run?.phase === "claimed") && event.reason === "threshold") {
702
+ run.transition("claimed", ctx);
664
703
  if (view(ctx).pending) {
665
704
  access();
666
705
  const current = view(ctx), { type: _, ...compaction } = run.cut.take();
@@ -711,7 +750,7 @@ export async function installCompaction(pi, options = {}) {
711
750
  : { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
712
751
  },
713
752
  });
714
- estimatedTokens = corrected(before + mandatory, ctx);
753
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
715
754
  let decision = decide();
716
755
  const { hardLine } = limits(ctx);
717
756
  if (!operatorManual && hardLine > room && decision.kind === "fault") {
@@ -742,22 +781,22 @@ export async function installCompaction(pi, options = {}) {
742
781
  }
743
782
  });
744
783
  pi.on("session_before_tree", (event, ctx) => !standDown(ctx) && event.preparation.userWantsSummary ? { cancel: true } : undefined);
745
- pi.on("session_start", () => { resetRun(); recorder.stop("session-transition"); proposalId = undefined; commitFault = undefined; estimatedTokens = 0; identity = ""; factor = 1; learnedContextWindow = undefined; windowObservation = undefined; });
784
+ pi.on("session_start", (_event, ctx) => { resetRun(true); recorder.stop("session-transition"); proposalId = undefined; calibration.reseed(ctx, "session"); });
746
785
  const historyToolsEnabled = (ctx) => stateFor(ctx).kind === "active" && view(ctx).hasTuckCut;
747
786
  const syncHistoryTools = (ctx) => { if (active())
748
787
  applyHistoryTools(pi, historyToolsEnabled(ctx)); };
749
788
  pi.on("session_start", (_event, ctx) => syncHistoryTools(ctx));
750
789
  // A plan decided on `input` is for the branch it was decided on: moving in the tree leaves it planned for another branch, whose kept entry
751
790
  // may not be on this one.
752
- pi.on("session_tree", (_event, ctx) => { resetRun(); windowObservation = undefined; identity = ""; identityFor(ctx); syncHistoryTools(ctx); });
791
+ pi.on("session_tree", (_event, ctx) => { resetRun(); calibration.reseed(ctx, "tree"); syncHistoryTools(ctx); });
753
792
  pi.on("session_compact", (_event, ctx) => { if (run?.phase !== "admitted")
754
793
  syncHistoryTools(ctx); });
755
794
  pi.on("turn_start", (_event, ctx) => syncHistoryTools(ctx));
756
795
  pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
757
796
  const plannedView = (ctx, cut) => {
758
- const pending = new PendingCut();
759
- pending.plan(cut, ctx.sessionManager.getBranch().length);
760
- return pending.view(ctx);
797
+ const preview = new PendingCut();
798
+ preview.plan(cut, ctx.sessionManager.getBranch().length);
799
+ return preview.view(ctx);
761
800
  };
762
801
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
763
802
  // get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
@@ -798,8 +837,9 @@ export async function installCompaction(pi, options = {}) {
798
837
  // The cut before a run, decided on `input` while the session is idle; before_agent_start decides only for a run no input started (one a
799
838
  // custom message starts). The cut is pi-tuck's own, planned as at a tool boundary. It is not Pi's: Pi's cut finder keeps the last
800
839
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
801
- // Pi's defaults on a 32k window). Each request of the run carries the cut, and the run's first boundary saves it.
802
- const preflight = (ctx, incomingPart, incomingMessages, observedPrompt, tools, hostSnapshot) => {
840
+ // Pi's defaults on a 32k window). Each request carries the cut until the next boundary saves it. A late steer uses the same path with
841
+ // its existing run owner's entry protected; an incoming prompt that starts a run has no saved owner yet.
842
+ const preflight = (ctx, incomingPart, incomingMessages, observedPrompt, tools, hostSnapshot, protectedId) => {
803
843
  if (standDown(ctx))
804
844
  return;
805
845
  run.cut.clear();
@@ -819,7 +859,7 @@ export async function installCompaction(pi, options = {}) {
819
859
  const hostInput = hostSnapshot ?? hostMessages(ctx), host = conversationTokens(hostInput), measure = measureFor(ctx), before = measure(saved);
820
860
  const incoming = incomingPart + system, mandatory = incoming + host;
821
861
  observeBudget(before + mandatory, ctx);
822
- estimatedTokens = corrected(before + mandatory, ctx);
862
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
823
863
  if (!fits(incoming, limits(ctx).hardLine, ctx))
824
864
  throw new CapacityError("Incoming Pi prompt and response reserve cannot fit the estimated request budget");
825
865
  // A cut removes only conversation. If the mandatory request, host input included, does not fit by itself, no cut can
@@ -835,7 +875,9 @@ export async function installCompaction(pi, options = {}) {
835
875
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
836
876
  // 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
837
877
  // there buys nothing the request needed and costs history the next recall would have found.
838
- const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary, newPrompt: true, reRenderSummary: !opportunistic }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, false);
878
+ // A steer joins the admitted run: keep its starting prompt and the unexposed tool round, just as at a tool boundary.
879
+ const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
880
+ newPrompt: !protectedId, protectedPromptEntryId: protectedId, reRenderSummary: !opportunistic }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, Boolean(protectedId));
839
881
  if (!draft.compaction)
840
882
  return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
841
883
  const candidate = new PendingCut();
@@ -850,7 +892,7 @@ export async function installCompaction(pi, options = {}) {
850
892
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
851
893
  decision = fits(before + mandatory, hardLine, ctx) ? { kind: "none" } :
852
894
  fits(mandatory, hardLine, ctx) ? decide(hardLine, hardLine, false) : { kind: "defer" };
853
- 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, true, false));
895
+ 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)));
854
896
  }
855
897
  if (decision.kind === "defer")
856
898
  return;
@@ -859,7 +901,7 @@ export async function installCompaction(pi, options = {}) {
859
901
  return;
860
902
  if (decision.kind === "fault")
861
903
  throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
862
- const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, false, false, previousSummary, { response, host, mandatory, target: decision.target, margin: room - band });
904
+ 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 });
863
905
  run.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, branchLength);
864
906
  };
865
907
  pi.on("before_agent_start", async (event, ctx) => {
@@ -867,12 +909,12 @@ export async function installCompaction(pi, options = {}) {
867
909
  return;
868
910
  // A decided plan is for the prompt `input` saw. A run that a custom message starts is not that run (another extension handled the
869
911
  // input, so no run started for it): plan afresh.
870
- const prompted = run?.phase === "decided" && event.messageType !== "custom";
871
- if (!prompted && run?.phase !== "failed")
872
- run = createRun("starting");
912
+ const prompted = run && ["decided", "claimed", "expired"].includes(run.phase) && event.messageType !== "custom";
913
+ if (!prompted && !failure())
914
+ beginRun("starting");
873
915
  run ??= createRun("starting");
874
- run.claimed = true;
875
- run.phase = "starting";
916
+ if (!failure() && run.phase !== "starting")
917
+ run.transition("starting", ctx);
876
918
  const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
877
919
  run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
878
920
  try {
@@ -914,7 +956,7 @@ export async function installCompaction(pi, options = {}) {
914
956
  const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), saved, ctx.getSystemPrompt());
915
957
  if (fits(conversationTokens(saved) + system + incoming + host, limits(ctx).room, ctx))
916
958
  return;
917
- preflight(ctx, incoming, [message], ctx.getSystemPrompt(), pi.getActiveTools(), hostInput);
959
+ preflight(ctx, incoming, [message], ctx.getSystemPrompt(), pi.getActiveTools(), hostInput, protectedPrompt(ctx));
918
960
  syncHistoryTools(ctx);
919
961
  }
920
962
  catch (error) {
@@ -1014,7 +1056,7 @@ export async function installCompaction(pi, options = {}) {
1014
1056
  const entryIdOf = (toolCallId) => branch.findLast(entry => entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolCallId === toolCallId)?.id;
1015
1057
  const fresh = new Set(event.toolResults.map(result => result.toolCallId));
1016
1058
  const kept = previews.length ? Math.max(...previews.map(preview => measure(preview.filter(message => !(message.role === "toolResult" && fresh.has(message.toolCallId)))))) : floorKept;
1017
- for (const budget of clipBudgets(clipRoom, factor, mandatory, kept)) {
1059
+ for (const budget of clipBudgets(clipRoom, calibration.factor, mandatory, kept)) {
1018
1060
  const round = clipFor(event.toolResults, entryIdOf, budget);
1019
1061
  if (!round.length)
1020
1062
  continue;
@@ -1033,7 +1075,7 @@ export async function installCompaction(pi, options = {}) {
1033
1075
  tryClips(room, band);
1034
1076
  const before = measure(saved);
1035
1077
  observeBudget(before + mandatory, ctx);
1036
- estimatedTokens = corrected(before + mandatory, ctx);
1078
+ calibration.estimatedTokens = corrected(before + mandatory, ctx);
1037
1079
  const { hardLine } = limits(ctx);
1038
1080
  if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
1039
1081
  if (fits(before + mandatory, hardLine, ctx))
@@ -1064,7 +1106,6 @@ export async function installCompaction(pi, options = {}) {
1064
1106
  if (!run)
1065
1107
  return;
1066
1108
  run.pendingBoundaryReceipts = entries.flatMap(entry => entry.type === "compaction" ? receiptId(entry) ?? [] : []);
1067
- run.pendingBoundaryCommit = run.pendingBoundaryReceipts.length > 0;
1068
1109
  };
1069
1110
  const boundarySaved = (ctx) => {
1070
1111
  const wanted = run?.pendingBoundaryReceipts ?? [];
@@ -1292,7 +1333,7 @@ export async function installCompaction(pi, options = {}) {
1292
1333
  pi.on("agent_before_settle", (event, ctx) => {
1293
1334
  if (standDown(ctx))
1294
1335
  return;
1295
- if (run?.pendingBoundaryCommit) {
1336
+ if (run?.pendingBoundaryReceipts.length) {
1296
1337
  if (event.outcome === "error") {
1297
1338
  try {
1298
1339
  if (!boundarySaved(ctx))
@@ -1303,7 +1344,6 @@ export async function installCompaction(pi, options = {}) {
1303
1344
  }
1304
1345
  }
1305
1346
  if (run) {
1306
- run.pendingBoundaryCommit = false;
1307
1347
  run.pendingBoundaryReceipts = [];
1308
1348
  }
1309
1349
  }
@@ -1325,10 +1365,9 @@ export async function installCompaction(pi, options = {}) {
1325
1365
  return;
1326
1366
  // Reaching the next request boundary proves native commit returned, not durable storage.
1327
1367
  if (run) {
1328
- run.pendingBoundaryCommit = false;
1329
1368
  run.pendingBoundaryReceipts = [];
1330
1369
  }
1331
- pending = undefined;
1370
+ calibration.pending = undefined;
1332
1371
  try {
1333
1372
  if (!active())
1334
1373
  return;
@@ -1351,16 +1390,16 @@ export async function installCompaction(pi, options = {}) {
1351
1390
  assertNativeToolRounds(messages);
1352
1391
  }
1353
1392
  observeBudget(tokens, ctx);
1354
- estimatedTokens = corrected(tokens, ctx);
1393
+ calibration.estimatedTokens = corrected(tokens, ctx);
1355
1394
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1356
1395
  throw new Refusal("Prompt check failed: the request is missing the whole text of the prompt that started this run. Shorten the prompt or choose a model with a larger context window, then retry");
1357
1396
  if (!fits(tokens, hardLine, ctx))
1358
1397
  throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
1359
1398
  // Pi's request estimator and its compaction estimator need not agree. The hard line is
1360
1399
  // necessary; above the room, also require the real request clamp to preserve the floor.
1361
- if (!options.requestReserve && estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1400
+ if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1362
1401
  throw new CapacityError(clampMessage);
1363
- if (estimatedTokens > room)
1402
+ if (calibration.estimatedTokens > room)
1364
1403
  receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1365
1404
  if (recorder.enabled && !recorder.waitingForCut)
1366
1405
  recorder.measureInline(() => {
@@ -1372,7 +1411,7 @@ export async function installCompaction(pi, options = {}) {
1372
1411
  recorder.capture("prepared-request", "public-context-with-system-hook-before-later-transforms-not-wire", { messages: permitted, estimatedInputTokens: tokens }, permitted.length !== event.messages.length);
1373
1412
  });
1374
1413
  if (tokens > 0 && Number.isSafeInteger(tokens))
1375
- pending = {
1414
+ calibration.pending = {
1376
1415
  identity: identityFor(ctx), tokens, messages, snapshot: structuredClone(convertToLlm(messages)),
1377
1416
  };
1378
1417
  if (messages !== event.messages)
@@ -1382,7 +1421,7 @@ export async function installCompaction(pi, options = {}) {
1382
1421
  fail(error, ctx);
1383
1422
  }
1384
1423
  });
1385
- return { close: async () => { semanticRequest++; recorder.stop("caller-close"); await semantic.close(); await Promise.allSettled([...semanticPending]); }, semanticRecall: semantic, setSemanticEnabled, semanticStatus, state: stateFor };
1424
+ return { close: async () => { semanticRequest++; recorder.stop("caller-close"); await semantic.close(); await Promise.allSettled([...semanticPending]); }, semanticRecall: semantic, setSemanticEnabled, semanticStatus, state: stateFor, inspectState: (ctx) => ({ run: run, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending }) };
1386
1425
  }
1387
1426
  function checkedInput(raw) { if (!Check(RecallInput, raw))
1388
1427
  throw new Error("Invalid recall input"); return structuredClone(raw); }