pi-tuck 1.11.2 → 1.12.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,28 @@
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.12.1]
7
+
8
+ ### Fixed
9
+
10
+ - The first user turn (the task statement) rides whole in every summary, the smallest one after a length retry included, so an
11
+ instruction past its opening line is no longer cut off after a few chained cuts. A first turn over 8,000 characters keeps its first
12
+ and last 4,000, with a `tuck_recall` locator for the rest. Below a 64k-token room the cap is one character per 8 tokens of room, so
13
+ a small window keeps room to cut.
14
+
15
+ ## [1.12.0]
16
+
17
+ ### Changed
18
+
19
+ - Reply cap: on a Chat Completions reasoning model, each request (other than the act-now turn) asks for at most twice the largest reply
20
+ this model wrote on the branch, finished or length-stopped, at least 32,768 tokens, and never more than `maxTokens` or what Pi sends.
21
+ A large `maxTokens` no longer needs a hand-set lower value. A thinking-only stop at this cap is a full-cap stop: the act-now turn
22
+ follows, and the stopped output raises the next cap. The `llamaContinuation` model keeps its configured cap.
23
+ - Thinking level: when Pi sends `reasoning_effort` only in the chat template arguments and the server lists thinking levels, pi-tuck
24
+ also sends it at the top level.
25
+ - Lean line: off for a model whose `models.json` input and cache-read prices are both 0. `cacheSensitiveModels` still turns it off for
26
+ any model.
27
+
6
28
  ## [1.11.2]
7
29
 
8
30
  ### Fixed
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.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.
15
+ This README describes pi-tuck 1.12.1. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.12.1` or `pi install git:github.com/galyavin/pi-tuck@v1.12.1`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
@@ -40,11 +40,11 @@ Pi-tuck needs a supported Pi version and a nonvirtual model with a valid context
40
40
 
41
41
  ## Long runs
42
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.
43
+ Three Pi agents worked for 72 hours on a hard research codebase, on one local model with a 272k window (later 230k). That came to 4,877 model requests and over 560M tokens of context.
44
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.
45
+ Each time an agent filled its window, pi-tuck cut it back with no model call: 23 times in all. After a cut, pi-tuck kept about 20k tokens of conversation; with the system prompt and tools, the context was about 40k. Every agent kept working after every cut.
46
46
 
47
- The run showed us a few rough edges, and later releases fixed them. We keep watching long runs like this one.
47
+ The run showed us a few rough edges; the [case study](docs/case-study-long-run.md) lists each one and what changed. We keep watching long runs like this one.
48
48
 
49
49
  ## Footer
50
50
 
@@ -66,7 +66,7 @@ Once per Pi start, in the background, pi-tuck reads the server's own model list
66
66
  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.
67
67
 
68
68
  - **`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`.
69
- - **`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.
69
+ - **`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. The lean line is also off, with no setting, for a model whose `models.json` input and cache-read prices are both 0 (a free or local model), where a carried token costs nothing.
70
70
  - **`footer`** set to `false` keeps Pi's own footer.
71
71
  - **`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.
72
72
 
@@ -83,7 +83,7 @@ Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by
83
83
 
84
84
  ## Output exhaustion and small windows
85
85
 
86
- - 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. On a Chat Completions model, that request alone goes out at the lowest thinking effort the server lists (pi-tuck reads the list at session start) and with at most 20,480 output tokens; a stop at that cap counts as a full-cap stop. 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.
86
+ - 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. On a Chat Completions model, that request alone goes out at the lowest thinking effort the server lists (pi-tuck reads the list at session start) and with at most 20,480 output tokens; a stop at that cap counts as a full-cap stop. 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. On a Chat Completions reasoning model, every other request asks for at most twice the largest reply this model has written on the branch (finished or length-stopped), at least 32,768 tokens and never more than `maxTokens` or what Pi sends, so a large `maxTokens` needs no hand-set lower value; a thinking-only stop at that cap takes the act-now path above, and its output raises the next cap. The continuation model (`llamaContinuation`) keeps its configured cap. When Pi sends a thinking level only inside the chat template arguments and the server lists thinking levels, pi-tuck also sends it at the top level, so no per-level sampling setting is needed.
87
87
  - 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.
88
88
  - 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.
89
89
 
