pi-tuck 1.11.0 → 1.11.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,23 @@
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.11.2]
7
+
8
+ ### Fixed
9
+
10
+ - Kept prompt outputs: when a user prompt names a command (for example "Run: telex read NAME") and the agent runs it as
11
+ `cd DIR && telex read NAME`, the output is now carried whole in the summary, as it already was without the `cd` prefix.
12
+
13
+ ## [1.11.1]
14
+
15
+ ### Fixed
16
+
17
+ - Reply room under Pi 1.7: Pi 1.7 keeps a safety margin of 15% of the input (at least 4,096 tokens) while that still leaves 32,768 output
18
+ tokens. pi-tuck assumed a fixed 4,096, so at long context with a model allowing more than 32,768 output tokens it planned more reply
19
+ room than Pi gives (for example 128,000 instead of 80,000 at 800,000 input in a 1M window). pi-tuck now asks Pi's own limit, at the
20
+ input size in question, how much input still leaves a given reply, wherever it planned with the fixed margin. Under earlier Pi
21
+ versions, and for any model allowing at most 32,768 output tokens, nothing changes.
22
+
6
23
  ## [1.11.0]
7
24
 
8
25
  ### Changed
package/README.md CHANGED
@@ -12,7 +12,7 @@ pi install npm:pi-tuck
12
12
 
13
13
  Start a new Pi process after installing or updating. pi-tuck handles automatic compaction and `/compact` by default. Run `/tuck` to see the loaded version, cut history, and active cut policy.
14
14
 
15
- This README describes pi-tuck 1.11.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.11.0` or `pi install git:github.com/galyavin/pi-tuck@v1.11.0`. To uninstall, run `pi remove` with the source you installed.
15
+ This README describes pi-tuck 1.11.2. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.11.2` or `pi install git:github.com/galyavin/pi-tuck@v1.11.2`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
@@ -38,6 +38,14 @@ Read the original by the hit's `entryId`, or use `{"index": 212}` to follow a `#
38
38
 
39
39
  Pi-tuck needs a supported Pi version and a nonvirtual model with a valid context window. Setting `"compaction": { "enabled": false }` in Pi's settings disables automatic compaction and makes pi-tuck stand down, including for `/compact` and recall. `/tuck` reports why a loaded compactor is standing down. Capacity notices go to stderr in headless runs.
40
40
 
41
+ ## Long runs
42
+
43
+ Three Pi agents worked for about two days on a hard research codebase, on one local model with a 272k window. That came to about 2,500 model requests and over 300M tokens of context.
44
+
45
+ Each time an agent filled its window, pi-tuck cut it back to about 40k tokens, with no model call. That happened about ten times, and every agent kept working after every cut.
46
+
47
+ The run showed us a few rough edges, and later releases fixed them. We keep watching long runs like this one.
48
+
41
49
  ## Footer
42
50
 
43
51
  In Pi's terminal UI, pi-tuck replaces Pi's footer. Under the folder and git branch, the bar fills toward pi-tuck's trim point, the number `/tuck` reports: a full bar means pi-tuck trims. Next to it are the context size and the trim point, the trim count once pi-tuck has trimmed, the cost when it is above $0, and the model with its thinking level. Other extensions' statuses stay below. The bar turns yellow at 85% of the trim point. A narrow terminal shows only the bar and the two sizes. Right after a trim, before the next reply, the size is the trim's own estimate, shown with `~`. When pi-tuck is not trimming for the model, the line shows the context against the window. `/tuck` shows the trim history.
@@ -1 +1 @@
1
- export declare const BUILD_ID = "e11927281c0dc22058687647b4d0658d8a588470b4fae558169cc0532bb02d4e";
1
+ export declare const BUILD_ID = "af3354d4b75532f8a65d30e805ce634249fd18de42eb8988de21b51103e9acc2";
@@ -1 +1 @@
1
- export const BUILD_ID = "e11927281c0dc22058687647b4d0658d8a588470b4fae558169cc0532bb02d4e";
1
+ export const BUILD_ID = "af3354d4b75532f8a65d30e805ce634249fd18de42eb8988de21b51103e9acc2";
@@ -1,6 +1,6 @@
1
1
  import { textOf } from "./tuck/core/content.js";
2
2
  import { PendingCut, StartingPrompt, Run } from "./run.js";
