pi-tuck 1.3.1 → 1.3.2

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,21 @@
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.3.2] - 2026-11-15
7
+
8
+ ### Fixed
9
+
10
+ - **pi-tuck no longer refuses a request that Pi itself would send.** When a reply mid-run is too large for any cut to fit pi-tuck's own
11
+ limit (seen live: a reply with about 12,000 tokens of reasoning at a 32,768-token window), pi-tuck now sends its smallest cut whenever Pi's
12
+ own request math fits it in the window, with the reply cap Pi's clamp leaves. Nothing is removed from the request. It refuses only past
13
+ the window, and the refusal now names what does not fit instead of always blaming the starting prompt.
14
+
15
+ ### Changed
16
+
17
+ - **Tests no longer assert wall time in CI.** Timing bounds run in a local bench before each release; per-test timeouts are 120 s.
18
+ Local timing bench for this release (Apple silicon, `npm run timing`): every regression-bench cell within its bound; keyword recall on an
19
+ 85 MB session 671 ms before and 688 ms after growth, against a 3,000 ms budget.
20
+
6
21
  ## [1.3.1] - 2026-11-15
7
22
 
8
23
  ### Changed
package/README.md CHANGED
@@ -62,8 +62,8 @@ pi install npm:pi-tuck
62
62
  Then start a new Pi session. That is all. pi-tuck takes over Pi's compaction, both automatic and `/compact`. You change no setting.
63
63
 
64
64
  - Needs Pi 1.2.0 or later (tested on 1.2.0 and 1.4.0), on macOS, Linux or Windows (Windows since 1.2.0, tested on Windows 10 with Node 24 and Pi 1.5.2). On an older Pi, pi-tuck stays off, Pi's own compaction runs, and pi-tuck says so once.
65
- - Prefer GitHub? `pi install git:github.com/galyavin/pi-tuck@v1.2.0`.
66
- - To pin a version, add it: `pi install npm:pi-tuck@1.2.0`.
65
+ - Prefer GitHub? `pi install git:github.com/galyavin/pi-tuck@v1.3.1`.
66
+ - To pin a version, add it: `pi install npm:pi-tuck@1.3.1`.
67
67
 
68
68
  ## Uninstall
69
69
 
@@ -80,6 +80,7 @@ When context fills up, pi-tuck replaces the older turns with one summary. The su
80
80
  - **The dialogue and your prompts, ranked.** Since 1.0.18, one ranked list decides what a cut carries, across the summary and the kept tail together: the current prompt, whole; the openings of the first prompt and the newest answered prompts, sized to the room; the newest part of the conversation, kept as it is; the file and action lists below; and the rest of the conversation. Dropped turns and tool results are counted with index ranges that `tuck_recall` reads back. Clipped text says how to read it in full.
81
81
  - **The files.** Files the agent read, wrote or edited, newest first (up to 60), each with a pointer to read it back.
82
82
  - **Kept reads** (1.1.0 and later). After the Files list, the summary carries the newest whole read of each file that has no later write or edit, headed `read PATH (as recorded at #N; no write or edit recorded since):`. It keeps at most 4 files, whole outputs only, within 20% of the summary's room and never more than 24,000 characters. Since 1.2.0, a read is also dropped from the summary when a later shell command that is not read-only names the file, or when a git command such as `checkout`, `stash`, `restore` or `reset` ran, and paths are compared after normalising their spelling. When the summary is over its target, these records are dropped first, oldest first. With no such reads the summary is unchanged, and tool outputs are never touched. The header says only that no write or edit was recorded since the read; it does not say the file on disk is unchanged. After a cut, agents often doubted what an earlier read had shown and read the same file again, and this is meant to spare that. It has no effectiveness claim; see Benchmarks.
83
+ - **Kept searches** (1.3.0 and later; 1.3.0 never reached npm, so 1.3.1 is the first release with them). A cut's summary also keeps the latest output of a `grep` or `rg` search, per command and at most 4, beside the kept reads, while nothing the search lists has changed since: a later write or edit of a listed file, or a shell command that is not read-only and names one, drops it. Searches with shell syntax pi-tuck cannot classify are never kept. Kept searches share kept reads' space in the summary, so the summary's size target is unchanged. It has no effectiveness claim; see Benchmarks.
83
84
  - **The action trail.** The agent's other tool calls, such as shell commands, newest first (up to 30). The output is left out. A pointer leads to it.
84
85
 
85
86
  Tool output stays in the session file, not in the summary. Each summary ends with a short instruction to the agent: re-read a file before you edit it, look things up, and treat anything not shown as unknown.