@@ -134,6 +134,10 @@ See [Contributing](CONTRIBUTING.md) for stress tests and [the changelog](CHANGEL
134
134
 
135
135
  The [benchmark index](benchmark/README.md) records the models, versions, plans, and scope of each result.
136
136
 
137
+ ## Author
138
+
139
+ Rustem Galyavin · [galyavin.com](https://galyavin.com)
140
+
137
141
  ## Credits and license
138
142
 
139
143
  MIT. pi-tuck grew out of [pi-vcc](https://github.com/sting8k/pi-vcc) and includes code from [pi-blackhole](https://github.com/k0valik/pi-blackhole) and [Pi](https://github.com/earendil-works/pi). See [NOTICE](NOTICE).
@@ -1 +1 @@
1
- export declare const BUILD_ID = "af3354d4b75532f8a65d30e805ce634249fd18de42eb8988de21b51103e9acc2";
1
+ export declare const BUILD_ID = "ac0f5521dbcebddc66d89232ea3f21b9a914f51fa4ed281af9e9993f786b877e";
@@ -1 +1 @@
1
- export const BUILD_ID = "af3354d4b75532f8a65d30e805ce634249fd18de42eb8988de21b51103e9acc2";
1
+ export const BUILD_ID = "ac0f5521dbcebddc66d89232ea3f21b9a914f51fa4ed281af9e9993f786b877e";
@@ -4,6 +4,12 @@ export interface Clip {
4
4
  toolCallId: string;
5
5
  content: ToolResultMessage["content"];
6
6
  }
7
+ /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at. */
8
+ export declare const clipText: (text: string, keep: number, locator: {
9
+ entryId: string;
10
+ } | {
11
+ index: number;
12
+ }) => string;
7
13
  /** The budgets to offer a fresh round the room cannot hold whole, in the units the round and the mandatory input are counted in, tried in order.
8
14
  * The room is the provider's, so it is divided by the factor the provider's counts have been running at - the same conversion the planner's own
9
15
  * reserve makes (budget.ts) - before the input no cut can remove is taken out; counting the provider's room against an estimate asks the round for
package/dist/src/clip.js CHANGED
@@ -3,12 +3,14 @@ import { MAX_RECALL_CHARACTERS } from "./recall.js";
3
3
  /** The text `tuck_recall {entryId, offset}` reads from a text-only result; any other result is not clipped. */
4
4
  const textOf = (message) => message.content.every(block => block.type === "text")
5
5
  ? message.content.map(block => block.type === "text" ? block.text : "").join("\n") : undefined;
6
- const clipped = (text, keep, entryId) => {
6
+ /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at. */
7
+ export const clipText = (text, keep, locator) => {
7
8
  const head = Math.ceil(keep / 2), tail = keep - head;
8
- return [{ type: "text", text: text.slice(0, head) +
9
- `\n[pi-tuck: characters ${head}-${text.length - tail} of ${text.length} are not shown, to fit the context window; read them with ` +
10
- `tuck_recall {"entryId":"${entryId}","offset":${head}}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail) }];
9
+ return text.slice(0, head) +
10
+ `\n[pi-tuck: characters ${head}-${text.length - tail} of ${text.length} are not shown, to fit the context window; read them with ` +
11
+ `tuck_recall ${JSON.stringify({ ...locator, offset: head })}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail);
11
12
  };
13
+ const clipped = (text, keep, entryId) => [{ type: "text", text: clipText(text, keep, { entryId }) }];
12
14
  /** The budgets to offer a fresh round the room cannot hold whole, in the units the round and the mandatory input are counted in, tried in order.
13
15
  * The room is the provider's, so it is divided by the factor the provider's counts have been running at - the same conversion the planner's own
14
16
  * reserve makes (budget.ts) - before the input no cut can remove is taken out; counting the provider's room against an estimate asks the round for
@@ -20,6 +20,21 @@ export declare function actNowPayload(payload: unknown, effort: string | undefin
20
20
  payload: Record<string, unknown>;
21
21
  cap?: number;
22
22
  } | undefined;
23
+ /** Zero tuning (1.12.0): the reply cap a reasoning request asks for, never above what Pi sent. A reply this model wrote on the branch is
24
+ * evidence of the room it needs, so the cap is twice the largest one (finished or length-stopped), at least 32,768. A thinking-only stop at
25
+ * this cap takes the act-now path; its saved output then raises the next cap. Read from the log, so a restart or /tree keeps it. */
26
+ export declare const AUTO_CAP_FLOOR = 32768;
27
+ export declare function autoReplyCap(branch: readonly SessionEntry[], model: {
28
+ provider: string;
29
+ api: string;
30
+ id: string;
31
+ }): number;
32
+ /** Lower the reply cap fields to `cap` (when given) and copy a template-only reasoning effort to the top level (when the server listed
33
+ * efforts). `cap` in the result is set only when it lowered what Pi sent: a stop there is a full-cap stop. Undefined when nothing changes. */
34
+ export declare function zeroTuningPayload(payload: unknown, cap: number | undefined, mirrorEffort: boolean): {
35
+ payload: Record<string, unknown>;
36
+ cap?: number;
37
+ } | undefined;
23
38
  /** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
24
39
  * 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. */
25
40
  export declare function actNowsInARow(branch: readonly SessionEntry[]): number;
@@ -98,6 +98,48 @@ export function actNowPayload(payload, effort) {
98
98
  }
99
99
  return { payload: out, cap };
100
100
  }
101
+ /** Zero tuning (1.12.0): the reply cap a reasoning request asks for, never above what Pi sent. A reply this model wrote on the branch is
102
+ * evidence of the room it needs, so the cap is twice the largest one (finished or length-stopped), at least 32,768. A thinking-only stop at
103
+ * this cap takes the act-now path; its saved output then raises the next cap. Read from the log, so a restart or /tree keeps it. */
104
+ export const AUTO_CAP_FLOOR = 32_768;
105
+ export function autoReplyCap(branch, model) {
106
+ let largest = 0;
107
+ for (const entry of branch) {
108
+ if (entry.type !== "message" || entry.message.role !== "assistant")
109
+ continue;
110
+ const message = entry.message;
111
+ if (message.model !== model.id || message.provider !== model.provider || message.api !== model.api)
112
+ continue;
113
+ if (message.stopReason !== "stop" && message.stopReason !== "toolUse" && message.stopReason !== "length")
114
+ continue;
115
+ const output = message.usage?.output;
116
+ if (typeof output === "number" && Number.isFinite(output) && output > largest)
117
+ largest = output;
118
+ }
119
+ return Math.max(AUTO_CAP_FLOOR, Math.ceil(2 * largest));
120
+ }
121
+ /** Lower the reply cap fields to `cap` (when given) and copy a template-only reasoning effort to the top level (when the server listed
122
+ * efforts). `cap` in the result is set only when it lowered what Pi sent: a stop there is a full-cap stop. Undefined when nothing changes. */
123
+ export function zeroTuningPayload(payload, cap, mirrorEffort) {
124
+ const body = payload;
125
+ if (!body || typeof body !== "object" || !Array.isArray(body.messages))
126
+ return undefined;
127
+ const out = { ...body };
128
+ let changed = false, lowered;
129
+ if (cap !== undefined)
130
+ for (const field of ["max_tokens", "max_completion_tokens"]) {
131
+ if (typeof out[field] === "number" && out[field] > cap) {
132
+ out[field] = lowered = cap;
133
+ changed = true;
134
+ }
135
+ }
136
+ const kwargs = out.chat_template_kwargs;
137
+ if (mirrorEffort && out.reasoning_effort === undefined && kwargs && typeof kwargs === "object" && typeof kwargs.reasoning_effort === "string") {
138
+ out.reasoning_effort = kwargs.reasoning_effort;
139
+ changed = true;
140
+ }
141
+ return changed ? { payload: out, cap: lowered } : undefined;
142
+ }
101
143
  /** 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). */
102
144
  const ACT_NOW_LIMIT = 2;
103
145
  /** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
@@ -395,19 +437,30 @@ export async function installCompaction(pi, options = {}) {
395
437
  if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel)
396
438
  run?.rearmLengthRetry();
397
439
  };
398
- // The act-now request asks for a short act, so it goes out at the server's lowest effort with a smaller cap. The cap sent is kept: a stop
399
- // at it is a full-cap stop, not a squeezed one.
400
- let actNowCap;
440
+ // The act-now request asks for a short act, so it goes out at the server's lowest effort with a smaller cap. Other requests get the
441
+ // zero-tuning cap (reasoning models) and effort mirror. The cap pi-tuck set is kept: a stop at it is a full-cap stop, not a squeezed one.
442
+ // The continuation model keeps its configured cap: its continuation only follows a stop at exactly that cap.
443
+ let ownCap;
401
444
  pi.on("before_provider_request", async (event, ctx) => {
445
+ ownCap = undefined;
402
446
  const model = ctx.model;
403
- if (model?.api !== "openai-completions" || !actNowPayload(event.payload, undefined)) {
404
- actNowCap = undefined;
447
+ if (model?.api !== "openai-completions")
448
+ return undefined;
449
+ const body = event.payload;
450
+ if (body && typeof body === "object" && body.continue_final_message !== undefined)
405
451
  return undefined;
406
- }
407
452
  await pendingCheck;
408
- const rewritten = actNowPayload(event.payload, lowestEffort(serverEfforts.get(`${model.provider}/${model.id}`)));
409
- actNowCap = rewritten.cap;
410
- return rewritten.payload;
453
+ const efforts = serverEfforts.get(`${model.provider}/${model.id}`);
454
+ if (actNowPayload(event.payload, undefined)) {
455
+ const rewritten = actNowPayload(event.payload, lowestEffort(efforts));
456
+ ownCap = rewritten.cap;
457
+ return rewritten.payload;
458
+ }
459
+ const cap = model.reasoning && `${model.provider}/${model.id}` !== options.continuationModel
460
+ ? autoReplyCap(ctx.sessionManager.getBranch(), model) : undefined;
461
+ const rewritten = zeroTuningPayload(event.payload, cap, efforts !== undefined);
462
+ ownCap = rewritten?.cap;
463
+ return rewritten?.payload;
411
464
  });
412
465
  // The act-now turn is pi-tuck's own, not the operator's: it grants no retry.
413
466
  pi.on("message_start", (event, ctx) => { if (event.message.role === "user" && textOf(event.message.content) !== ACT_NOW)
@@ -494,10 +547,13 @@ export async function installCompaction(pi, options = {}) {
494
547
  };
495
548
  // 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
496
549
  // economic order quantity of the context, when that is below the line above. Never later than it, and admission is unchanged: a cut it
497
- // asks for is opportunistic, so one that cannot be planned is no cut. Off where the thrash line is off.
550
+ // asks for is opportunistic, so one that cannot be planned is no cut. Off where the thrash line is off, and on a free model (input and
551
+ // cache-read prices both 0, 1.12.0): there a held token costs nothing, so an early cut only spends prefill time.
498
552
  const leanLimit = (ctx) => {
499
553
  if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx))
500
554
  return undefined;
555
+ if (!ctx.model.cost?.input && !ctx.model.cost?.cacheRead)
556
+ return undefined;
501
557
  return leanLine(ctx.sessionManager.getBranch());
502
558
  };
503
559
  // A cut the lean line makes due inside the band is sized by that line, not by the tenth-of-the-room rule for opportunistic cuts.
@@ -1288,7 +1344,7 @@ export async function installCompaction(pi, options = {}) {
1288
1344
  if (event.message.role !== "assistant" || !ctx.model)
1289
1345
  return;
1290
1346
  const stoppedOutput = event.message.usage?.output;
1291
- if (stoppedOutput >= (actNowCap ?? ctx.model.maxTokens)) {
1347
+ if (stoppedOutput >= (ownCap ?? ctx.model.maxTokens)) {
1292
1348
  return { entries: event.entries, continue: false };
1293
1349
  }
1294
1350
  // Pi's supported boundary drafts commit before finishTurn honors `continue`. Omitting the selected failed response also prevents
@@ -34,6 +34,8 @@ export interface RecallContinuation {
34
34
  export declare const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
35
35
  /** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
36
36
  export declare const WORKING_SET_SHARE: number;
37
+ /** The first user turn (the task statement) rides whole in every summary up to this many characters, and no more characters than an eighth of the room's tokens (rooms below 64k); a longer one keeps its head and tail (1.12.1). */
38
+ export declare const FIRST_TURN_CHARACTERS = 8000;
37
39
  /** Deliberately narrow contract with the pinned pi-tuck source exports. No standalone hooks are installed. */
38
40
  export interface Tuck {
39
41
  buildOwnCut(entries: SessionEntry[], keep: number): Cut;
package/dist/src/tuck.js CHANGED
@@ -10,6 +10,7 @@ import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerI
10
10
  import { keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
11
11
  import { workingSetCandidates } from "./working-set.js";
12
12
  import { keptSearchCandidates } from "./kept-searches.js";
13
+ import { clipText } from "./clip.js";
13
14
  import { fileObservations, thinkingRecords } from "./content-observations.js";
14
15
  import { pathKey } from "./path-key.js";
15
16
  import { convertToLlm, SessionManager } from "@earendil-works/pi-coding-agent";
@@ -18,6 +19,8 @@ import { ATTEMPT_NOTICE, createRecall } from "./recall.js";
18
19
  export const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
19
20
  /** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
20
21
  export const WORKING_SET_SHARE = 2 / 3;
22
+ /** The first user turn (the task statement) rides whole in every summary up to this many characters, and no more characters than an eighth of the room's tokens (rooms below 64k); a longer one keeps its head and tail (1.12.1). */
23
+ export const FIRST_TURN_CHARACTERS = 8_000;
21
24
  import { buildOwnCut, applyTailBudget, MAX_TAIL_TOKENS, OVERSIZED_TAIL_FACTOR } from "./tuck/cut.js";
22
25
  import { calibrateCharsPerToken, estimateSourceMessageChars } from "./tuck/core/token-estimate.js";
23
26
  import { buildGlobalIndexById } from "./tuck/core/global-indices.js";
@@ -162,6 +165,8 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
162
165
  throw new Error("Missing native session header");
163
166
  const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
164
167
  const minimumOpeningLength = 80, openingLength = Math.max(80, Math.floor(Math.sqrt(room * 4)));
168
+ // At most about a thirty-second of the room in tokens, so a small window keeps its cut room (1.12.1).
169
+ const firstTurnCap = Math.min(FIRST_TURN_CHARACTERS, Math.floor(room / 8));
165
170
  const positions = new Map(entries.map((entry, at) => [entry.id, at]));
166
171
  const originals = tuck.buildOwnCut(entries.filter(entry => entry.type !== "compaction"), 0);
167
172
  if (!originals.ok)
@@ -259,6 +264,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
259
264
  list.forEach((unit, at) => count[at + 1] = count[at] + unit.count);
260
265
  return [role, { end, count }];
261
266
  }));
267
+ const shorter = (a, b) => a.length < b.length ? a : b;
262
268
  const quoteCache = new Map();
263
269
  const quote = (entry, take) => {
264
270
  const key = `${entry.id}:${take}`;
@@ -269,11 +275,14 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
269
275
  const text = entry.type === "custom_message" ? textOf(entry.content) : entry.type === "message" && entry.message.role === "user" ? textOf(entry.message.content) : "";
270
276
  const sourceTimes = index === undefined ? undefined : [{ sourceIndex: index, ...resolveSourceTime(entry) }];
271
277
  // Custom entries have a native identity but no global message index.
272
- const records = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity
273
- ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }), text, sourceTimes,
278
+ // The first user turn as an anchor: whole up to its cap, else its head and tail (1.12.1). A protected input stays whole.
279
+ const firstTurn = entry.id === firstUser?.id && take === firstTurnCap;
280
+ const records = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity || firstTurn
281
+ ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }),
282
+ text: firstTurn && text.length > take ? shorter(clipText(text, take, { index: index }), text) : text, sourceTimes,
274
283
  ...(entry.type === "custom_message" ? { sourceEntryId: entry.id } : {}) }]