3
- import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
3
+ import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, piInputFor, loadPiRequestMath } from "./request-capacity.js";
4
4
  import { BUILD_ID } from "./build-id.js";
5
5
  import { lowestEffort, pendingCheck, serverEfforts } from "./config-check.js";
6
6
  import { IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry } from "./diagnostics.js";
@@ -209,6 +209,18 @@ export async function installCompaction(pi, options = {}) {
209
209
  const piMath = await loadPiRequestMath();
210
210
  const piMargin = options.requestReserve ? 0 : await piContextSafetyMargin(piMath);
211
211
  const piClamp = piMath?.clampMaxTokensToContext;
212
+ // The largest input Pi still gives `reply` tokens (Pi 1.7's margin grows with the input). A host reserve keeps the fixed arithmetic.
213
+ const inputCache = new Map();
214
+ const inputFor = (ctx, reply) => {
215
+ const window = contextWindow(ctx), key = `${window}:${reply}`;
216
+ let input = inputCache.get(key);
217
+ if (input === undefined) {
218
+ if (inputCache.size > 256)
219
+ inputCache.clear();
220
+ inputCache.set(key, input = piInputFor(options.requestReserve ? undefined : piMath, window, reply, piMargin));
221
+ }
222
+ return input;
223
+ };
212
224
  const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
213
225
  if (!validCutAt(cutAt))
214
226
  throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
@@ -453,13 +465,13 @@ export async function installCompaction(pi, options = {}) {
453
465
  const limits = (ctx) => {
454
466
  const reserve = responseReserve(ctx);
455
467
  const floor = options.requestReserve || !ctx.model ? reserve : requestReplyFloor(ctx.sessionManager.getBranch(), reserve, ctx.model, floorMinimum);
456
- // After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math: Pi gives a request
457
- // min(maxTokens, window - input - margin), so the room is window - margin - raised. Admission (floor, hard line) stays as without a
468
+ // After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math: the room is the largest input
469
+ // Pi still gives the raised reply (window - margin - raised under a fixed margin). Admission (floor, hard line) stays as without a
458
470
  // stop: the raise asks cuts for more reply room, it never refuses a request Pi would send. No stop: exactly the reserve, as before.
459
471
  const raised = options.requestReserve || !ctx.model ? undefined : stoppedReplyRoom(ctx.sessionManager.getBranch(), ctx.model, contextWindow(ctx), piMargin);
460
- const response = raised === undefined ? reserve : Math.max(reserve, raised + piMargin), room = inputRoom(response, ctx);
461
- const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
462
- return { response, room, hardLine, replyFloor: floor };
472
+ const response = raised === undefined ? reserve : Math.max(reserve, contextWindow(ctx) - inputFor(ctx, raised)), room = inputRoom(response, ctx);
473
+ const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve, inputFor(ctx, floor)), calibration.lastCeiling ?? Infinity);
474
+ return { response, room, hardLine, replyFloor: floor, want: Math.max(reserve - piMargin, raised ?? -Infinity) };
463
475
  };
464
476
  const preservePrefix = (ctx) => ctx.model !== undefined &&
465
477
  options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
@@ -467,7 +479,7 @@ export async function installCompaction(pi, options = {}) {
467
479
  // Thrash-adaptive trigger. Only in a branch whose cuts drop files the agent then re-reads unchanged (thrash.ts): there the trigger moves
468
480
  // to native's line, max(window - reserve, keepRecentTokens + the oldest turn), mirrored as max(band, keepRecentTokens) (parked 4302e2c).
469
481
  // Its cap keeps the reply room a cut aims for (the reply floor, at least CUT_REPLY_FLOOR) and, after a length stop, 1.7.0's raised reply
470
- // room: window - Pi's margin - the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
482
+ // room: the largest input Pi still gives the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
471
483
  // sensitive model, or a host reserve; in a branch without thrash it returns nothing and the trigger is the band, as in 1.7.0.
472
484
  const triggerLine = (ctx, room) => {
473
485
  if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx))
@@ -477,7 +489,7 @@ export async function installCompaction(pi, options = {}) {
477
489
  return undefined;
478
490
  const { hardLine, replyFloor } = limits(ctx), raised = stoppedReplyRoom(branch, ctx.model, contextWindow(ctx), piMargin) ?? 0;
479
491
  const reply = Math.max(replyFloor, CUT_REPLY_FLOOR, raised);
480
- const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
492
+ const cap = Math.min(hardLine, inputFor(ctx, reply)) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
481
493
  return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
482
494
  };