@@ -154,6 +155,7 @@ Each row says what was measured, under which conditions, and where the data is.
154
155
  | Pi's default compaction settings, 32k window, pi-tuck 1.0.10 candidate | Passed as registered: 0 dead tasks and 0 stuck sessions on 30 tasks, on a slow local server (27 of 30 tasks hit the 30-minute wall cap, and 2 had a first request the server never answered). 6 resolved. A counter written later, which counts a task with no token as dead, would count those 2. **The registered counter counts refusals and cannot see a task that began without its prompt**: in 8 of the 30 tasks (4, 8, 9, 10, 13, 14, 17, 21) a cut at the prompt kept no turn, none of the 8 resolved, and 6 ended with an empty patch. So the pass shows no refusal, not that every task began with its prompt. The 1.0.11 candidate on the same test had 7 of 30 such tasks, 1 resolved. Fixed in 1.0.12 | Candidate `a67ec30` of 1.0.10, `mac-studio/main`, window 32,768, output cap 16,384, Pi's default `reserveTokens` 16,384 and `keepRecentTokens` 20,000, one session of chain t06. One mid-run refusal (a round with 9,020 tokens of reasoning against the 16,384-token room). One session per arm, one model. In 12 of the 15 tasks across both arms the model's own first messages show it lacked the prompt; the other 3 are not clear from the records | [`benchmark/RESULTS-DEFAULTS-1010.md`](benchmark/RESULTS-DEFAULTS-1010.md) |
155
156
  | Pi's default compaction settings, 32k window, pi-tuck 1.0.8 | 28 of 30 tasks lost (tasks 3 to 30, each refused at its prompt); 1 resolved. Fails the pre-registered bar of 0 lost tasks | pi-tuck 1.0.8 (`86935e9`), `mac-studio/main`, window 32,768, output cap 16,384, `reserveTokens` 16,384 and `keepRecentTokens` 20,000 (larger than the room), one session of chain t06. One session, one model, one build: it shows that the failure occurs at these settings, not how often. Not comparable with other rows | [`benchmark/RESULTS-DEFAULTS.md`](benchmark/RESULTS-DEFAULTS.md) |
156
157
  | Tasks resolved, 32k window | Pi's built-in compaction 94 of 150; pi-tuck 120 of 150 (+17.3 points, 95% lower bound +10.7); observation masking 117 of 150 (pi-tuck +2.0, lower bound −2.7: no difference shown). Turns per task: 9.4 (built-in), 24.0 (pi-tuck), 11.9 (masking). Tokens per session: 6.10 M, 6.39 M, 7.02 M. Spend per arm for the five sessions: $0.87, $0.55, $0.94 | pi-tuck 1.0.5 (commit `aa30824`, the 1.0.5 code; 1.0.6 and 1.0.7 are not measured). DeepSeek V4.1 Flash pinned to one upstream, window 32,768, reserve 16,384, 5 chains of 30 SWE-bench Verified tasks, paired by task, one-sided bootstrap over tasks. **Limits:** only pi-tuck is held to the 16,384-token room (the built-in sent a request over it in 97 of 150 tasks, masking in 73, so the window is nominal for them). The difference by chain is +10.0, −3.3, +50.0, +16.7 and +13.3 points; leaving out chain t03 it is +9.2. The bootstrap resamples tasks, not chains. The pi-tuck arm ran at a different time from the others. One model, one window. pi-tuck refused to cut mid-run in 5 tasks, where one fresh tool result was larger than the room; they count as unresolved. In the same setup pi-tuck 1.0.3 resolved 72 of 150, with 52 dead tasks (tasks refused at their prompt after an earlier failure). In the pi-tuck arm of this row there was 1 dead task (t03 task 24: refused at its prompt with "Nothing to compact"; the next task ran normally), so this build missed the pre-registered acceptance bar of zero dead tasks by one task (the other part of the bar, no loss against 1.0.3 by more than 3 points, was met) | [`benchmark/RESULTS-32K-ACCEPT.md`](benchmark/RESULTS-32K-ACCEPT.md) |
158
+ | Kept searches (1.3.0, shipped in 1.3.1): live gate against 1.2.0's line | In a 10-task paired live gate, the agent repeated a search after a cut 0.23 times per cut against 0.45, and resolved 5 tasks the other build missed against 2, with no refusals, lost tasks or error stops | NVIDIA Nemotron, room 16,384, 10 paired tasks, one model, one room, one run per arm. The counts are what the ten tasks showed, and no effectiveness claim is made. 1.3.1 is 1.3.0's code: 1.3.0 never reached npm because a timing check in the test suite stopped its publish on the release runner | [`CHANGELOG.md`](CHANGELOG.md) 1.3.0 and 1.3.1 |
157
159
  | pi-tuck 1.2.0: live gate against 1.1.2, and replay against 1.1.3 | Live gate, 10 paired tasks at room 16,384: solved wins minus losses +1 (bar: at least −1), turn-cap stops 3 against 4, doubt moments 6 against 9, 0 lost tasks; kept-read records quoting a partial or stale read 0 against 141. Replay against 1.1.3 (byte-identical to 1.1.2): 29 recordings, cuts 1,975 to 1,869 and clips 16 to 8 with the smaller tool list and the stricter kept reads, 0 lost or dead tasks, 0 faults | Ten tasks on NIM Nemotron, one model, one room, one run per arm: no effectiveness claim is made. The gate found one false refusal after a steering message, fixed in 1.1.3 and pinned by tests built from that run. Strict stress: 322 cells, 0 findings. Tests and CI on macOS and Ubuntu; the full suite also passed on Windows | [`CHANGELOG.md`](CHANGELOG.md) 1.2.0 |