275
284
  : userPrefixRecords({ kind: "user", text, originalText: text, startsSource: true, sourceIndex: index }, undefined, take).map(record => ({ ...record, sourceTimes }));
276
- cached = { records, cost: lineCost(records), whole: take >= text.length };
285
+ cached = { records, cost: lineCost(records), whole: take >= text.length || firstTurn && records[0]?.text === text };
277
286
  quoteCache.set(key, cached);
278
287
  return cached;
279
288
  };
@@ -296,7 +305,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
296
305
  add(current, Infinity);
297
306
  for (const entry of anchors)
298
307
  if (entry.id !== latest?.id && entry.id !== current?.id && positions.get(entry.id) < boundary)
299
- add(entry, length);
308
+ add(entry, entry.id === firstUser?.id ? firstTurnCap : length);
300
309
  const omissions = [];
301
310
  for (const role of ["user", "assistant", "toolResult"]) {
302
311
  const list = units[role], prefix = prefixes[role];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.11.2",
3
+ "version": "1.12.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 = "af3354d4b75532f8a65d30e805ce634249fd18de42eb8988de21b51103e9acc2";
1
+ export const BUILD_ID = "ac0f5521dbcebddc66d89232ea3f21b9a914f51fa4ed281af9e9993f786b877e";
package/src/clip.ts CHANGED
@@ -9,13 +9,16 @@ export interface Clip { toolCallId: string; content: ToolResultMessage["content"
9
9
  const textOf = (message: ToolResultMessage) => message.content.every(block => block.type === "text")
10
10
  ? message.content.map(block => block.type === "text" ? block.text : "").join("\n") : undefined;
11
11
 
12
- const clipped = (text: string, keep: number, entryId: string): ToolResultMessage["content"] => {
12
+ /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at. */
13
+ export const clipText = (text: string, keep: number, locator: { entryId: string } | { index: number }): string => {
13
14
  const head = Math.ceil(keep / 2), tail = keep - head;
14
- return [{ type: "text", text: text.slice(0, head) +
15
+ return text.slice(0, head) +
15
16
  `\n[pi-tuck: characters ${head}-${text.length - tail} of ${text.length} are not shown, to fit the context window; read them with ` +
16
- `tuck_recall {"entryId":"${entryId}","offset":${head}}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail) }];
17
+ `tuck_recall ${JSON.stringify({ ...locator, offset: head })}, up to ${MAX_RECALL_CHARACTERS} characters a call]\n` + text.slice(text.length - tail);
17
18
  };
18
19
 
20
+ const clipped = (text: string, keep: number, entryId: string): ToolResultMessage["content"] => [{ type: "text", text: clipText(text, keep, { entryId }) }];
21
+
19
22
  /** The budgets to offer a fresh round the room cannot hold whole, in the units the round and the mandatory input are counted in, tried in order.
20
23
  * The room is the provider's, so it is divided by the factor the provider's counts have been running at - the same conversion the planner's own
21
24
  * reserve makes (budget.ts) - before the input no cut can remove is taken out; counting the provider's room against an estimate asks the round for
package/src/compaction.ts CHANGED
@@ -97,6 +97,38 @@ export function actNowPayload(payload: unknown, effort: string | undefined): { p
97
97
  }
98
98
  return { payload: out, cap };
99
99
  }
100
+ /** Zero tuning (1.12.0): the reply cap a reasoning request asks for, never above what Pi sent. A reply this model wrote on the branch is
101
+ * evidence of the room it needs, so the cap is twice the largest one (finished or length-stopped), at least 32,768. A thinking-only stop at
102
+ * this cap takes the act-now path; its saved output then raises the next cap. Read from the log, so a restart or /tree keeps it. */
103
+ export const AUTO_CAP_FLOOR = 32_768;
104
+ export function autoReplyCap(branch: readonly SessionEntry[], model: { provider: string; api: string; id: string }): number {
105
+ let largest = 0;
106
+ for (const entry of branch) {
107
+ if (entry.type !== "message" || entry.message.role !== "assistant") continue;
108
+ const message = entry.message;
109
+ if (message.model !== model.id || message.provider !== model.provider || message.api !== model.api) continue;
110
+ if (message.stopReason !== "stop" && message.stopReason !== "toolUse" && message.stopReason !== "length") continue;
111
+ const output = message.usage?.output;
112
+ if (typeof output === "number" && Number.isFinite(output) && output > largest) largest = output;
113
+ }
114
+ return Math.max(AUTO_CAP_FLOOR, Math.ceil(2 * largest));
115
+ }
116
+ /** Lower the reply cap fields to `cap` (when given) and copy a template-only reasoning effort to the top level (when the server listed
117
+ * efforts). `cap` in the result is set only when it lowered what Pi sent: a stop there is a full-cap stop. Undefined when nothing changes. */
118
+ export function zeroTuningPayload(payload: unknown, cap: number | undefined, mirrorEffort: boolean): { payload: Record<string, unknown>; cap?: number } | undefined {
119
+ const body = payload as Record<string, unknown> | null;
120
+ if (!body || typeof body !== "object" || !Array.isArray(body.messages)) return undefined;
121
+ const out: Record<string, unknown> = { ...body };
122
+ let changed = false, lowered: number | undefined;
123
+ if (cap !== undefined) for (const field of ["max_tokens", "max_completion_tokens"]) {
124
+ if (typeof out[field] === "number" && (out[field] as number) > cap) { out[field] = lowered = cap; changed = true; }
125
+ }
126
+ const kwargs = out.chat_template_kwargs as Record<string, unknown> | undefined;
127
+ if (mirrorEffort && out.reasoning_effort === undefined && kwargs && typeof kwargs === "object" && typeof kwargs.reasoning_effort === "string") {
128
+ out.reasoning_effort = kwargs.reasoning_effort; changed = true;
129
+ }
130
+ return changed ? { payload: out, cap: lowered } : undefined;
131
+ }
100
132
  /** 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). */
101
133
  const ACT_NOW_LIMIT = 2;
102
134
  /** Act-now turns on the branch since its last finished reply (stopReason "stop" or "toolUse"). Read from the log, so a restart, /tree
@@ -367,16 +399,28 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
367
399
  const rearmLengthRetry = (ctx: ExtensionContext) => {
368
400
  if (ctx.model && `${ctx.model.provider}/${ctx.model.id}` !== options.continuationModel) run?.rearmLengthRetry();
369
401
  };
370
- // The act-now request asks for a short act, so it goes out at the server's lowest effort with a smaller cap. The cap sent is kept: a stop
371
- // at it is a full-cap stop, not a squeezed one.
372
- let actNowCap: number | undefined;
402
+ // The act-now request asks for a short act, so it goes out at the server's lowest effort with a smaller cap. Other requests get the
403
+ // zero-tuning cap (reasoning models) and effort mirror. The cap pi-tuck set is kept: a stop at it is a full-cap stop, not a squeezed one.
404
+ // The continuation model keeps its configured cap: its continuation only follows a stop at exactly that cap.
405
+ let ownCap: number | undefined;
373
406
  pi.on("before_provider_request", async (event, ctx) => {
407
+ ownCap = undefined;
374
408
  const model = ctx.model;
375
- if (model?.api !== "openai-completions" || !actNowPayload(event.payload, undefined)) { actNowCap = undefined; return undefined; }
409
+ if (model?.api !== "openai-completions") return undefined;
410
+ const body = event.payload as Record<string, unknown> | null;
411
+ if (body && typeof body === "object" && body.continue_final_message !== undefined) return undefined;
376
412
  await pendingCheck;
377
- const rewritten = actNowPayload(event.payload, lowestEffort(serverEfforts.get(`${model.provider}/${model.id}`)))!;
378
- actNowCap = rewritten.cap;
379
- return rewritten.payload;
413
+ const efforts = serverEfforts.get(`${model.provider}/${model.id}`);
414
+ if (actNowPayload(event.payload, undefined)) {
415
+ const rewritten = actNowPayload(event.payload, lowestEffort(efforts))!;
416
+ ownCap = rewritten.cap;
417
+ return rewritten.payload;
418
+ }
419
+ const cap = model.reasoning && `${model.provider}/${model.id}` !== options.continuationModel
420
+ ? autoReplyCap(ctx.sessionManager.getBranch(), model) : undefined;
421
+ const rewritten = zeroTuningPayload(event.payload, cap, efforts !== undefined);
422
+ ownCap = rewritten?.cap;
423
+ return rewritten?.payload;
380
424
  });
381
425
  // The act-now turn is pi-tuck's own, not the operator's: it grants no retry.
382
426
  pi.on("message_start", (event, ctx) => { if (event.message.role === "user" && textOf(event.message.content) !== ACT_NOW) rearmLengthRetry(ctx); });
@@ -454,9 +498,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
454
498
  };
455
499
  // 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
456
500
  // economic order quantity of the context, when that is below the line above. Never later than it, and admission is unchanged: a cut it
457
- // asks for is opportunistic, so one that cannot be planned is no cut. Off where the thrash line is off.
501
+ // asks for is opportunistic, so one that cannot be planned is no cut. Off where the thrash line is off, and on a free model (input and
502
+ // cache-read prices both 0, 1.12.0): there a held token costs nothing, so an early cut only spends prefill time.
458
503
  const leanLimit = (ctx: ExtensionContext): number | undefined => {
459
504
  if (options.cutAt !== undefined || options.requestReserve || !ctx.model || preservePrefix(ctx)) return undefined;
505
+ if (!ctx.model.cost?.input && !ctx.model.cost?.cacheRead) return undefined;
460
506
  return leanLine(ctx.sessionManager.getBranch());
461
507
  };
462
508
  // A cut the lean line makes due inside the band is sized by that line, not by the tenth-of-the-room rule for opportunistic cuts.
@@ -1139,7 +1185,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1139
1185
  // Native Pi does not compact-and-retry output that reached the catalogue cap.
1140
1186
  if (event.message.role !== "assistant" || !ctx.model) return;
1141
1187
  const stoppedOutput = event.message.usage?.output;
1142
- if (stoppedOutput >= (actNowCap ?? ctx.model.maxTokens)) {
1188
+ if (stoppedOutput >= (ownCap ?? ctx.model.maxTokens)) {
1143
1189
  return { entries: event.entries, continue: false };
1144
1190
  }
1145
1191
  // Pi's supported boundary drafts commit before finishTurn honors `continue`. Omitting the selected failed response also prevents
package/src/tuck.ts CHANGED
@@ -10,6 +10,7 @@ import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerI
10
10
  import { keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
11
11
  import { workingSetCandidates, type WorkingFile } from "./working-set.js";
12
12
  import { keptSearchCandidates } from "./kept-searches.js";
13
+ import { clipText } from "./clip.js";
13
14
  import { fileObservations, thinkingRecords } from "./content-observations";
14
15
  import { pathKey } from "./path-key";
15
16
  import { convertToLlm, SessionManager, type ExtensionContext,
@@ -34,6 +35,8 @@ export interface RecallContinuation { query: string; throughEntryId: string; off
34
35
  export const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
35
36
  /** The share of the summary's own allowance (beyond protected prompts) that the working set may take. */
36
37
  export const WORKING_SET_SHARE = 2 / 3;
38
+ /** The first user turn (the task statement) rides whole in every summary up to this many characters, and no more characters than an eighth of the room's tokens (rooms below 64k); a longer one keeps its head and tail (1.12.1). */
39
+ export const FIRST_TURN_CHARACTERS = 8_000;
37
40
  /** Deliberately narrow contract with the pinned pi-tuck source exports. No standalone hooks are installed. */
38
41
  export interface Tuck {
39
42
  buildOwnCut(entries: SessionEntry[], keep: number): Cut;
@@ -181,6 +184,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
181
184
  if (!header) throw new Error("Missing native session header");
182
185
  const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
183
186
  const minimumOpeningLength = 80, openingLength = Math.max(80, Math.floor(Math.sqrt(room * 4)));
187
+ // At most about a thirty-second of the room in tokens, so a small window keeps its cut room (1.12.1).
188
+ const firstTurnCap = Math.min(FIRST_TURN_CHARACTERS, Math.floor(room / 8));
184
189
  const positions = new Map(entries.map((entry, at) => [entry.id, at]));
185
190
  const originals = tuck.buildOwnCut(entries.filter(entry => entry.type !== "compaction"), 0);
186
191
  if (!originals.ok) return { unavailable: "No eligible original prefix to compile" };
@@ -263,6 +268,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
263
268
  list.forEach((unit, at) => count[at + 1] = count[at]! + unit.count);
264
269
  return [role, { end, count }];
265
270
  })) as Record<keyof typeof units, { end: Int32Array; count: Int32Array }>;
271
+ const shorter = (a: string, b: string) => a.length < b.length ? a : b;
266
272
  const quoteCache = new Map<string, { records: TranscriptRecord[]; cost: number; whole: boolean }>();
267
273
  const quote = (entry: SessionEntry, take: number) => {
268
274
  const key = `${entry.id}:${take}`;
@@ -272,11 +278,14 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
272
278
  const text = entry.type === "custom_message" ? textOf(entry.content) : entry.type === "message" && entry.message.role === "user" ? textOf(entry.message.content) : "";
273
279
  const sourceTimes = index === undefined ? undefined : [{ sourceIndex: index, ...resolveSourceTime(entry) }];
274
280
  // Custom entries have a native identity but no global message index.
275
- const records: TranscriptRecord[] = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity
276
- ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }), text, sourceTimes,
281
+ // The first user turn as an anchor: whole up to its cap, else its head and tail (1.12.1). A protected input stays whole.
282
+ const firstTurn = entry.id === firstUser?.id && take === firstTurnCap;
283
+ const records: TranscriptRecord[] = index === undefined && entry.type !== "custom_message" ? [] : take === Infinity || firstTurn
284
+ ? [{ kind: "excerpt", role: entry.type === "custom_message" ? "custom" : "user", ...(index === undefined ? {} : { sourceIndex: index }),
285
+ text: firstTurn && text.length > take ? shorter(clipText(text, take, { index: index! }), text) : text, sourceTimes,
277
286
  ...(entry.type === "custom_message" ? { sourceEntryId: entry.id } : {}) }]
278
287
  : userPrefixRecords({ kind: "user", text, originalText: text, startsSource: true, sourceIndex: index }, undefined, take).map(record => ({ ...record, sourceTimes }));
279
- cached = { records, cost: lineCost(records), whole: take >= text.length };
288
+ cached = { records, cost: lineCost(records), whole: take >= text.length || firstTurn && records[0]?.text === text };
280
289
  quoteCache.set(key, cached);
281
290
  return cached;
282
291
  };
@@ -290,7 +299,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
290
299
  };
291
300
  if (latestPosition >= 0 && latestPosition < boundary && latestTextOnly) add(latest!, Infinity);
292
301
  if (currentPosition >= 0 && currentPosition < boundary && current?.id !== latest?.id) add(current!, Infinity);
293
- for (const entry of anchors) if (entry.id !== latest?.id && entry.id !== current?.id && positions.get(entry.id)! < boundary) add(entry, length);
302
+ for (const entry of anchors) if (entry.id !== latest?.id && entry.id !== current?.id && positions.get(entry.id)! < boundary) add(entry, entry.id === firstUser?.id ? firstTurnCap : length);
294
303
  const omissions: TranscriptRecord[] = [];
295
304
  for (const role of ["user", "assistant", "toolResult"] as const) {
296
305
  const list = units[role], prefix = prefixes[role];