483
495
  // Lean line (lean.ts): once the branch has a cut and a measured growth rate, a cut also becomes due at K + sqrt(2(K + R)·δ / h), the
@@ -598,7 +610,7 @@ export async function installCompaction(pi, options = {}) {
598
610
  return lastAttempt();
599
611
  // Shrink in the planner's units by Pi's measured shortfall, at most three times. Once we reach the original room,
600
612
  // use its existing band/room policy; admission below the room is deliberately unchanged.
601
- target = Math.max(room, Math.floor(target * (contextWindow(ctx) - piMargin - limits(ctx).replyFloor) / check.estimate));
613
+ target = Math.max(room, Math.floor(target * inputFor(ctx, limits(ctx).replyFloor) / check.estimate));
602
614
  decision = replan(target);
603
615
  if (decision.kind === "defer" || decision.kind === "fault")
604
616
  return lastAttempt();
@@ -1241,7 +1253,7 @@ export async function installCompaction(pi, options = {}) {
1241
1253
  const saved = ctx.sessionManager.buildSessionProjection().messages, before = conversationTokens(projectContext(saved, ctx));
1242
1254
  const mandatory = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), asIs, ctx.getSystemPrompt()) + conversationTokens(host) + conversationTokens(pending);
1243
1255
  const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
1244
- const { response, room } = limits(ctx), want = response - piMargin, band = decisionBand(ctx, room);
1256
+ const { want, room } = limits(ctx), band = decisionBand(ctx, room);
1245
1257
  let target = room;