158
160
  | Kept reads (1.1.0): 5-task check against 1.0.31, and replay against 1.0.33 | No breakage in 5 of 5 tasks, and all 5 solved on both builds. Re-checks after a doubt 22 against 45; doubt moments 9 against 24; cuts 22 against 26; turns 305 against 384. One heavy task went worse: 90 turns against 59, 9 cuts against 4, 3 doubts against 1. Replay against 1.0.33: 13,946 requests, 0 lost or dead tasks, clips 17 to 16, cuts 1,946 to 1,971; in every recording that differs, the first difference is the first summary carrying a kept read, and 11 of 29 never differ | Five tasks, before the Tier 1. This is not an effectiveness result and no effectiveness claim is made for kept reads. The Tier 1 against 1.0.33 is still running; if it fails, npm and installs go back to 1.0.33. Strict stress: 0 findings in 313 cells on Pi 1.2.0 and the newest Pi | [`CHANGELOG.md`](CHANGELOG.md) 1.1.0 |
159
161
  | pi-tuck 1.0.18 against the recorded 1.0.16 arm, 81,920 window | Registered bar (Tier 1) met: both arms resolved the same 56 of 60 tasks (+0.0 points, one-sided 95% lower bound +0.0, against a bar of above −10); 0 lost tasks: dead tasks, mid-run refusals and dropped prompts are 0 in both arms, and the audit listed one candidate task (t06 task 21), which, with the two other candidate tasks that had a cut at a prompt (t06 task 8, t07 task 24), was read by hand and works on its own task. Readouts: turns per task 22.27 against 29.35, cuts 57 against 61, total tokens 40.3 M against 62.1 M. Against the recorded 1.0.13 arm of the adaptive gate, a different pair of runs a day apart, 1.0.18 is at 22.27 turns per task against 20.22 and 40.3 M tokens against 37.4 M | Pre-registered gate. pi-tuck 1.0.18 (`2d1f830`, tag `v1.0.18`), run from the unpacked npm tarball; its `src/` is byte-identical to `1ea1e1e`, the commit replay and the stress test measured, ran alone on chains t06 and t07 (60 tasks) against the recorded 1.0.16 arm; the arms did not run side by side, the base earlier the same day, so seconds are not compared. One model, one window, one run per arm. The resolved result is a bound, not a gain. The turn, cut and token readouts are reported, not claimed | [`benchmark/RESULTS-V1018.md`](benchmark/RESULTS-V1018.md) |
@@ -1 +1 @@
1
- export declare const BUILD_ID = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
1
+ export declare const BUILD_ID = "b6a612ac60abaf5564c6020053627662851d7c7162337cf023ed686c1d598466";
@@ -1 +1 @@
1
- export const BUILD_ID = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
1
+ export const BUILD_ID = "b6a612ac60abaf5564c6020053627662851d7c7162337cf023ed686c1d598466";
@@ -440,8 +440,9 @@ export async function installCompaction(pi, options = {}) {
440
440
  const requestClamp = (messages, ctx) => {
441
441
  const context = normalizeContext({ messages: convertToLlm(messages) });
442
442
  const cap = piClamp?.({ ...ctx.model, contextWindow: contextWindow(ctx) }, context, ctx.model.maxTokens);
443
- return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor,
444
- estimate: piMath ? piMath.estimateContextTokens(context).tokens : 0 };
443
+ const estimate = piMath ? piMath.estimateContextTokens(context).tokens : 0;
444
+ return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor, estimate,
445
+ fitsWindow: cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx) };
445
446
  };
446
447
  const projectedRequest = (messages, ctx, host, incoming, prompt, tools, cut) => {
447
448
  const enabled = cut || historyToolsEnabled(ctx), shapes = toolShapes(historyToolNames(pi, tools, enabled));
@@ -485,13 +486,14 @@ export async function installCompaction(pi, options = {}) {
485
486
  const isNoWork = (message) => ["Already compacted", "Nothing to compact (session too small)"].includes(message?.replace(/^Compaction failed: /, "") ?? "");
486
487
  // A missing model is configuration, not capacity.
487
488
  const missingModel = () => new Error("No context model for the request budget");
488
- const receipt = (kind, reason, ctx) => {
489
+ const receipt = (kind, reason, ctx, check) => {
489
490
  let room = null, hardLine = null;
490
491
  try {
491
492
  ({ room, hardLine } = limits(ctx));
492
493
  }
493
494
  catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
494
- pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID });
495
+ pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID,
496
+ ...(check ? { piEstimateTokens: check.estimate, piCap: check.cap } : {}) });
495
497
  };
