pi-tuck 1.9.0 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,31 @@
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.10.1]
7
+
8
+ ### Fixed
9
+
10
+ - Lean line: a cut planned when a prompt arrives, or by the request guard, is saved after the first reply that carried it. The lean line
11
+ took that drop in prompt size as negative growth, which pulled the line toward what the cut kept and could trigger cut after cut. Each
12
+ reply now counts under the cut it was sent with, and the line waits for a reply after a fresh cut. Re-reads after a cut count the same way.
13
+ - Act-now turn: the limit of two in a row now holds until a reply finishes (stop or tool use); a reply cut off in the middle of a tool call
14
+ no longer resets it. The count is read from the session, so it survives a restart and follows `/tree`. No act-now turn is sent when the
15
+ operator has already queued a message.
16
+
17
+ ## [1.10.0]
18
+
19
+ ### Added
20
+
21
+ - Act-now turn: when a reply stops at its output limit while still thinking (no text, no tool call) and pi-tuck does not retry it, pi-tuck
22
+ queues one more user turn asking the model to act now, with the next tool call or the answer. The stopped reply stays saved but leaves
23
+ that request's context, and the request gets the raised reply room. At most two such turns go out in a row, and only when the request
24
+ fits; if the second also stops, the exhaustion notice shows as before. A reply that is not such a stop re-arms it. The act-now turn
25
+ does not re-arm the length retry.
26
+
27
+ ### Changed
28
+
29
+ - README: `cacheSensitiveModels` also turns off the lean line (as in 1.9.0); a local server with a strong prompt cache belongs in it.
30
+
6
31
  ## [1.9.0]
7
32
 
8
33
  ### 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.9.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.9.0` or `pi install git:github.com/galyavin/pi-tuck@v1.9.0`. To uninstall, run `pi remove` with the source you installed.