1246
1258
  for (let attempt = 0; attempt < 4 && fits(mandatory, target, ctx); attempt++) {
1247
1259
  const targetBand = target === room ? band : target;
@@ -91,7 +91,10 @@ export function promptOutputCandidates(entries, indices, resolvable) {
91
91
  for (const block of message.content) {
92
92
  if (block.type !== "toolCall" || block.name !== "bash" || typeof block.arguments?.command !== "string")
93
93
  continue;
94
- const command = block.arguments.command, lead = words(command.split(/[|;&<>]|\d>/u)[0]);
94
+ const command = block.arguments.command;
95
+ // A leading "cd DIR &&" is not what the prompt names; classifyBash already recognizes it.
96
+ const rest = classifyBash(command).directory === undefined ? command : command.slice(command.indexOf("&&") + 2);
97
+ const lead = words(rest.split(/[|;&<>]|\d>/u)[0]);
95
98
  if (lead.includes(" ") && prompt.includes(lead))
96
99
  named.set(block.id, command);
97
100
  }
@@ -16,6 +16,12 @@ export declare function loadPiRequestMath(): Promise<PiRequestMath | undefined>;
16
16
  * Without Pi's request arithmetic, fall back to Pi 1.2–1.5's documented 4,096-token allowance.
17
17
  */
18
18
  export declare function piContextSafetyMargin(math?: PiRequestMath): Promise<number>;
19
+ /** The largest input Pi still gives a reply of `reply` tokens, read from Pi's own clamp rather than a copied formula. Pi 1.2-1.6 keep a fixed
20
+ * margin, so this is window - margin - reply. Pi 1.7 keeps 15% of the input while that leaves 32,768 output, so at long context with a large
21
+ * maxTokens it is lower. The clamp only reads the window and the estimate, and an estimate is a reply's usage plus what follows it, so a
22
+ * context of one assistant reply whose usage is `input` asks Pi about any input size. Pi's cap never grows with the input, so search.
23
+ * Without Pi's request arithmetic: window - margin - reply. */
24
+ export declare function piInputFor(math: PiRequestMath | undefined, window: number, reply: number, margin: number): number;
19
25
  /** A length stop with visible reasoning but no visible answer or work. */
20
26
  export declare const thinkingOnlyLength: (message: AgentMessage) => boolean;
21
27
  type ReplyModel = {
@@ -56,6 +56,36 @@ export async function piContextSafetyMargin(math) {
56
56
  return 4_096;
57
57
  }
58
58
  }
59
+ /** The largest input Pi still gives a reply of `reply` tokens, read from Pi's own clamp rather than a copied formula. Pi 1.2-1.6 keep a fixed
60
+ * margin, so this is window - margin - reply. Pi 1.7 keeps 15% of the input while that leaves 32,768 output, so at long context with a large
61
+ * maxTokens it is lower. The clamp only reads the window and the estimate, and an estimate is a reply's usage plus what follows it, so a
62
+ * context of one assistant reply whose usage is `input` asks Pi about any input size. Pi's cap never grows with the input, so search.
63
+ * Without Pi's request arithmetic: window - margin - reply. */
64
+ export function piInputFor(math, window, reply, margin) {
65
+ const fixed = window - margin - reply;
66
+ if (!math || !(window > 0) || !Number.isSafeInteger(window))
67
+ return fixed;
68
+ const cap = (input) => math.clampMaxTokensToContext({ contextWindow: window, maxTokens: window }, { messages: [{ role: 'assistant', content: [], api: 'openai-completions', provider: 'pi-tuck', model: 'probe', stopReason: 'stop', timestamp: 0,
69
+ usage: { input, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: input, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } }] }, window);
70
+ // Pi's cap bottoms out at one token even past the window; a cap counts only while it fits beside the fixed margin.
71
+ const gives = (input) => { const c = cap(input); return c >= reply && input + margin + c <= window; };
72
+ try {
73
+ if (!gives(0))
74
+ return fixed;
75
+ let low = 0, high = window;
76
+ while (low < high) {
77
+ const mid = Math.ceil((low + high) / 2);
78
+ if (gives(mid))
79
+ low = mid;
80
+ else
81
+ high = mid - 1;
82
+ }
83
+ return low;
84
+ }
85
+ catch {
86
+ return fixed;
87
+ }
88
+ }
59
89
  /** A length stop with visible reasoning but no visible answer or work. */
60
90
  export const thinkingOnlyLength = (message) => message.role === 'assistant' && message.stopReason === 'length' &&
61
91
  message.content.length > 0 && message.content.every(block => block.type === 'thinking');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.11.0",
3
+ "version": "1.11.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",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "e11927281c0dc22058687647b4d0658d8a588470b4fae558169cc0532bb02d4e";
1
+ export const BUILD_ID = "af3354d4b75532f8a65d30e805ce634249fd18de42eb8988de21b51103e9acc2";
package/src/compaction.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { textOf } from "./tuck/core/content.js";
2
2
  import { PendingCut, StartingPrompt, Run, type CutEntry } from "./run.js";
3
- import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath } from "./request-capacity.js";
3
+ import { CUT_REPLY_FLOOR, requestReplyFloor, stoppedReplyRoom, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, piInputFor, loadPiRequestMath } from "./request-capacity.js";
4
4
  import { BUILD_ID } from "./build-id.js";
5
5
  import { lowestEffort, pendingCheck, serverEfforts } from "./config-check.js";
6
6
  import { IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry, type Receipt, type RecorderOptions } from "./diagnostics.js";
@@ -226,6 +226,17 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
226
226
  const piMath = await loadPiRequestMath();
227
227
  const piMargin = options.requestReserve ? 0 : await piContextSafetyMargin(piMath);
228
228
  const piClamp = piMath?.clampMaxTokensToContext;
229
+ // The largest input Pi still gives `reply` tokens (Pi 1.7's margin grows with the input). A host reserve keeps the fixed arithmetic.
230
+ const inputCache = new Map<string, number>();
231
+ const inputFor = (ctx: ExtensionContext, reply: number) => {
232
+ const window = contextWindow(ctx), key = `${window}:${reply}`;
233
+ let input = inputCache.get(key);
234
+ if (input === undefined) {
235
+ if (inputCache.size > 256) inputCache.clear();
236
+ inputCache.set(key, input = piInputFor(options.requestReserve ? undefined : piMath, window, reply, piMargin));
237
+ }
238
+ return input;
239
+ };
229
240
  const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
230
241
  if (!validCutAt(cutAt)) throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
231
242
  const view = (ctx: ExtensionContext, threshold = false) => (threshold && run?.expired ? liveCut : run?.cut ?? liveCut).view(ctx);
@@ -416,13 +427,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
416
427
  const limits = (ctx: ExtensionContext) => {
417
428
  const reserve = responseReserve(ctx);
418
429
  const floor = options.requestReserve || !ctx.model ? reserve : requestReplyFloor(ctx.sessionManager.getBranch(), reserve, ctx.model, floorMinimum);
419
- // After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math: Pi gives a request
420
- // min(maxTokens, window - input - margin), so the room is window - margin - raised. Admission (floor, hard line) stays as without a
430
+ // After a length stop the trim point moves so the next reply gets the raised room by Pi's clamp math: the room is the largest input
431
+ // Pi still gives the raised reply (window - margin - raised under a fixed margin). Admission (floor, hard line) stays as without a
421
432
  // stop: the raise asks cuts for more reply room, it never refuses a request Pi would send. No stop: exactly the reserve, as before.
422
433
  const raised = options.requestReserve || !ctx.model ? undefined : stoppedReplyRoom(ctx.sessionManager.getBranch(), ctx.model, contextWindow(ctx), piMargin);
423
- const response = raised === undefined ? reserve : Math.max(reserve, raised + piMargin), room = inputRoom(response, ctx);
424
- const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve, contextWindow(ctx) - piMargin - floor), calibration.lastCeiling ?? Infinity);
425
- return { response, room, hardLine, replyFloor: floor };
434
+ const response = raised === undefined ? reserve : Math.max(reserve, contextWindow(ctx) - inputFor(ctx, raised)), room = inputRoom(response, ctx);
435
+ const hardLine = Math.min(Math.max(contextWindow(ctx) - reserve, inputFor(ctx, floor)), calibration.lastCeiling ?? Infinity);
436
+ return { response, room, hardLine, replyFloor: floor, want: Math.max(reserve - piMargin, raised ?? -Infinity) };
426
437
  };