496
498
  const fail = (error, ctx) => {
497
499
  recorder.stop("native-attempt-failed");
@@ -689,9 +691,9 @@ export async function installCompaction(pi, options = {}) {
689
691
  };
690
692
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
691
693
  // get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
692
- const deepestDecision = (ctx, newPrompt, retain) => {
694
+ const deepestDecision = (ctx, newPrompt, retain, clipFresh = true) => {
693
695
  const saved = ctx.sessionManager.buildSessionProjection().messages;
694
- if (!newPrompt) {
696
+ if (!newPrompt && clipFresh) {
695
697
  const at = saved.findLastIndex(message => message.role === "assistant" && !isDiscardedResponse(message));
696
698
  const response = saved[at];
697
699
  const calls = new Set(response?.role === "assistant" ? response.content.flatMap(block => block.type === "toolCall" ? [block.id] : []) : []);
@@ -723,6 +725,22 @@ export async function installCompaction(pi, options = {}) {
723
725
  return { kind: "cut", target: "room", plan: { draft: true, after: measureFor(ctx)(messages),
724
726
  compaction: draft.compaction, reserve: 0, messages } };
725
727
  };
728
+ // Refusal path only: the hard line remains the cut target, but the compiler's floor may use Pi's remaining reply cap.
729
+ // Read both the estimate and saturated clamp from the running Pi: a positive (minimum) cap alone does not prove window fit.
730
+ // This does not relax thinking-only length recovery: retryLength still requires the observed reply floor before continuing,
731
+ // and its pending retry cannot use this escape. No fresh content is clipped or edited by this admission attempt.
732
+ const nativeFloorDecision = (ctx, newPrompt, retain, project) => {
733
+ if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.thinkingRetryPending)
734
+ return;
735
+ const candidate = deepestDecision(ctx, newPrompt, retain, false);
736
+ if (candidate.kind !== "cut")
737
+ return;
738
+ const messages = project(candidate);
739
+ if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
740
+ return;
741
+ if (requestClamp(messages, ctx).fitsWindow)
742
+ return candidate;
743
+ };
726
744
  // 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
727
745
  // 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
728
746
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
@@ -732,6 +750,7 @@ export async function installCompaction(pi, options = {}) {
732
750
  if (standDown(ctx))
733
751
  return;
734
752
  run.cut.clear();
753
+ run.nativeFloorPending = false;
735
754
  const branchLength = ctx.sessionManager.getBranch().length;
736
755
  if (!active())
737
756
  return;
@@ -788,6 +807,13 @@ export async function installCompaction(pi, options = {}) {
788
807
  // An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
789
808
  if (decision.kind === "none")
790
809
  return;
810
+ if (decision.kind === "fault" && decision.capacity) {
811
+ const floor = nativeFloorDecision(ctx, !protectedId, Boolean(protectedId), candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, true));
812
+ if (floor) {
813
+ decision = floor;
814
+ run.nativeFloorPending = true;
815
+ }
816
+ }
791
817
  if (decision.kind === "fault")
792
818
  throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
793
819
  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 });
@@ -896,12 +922,10 @@ export async function installCompaction(pi, options = {}) {
896
922
  // request besides the fresh results. Reset per decision, so a retry sizes itself against the cut it is retrying, not an earlier attempt's.
897
923
  let previews = [];
898
924
  let floorKept;
899
- let wholePromptFloor;
900
925
  const protectedId = reason === "tool-loop" ? protectedPrompt(ctx) : undefined;
901
926
  const decide = (targetRoom = room, targetBand = band, required = false) => {
902
927
  previews = [];
903
928
  floorKept = undefined;
904
- wholePromptFloor = undefined;
905
929
  const before = measure(saved);
906
930
  const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan", opportunistic: false } :
907
931
  gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
@@ -914,8 +938,6 @@ export async function installCompaction(pi, options = {}) {
914
938
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
915
939
  const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
916
940
  if (!draft.compaction) {
917
- if (protectedId && draft.floorMessages)
918
- wholePromptFloor = measure(draft.floorMessages) + mandatory;
919
941
  // The planner's own floor, so a clip's second budget is measured against what the smallest cut really keeps.
920
942
  if (draft.floorMessages && event.toolResults) {
921
943
  const fresh = new Set(event.toolResults.map(result => result.toolCallId));
@@ -981,9 +1003,15 @@ export async function installCompaction(pi, options = {}) {
981
1003
  }, () => deepestDecision(ctx, false, true));
982
1004
  }
983
1005
  if (decision.kind === "fault" && reason === "tool-loop") {
984
- if (wholePromptFloor !== undefined && !fits(wholePromptFloor, hardLine, ctx))
1006
+ if (decision.capacity)
1007
+ decision = nativeFloorDecision(ctx, false, true, candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true)) ?? decision;
1008
+ }
1009
+ if (decision.kind === "fault" && reason === "tool-loop") {
1010
+ if (protectedId && run?.prompt && !fits(incomingTokens(run.prompt.text(ctx.sessionManager.getBranch()), []), room, ctx))
985
1011
  throw promptRefusal();
986
- throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
1012
+ if (decision.capacity)
1013
+ throw new CapacityError("The fresh tool round and required context exceed the estimated request budget");
1014
+ throw new Refusal(decision.message);
987
1015
  }
988
1016
  if (decision.kind !== "cut")
989
1017
  return;
@@ -1156,16 +1184,24 @@ export async function installCompaction(pi, options = {}) {
1156
1184
  };
1157
1185
  if (!accepts(decision))
1158
1186
  decision = deepestDecision(ctx, false, true);
1187
+ let native = false;
1159
1188
  if (decision.kind !== "cut" || !accepts(decision)) {
1160
1189
  clips().clear();
1161
1190
  for (const [id, clip] of previousClips)
1162
1191
  clips().set(id, clip);
1163
- return messages;
1192
+ const floor = nativeFloorDecision(ctx, false, true, project);
1193
+ if (!floor)
1194
+ return { messages };
1195
+ decision = floor;
1196
+ native = true;
1164
1197
  }
1198
+ if (decision.kind !== "cut")
1199
+ return { messages };
1165
1200
  const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary, { response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
1166
1201
  run.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx.sessionManager.getBranch().length);
1202
+ run.nativeFloorPending = native;
1167
1203
  syncHistoryTools(ctx);
1168
- return historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)), toolShapes(pi.getActiveTools()), true);
1204
+ return { messages: historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)), toolShapes(pi.getActiveTools()), true), native };
1169
1205
  };