15
+ This README describes pi-tuck 1.10.1. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.10.1` or `pi install git:github.com/galyavin/pi-tuck@v1.10.1`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
@@ -58,7 +58,7 @@ Once per Pi start, in the background, pi-tuck reads the server's own model list
58
58
  Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by default, or `PI_CODING_AGENT_DIR`). Restart Pi to apply changes. The input room starts at the model's context window minus Pi's `compaction.reserveTokens`. Invalid JSON uses defaults. An invalid field uses its own default, with a notice when compaction is active.
59
59
 
60
60
  - **`cutAt`** is a fraction above 0 and at most 1. By default pi-tuck cuts at the room, less a 2% margin. An explicit value fixes a fraction of the room, subject to the same margin even at `1`.
61
- - **`cacheSensitiveModels`** lists exact `provider/model` identifiers. For these models, the cut point is the full room, taking precedence over `cutAt`. This delays early cuts that would discard a reusable prompt prefix.
61
+ - **`cacheSensitiveModels`** lists exact `provider/model` identifiers. For these models, the cut point is the full room, taking precedence over `cutAt`. This delays early cuts that would discard a reusable prompt prefix. It also turns off the lean line for these models; list a local server with a strong prompt cache here, where cached input is nearly free and wall time is the cost.
62
62
  - **`footer`** set to `false` keeps Pi's own footer.
63
63
  - **`llamaContinuation`** opts one reasoning model into a single extra request after a thinking-only response exhausts the full configured output allowance. In Pi's `models.json`, configure that model on a llama.cpp provider using the `openai-completions` API. Verify that the runtime and template support `continue_final_message: "reasoning_content"` and report reused prompt tokens through `prompt_progress`. Pi-tuck requires the first cache report to match the prefix within 15 seconds. The positive integer `extraTokens` caps the additional allowance within the remaining context. The positive integer `deadlineMs` covers both requests.
64
64
 
@@ -75,7 +75,7 @@ Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by
75
75
 
76
76
  ## Output exhaustion and small windows
77
77
 
78
- - Pi-tuck preserves thinking-only stops in session history. At the model's full output allowance, it reports exhaustion if the reply remains unfinished. Below that allowance, it retries once, re-armed as Pi's overflow recovery is. After any length stop on the branch, pi-tuck trims so the next reply gets twice that stop's output (at most `maxTokens` and half the window). A stop at the full `maxTokens` while still thinking names the setting and `models.json`; a lower thinking level usually helps more than a bigger cap.
78
+ - Pi-tuck preserves thinking-only stops in session history. At the model's full output allowance, it reports exhaustion if the reply remains unfinished. Below that allowance, it retries once, re-armed as Pi's overflow recovery is. After any length stop on the branch, pi-tuck trims so the next reply gets twice that stop's output (at most `maxTokens` and half the window). When such a stop is not retried, pi-tuck queues one more user turn asking the model to act: "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning." The stopped reply stays saved but leaves that request's context. At most two such turns go out in a row until a reply finishes, and only when the request fits and no message is already queued; if the second also stops, the notice below stands. A stop at the full `maxTokens` while still thinking names the setting and `models.json`; a lower thinking level usually helps more than a bigger cap.
79
79
  - Pi-tuck uses the context window declared in Pi's model configuration. A length stop alone does not establish a smaller window. If the server has a smaller effective limit, set that limit in Pi's model configuration.
80
80
  - Pi's compaction reserve sets the cut target. For larger requests, pi-tuck estimates reply needs from observed output on the current branch for the active model, bounded by the reserve and model output limit. A cut above the room aims to leave 3,584 reply tokens within those bounds; where no cut can, the request goes out as before. If cuts cannot leave enough room for the protected prompt and a reply, try a shorter prompt, fewer tools, or a larger window. Pi-tuck's checks use estimates. Pi handles recognized provider overflows, and silent truncation can go undetected.
81
81
 
@@ -1 +1 @@
1
- export declare const BUILD_ID = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
1
+ export declare const BUILD_ID = "6582ec23dfaf8ff94cbd7a5979c69569e3156024d0fc636de44b748f2ccab8ec";
@@ -1 +1 @@
1
- export const BUILD_ID = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
1
+ export const BUILD_ID = "6582ec23dfaf8ff94cbd7a5979c69569e3156024d0fc636de44b748f2ccab8ec";
@@ -10,6 +10,13 @@ export declare const overflowNotice: (contextWindow: number, bound: number, lear
10
10
  /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
11
11
  /** The notice for a thinking-only reply that used the model's whole configured maxTokens. */
12
12
  export declare const capStopNotice: (model: string, maxTokens: number, file: string) => string;
13
+ /** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
14
+ export declare const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
15
+ /** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply finishes (stop or toolUse). */
16
+ export declare const ACT_NOW_LIMIT = 2;
17
+ /** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
18
+ * or fork keeps the count; a length stop with content (a cut-off tool call) does not reset it. Operator messages do not reset it. */
19
+ export declare function actNowsInARow(branch: readonly SessionEntry[]): number;
13
20
  export declare const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
14
21
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
15
22
  export declare const CALIBRATION_CEILING = 1.5;
@@ -67,6 +67,26 @@ export const overflowNotice = (contextWindow, bound, learned) => `pi-tuck: the p
67
67
  export const capStopNotice = (model, maxTokens, file) => `pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
68
68
  `The cap is maxTokens for this model in ${file}. A lower thinking level, or a task that writes to files as it goes, usually helps more than a bigger cap. ` +
69
69
  "The unfinished response is saved in the session.";
70
+ /** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
71
+ export const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
72
+ /** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply finishes (stop or toolUse). */
73
+ export const ACT_NOW_LIMIT = 2;
74
+ /** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
75
+ * or fork keeps the count; a length stop with content (a cut-off tool call) does not reset it. Operator messages do not reset it. */
76
+ export function actNowsInARow(branch) {
77
+ let count = 0;
78
+ for (let i = branch.length - 1; i >= 0; i--) {
79
+ const entry = branch[i];
80
+ if (entry.type !== "message")
81
+ continue;
82
+ const message = entry.message;
83
+ if (message.role === "assistant" && (message.stopReason === "stop" || message.stopReason === "toolUse"))
84
+ break;
85
+ if (message.role === "user" && textOf(message.content) === ACT_NOW)
86
+ count++;
87
+ }
88
+ return count;
89
+ }
70
90
  /** Pi's models.json, shown with ~ for the home folder. */
71
91
  function modelsPath() {
72
92
  try {
@@ -339,7 +359,8 @@ export async function installCompaction(pi, options = {}) {
339
359
  if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel)
340
360
  run?.rearmLengthRetry();
341
361
  };
342
- pi.on("message_start", (event, ctx) => { if (event.message.role === "user")
362
+ // The act-now turn is pi-tuck's own, not the operator's: it grants no retry.
363
+ pi.on("message_start", (event, ctx) => { if (event.message.role === "user" && textOf(event.message.content) !== ACT_NOW)
343
364
  rearmLengthRetry(ctx); });
344
365
  pi.on("message_end", (event, ctx) => {
345
366
  if (event.message.role !== "assistant")
@@ -1137,6 +1158,42 @@ export async function installCompaction(pi, options = {}) {
1137
1158
  const saved = { ...cut, firstKeptEntryId: current.keptFromId };
1138
1159
  return { entries: [...event.entries, saved, ...(more?.entries ?? [])] };
1139
1160
  };
1161
+ // After a stall that is not retried: leave the stalled reply out of the context (it stays saved, with its output usage, so the next
1162
+ // request keeps the raised reply room) and queue one act-now turn, if that request fits as it stands. Otherwise the notice stands.
1163
+ const actNow = (event, ctx, result) => {
1164
+ // Queued operator input already becomes the next turn; an act-now behind it would arrive after an answer and misstate the stall.
1165
+ if (event.context.pendingMessages.length > 0 || actNowsInARow(ctx.sessionManager.getBranch()) >= ACT_NOW_LIMIT || !ctx.model)
1166
+ return undefined;
1167
+ const edit = { type: "context_edit", targetId: event.messageEntryId, replacement: null };
1168
+ // The cap path returns before taking a pending cut: preview it in place, and take it only if the turn is queued.
1169
+ const untaken = !result || result.entries === event.entries;
1170
+ const base = result?.entries ?? event.entries;
1171
+ let entries = base.some(entry => entry.type === "context_edit" && entry.targetId === event.messageEntryId) ? [...base] : [...base, edit];
1172
+ const restore = untaken ? run?.cut.hold() : undefined;
1173
+ try {
1174
+ const preview = (untaken ? run?.cut ?? liveCut : liveCut).view(ctx, entries).session;
1175
+ const view = Object.create(ctx, { sessionManager: { value: preview } });
1176
+ const turn = { role: "user", content: [{ type: "text", text: ACT_NOW }], timestamp: 0 };
1177
+ const messages = projectedRequest(preview.buildSessionProjection().messages, view, hostMessages(ctx), [...event.context.pendingMessages, turn], ctx.getSystemPrompt(), pi.getActiveTools(), false);
1178
+ const tokens = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt()) + conversationTokens(messages);
1179
+ const { room, hardLine } = limits(view);
1180
+ if (!fits(tokens, hardLine, view) || !options.requestReserve && corrected(tokens, view) > room && piClamp && !requestClamp(messages, view).leavesFloor)
1181
+ return undefined;
1182
+ }
1183
+ finally {
1184
+ restore?.();
1185
+ }
1186
+ try {
1187
+ pi.sendUserMessage(ACT_NOW, { deliverAs: "followUp" });
1188
+ }
1189
+ catch {
1190
+ return undefined;
1191
+ }
1192
+ if (untaken)
1193
+ entries = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries), edit];
1194
+ markBoundary(entries);
1195
+ return { entries, continue: false };
1196
+ };
1140
1197
  const retryLength = (event, ctx) => {
1141
1198
  // Exhausting the full per-request allowance is not evidence that input is too large.
1142
1199
  // Preserve the unfinished response; provider-native continuation owns this case.
@@ -1215,8 +1272,11 @@ export async function installCompaction(pi, options = {}) {
1215
1272
  return;
1216
1273
  if (!active() || run?.phase !== "admitted")
1217
1274
  return;
1218
- if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
1219
- return retryLength(event, ctx);
1275
+ if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled) {
1276
+ // A stall that is not retried gets one follow-up turn asking the model to act; its reply replaces the cap-stop notice.
1277
+ const result = retryLength(event, ctx);
1278
+ return result?.continue ? result : actNow(event, ctx, result) ?? result;
1279
+ }
1220
1280
  run.finishLengthRetry();
1221
1281
  const decide = event.outcome === "completed" && !ctx.signal?.aborted && event.context.canContinue && event.toolResults.length > 0 &&
1222
1282
  settingsFor().getCompactionSettings(ctx.model).enabled;
@@ -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 = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
3
+ export declare const DIAGNOSTIC_BUILD = "6582ec23dfaf8ff94cbd7a5979c69569e3156024d0fc636de44b748f2ccab8ec";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -0,0 +1,22 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ /** A reply whose prompt is at least this share below the previous reply's prompt was sent with a new cut. */
3
+ export declare const EPOCH_DROP = 0.05;
4
+ /** The prompt a reply was sent with (input + cache read + cache write), or undefined for replies with no usable usage. */
5
+ export declare const promptTokens: (entry: SessionEntry) => number | undefined;
6
+ export interface CutEpochs {
7
+ /** The cut epoch in effect at each branch entry: replies carry the epoch of the context they were sent with. 0 before any cut. */
8
+ epoch: number[];
9
+ /** True at the first reply with usable usage in each epoch after the first: its prompt is what that cut left. */
10
+ opens: boolean[];
11
+ /** Epoch steps, one per cut. */
12
+ cuts: number;
13
+ /** Compaction entries on the branch. */
14
+ compactions: number;
15
+ }
16
+ /**
17
+ * Places each reply under the cut it was sent with. A cut planned at prompt time or by the request guard is carried by requests at once,
18
+ * but its compaction entry is saved only at the next boundary, after the reply that carried it. So a cut shows in the log either as a
19
+ * compaction entry before the first reply that carries it, or as a prompt drop (EPOCH_DROP) at that reply with the entry after it. A
20
+ * compaction entry steps the epoch only when no drop has stepped it since the previous compaction entry, so one cut is one step.
21
+ */
22
+ export declare function cutEpochs(branch: readonly SessionEntry[]): CutEpochs;
@@ -0,0 +1,52 @@
1
+ import { isDiscardedResponse } from "./protocol.js";
2
+ /** A reply whose prompt is at least this share below the previous reply's prompt was sent with a new cut. */
3
+ export const EPOCH_DROP = 0.05;
4
+ /** The prompt a reply was sent with (input + cache read + cache write), or undefined for replies with no usable usage. */
5
+ export const promptTokens = (entry) => {
6
+ if (entry.type !== "message" || entry.message.role !== "assistant" || isDiscardedResponse(entry.message))
7
+ return undefined;
8
+ const message = entry.message;
9
+ if (message.stopReason === "error" || message.stopReason === "aborted")
10
+ return undefined;
11
+ const u = message.usage;
12
+ const total = (u?.input ?? 0) + (u?.cacheRead ?? 0) + (u?.cacheWrite ?? 0);
13
+ return Number.isFinite(total) && total > 0 ? total : undefined;
14
+ };
15
+ /**
16
+ * Places each reply under the cut it was sent with. A cut planned at prompt time or by the request guard is carried by requests at once,
17
+ * but its compaction entry is saved only at the next boundary, after the reply that carried it. So a cut shows in the log either as a
18
+ * compaction entry before the first reply that carries it, or as a prompt drop (EPOCH_DROP) at that reply with the entry after it. A
19
+ * compaction entry steps the epoch only when no drop has stepped it since the previous compaction entry, so one cut is one step.
20
+ */
21
+ export function cutEpochs(branch) {
22
+ const epoch = [], opens = [];
23
+ let current = 0, compactions = 0, previous, dropped = false, open = false;
24
+ for (const entry of branch) {
25
+ if (entry.type === "compaction") {
26
+ compactions++;
27
+ if (dropped)
28
+ dropped = false;
29
+ else {
30
+ current++;
31
+ previous = undefined;
32
+ open = true;
33
+ }
34
+ epoch.push(current);
35
+ opens.push(false);
36
+ continue;
37
+ }
38
+ const prompt = promptTokens(entry);
39
+ if (prompt !== undefined && previous !== undefined && prompt < previous * (1 - EPOCH_DROP)) {
40
+ current++;
41
+ dropped = true;
42
+ open = true;
43
+ }
44
+ epoch.push(current);
45
+ opens.push(prompt !== undefined && open && current > 0);
46
+ if (prompt !== undefined) {
47
+ previous = prompt;
48
+ open = false;
49
+ }
50
+ }
51
+ return { epoch, opens, cuts: current, compactions };
52
+ }
package/dist/src/lean.js CHANGED
@@ -1,45 +1,35 @@
1
- import { isDiscardedResponse } from "./protocol.js";
1
+ import { cutEpochs, promptTokens } from "./epochs.js";
2
2
  import { rereadsAfterCuts } from "./thrash.js";
3
3
  /** Holding cost of a context token per request, as a share of its fresh price: a cached re-send costs about a tenth. */
4
4
  export const LEAN_HOLDING = 0.1;
5
5
  /** Growth samples (consecutive replies with no cut between) needed before the growth rate counts. */
6
6
  export const LEAN_MIN_SAMPLES = 4;
7
- const promptTokens = (entry) => {
8
- if (entry.type !== "message" || entry.message.role !== "assistant" || isDiscardedResponse(entry.message))
9
- return undefined;
10
- const message = entry.message;
11
- if (message.stopReason === "error" || message.stopReason === "aborted")
12
- return undefined;
13
- const u = message.usage;
14
- const total = (u?.input ?? 0) + (u?.cacheRead ?? 0) + (u?.cacheWrite ?? 0);
15
- return Number.isFinite(total) && total > 0 ? total : undefined;
16
- };
17
7
  /** The quantities the lean line is built from, read from the branch's recorded usage only. `kept` (K): the prompt of the first reply after
18
8
  * the latest cut, what that cut left (system, summary, kept turns, carried files). `growth` (δ): the mean rise of the prompt between
19
9
  * consecutive replies with no cut between. `rereads` (R): the mean tokens per cut of unchanged files re-read soon after it (thrash.ts). */
20
10
  export function leanInputs(branch) {
21
- let kept = 0, previous, afterCut = false, sum = 0, samples = 0;
22
- for (const entry of branch) {
23
- if (entry.type === "compaction") {
11
+ // Epochs place each reply under the cut it was sent with (epochs.ts): growth is measured only inside an epoch, never across a cut.
12
+ const { epoch, opens, compactions } = cutEpochs(branch);
13
+ let kept = 0, previous, previousEpoch = -1, sum = 0, samples = 0;
14
+ branch.forEach((entry, i) => {
15
+ if (entry.type === "compaction" && epoch[i] !== previousEpoch && previousEpoch >= 0) {
16
+ kept = 0;
24
17
  previous = undefined;
25
- afterCut = true;
26
- continue;
27
18
  }
28
19
  const prompt = promptTokens(entry);
29
20
  if (prompt === undefined)
30
- continue;
31
- if (afterCut) {
21
+ return;
22
+ if (opens[i])
32
23
  kept = prompt;
33
- afterCut = false;
34
- }
35
- if (previous !== undefined) {
24
+ else if (previous !== undefined && epoch[i] === previousEpoch) {
36
25
  sum += prompt - previous;
37
26
  samples++;
38
27
  }
39
28
  previous = prompt;
40
- }
29
+ previousEpoch = epoch[i];
30
+ });
41
31
  const { cuts, tokens } = rereadsAfterCuts(branch);
42
- return { kept, growth: samples ? sum / samples : 0, rereads: cuts ? tokens / cuts : 0, samples, cuts };
32
+ return { kept, growth: samples ? sum / samples : 0, rereads: cuts ? tokens / cuts : 0, samples, cuts: compactions };
43
33
  }
44
34
  /**
45
35
  * The lean cut line: the economic order quantity of a context. Each cut costs a fresh re-send of what it keeps (K) and the re-reads it causes
package/dist/src/run.d.ts CHANGED
@@ -20,6 +20,8 @@ export declare class PendingCut {
20
20
  private preview?;
21
21
  plan(cut: CutEntry, ctx: Context): void;
22
22
  clear(): void;
23
+ /** Puts the plan back after a check that read a preview session (a read from another session clears it). */
24
+ hold(): () => void;
23
25
  take(ctx: Context): CutEntry | undefined;
24
26
  view(ctx: Context, entries?: readonly SessionBoundaryDraft[]): CutView;
25
27
  }
package/dist/src/run.js CHANGED
@@ -14,6 +14,8 @@ export class PendingCut {
14
14
  this.preview = undefined;
15
15
  }
16
16
  clear() { this.proposal = undefined; this.preview = undefined; }
17
+ /** Puts the plan back after a check that read a preview session (a read from another session clears it). */
18
+ hold() { const proposal = this.proposal; return () => { this.proposal = proposal; this.preview = undefined; }; }
17
19
  take(ctx) {
18
20
  if (!this.view(ctx).pending)
19
21
  return;
@@ -1,4 +1,5 @@
1
1
  import { isDiscardedResponse } from "./protocol.js";
2
+ import { cutEpochs } from "./epochs.js";
2
3
  import { pathKey } from "./path-key.js";
3
4
  import { isTextOnly, textOf } from "./tuck/core/content.js";
4
5
  import { extractPath } from "./tuck/core/tool-args.js";
@@ -8,20 +9,22 @@ export const THRASH_WINDOW_REPLIES = 3;
8
9
  export const THRASH_BAR = 0.5;
9
10
  /** The branch's cuts and the re-reads that followed them (as `thrashing` defines a re-read), with their text in tokens at 4 characters each. */
10
11
  export function rereadsAfterCuts(branch) {
11
- let cuts = 0, replies = 0, rereads = 0, chars = 0;
12
+ // Each reply counts under the cut it was sent with (epochs.ts), so the reply that first carries a cut opens that cut's window.
13
+ const { epoch, cuts } = cutEpochs(branch);
14
+ let current = 0, replies = 0, rereads = 0, chars = 0;
12
15
  const pending = new Map(), last = new Map();
13
- for (const entry of branch) {
14
- if (entry.type === "compaction") {
15
- cuts++;
16
- replies = 0;
17
- continue;
18
- }
16
+ for (const [i, entry] of branch.entries()) {
19
17
  if (entry.type !== "message")
20
18
  continue;
21
19
  const message = entry.message;
22
20
  if (message.role === "assistant") {
23
21
  if (isDiscardedResponse(message))
24
22
  continue;
23
+ if (epoch[i] !== current) {
24
+ current = epoch[i];
25
+ replies = 0;
26
+ }
27
+ const cuts = current;
25
28
  replies++;
26
29
  for (const block of message.content) {
27
30
  if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.9.0",
3
+ "version": "1.10.1",
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 = "c5a9fd0090bc62e33b94880449bf979f5190ce1cf8048994fefd817c8cedcc8d";
1
+ export const BUILD_ID = "6582ec23dfaf8ff94cbd7a5979c69569e3156024d0fc636de44b748f2ccab8ec";
package/src/compaction.ts CHANGED
@@ -71,6 +71,23 @@ export const capStopNotice = (model: string, maxTokens: number, file: string) =>
71
71
  `pi-tuck: ${model} used its whole reply cap (maxTokens ${maxTokens.toLocaleString("en-US")}) while still thinking, before any answer or tool call. ` +
72
72
  `The cap is maxTokens for this model in ${file}. A lower thinking level, or a task that writes to files as it goes, usually helps more than a bigger cap. ` +
73
73
  "The unfinished response is saved in the session.";
74
+ /** The follow-up turn sent after a reply that spent its whole output on thinking, with no text or tool call. */
75
+ export const ACT_NOW = "Your last reply used the whole output budget on thinking. Act now: make the next tool call or give the answer, with brief reasoning.";
76
+ /** At most this many act-now turns in a row; after that a stall gets the cap-stop notice until a reply finishes (stop or toolUse). */
77
+ export const ACT_NOW_LIMIT = 2;
78
+ /** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
79
+ * or fork keeps the count; a length stop with content (a cut-off tool call) does not reset it. Operator messages do not reset it. */
80
+ export function actNowsInARow(branch: readonly SessionEntry[]): number {
81
+ let count = 0;
82
+ for (let i = branch.length - 1; i >= 0; i--) {
83
+ const entry = branch[i]!;
84
+ if (entry.type !== "message") continue;
85
+ const message = entry.message;
86
+ if (message.role === "assistant" && (message.stopReason === "stop" || message.stopReason === "toolUse")) break;
87
+ if (message.role === "user" && textOf(message.content) === ACT_NOW) count++;
88
+ }
89
+ return count;
90
+ }
74
91
  /** Pi's models.json, shown with ~ for the home folder. */
75
92
  function modelsPath(): string {
76
93
  try {
@@ -319,7 +336,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
319
336
  const rearmLengthRetry = (ctx: ExtensionContext) => {
320
337
  if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel) run?.rearmLengthRetry();
321
338
  };
322
- pi.on("message_start", (event, ctx) => { if (event.message.role === "user") rearmLengthRetry(ctx); });
339
+ // The act-now turn is pi-tuck's own, not the operator's: it grants no retry.
340
+ pi.on("message_start", (event, ctx) => { if (event.message.role === "user" && textOf(event.message.content) !== ACT_NOW) rearmLengthRetry(ctx); });
323
341
  pi.on("message_end", (event, ctx) => {
324
342
  if (event.message.role !== "assistant") return;
325
343
  if (event.message.stopReason !== "error" && event.message.stopReason !== "length") rearmLengthRetry(ctx);
@@ -1015,6 +1033,31 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1015
1033
  const saved = { ...cut, firstKeptEntryId: current.keptFromId! };
1016
1034
  return { entries: [...event.entries as CutEntry[], saved, ...(more?.entries ?? [])] };
1017
1035
  };
1036
+ // After a stall that is not retried: leave the stalled reply out of the context (it stays saved, with its output usage, so the next
1037
+ // request keeps the raised reply room) and queue one act-now turn, if that request fits as it stands. Otherwise the notice stands.
1038
+ const actNow = (event: TurnEndEvent, ctx: ExtensionContext, result: { entries: readonly SessionBoundaryDraft[] } | undefined) => {
1039
+ // Queued operator input already becomes the next turn; an act-now behind it would arrive after an answer and misstate the stall.
1040
+ if (event.context.pendingMessages.length > 0 || actNowsInARow(ctx.sessionManager.getBranch()) >= ACT_NOW_LIMIT || !ctx.model) return undefined;
1041
+ const edit: SessionBoundaryDraft = { type: "context_edit", targetId: event.messageEntryId, replacement: null };
1042
+ // The cap path returns before taking a pending cut: preview it in place, and take it only if the turn is queued.
1043
+ const untaken = !result || result.entries === event.entries;
1044
+ const base = result?.entries ?? event.entries;
1045
+ let entries: SessionBoundaryDraft[] = base.some(entry => entry.type === "context_edit" && entry.targetId === event.messageEntryId) ? [...base] : [...base, edit];
1046
+ const restore = untaken ? run?.cut.hold() : undefined;
1047
+ try {
1048
+ const preview = (untaken ? run?.cut ?? liveCut : liveCut).view(ctx, entries).session;
1049
+ const view: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
1050
+ const turn = { role: "user" as const, content: [{ type: "text" as const, text: ACT_NOW }], timestamp: 0 };
1051
+ const messages = projectedRequest(preview.buildSessionProjection().messages, view, hostMessages(ctx), [...event.context.pendingMessages, turn], ctx.getSystemPrompt(), pi.getActiveTools(), false);
1052
+ const tokens = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt()) + conversationTokens(messages);
1053
+ const { room, hardLine } = limits(view);
1054
+ if (!fits(tokens, hardLine, view) || !options.requestReserve && corrected(tokens, view) > room && piClamp && !requestClamp(messages, view).leavesFloor) return undefined;
1055
+ } finally { restore?.(); }
1056
+ try { pi.sendUserMessage(ACT_NOW, { deliverAs: "followUp" }); } catch { return undefined; }
1057
+ if (untaken) entries = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries), edit];
1058
+ markBoundary(entries);
1059
+ return { entries, continue: false };
1060
+ };
1018
1061
  const retryLength = (event: TurnEndEvent, ctx: ExtensionContext) => {
1019
1062
  // Exhausting the full per-request allowance is not evidence that input is too large.
1020
1063
  // Preserve the unfinished response; provider-native continuation owns this case.
@@ -1084,8 +1127,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1084
1127
  try {
1085
1128
  if (standDown(ctx)) return;
1086
1129
  if (!active() || run?.phase !== "admitted") return;
1087
- if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
1088
- return retryLength(event, ctx);
1130
+ if (thinkingOnlyLength(event.message) && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled) {
1131
+ // A stall that is not retried gets one follow-up turn asking the model to act; its reply replaces the cap-stop notice.
1132
+ const result = retryLength(event, ctx);
1133
+ return result?.continue ? result : actNow(event, ctx, result) ?? result;
1134
+ }
1089
1135
  run.finishLengthRetry();
1090
1136
  const decide = event.outcome === "completed" && !ctx.signal?.aborted && event.context.canContinue && event.toolResults.length > 0 &&
1091
1137
  settingsFor().getCompactionSettings(ctx.model).enabled;
package/src/epochs.ts ADDED
@@ -0,0 +1,52 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import { isDiscardedResponse } from "./protocol";
3
+
4
+ /** A reply whose prompt is at least this share below the previous reply's prompt was sent with a new cut. */
5
+ export const EPOCH_DROP = 0.05;
6
+
7
+ /** The prompt a reply was sent with (input + cache read + cache write), or undefined for replies with no usable usage. */
8
+ export const promptTokens = (entry: SessionEntry): number | undefined => {
9
+ if (entry.type !== "message" || entry.message.role !== "assistant" || isDiscardedResponse(entry.message)) return undefined;
10
+ const message = entry.message;
11
+ if (message.stopReason === "error" || message.stopReason === "aborted") return undefined;
12
+ const u = message.usage;
13
+ const total = (u?.input ?? 0) + (u?.cacheRead ?? 0) + (u?.cacheWrite ?? 0);
14
+ return Number.isFinite(total) && total > 0 ? total : undefined;
15
+ };
16
+
17
+ export interface CutEpochs {
18
+ /** The cut epoch in effect at each branch entry: replies carry the epoch of the context they were sent with. 0 before any cut. */
19
+ epoch: number[];
20
+ /** True at the first reply with usable usage in each epoch after the first: its prompt is what that cut left. */
21
+ opens: boolean[];
22
+ /** Epoch steps, one per cut. */
23
+ cuts: number;
24
+ /** Compaction entries on the branch. */
25
+ compactions: number;
26
+ }
27
+
28
+ /**
29
+ * Places each reply under the cut it was sent with. A cut planned at prompt time or by the request guard is carried by requests at once,
30
+ * but its compaction entry is saved only at the next boundary, after the reply that carried it. So a cut shows in the log either as a
31
+ * compaction entry before the first reply that carries it, or as a prompt drop (EPOCH_DROP) at that reply with the entry after it. A
32
+ * compaction entry steps the epoch only when no drop has stepped it since the previous compaction entry, so one cut is one step.
33
+ */
34
+ export function cutEpochs(branch: readonly SessionEntry[]): CutEpochs {
35
+ const epoch: number[] = [], opens: boolean[] = [];
36
+ let current = 0, compactions = 0, previous: number | undefined, dropped = false, open = false;
37
+ for (const entry of branch) {
38
+ if (entry.type === "compaction") {
39
+ compactions++;
40
+ if (dropped) dropped = false;
41
+ else { current++; previous = undefined; open = true; }
42
+ epoch.push(current); opens.push(false);
43
+ continue;
44
+ }
45
+ const prompt = promptTokens(entry);
46
+ if (prompt !== undefined && previous !== undefined && prompt < previous * (1 - EPOCH_DROP)) { current++; dropped = true; open = true; }
47
+ epoch.push(current);
48
+ opens.push(prompt !== undefined && open && current > 0);
49
+ if (prompt !== undefined) { previous = prompt; open = false; }
50
+ }
51
+ return { epoch, opens, cuts: current, compactions };
52
+ }
package/src/lean.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
- import { isDiscardedResponse } from "./protocol";
2
+ import { cutEpochs, promptTokens } from "./epochs";
3
3
  import { rereadsAfterCuts } from "./thrash";
4
4
 
5
5
  /** Holding cost of a context token per request, as a share of its fresh price: a cached re-send costs about a tenth. */
@@ -7,31 +7,24 @@ export const LEAN_HOLDING = 0.1;
7
7
  /** Growth samples (consecutive replies with no cut between) needed before the growth rate counts. */
8
8
  export const LEAN_MIN_SAMPLES = 4;
9
9
 
10
- const promptTokens = (entry: SessionEntry): number | undefined => {
11
- if (entry.type !== "message" || entry.message.role !== "assistant" || isDiscardedResponse(entry.message)) return undefined;
12
- const message = entry.message;
13
- if (message.stopReason === "error" || message.stopReason === "aborted") return undefined;
14
- const u = message.usage;
15
- const total = (u?.input ?? 0) + (u?.cacheRead ?? 0) + (u?.cacheWrite ?? 0);
16
- return Number.isFinite(total) && total > 0 ? total : undefined;
17
- };
18
-
19
10
  export interface LeanInputs { kept: number; growth: number; rereads: number; samples: number; cuts: number }
20
11
  /** The quantities the lean line is built from, read from the branch's recorded usage only. `kept` (K): the prompt of the first reply after
21
12
  * the latest cut, what that cut left (system, summary, kept turns, carried files). `growth` (δ): the mean rise of the prompt between
22
13
  * consecutive replies with no cut between. `rereads` (R): the mean tokens per cut of unchanged files re-read soon after it (thrash.ts). */
23
14
  export function leanInputs(branch: readonly SessionEntry[]): LeanInputs {
24
- let kept = 0, previous: number | undefined, afterCut = false, sum = 0, samples = 0;
25
- for (const entry of branch) {
26
- if (entry.type === "compaction") { previous = undefined; afterCut = true; continue; }
15
+ // Epochs place each reply under the cut it was sent with (epochs.ts): growth is measured only inside an epoch, never across a cut.
16
+ const { epoch, opens, compactions } = cutEpochs(branch);
17
+ let kept = 0, previous: number | undefined, previousEpoch = -1, sum = 0, samples = 0;
18
+ branch.forEach((entry, i) => {
19
+ if (entry.type === "compaction" && epoch[i] !== previousEpoch && previousEpoch >= 0) { kept = 0; previous = undefined; }
27
20
  const prompt = promptTokens(entry);
28
- if (prompt === undefined) continue;
29
- if (afterCut) { kept = prompt; afterCut = false; }
30
- if (previous !== undefined) { sum += prompt - previous; samples++; }
31
- previous = prompt;
32
- }
21
+ if (prompt === undefined) return;
22
+ if (opens[i]) kept = prompt;
23
+ else if (previous !== undefined && epoch[i] === previousEpoch) { sum += prompt - previous; samples++; }
24
+ previous = prompt; previousEpoch = epoch[i];
25
+ });
33
26
  const { cuts, tokens } = rereadsAfterCuts(branch);
34
- return { kept, growth: samples ? sum / samples : 0, rereads: cuts ? tokens / cuts : 0, samples, cuts };
27
+ return { kept, growth: samples ? sum / samples : 0, rereads: cuts ? tokens / cuts : 0, samples, cuts: compactions };
35
28
  }
36
29
 
37
30
  /**
package/src/run.ts CHANGED
@@ -20,6 +20,8 @@ export class PendingCut {
20
20
  this.preview = undefined;
21
21
  }
22
22
  clear() { this.proposal = undefined; this.preview = undefined; }
23
+ /** Puts the plan back after a check that read a preview session (a read from another session clears it). */
24
+ hold() { const proposal = this.proposal; return () => { this.proposal = proposal; this.preview = undefined; }; }
23
25
  take(ctx: Context) {
24
26
  if (!this.view(ctx).pending) return;
25
27
  const cut = this.proposal?.cut;
package/src/thrash.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
2
  import { isDiscardedResponse } from "./protocol";
3
+ import { cutEpochs } from "./epochs";
3
4
  import { pathKey } from "./path-key";
4
5
  import { isTextOnly, textOf } from "./tuck/core/content";
5
6
  import { extractPath } from "./tuck/core/tool-args";
@@ -18,14 +19,17 @@ export const THRASH_BAR = 0.5;
18
19
  export interface Rereads { cuts: number; rereads: number; tokens: number }
19
20
  /** The branch's cuts and the re-reads that followed them (as `thrashing` defines a re-read), with their text in tokens at 4 characters each. */
20
21
  export function rereadsAfterCuts(branch: readonly SessionEntry[]): Rereads {
21
- let cuts = 0, replies = 0, rereads = 0, chars = 0;
22
+ // Each reply counts under the cut it was sent with (epochs.ts), so the reply that first carries a cut opens that cut's window.
23
+ const { epoch, cuts } = cutEpochs(branch);
24
+ let current = 0, replies = 0, rereads = 0, chars = 0;
22
25
  const pending = new Map<string, { key: string; cut: number; soon: boolean }>(), last = new Map<string, { cut: number; text: string }>();
23
- for (const entry of branch) {
24
- if (entry.type === "compaction") { cuts++; replies = 0; continue; }
26
+ for (const [i, entry] of branch.entries()) {
25
27
  if (entry.type !== "message") continue;
26
28
  const message = entry.message;
27
29
  if (message.role === "assistant") {
28
30
  if (isDiscardedResponse(message)) continue;
31
+ if (epoch[i] !== current) { current = epoch[i]; replies = 0; }
32
+ const cuts = current;
29
33
  replies++;
30
34
  for (const block of message.content) {
31
35
  if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object") continue;