427
438
  const preservePrefix = (ctx: ExtensionContext) => ctx.model !== undefined &&
428
439
  options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
@@ -430,7 +441,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
430
441
  // Thrash-adaptive trigger. Only in a branch whose cuts drop files the agent then re-reads unchanged (thrash.ts): there the trigger moves
431
442
  // to native's line, max(window - reserve, keepRecentTokens + the oldest turn), mirrored as max(band, keepRecentTokens) (parked 4302e2c).
432
443
  // Its cap keeps the reply room a cut aims for (the reply floor, at least CUT_REPLY_FLOOR) and, after a length stop, 1.7.0's raised reply
433
- // room: window - Pi's margin - the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
444
+ // room: the largest input Pi still gives the largest of these, less the trigger margin. Cuts still plan to the band. Admission (floor, hard line) is unchanged. Off with an explicit cutAt, a cache-
434
445
  // sensitive model, or a host reserve; in a branch without thrash it returns nothing and the trigger is the band, as in 1.7.0.
435
446
  const triggerLine = (ctx: ExtensionContext, room: number): number | undefined => {
436
447
  if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx)) return undefined;
@@ -438,7 +449,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
438
449
  if (!thrashing(branch)) return undefined;
439
450
  const { hardLine, replyFloor } = limits(ctx), raised = stoppedReplyRoom(branch, ctx.model, contextWindow(ctx), piMargin) ?? 0;
440
451
  const reply = Math.max(replyFloor, CUT_REPLY_FLOOR, raised);
441
- const cap = Math.min(hardLine, contextWindow(ctx) - piMargin - reply) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
452
+ const cap = Math.min(hardLine, inputFor(ctx, reply)) - Math.ceil(Math.max(0, room) * TRIGGER_MARGIN_FRACTION);
442
453
  return Math.min(cap, settingsFor().getCompactionSettings(ctx.model).keepRecentTokens);
443
454
  };
444
455
  // Lean line (lean.ts): once the branch has a cut and a measured growth rate, a cut also becomes due at K + sqrt(2(K + R)·δ / h), the
@@ -543,7 +554,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
543
554
  if (retry === 3) return lastAttempt();
544
555
  // Shrink in the planner's units by Pi's measured shortfall, at most three times. Once we reach the original room,
545
556
  // use its existing band/room policy; admission below the room is deliberately unchanged.
546
- target = Math.max(room, Math.floor(target * (contextWindow(ctx) - piMargin - limits(ctx).replyFloor) / check.estimate));
557
+ target = Math.max(room, Math.floor(target * inputFor(ctx, limits(ctx).replyFloor) / check.estimate));
547
558
  decision = replan(target);