1170
1206
  pi.on("context", (event, ctx) => {
1171
1207
  try {
@@ -1263,8 +1299,13 @@ export async function installCompaction(pi, options = {}) {
1263
1299
  let system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1264
1300
  let tokens = system + conversationTokens(messages);
1265
1301
  const { room, hardLine } = limits(ctx);
1266
- if (!fits(tokens, hardLine, ctx) && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1267
- messages = guardCut(messages, tokens, system, ctx);
1302
+ let native = false;
1303
+ const wouldRefuse = !fits(tokens, hardLine, ctx) || !options.requestReserve && corrected(tokens, ctx) > room &&
1304
+ piClamp && !requestClamp(messages, ctx).leavesFloor;
1305
+ if (wouldRefuse && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1306
+ const cut = guardCut(messages, tokens, system, ctx);
1307
+ messages = cut.messages;
1308
+ native = Boolean(cut.native);
1268
1309
  system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1269
1310
  tokens = system + conversationTokens(messages);
1270
1311
  assertNativeToolRounds(messages);
@@ -1273,13 +1314,18 @@ export async function installCompaction(pi, options = {}) {
1273
1314
  calibration.estimatedTokens = corrected(tokens, ctx);
1274
1315
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1275
1316
  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");
1276
- if (!fits(tokens, hardLine, ctx))
1317
+ // A floor already planned at input is pending here; recheck the exact complete request with Pi's own math.
1318
+ native ||= Boolean(wouldRefuse && view(ctx).pending && run?.nativeFloorPending);
1319
+ native &&= requestClamp(messages, ctx).fitsWindow;
1320
+ if (!native && !fits(tokens, hardLine, ctx))
1277
1321
  throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
1278
- // Pi's request estimator and its compaction estimator need not agree. The hard line is
1279
- // necessary; above the room, also require the real request clamp to preserve the floor.
1280
- if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1322
+ // Ordinary admission above the room also asks Pi's real clamp to preserve the reply floor;
1323
+ // only the refusal-path compiler floor may instead use native window admission.
1324
+ if (!native && !options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1281
1325
  throw new CapacityError(clampMessage);
1282
- if (calibration.estimatedTokens > room)
1326
+ if (native)
1327
+ receipt("native-floor", "Planner floor fits Pi's native request limit after ordinary admission failed", ctx, requestClamp(messages, ctx));
1328
+ else if (calibration.estimatedTokens > room)
1283
1329
  receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1284
1330
  if (recorder.enabled && !recorder.waitingForCut)
1285
1331
  recorder.measureInline(() => {
@@ -1,6 +1,6 @@
1
1
  import { type RecallPolicy } from './recall.js';
2
2
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
3
- export declare const DIAGNOSTIC_BUILD = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
3
+ export declare const DIAGNOSTIC_BUILD = "b6a612ac60abaf5564c6020053627662851d7c7162337cf023ed686c1d598466";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
package/dist/src/run.d.ts CHANGED
@@ -52,6 +52,8 @@ export declare class Run {
52
52
  clips: Map<string, Clip>;
53
53
  pendingBoundaryReceipts: string[];
54
54
  thinkingRetryPending: boolean;
55
+ /** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
56
+ nativeFloorPending: boolean;
55
57
  refusalReceipted: boolean;
56
58
  clear(): void;
57
59
  }
package/dist/src/run.js CHANGED
@@ -129,6 +129,8 @@ export class Run {
129
129
  clips = new Map();
130
130
  pendingBoundaryReceipts = [];
131
131
  thinkingRetryPending = false;
132
+ /** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
133
+ nativeFloorPending = false;
132
134
  refusalReceipted = false;
133
135
  clear() {
134
136
  this.prompt = undefined;
@@ -136,6 +138,7 @@ export class Run {
136
138
  this.clips.clear();
137
139
  this.pendingBoundaryReceipts = [];
138
140
  this.thinkingRetryPending = false;
141
+ this.nativeFloorPending = false;
139
142
  this.refusalReceipted = false;
140
143
  this.expiredPlan = false;
141
144
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.3.1",
3
+ "version": "1.3.2",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -52,7 +52,8 @@
52
52
  "check": "tsc -p tsconfig.tests.json",
53
53
  "test": "vitest run --config vitest.config.ts",
54
54
  "build": "node scripts/build.mjs",
55
- "prepack": "npm run build"
55
+ "prepack": "npm run build",
56
+ "timing": "PI_TUCK_TIMING=1 STRESS=1 vitest run --config vitest.config.ts --maxWorkers=1 test/regression-bench.test.ts test/stress/large-session.test.ts"
56
57
  },
57
58
  "peerDependencies": {
58
59
  "@earendil-works/pi-ai": ">=1.2.0",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
1
+ export const BUILD_ID = "b6a612ac60abaf5564c6020053627662851d7c7162337cf023ed686c1d598466";
package/src/compaction.ts CHANGED
@@ -411,8 +411,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
411
411
  const requestClamp = (messages: Messages, ctx: ExtensionContext) => {
412
412
  const context = normalizeContext({ messages: convertToLlm(messages) });
413
413
  const cap = piClamp?.({ ...ctx.model!, contextWindow: contextWindow(ctx) }, context, ctx.model!.maxTokens);
414
- return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor,
415
- estimate: piMath ? piMath.estimateContextTokens(context).tokens : 0 };
414
+ const estimate = piMath ? piMath.estimateContextTokens(context).tokens : 0;
415
+ return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor, estimate,
416
+ fitsWindow: cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx) };
416
417
  };
417
418
  const projectedRequest = (messages: Messages, ctx: ExtensionContext, host: Messages, incoming: Messages, prompt: string, tools: readonly string[], cut: boolean) => {
418
419
  const enabled = cut || historyToolsEnabled(ctx), shapes = toolShapes(historyToolNames(pi, tools, enabled));
@@ -450,10 +451,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
450
451
  // A missing model is configuration, not capacity.
451
452
  const missingModel = () => new Error("No context model for the request budget");
452
453
  type CutPlan = { compaction: NonNullable<ReturnType<typeof tuckDraft>["compaction"]>; reserve: number; messages: Messages };
453
- const receipt = (kind: "refusal" | "above-room", reason: string, ctx: ExtensionContext) => {
454
+ const receipt = (kind: "refusal" | "above-room" | "native-floor", reason: string, ctx: ExtensionContext, check?: ReturnType<typeof requestClamp>) => {
454
455
  let room: number | null = null, hardLine: number | null = null;
455
456
  try { ({ room, hardLine } = limits(ctx)); } catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
456
- pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID });
457
+ pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID,
458
+ ...(check ? { piEstimateTokens: check.estimate, piCap: check.cap } : {}) });
457
459
  };
458
460
  const fail = (error: unknown, ctx: ExtensionContext) => {
459
461
  recorder.stop("native-attempt-failed");
@@ -618,9 +620,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
618
620
  };
619
621
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
620
622
  // get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
621
- const deepestDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean): Decision<CutPlan> => {
623
+ const deepestDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean, clipFresh = true): Decision<CutPlan> => {
622
624
  const saved = ctx.sessionManager.buildSessionProjection().messages;
623
- if (!newPrompt) {
625
+ if (!newPrompt && clipFresh) {
624
626
  const at = saved.findLastIndex(message => message.role === "assistant" && !isDiscardedResponse(message));
625
627
  const response = saved[at];
626
628
  const calls = new Set(response?.role === "assistant" ? response.content.flatMap(block => block.type === "toolCall" ? [block.id] : []) : []);
@@ -646,6 +648,19 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
646
648
  return { kind: "cut", target: "room", plan: { draft: true, after: measureFor(ctx)(messages),
647
649
  compaction: draft.compaction, reserve: 0, messages } };
648
650
  };
651
+ // Refusal path only: the hard line remains the cut target, but the compiler's floor may use Pi's remaining reply cap.
652
+ // Read both the estimate and saturated clamp from the running Pi: a positive (minimum) cap alone does not prove window fit.
653
+ // This does not relax thinking-only length recovery: retryLength still requires the observed reply floor before continuing,
654
+ // and its pending retry cannot use this escape. No fresh content is clipped or edited by this admission attempt.
655
+ const nativeFloorDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean,
656
+ project: (candidate: Decision<CutPlan>) => Messages): Extract<Decision<CutPlan>, { kind: "cut" }> | undefined => {
657
+ if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.thinkingRetryPending) return;
658
+ const candidate = deepestDecision(ctx, newPrompt, retain, false);
659
+ if (candidate.kind !== "cut") return;
660
+ const messages = project(candidate);
661
+ if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role)) return;
662
+ if (requestClamp(messages, ctx).fitsWindow) return candidate;
663
+ };
649
664
  // 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
650
665
  // 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
651
666
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
@@ -654,6 +669,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
654
669
  const preflight = (ctx: ExtensionContext, incomingPart: number, incomingMessages: Messages, observedPrompt: string, tools: readonly string[], hostSnapshot?: Messages, protectedId?: string) => {
655
670
  if (standDown(ctx)) return;
656
671
  run!.cut.clear();
672
+ run!.nativeFloorPending = false;
657
673
  const branchLength = ctx.sessionManager.getBranch().length;
658
674
  if (!active()) return;
659
675
  access();
@@ -707,6 +723,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
707
723
  if (decision.kind === "defer") return;
708
724
  // An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
709
725
  if (decision.kind === "none") return;
726
+ if (decision.kind === "fault" && decision.capacity) {
727
+ const floor = nativeFloorDecision(ctx, !protectedId, Boolean(protectedId),
728
+ candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, true));
729
+ if (floor) { decision = floor; run!.nativeFloorPending = true; }
730
+ }
710
731
  if (decision.kind === "fault") throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
711
732
  const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, Boolean(protectedId), false, previousSummary,
712
733
  { response, host, mandatory, target: decision.target, margin: room - band });
@@ -799,12 +820,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
799
820
  // request besides the fresh results. Reset per decision, so a retry sizes itself against the cut it is retrying, not an earlier attempt's.
800
821
  let previews: Messages[] = [];
801
822
  let floorKept: number | undefined;
802
- let wholePromptFloor: number | undefined;
803
823
  const protectedId = reason === "tool-loop" ? protectedPrompt(ctx) : undefined;
804
824
  const decide = (targetRoom = room, targetBand = band, required = false) => {
805
825
  previews = [];
806
826
  floorKept = undefined;
807
- wholePromptFloor = undefined;
808
827
  const before = measure(saved);
809
828
  const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan" as const, opportunistic: false } :
810
829
  gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
@@ -816,7 +835,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
816
835
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
817
836
  const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
818
837
  if (!draft.compaction) {
819
- if (protectedId && draft.floorMessages) wholePromptFloor = measure(draft.floorMessages) + mandatory;
820
838
  // The planner's own floor, so a clip's second budget is measured against what the smallest cut really keeps.
821
839
  if (draft.floorMessages && event.toolResults) {
822
840
  const fresh = new Set(event.toolResults.map(result => result.toolCallId));
@@ -875,8 +893,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
875
893
  }, () => deepestDecision(ctx, false, true));
876
894
  }
877
895
  if (decision.kind === "fault" && reason === "tool-loop") {
878
- if (wholePromptFloor !== undefined && !fits(wholePromptFloor, hardLine, ctx)) throw promptRefusal();
879
- throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
896
+ if (decision.capacity) decision = nativeFloorDecision(ctx, false, true,
897
+ candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput,
898
+ event.context.pendingMessages as Messages, ctx.getSystemPrompt(), pi.getActiveTools(), true)) ?? decision;
899
+ }
900
+ if (decision.kind === "fault" && reason === "tool-loop") {
901
+ if (protectedId && run?.prompt && !fits(incomingTokens(run.prompt.text(ctx.sessionManager.getBranch()), []), room, ctx)) throw promptRefusal();
902
+ if (decision.capacity) throw new CapacityError("The fresh tool round and required context exceed the estimated request budget");
903
+ throw new Refusal(decision.message);
880
904
  }
881
905
  if (decision.kind !== "cut") return;
882
906
  const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, reason, before, true, false, previousSummary,
@@ -999,7 +1023,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
999
1023
  };
1000
1024
  // A late cut prices everything outside the saved conversation from this request itself. Its pending view is carried now and saved by
1001
1025
  // atBoundary, just like a prompt cut; the existing final checks still decide admission on the rebuilt request.
1002
- const guardCut = (messages: Messages, tokens: number, system: number, ctx: ExtensionContext): Messages => {
1026
+ const guardCut = (messages: Messages, tokens: number, system: number, ctx: ExtensionContext): { messages: Messages; native?: boolean } => {
1003
1027
  const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
1004
1028
  const before = conversationTokens(source), mandatory = tokens - before;
1005
1029
  const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room, system);
@@ -1036,16 +1060,22 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1036
1060
  return fits(reduced, hardLine, ctx) && (Boolean(options.requestReserve) || corrected(reduced, ctx) <= room || requestClamp(request, ctx).leavesFloor);
1037
1061
  };
1038
1062
  if (!accepts(decision)) decision = deepestDecision(ctx, false, true);
1063
+ let native = false;
1039
1064
  if (decision.kind !== "cut" || !accepts(decision)) {
1040
1065
  clips().clear(); for (const [id, clip] of previousClips) clips().set(id, clip);
1041
- return messages;
1066
+ const floor = nativeFloorDecision(ctx, false, true, project);
1067
+ if (!floor) return { messages };
1068
+ decision = floor;
1069
+ native = true;
1042
1070
  }
1071
+ if (decision.kind !== "cut") return { messages };
1043
1072
  const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary,
1044
1073
  { response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
1045
1074
  run!.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx.sessionManager.getBranch().length);
1075
+ run!.nativeFloorPending = native;
1046
1076
  syncHistoryTools(ctx);
1047
- return historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)),
1048
- toolShapes(pi.getActiveTools()), true);
1077
+ return { messages: historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)),
1078
+ toolShapes(pi.getActiveTools()), true), native };
1049
1079
  };
1050
1080
  pi.on("context", (event, ctx) => {
1051
1081
  try {
@@ -1108,8 +1138,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1108
1138
  let system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1109
1139
  let tokens = system + conversationTokens(messages);
1110
1140
  const { room, hardLine } = limits(ctx);
1111
- if (!fits(tokens, hardLine, ctx) && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1112
- messages = guardCut(messages, tokens, system, ctx);
1141
+ let native = false;
1142
+ const wouldRefuse = !fits(tokens, hardLine, ctx) || !options.requestReserve && corrected(tokens, ctx) > room &&
1143
+ piClamp && !requestClamp(messages, ctx).leavesFloor;
1144
+ if (wouldRefuse && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1145
+ const cut = guardCut(messages, tokens, system, ctx);
1146
+ messages = cut.messages;
1147
+ native = Boolean(cut.native);
1113
1148
  system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1114
1149
  tokens = system + conversationTokens(messages);
1115
1150
  assertNativeToolRounds(messages);
@@ -1118,13 +1153,17 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1118
1153
  calibration.estimatedTokens = corrected(tokens, ctx);
1119
1154
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1120
1155
  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");
1121
- if (!fits(tokens, hardLine, ctx))
1156
+ // A floor already planned at input is pending here; recheck the exact complete request with Pi's own math.
1157
+ native ||= Boolean(wouldRefuse && view(ctx).pending && run?.nativeFloorPending);
1158
+ native &&= requestClamp(messages, ctx).fitsWindow;
1159
+ if (!native && !fits(tokens, hardLine, ctx))
1122
1160
  throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
1123
- // Pi's request estimator and its compaction estimator need not agree. The hard line is
1124
- // necessary; above the room, also require the real request clamp to preserve the floor.
1125
- if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1161
+ // Ordinary admission above the room also asks Pi's real clamp to preserve the reply floor;
1162
+ // only the refusal-path compiler floor may instead use native window admission.
1163
+ if (!native && !options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1126
1164
  throw new CapacityError(clampMessage);
1127
- if (calibration.estimatedTokens > room) receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1165
+ if (native) receipt("native-floor", "Planner floor fits Pi's native request limit after ordinary admission failed", ctx, requestClamp(messages, ctx));
1166
+ else if (calibration.estimatedTokens > room) receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1128
1167
  if (recorder.enabled && !recorder.waitingForCut) recorder.measureInline(() => {
1129
1168
  recorder.request();
1130
1169
  // No system prompt or hidden assistant blocks; no provider payload/headers.
package/src/run.ts CHANGED
@@ -117,9 +117,11 @@ export class Run {
117
117
  clips = new Map<string, Clip>();
118
118
  pendingBoundaryReceipts: string[] = [];
119
119
  thinkingRetryPending = false;
120
+ /** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
121
+ nativeFloorPending = false;
120
122
  refusalReceipted = false;
121
123
  clear() {
122
124
  this.prompt = undefined; this.cut.clear(); this.clips.clear(); this.pendingBoundaryReceipts = [];
123
- this.thinkingRetryPending = false; this.refusalReceipted = false; this.expiredPlan = false;
125
+ this.thinkingRetryPending = false; this.nativeFloorPending = false; this.refusalReceipted = false; this.expiredPlan = false;
124
126
  }
125
127
  }