548
559
  if (decision.kind === "defer" || decision.kind === "fault") return lastAttempt();
549
560
  }
@@ -1098,7 +1109,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1098
1109
  const saved = ctx.sessionManager.buildSessionProjection().messages, before = conversationTokens(projectContext(saved, ctx));
1099
1110
  const mandatory = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), asIs, ctx.getSystemPrompt()) + conversationTokens(host) + conversationTokens(pending);
1100
1111
  const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
1101
- const { response, room } = limits(ctx), want = response - piMargin, band = decisionBand(ctx, room);
1112
+ const { want, room } = limits(ctx), band = decisionBand(ctx, room);
1102
1113
  let target = room;
1103
1114
  for (let attempt = 0; attempt < 4 && fits(mandatory, target, ctx); attempt++) {
1104
1115
  const targetBand = target === room ? band : target;
package/src/kept-reads.ts CHANGED
@@ -70,7 +70,10 @@ export function promptOutputCandidates(entries: readonly (SessionEntry | Session
70
70
  if (message.role !== "assistant" || prompt === undefined || isDiscardedResponse(message)) continue;
71
71
  for (const block of message.content) {
72
72
  if (block.type !== "toolCall" || block.name !== "bash" || typeof (block.arguments as { command?: unknown })?.command !== "string") continue;
73
- const command = (block.arguments as { command: string }).command, lead = words(command.split(/[|;&<>]|\d>/u)[0]!);
73
+ const command = (block.arguments as { command: string }).command;
74
+ // A leading "cd DIR &&" is not what the prompt names; classifyBash already recognizes it.
75
+ const rest = classifyBash(command).directory === undefined ? command : command.slice(command.indexOf("&&") + 2);
76
+ const lead = words(rest.split(/[|;&<>]|\d>/u)[0]!);
74
77
  if (lead.includes(" ") && prompt.includes(lead)) named.set(block.id, command);
75
78
  }
76
79
  prompt = undefined;
@@ -51,6 +51,27 @@ export async function piContextSafetyMargin(math?: PiRequestMath): Promise<numbe
51
51
  } catch { return 4_096; }
52
52
  }
53
53
 
54
+ /** The largest input Pi still gives a reply of `reply` tokens, read from Pi's own clamp rather than a copied formula. Pi 1.2-1.6 keep a fixed
55
+ * margin, so this is window - margin - reply. Pi 1.7 keeps 15% of the input while that leaves 32,768 output, so at long context with a large
56
+ * maxTokens it is lower. The clamp only reads the window and the estimate, and an estimate is a reply's usage plus what follows it, so a
57
+ * context of one assistant reply whose usage is `input` asks Pi about any input size. Pi's cap never grows with the input, so search.
58
+ * Without Pi's request arithmetic: window - margin - reply. */
59
+ export function piInputFor(math: PiRequestMath | undefined, window: number, reply: number, margin: number): number {
60
+ const fixed = window - margin - reply;
61
+ if (!math || !(window > 0) || !Number.isSafeInteger(window)) return fixed;
62
+ const cap = (input: number) => math.clampMaxTokensToContext({ contextWindow: window, maxTokens: window } as never,
63
+ { messages: [{ role: 'assistant', content: [], api: 'openai-completions', provider: 'pi-tuck', model: 'probe', stopReason: 'stop', timestamp: 0,
64
+ usage: { input, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: input, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } }] } as never, window);
65
+ // Pi's cap bottoms out at one token even past the window; a cap counts only while it fits beside the fixed margin.
66
+ const gives = (input: number) => { const c = cap(input); return c >= reply && input + margin + c <= window; };
67
+ try {
68
+ if (!gives(0)) return fixed;
69
+ let low = 0, high = window;
70
+ while (low < high) { const mid = Math.ceil((low + high) / 2); if (gives(mid)) low = mid; else high = mid - 1; }
71
+ return low;
72
+ } catch { return fixed; }
73
+ }
74
+
54
75
  /** A length stop with visible reasoning but no visible answer or work. */
55
76
  export const thinkingOnlyLength = (message: AgentMessage): boolean => message.role === 'assistant' && message.stopReason === 'length' &&
56
77
  message.content.length > 0 && message.content.every(block => block.type === 'thinking');