pi-tuck 1.3.4 → 1.4.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +58 -125
  3. package/dist/index.d.ts +1 -4
  4. package/dist/index.js +49 -10
  5. package/dist/src/budget.d.ts +6 -15
  6. package/dist/src/budget.js +6 -11
  7. package/dist/src/build-id.d.ts +1 -1
  8. package/dist/src/build-id.js +1 -1
  9. package/dist/src/compaction.d.ts +12 -20
  10. package/dist/src/compaction.js +220 -202
  11. package/dist/src/content-observations.d.ts +24 -0
  12. package/dist/src/content-observations.js +122 -0
  13. package/dist/src/diagnostics.d.ts +1 -3
  14. package/dist/src/ledger.d.ts +6 -3
  15. package/dist/src/ledger.js +14 -7
  16. package/dist/src/llama-continuation.d.ts +8 -0
  17. package/dist/src/llama-continuation.js +179 -0
  18. package/dist/src/recall.js +8 -25
  19. package/dist/src/request-capacity.d.ts +11 -26
  20. package/dist/src/request-capacity.js +20 -57
  21. package/dist/src/run.d.ts +16 -7
  22. package/dist/src/run.js +53 -25
  23. package/dist/src/status.d.ts +2 -0
  24. package/dist/src/status.js +6 -5
  25. package/dist/src/tuck/core/format.js +1 -1
  26. package/dist/src/tuck/core/readable-content.d.ts +14 -0
  27. package/dist/src/tuck/core/readable-content.js +43 -0
  28. package/dist/src/tuck.d.ts +2 -1
  29. package/dist/src/tuck.js +92 -30
  30. package/index.ts +42 -10
  31. package/package.json +1 -1
  32. package/src/budget.ts +7 -12
  33. package/src/build-id.ts +1 -1
  34. package/src/compaction.ts +220 -193
  35. package/src/content-observations.ts +115 -0
  36. package/src/diagnostics.ts +1 -1
  37. package/src/ledger.ts +17 -10
  38. package/src/llama-continuation.ts +176 -0
  39. package/src/recall.ts +8 -20
  40. package/src/request-capacity.ts +18 -57
  41. package/src/run.ts +48 -22
  42. package/src/status.ts +8 -5
  43. package/src/tuck/core/format.ts +1 -1
  44. package/src/tuck/core/readable-content.ts +44 -0
  45. package/src/tuck.ts +79 -28
package/CHANGELOG.md CHANGED
@@ -3,6 +3,39 @@
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.4.1]
7
+
8
+ ### Fixed
9
+
10
+ - The release workflow fetches full history, so the Part 6 reference test runs before publishing. 1.4.0 was tagged but never
11
+ published; 1.4.1 ships the same code.
12
+
13
+ ## [1.4.0]
14
+
15
+ ### Added
16
+
17
+ - Content lane: kept output, definition maps and plain-text thinking openings rank below kept reads and searches in the summary.
18
+
19
+ ### Changed
20
+
21
+ - Post-cut headroom: cut at the room by default, and carry no more native history than Pi keeps. The adaptive cut point is gone.
22
+
23
+ - Use Pi's reserve as the cut target and replace the fixed reply floor with observed output for the active model. Observed reply demand stays within the reserve and the model's output limit.
24
+ - A cut above the room aims to leave 3,584 reply tokens, within the reserve and the model's output limit. Where no cut can, the request goes
25
+ out as before.
26
+ - Allow selected local models to defer early cuts.
27
+ - Support bounded native llama.cpp continuation for an explicitly configured and verified provider.
28
+
29
+ ### Fixed
30
+
31
+ - Preserve reasoning-only output exhaustion at the model's output limit. Below it, retry once, re-armed as Pi's overflow recovery is, and uncut
32
+ when a cut adds no reply room. A model with llama.cpp continuation retries at most once per run, and only when a cut increases the estimated
33
+ reply cap.
34
+ - Require standalone overflow recovery cuts to lower estimated input and combined request size when the failed request has a paired estimate.
35
+ - Stop inferring a smaller context window from an ambiguous length stop. Windows inferred by earlier versions no longer constrain requests.
36
+ - Reject invalid run transitions and discard pending cuts when their branch or model budget changes.
37
+ - Keep valid settings active when another field in `pi-tuck.json` is invalid.
38
+
6
39
  ## [1.3.4] - 2026-11-20
7
40
 
8
41
  ### Fixed
package/README.md CHANGED
@@ -1,154 +1,75 @@
1
1
  # pi-tuck
2
2
 
3
- pi-tuck is an extension for [Pi](https://pi.dev). It writes Pi's compaction summary from the session itself, with no model call. In our 128k live run, a cut took a median 0.08 s (pi-tuck 1.0.1). A cut costs no tokens. The same session always gives the same summary. The agent can read back any earlier message or tool result, word for word.
3
+ pi-tuck is an extension for [Pi](https://pi.dev). It builds deterministic compaction summaries from the saved session without calling a model. After a cut, the agent can look up original text and tool results on the current branch.
4
+
5
+ ## Install
6
+
7
+ Use Pi 1.2.0 or later and Node.js 22.19.0 or later on macOS, Linux, or Windows.
4
8
 
5
9
  ```sh
6
10
  pi install npm:pi-tuck
7
11
  ```
8
12
 
9
- Words used on this page:
10
-
11
- - **Window**: the tokens the model accepts in one request.
12
- - **Reply reserve**: the tokens Pi keeps free for the reply (`compaction.reserveTokens`, default 16,384).
13
- - **Room**: the window less the reply reserve.
14
- - **Cut**: the replacement of older turns with one summary.
15
- - **Recall**: the agent's way to read back what a cut removed (`tuck_recall`).
16
-
17
- ## How pi-tuck compares with Pi's built-in compaction
18
-
19
- Pi's built-in compaction asks a model to write the summary. pi-tuck builds it from the session. The 128k rows compare pi-tuck 1.0.1 with Pi 1.4.0's built-in compaction, with a local model writing the built-in summary. The 32k row is a different run, described below.
20
-
21
- | | Pi's built-in | pi-tuck |
22
- |---|---|---|
23
- | Model call per cut | One | None |
24
- | Time per cut (median) | 235 s | 0.08 s |
25
- | Context carried after a cut | 27,750 tokens | 26,790 tokens |
26
- | Same session, same summary | Not guaranteed | Yes |
27
- | Can the summary invent history | It can, since a model writes it | No, it holds only recorded text |
28
- | What the summary leaves out | Whatever the model dropped | Tool output only |
29
- | Can the agent read back cut detail | No recall tool | Yes, with `tuck_recall` |
30
- | Facts asked back after a cut, 128k window | From the summary alone | Not more than 3 points below Pi's summary (cuts 1 to 4 only; claim below) |
31
- | Tasks resolved, 128k window, 300 per arm | 251 | 258 (claim: no loss larger than 0.4 points) |
32
- | Tasks resolved, 32k window, 150 per arm | 94 | 120 (+17.3 points, 95% lower bound +10.7) |
33
-
34
- What these numbers cover:
35
-
36
- - **Time, context and 128k tasks.** One live run of pi-tuck 1.0.1: 10 chains of 30 SWE-bench Verified tasks, window 128,000. A local model wrote the built-in summaries. The medians come from 46 pi-tuck cuts and 48 built-in cuts. The pi-tuck time is an upper bound, read from the session file.
37
- - **Retention.** The claim, as [`benchmark/RESULTS-MAIN.md`](benchmark/RESULTS-MAIN.md) words it: **pi-tuck, answering with its recall tools, retains probed facts at a rate not more than 3 points below that of "Pi's compaction prompts on mac-studio/main:xhigh" (20 recordings) or of "Pi's compaction prompts on GPT-6.1 Terra" (19 of 20 recordings, s09-A missing), each answering from its summary alone, on these probes.** The test compares pi-tuck with its recall tool against Pi's summary alone. It does not compare summary with summary. Every probe was a mechanical fact: files changed, test result, required tag, error class or the session's result-line rule. The numbers cover cuts 1 to 4 only, because 52 of pi-tuck's 95 answer sets in the replay ended in an abort. This README makes no retention claim past cut 4.
38
- - **128k tasks.** The claim is only "no loss larger than 0.4 points". Chain s09 decides it: Pi's compaction failed 44 times there. Without s09 the lower bound is −0.4 points. With it, the bound is +0.3.
39
- - **32k tasks.** One model (DeepSeek V4.1 Flash), one window, pi-tuck 1.0.5. Only pi-tuck was held to the 16,384-token room: Pi's built-in compaction sent a request over it in 97 of 150 tasks. Observation masking, a third approach, resolved 117 (pi-tuck +2.0 points, lower bound −2.7: no difference shown). The pi-tuck arm had 1 dead task, so it missed its pre-registered bar of zero by one task.
40
- - **All results.** They come from SWE-bench-style tasks and may not carry to your work.
41
-
42
- This README does not say that pi-tuck is as good as or better than any compactor, model, window or kind of task other than those named. It never calls pi-tuck "the best LLM compactor". The plans were written before any result. Every plan and result, including those that did not favour pi-tuck, is in [`benchmark/`](benchmark) (index: [`benchmark/README.md`](benchmark/README.md)).
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.
43
14
 
44
- ## Install
45
-
46
- Run the command at the top, then start a new Pi session. pi-tuck takes over automatic compaction and `/compact`. You change no setting. pi-tuck downloads nothing.
47
-
48
- - Use Pi 1.2.0 or later (tested on 1.2.0 and 1.4.0), on macOS, Linux or Windows. Windows works since 1.2.0 (tested on Windows 10 with Node 24 and Pi 1.5.2).
49
- - On an older Pi, pi-tuck stays off, Pi's own compaction runs, and pi-tuck says so once.
50
- - To install from GitHub, run `pi install git:github.com/galyavin/pi-tuck@v1.3.4`.
51
- - To pin a version, run `pi install npm:pi-tuck@1.3.4`.
52
- - Restart an open Pi session after an update. It keeps the build it started with.
15
+ This README describes pi-tuck 1.4.1. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.4.1` or `pi install git:github.com/galyavin/pi-tuck@v1.4.1`. To uninstall, run `pi remove` with the source you installed.
53
16
 
54
- ## Ask your history
17
+ ## Compaction and recall
55
18
 
56
- A summary cannot hold everything, so pi-tuck lets the agent look things up. Say you fixed a login bug two hours ago, and the summary no longer holds the details. You ask:
19
+ A cut replaces older turns in the model's context with a summary while keeping the original entries in the session. The summary prioritizes the current prompt, recent turns, excerpts from earlier prompts, and pointers to files and tool actions. It can also carry recent reads and searches when the session records no action that could have changed their files. The recorded text is historical evidence about the session. Re-read a file before editing it.
57
20
 
58
- > "What was the reason we dropped the retry on the token refresh?"
59
-
60
- The agent searches its history by keyword with `tuck_recall`:
21
+ When pi-tuck is active, `tuck_recall` becomes available after a cut on the current branch. Use a keyword query to locate a passage.
61
22
 
62
23
  ```json
63
24
  { "query": "retry token refresh" }
64
25
  ```
65
26
 
66
- It gets ranked passages with a pointer such as `#212`. It reads the whole message, exactly as written:
67
-
68
- ```json
69
- { "index": 212 }
70
- ```
71
-
72
- The agent answers from the original text. This example is an illustration, not a recorded session. Keyword recall finds only the words that the original message contains.
73
-
74
- ## How it works
75
-
76
- When the context passes the cut point, pi-tuck replaces the older turns with one summary. The summary keeps:
27
+ Read the original by the hit's `entryId`, or use `{"index": 212}` to follow a `#212` reference in the summary. Pass a search result's `next` value as `continuation` to get the next page. Page long sources with `offset` and `limit` in UTF-16 characters. Use `outputPath` with an `entryId` or `index` to export eligible text through Pi's `write` tool. Recall excludes hidden reasoning and system records.
77
28
 
78
- - your current prompt, whole;
79
- - the start of your first prompt and of your recent prompts;
80
- - the newest turns, as they were;
81
- - the files the agent read, wrote or edited (up to 60), each with a pointer;
82
- - **kept reads**: up to 4 whole reads of files that did not change since;
83
- - **kept searches**: the latest `grep` or `rg` output of each command (up to 4), under the same rules;
84
- - an action trail: the agent's other tool calls (up to 30), without their output, each with a pointer.
85
-
86
- A later write or edit, a shell command that is not read-only and names the file, or a git `checkout`, `stash`, `restore` or `reset` drops a kept read or search. A search that pi-tuck cannot classify is never kept. The header of a kept read says only that no write or edit was recorded since. It does not prove that the file on disk is unchanged.
87
-
88
- Whatever does not fit is counted. `tuck_recall` reads it back by index range. Tool output stays in the session file. Each summary ends with a short instruction to the agent: re-read a file before you edit it, look things up, and treat anything not shown as unknown.
89
-
90
- The summary is plain text, one line per record, such as `#12 user @2026-10-30T14:00:00Z: text`. The number is the index that `tuck_recall` takes.
91
-
92
- `tuck_recall` finds earlier text by keyword. It reads any original message or tool result by index. It can write an original out to a file. The tool appears only after the first cut. Before that, a request is the same as one without pi-tuck.
93
-
94
- | Command | Does |
29
+ | Command | Purpose |
95
30
  |---|---|
96
- | `/tuck` | Shows the loaded version, the cuts so far, the cut point and, if pi-tuck is not acting, why. |
97
- | `/tuck-incident on\|next\|off\|status` | Records this session's compaction decisions to a file that you can attach to a bug report. |
31
+ | `/compact` | Request a cut. pi-tuck builds the summary from the session and ignores any appended instructions. |
32
+ | `/tuck` | Inspect the loaded version, saved cuts, and cut point. |
33
+ | `/tuck-incident on\|next\|off\|status` | Control diagnostic recording. The default directory is `~/.local/state/pi-tuck-incidents`. |
98
34
 
99
- pi-tuck stands down to native Pi when it cannot work safely: the window is unknown, the model is a Pi virtual model, or Pi's auto-compaction is off. Pi then does what it does without pi-tuck, and `/tuck` says `standing down:` with the reason. With no UI (`pi -p`, JSON runs), refusal, overflow and manual-cut notices go to stderr.
100
-
101
- `/compact` works as usual. Text after it does not steer the summary. pi-tuck cuts as plain `/compact` does and says it did not use the text. Pi's setting `"compaction": { "enabled": false }` turns compaction off.
35
+ 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.
102
36
 
103
37
  ## Settings
104
38
 
105
- pi-tuck needs no setting. One is optional. Put it in `pi-tuck.json` in Pi's agent folder (`~/.pi/agent`, or the folder that `PI_CODING_AGENT_DIR` names):
39
+ 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.
40
+
41
+ - **`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`.
42
+ - **`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.
43
+ - **`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.
106
44
 
107
45
  ```json
108
- { "cutAt": 0.8 }
46
+ {
47
+ "cacheSensitiveModels": ["my-provider/my-model"],
48
+ "llamaContinuation": {
49
+ "model": "my-provider/my-model",
50
+ "extraTokens": 4096,
51
+ "deadlineMs": 5400000
52
+ }
53
+ }
109
54
  ```
110
55
 
111
- - If you do not set `cutAt`, the cut point adapts to the session. It stays between 60% of the room and just under the room.
112
- - A number above 0 and at most 1 fixes the cut point as a share of the room. `1` cuts at the full room.
113
- - If the file is bad, pi-tuck says so at session start and uses the defaults.
114
-
115
- ## Small windows
56
+ ## Output exhaustion and small windows
116
57
 
117
- - pi-tuck keeps the same reply room as native Pi (`reserveTokens`).
118
- - After a reply that stops for length with thinking only, pi-tuck retries the turn once.
119
- - When a run ends on a reply cut at the output limit, pi-tuck says so.
120
- - When a server clips replies below the window, pi-tuck learns the smaller window. It drops that window when the model's window changes.
121
- - pi-tuck refuses a request only past the window. The refusal names what does not fit.
58
+ - 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.
59
+ - 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.
60
+ - 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.
122
61
 
123
- If a small window refuses, use a larger window. With OpenRouter, you can also pin one upstream. Add this to `models.json` in Pi's agent folder, and name the upstream:
62
+ When using OpenRouter, you can pin an upstream in Pi's `models.json` if upstreams count context differently.
124
63
 
125
64
  ```json
126
65
  { "providers": { "openrouter": { "compat": { "openRouterRouting": { "only": ["your-upstream"], "allow_fallbacks": false } } } } }
127
66
  ```
128
67
 
129
- The details are in [`docs/small-windows.md`](docs/small-windows.md).
130
-
131
- ## Known limits
132
-
133
- - The summary holds the words that were said, not why. The agent must look things up, and each look-up costs a tool call.
134
- - A very large fixed setup in a small window keeps cuts frequent, and each frees little. Example: 40k of system prompt and tools at a 65,536 window.
135
- - Between the room and the window, the reply reserve does not cushion a wrong token count. At a cold start, an undercount can reach the provider. A provider that errors is learned from. A server that truncates silently truncates, as it does for native Pi.
136
- - pi-tuck learns from a provider refusal only when Pi classes it as a context overflow. After a refusal in another wording, or a bare HTTP 413, pi-tuck does not recover. The session stays intact. Every prompt can fail until the request shrinks. Try `/compact`.
137
- - A custom message with no text has nothing to quote. If a run starts from one, the message stays unprotected after a cut in the middle of the run.
138
-
139
- Fixed problems are in [`CHANGELOG.md`](CHANGELOG.md).
140
-
141
- ## Uninstall
142
-
143
- ```sh
144
- pi remove npm:pi-tuck
145
- ```
146
-
147
- Use the same source that you installed from. If you turned `/tuck-incident` on, its records are in `~/.local/state/pi-tuck-incidents`. Versions before 1.2.0 downloaded about 460 MB for a feature that no longer exists. pi-tuck deletes those files once per machine when it first starts, and shows a notice. On Windows, delete `~/.pi/agent/pi-tuck` yourself.
68
+ See [Small windows](docs/small-windows.md) for the current budgeting policy and the [proposed Pi request contract](docs/pi-request-boundary.md) for the limits on final request admission and retry coordination.
148
69
 
149
70
  ## Use from code
150
71
 
151
- Hosts that embed Pi through its SDK can use the package:
72
+ Hosts that embed Pi through its SDK can import the compactor directly.
152
73
 
153
74
  ```ts
154
75
  import { installCompaction } from "pi-tuck";
@@ -156,23 +77,35 @@ import { installCompaction } from "pi-tuck";
156
77
  const handle = await installCompaction(pi);
157
78
  ```
158
79
 
159
- [`src/compaction.ts`](src/compaction.ts) documents the options of `installCompaction`: reply reserve, host-injected messages, recall policy, `cutAt` and others. Call `handle.close()` before you dispose a session. It stops the incident recorder.
80
+ Use `hostMessages` for context the host injects, `requestReserve` for a host reply budget, and `recallPolicy` to restrict recall. Set `responseExact: true` in the reserve result to use the declared value. By default a host reserve is at least the model's configured output limit. Call `await handle.close()` before disposing the session to stop the incident recorder. [SDK options](src/compaction.ts)
160
81
 
161
82
  ## Development
162
83
 
84
+ From the repository root, install the locked dependencies and run the checks.
85
+
163
86
  ```sh
164
- npm install
165
- npm run check # types
166
- npm test # unit tests (Vitest)
167
- npm run build # dist/ for the library export
87
+ npm ci
88
+ npm run build
89
+ npm run check
90
+ npm test
168
91
  ```
169
92
 
170
- [`CHANGELOG.md`](CHANGELOG.md) lists the changes. GitHub Actions publishes releases with npm trusted publishing and provenance.
93
+ The build emits the SDK in `dist/` and refreshes the tracked `src/build-id.ts`. Include the refreshed ID when committing changes to `index.ts` or `src/`. To run one file, use `npm test -- test/llama-continuation.test.ts`. To load this checkout for one Pi invocation, run `pi --no-extensions -e ./index.ts` from the repository root.
94
+
95
+ - The extension entry point reads settings and registers the optional provider adapter. [Entry point](index.ts) · [Continuation adapter](src/llama-continuation.ts)
96
+ - Session hooks plan cuts for Pi to commit. [Compaction hooks](src/compaction.ts) · [Reply budgeting and Pi's clamp](src/request-capacity.ts)
97
+ - The summary compiler renders the cut. Recall reads eligible source entries from the branch. [Summary compiler](src/tuck.ts) · [Recall](src/recall.ts)
98
+
99
+ See [Contributing](CONTRIBUTING.md) for stress tests and [the changelog](CHANGELOG.md) for release changes.
100
+
101
+ ## Benchmarks
171
102
 
172
- ## Credits
103
+ - **128k live run.** pi-tuck 1.0.1 resolved 258 of 300 SWE-bench Verified tasks versus Pi's 251. Median completed cuts took 0.081 s (an upper bound from session timestamps) versus 235.3 s with a local summarizer. The one-sided 95% lower bound on the resolution difference fell from +0.3 to −0.4 points when the chain with 44 Pi compaction failures was excluded. [128k results](benchmark/RESULTS-MAIN.md)
104
+ - **128k recall replay.** Completed answer sets at cuts 1–4 supported the registered 3-point margin against Pi's summaries and kept messages. The scoring excluded 52 of 95 pi-tuck sets that aborted. [Retention results](benchmark/RESULTS-MAIN.md)
105
+ - **32k live run.** pi-tuck 1.0.5 resolved 120 of 150 tasks versus Pi's 94 and observation masking's 117. The one-sided 95% lower bounds were +10.7 and −2.7 points, respectively. pi-tuck recorded one dead task against a target of zero. [32k results](benchmark/RESULTS-32K-ACCEPT.md)
173
106
 
174
- pi-tuck grew out of [pi-vcc](https://github.com/sting8k/pi-vcc) by sting8k. It includes code from [pi-blackhole](https://github.com/k0valik/pi-blackhole) by k0valik and from [Pi](https://github.com/earendil-works/pi) by Mario Zechner, all MIT. Their notices are in [NOTICE](NOTICE).
107
+ The [benchmark index](benchmark/README.md) records the models, versions, plans, and scope of each result.
175
108
 
176
- ## License
109
+ ## Credits and license
177
110
 
178
- MIT
111
+ 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).
package/dist/index.d.ts CHANGED
@@ -2,10 +2,7 @@ import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  export type { CompactionOptions } from "./src/compaction.js";
3
3
  export { installCompaction } from "./src/compaction.js";
4
4
  export { inspectIncident, readableIncident } from "./src/diagnostic-replay.js";
5
- /** pi-tuck as a Pi extension: compaction and history recall. `"cutAt"` in `pi-tuck.json` in Pi's agent folder (a number above 0 and at most
6
- * 1) fixes the cut point as a fraction of the input room; without it, the cut point adapts. */
7
- /** The oldest Pi with every hook and API pi-tuck uses, and the oldest its tests pass on (Pi 1.2 added the custom message that starts a
8
- * run to before_agent_start, which the prompt's cut counts). */
5
+ /** Pi 1.2 added the run's custom message to before_agent_start so preflight can count it. */
9
6
  export declare const PI_FLOOR = "1.2.0";
10
7
  /** Whether a Pi version is at or above the floor. A version that does not parse is taken as supported. */
11
8
  export declare function piSupported(version: string): boolean;
package/dist/index.js CHANGED
@@ -7,10 +7,7 @@ import { notify } from "./src/notify.js";
7
7
  import { cleanupLegacyFiles } from "./src/legacy-cleanup.js";
8
8
  export { installCompaction } from "./src/compaction.js";
9
9
  export { inspectIncident, readableIncident } from "./src/diagnostic-replay.js";
10
- /** pi-tuck as a Pi extension: compaction and history recall. `"cutAt"` in `pi-tuck.json` in Pi's agent folder (a number above 0 and at most
11
- * 1) fixes the cut point as a fraction of the input room; without it, the cut point adapts. */
12
- /** The oldest Pi with every hook and API pi-tuck uses, and the oldest its tests pass on (Pi 1.2 added the custom message that starts a
13
- * run to before_agent_start, which the prompt's cut counts). */
10
+ /** Pi 1.2 added the run's custom message to before_agent_start so preflight can count it. */
14
11
  export const PI_FLOOR = "1.2.0";
15
12
  /** Whether a Pi version is at or above the floor. A version that does not parse is taken as supported. */
16
13
  export function piSupported(version) {
@@ -38,17 +35,39 @@ export default async function (pi) {
38
35
  return;
39
36
  }
40
37
  const settings = readSettings(join(getAgentDir(), "pi-tuck.json"));
41
- const handle = await installCompaction(pi, { cutAt: settings.cutAt });
38
+ const handle = await installCompaction(pi, { cutAt: settings.cutAt, cacheSensitiveModels: settings.cacheSensitiveModels, continuationModel: settings.llamaContinuation?.model });
39
+ const continuation = settings.llamaContinuation;
40
+ let continuationError;
41
+ if (continuation) {
42
+ try {
43
+ const [{ getApiProvider }, { llamaContinuationStream }] = await Promise.all([
44
+ import("@earendil-works/pi-ai/compat"), import("./src/llama-continuation.js"),
45
+ ]);
46
+ const native = getApiProvider("openai-completions")?.streamSimple;
47
+ if (!native)
48
+ throw new Error("Pi's Chat Completions provider is unavailable");
49
+ pi.registerProvider(continuation.model.split("/")[0], {
50
+ api: "openai-completions",
51
+ streamSimple: llamaContinuationStream(continuation, native),
52
+ });
53
+ }
54
+ catch (error) {
55
+ continuationError = `pi-tuck: native continuation unavailable: ${String(error)}`;
56
+ }
57
+ }
42
58
  let said = false;
43
59
  pi.on("session_start", async (_event, ctx) => {
44
60
  await cleanupLegacyFiles(ctx);
45
61
  if (handle.state?.(ctx).kind === "standingDown")
46
62
  return;
63
+ if (continuationError)
64
+ notify(ctx, continuationError, "warning");
47
65
  if (settings.error && !said) {
48
- said = notify(ctx, `pi-tuck: ${settings.error}; using the defaults.`, "warning");
66
+ said = notify(ctx, `pi-tuck: ${settings.error}`, "warning");
49
67
  }
50
68
  });
51
69
  }
70
+ const modelRef = (value) => typeof value === "string" && /^[^/]+\/.+/.test(value);
52
71
  function readSettings(path) {
53
72
  let text;
54
73
  try {
@@ -57,12 +76,32 @@ function readSettings(path) {
57
76
  catch {
58
77
  return {};
59
78
  }
79
+ const cutAtHint = `${path} should be a JSON object like {"cutAt": 0.8}, with cutAt a number above 0 and at most 1`;
60
80
  try {
61
81
  const value = JSON.parse(text);
62
- if (value && typeof value === "object" &&
63
- (value.cutAt === undefined || validCutAt(value.cutAt)))
64
- return { cutAt: value.cutAt };
82
+ if (value && typeof value === "object" && !Array.isArray(value)) {
83
+ const settings = {};
84
+ const warnings = [];
85
+ if (value.cutAt === undefined || validCutAt(value.cutAt))
86
+ settings.cutAt = value.cutAt;
87
+ else
88
+ warnings.push(`${cutAtHint}; using the default cut point.`);
89
+ const models = value.cacheSensitiveModels;
90
+ if (Array.isArray(models) && models.every(modelRef))
91
+ settings.cacheSensitiveModels = models;
92
+ else if (models !== undefined)
93
+ warnings.push(`${path} cacheSensitiveModels must be an array of provider/model identifiers; ignoring that setting.`);
94
+ const c = value.llamaContinuation;
95
+ if (c && modelRef(c.model) && Number.isSafeInteger(c.extraTokens) && c.extraTokens > 0 &&
96
+ Number.isSafeInteger(c.deadlineMs) && c.deadlineMs > 0 && c.deadlineMs <= 2_147_483_647)
97
+ settings.llamaContinuation = c;
98
+ else if (c !== undefined)
99
+ warnings.push(`${path} llamaContinuation requires a provider/model identifier in model, a positive safe integer extraTokens, and an integer deadlineMs from 1 to 2147483647; native continuation is off.`);
100
+ if (warnings.length)
101
+ settings.error = warnings.join(" ");
102
+ return settings;
103
+ }
65
104
  }
66
105
  catch { /* reported below */ }
67
- return { error: `${path} should be a JSON object like {"cutAt": 0.8}, with cutAt a number above 0 and at most 1` };
106
+ return { error: `${cutAtHint}; using the defaults.` };
68
107
  }
@@ -18,21 +18,12 @@ export interface ToolShape {
18
18
  export declare const TRIGGER_MARGIN_FRACTION = 0.02;
19
19
  /** Whether `value` is a cut point: a fraction of the room above 0 and at most 1. */
20
20
  export declare const validCutAt: (value: unknown) => value is number;
21
- /**
22
- * The one owner of the band: the limit a cut is triggered at and preferably planned to. An adaptive default may raise the cut point above
23
- * 60% using the last cut's conversation size and current system size, both estimates, so they are converted to the room's units by the factor. Explicit cut points use the fraction alone. The margin caps both.
24
- */
25
- /** The initial default cut point: 60% of the room before a usable previous cut. Measured against 1 with paired replays (no answer loss) and billed
26
- * input under automatic and explicit prompt caching (about 17% less at 128k, 10-14% at 32k). */
27
- export declare const DEFAULT_CUT_AT = 0.6;
28
- /** Preferred native carry, in the planner's estimate: never more than the
29
- * keep-recent cut offers or the tail amount the adaptive band assumes. */
21
+ /** Trigger at the room for native parity of post-cut headroom. */
22
+ export declare const DEFAULT_CUT_AT = 1;
23
+ /** Preferred native carry, in the planner's estimate, bounded by the keep-recent offer and the existing tail limit. */
30
24
  export declare const carriedTailTokens: (offeredTokens: number) => number;
31
- export declare const bandOf: (room: number, cutAt?: number, adaptive?: {
32
- system: number;
33
- tokensAfter: number;
34
- factor: number;
35
- }) => number;
25
+ /** The one owner of the band: the trigger and preferred planning limit, capped by the margin. */
26
+ export declare const bandOf: (room: number, cutAt?: number) => number;
36
27
  /** The cut's one carried-context grant, in the planner's estimate. Combines
37
28
  * the existing native/fixed base with the quarter-free historical amount;
38
29
  * neither component remains an independent spending limit in the fill.
@@ -99,7 +90,7 @@ export type Decision<D extends object = {}> =
99
90
  message: string;
100
91
  };
101
92
  export interface CutInput<D extends object = {}> {
102
- /** The band adapts by itself (no explicit cut point), so a cut that isn't due must also free a tenth of the room. */
93
+ /** With no explicit cut point, a cut that isn't due must also free a tenth of the room. */
103
94
  usefulOnly?: boolean;
104
95
  /** Saved conversation, measured by the planner's own function. */
105
96
  before: number;
@@ -7,20 +7,15 @@ import { MAX_TAIL_TOKENS } from "./tuck/cut.js";
7
7
  export const TRIGGER_MARGIN_FRACTION = 0.02;
8
8
  /** Whether `value` is a cut point: a fraction of the room above 0 and at most 1. */
9
9
  export const validCutAt = (value) => typeof value === "number" && value > 0 && value <= 1;
10
- /**
11
- * The one owner of the band: the limit a cut is triggered at and preferably planned to. An adaptive default may raise the cut point above
12
- * 60% using the last cut's conversation size and current system size, both estimates, so they are converted to the room's units by the factor. Explicit cut points use the fraction alone. The margin caps both.
13
- */
14
- /** The initial default cut point: 60% of the room before a usable previous cut. Measured against 1 with paired replays (no answer loss) and billed
15
- * input under automatic and explicit prompt caching (about 17% less at 128k, 10-14% at 32k). */
16
- export const DEFAULT_CUT_AT = 0.6;
17
- /** Preferred native carry, in the planner's estimate: never more than the
18
- * keep-recent cut offers or the tail amount the adaptive band assumes. */
10
+ /** Trigger at the room for native parity of post-cut headroom. */
11
+ export const DEFAULT_CUT_AT = 1;
12
+ /** Preferred native carry, in the planner's estimate, bounded by the keep-recent offer and the existing tail limit. */
19
13
  export const carriedTailTokens = (offeredTokens) => Math.min(offeredTokens, MAX_TAIL_TOKENS / 2);
20
- export const bandOf = (room, cutAt = 1, adaptive) => {
14
+ /** The one owner of the band: the trigger and preferred planning limit, capped by the margin. */
15
+ export const bandOf = (room, cutAt = DEFAULT_CUT_AT) => {
21
16
  const positive = Math.max(0, room);
22
17
  const base = Math.floor(positive * cutAt);
23
- return Math.min(room - Math.ceil(positive * TRIGGER_MARGIN_FRACTION), adaptive ? Math.max(base, Math.ceil((adaptive.system + adaptive.tokensAfter + carriedTailTokens(MAX_TAIL_TOKENS)) * adaptive.factor)) : base);
18
+ return Math.min(room - Math.ceil(positive * TRIGGER_MARGIN_FRACTION), base);
24
19
  };
25
20
  /** The cut's one carried-context grant, in the planner's estimate. Combines
26
21
  * the existing native/fixed base with the quarter-free historical amount;
@@ -1 +1 @@
1
- export declare const BUILD_ID = "6a84733ab75ecf863fe77c6dd6d0a91602a8a0d353a785c3fdb34585f42637a2";
1
+ export declare const BUILD_ID = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
@@ -1 +1 @@
1
- export const BUILD_ID = "6a84733ab75ecf863fe77c6dd6d0a91602a8a0d353a785c3fdb34585f42637a2";
1
+ export const BUILD_ID = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
@@ -3,27 +3,19 @@ import { type RecorderOptions } from "./diagnostics.js";
3
3
  import { type AgentMessage } from "./budget.js";
4
4
  import { SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
5
5
  import type { RecallPolicy } from "./recall.js";
6
- /** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
7
- * likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
6
+ /** Explain a high planning factor, which can come from reported usage or an overflow estimate. */
8
7
  export declare const refusalNotice: (message: string, factor: number) => string;
9
- /** What the operator hears when the provider refuses a request pi-tuck admitted as over its window: the bound that reply puts on the counting, and
10
- * what pi-tuck did with it. A bound pi-tuck cannot carry (above the ceiling) says so rather than implying the next request is planned at it. */
8
+ /** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
11
9
  export declare const overflowNotice: (contextWindow: number, bound: number, learned: boolean) => string;
12
10
  /** 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. */
13
11
  export declare const CALIBRATION_CEILING = 1.5;
14
12
  /** How many recent paired replies (and overflow bounds, and the seed while it is among them) the calibration factor is the maximum of. */
15
13
  export declare const CALIBRATION_WINDOW = 32;
16
- /** Measured provider-input undercount by model, as "provider/id". An identity with no usable receipt of its own starts its window with this entry, which
17
- * ages out after CALIBRATION_WINDOW later entries; every other model starts at 1. Empty: an undercount of 1.18 once measured for openai/gpt-6.1-sol
18
- * was replayed reasoning, which the estimate now counts; with it counted, the first 32 requests of a real session measured at most 0.97. */
19
- export declare const MEASURED_CALIBRATION: Readonly<Record<string, number>>;
20
14
  export declare const CALIBRATION_RECEIPT = "pi-tuck-calibration";
21
- /** The calibration window a session starts with under accounting identity `key`: the newest calibration entry or compaction on the branch that carries this package's
22
- * receipt decides, and no older receipt is consulted. A receipt without the identity field (written before it existed) or from another identity gives `initialWindow`.
23
- * Otherwise its `calibrationWindow` (an array of 1..CALIBRATION_WINDOW finite numbers, oldest first) is the window, each entry clamped to
24
- * [0, CALIBRATION_CEILING]; without a valid one, the window is its `calibrationFactor` clamped to [1, CALIBRATION_CEILING] as one entry, else
25
- * `initialWindow`. A usable receipt of the identity's own wins over the measured seed, as a learned window replaces it: a Resume from a receipt
26
- * written before the seed existed, or after it aged out, starts at that receipt's window (as low as 1). Reads only; a malformed receipt never throws. */
15
+ /** Read the newest applicable calibration receipt on the branch for `key` ([provider, api, id]). A custom
16
+ * observation for another identity is skipped. A compaction receipt for another or missing identity resets
17
+ * the seed to [1]. A matching receipt supplies its recent ratios clamped to [0, CALIBRATION_CEILING],
18
+ * or its legacy factor clamped to [1, CALIBRATION_CEILING]. Without a usable seed, start at [1]. */
27
19
  export declare function seedWindow(branch: readonly SessionEntry[], key: string): number[];
28
20
  export type CompactionState = {
29
21
  kind: "active";
@@ -55,12 +47,12 @@ export interface CompactionOptions {
55
47
  * which is the room less 2% of it, or this fraction of the room when that is lower; a lower value cuts earlier and leaves less. The room
56
48
  * owns cut targets; standalone final capacity admission uses the branch reply floor. If omitted, the band adapts to the last cut. */
57
49
  cutAt?: number;
58
- /** A host's response reserve: without `responseExact: true`, the catalogue maximum output stays its floor; with it, `response` is exact.
59
- * Standalone cuts against Pi's reserveTokens, then admits up to the window less Pi's safety margin and max(3,584, largest branch output), capped at that reserve.
60
- * After a genuine length stop with text/tool output or context overflow it holds the full reserve, also raised to the catalogue maximum.
61
- * Server clipping below the sent reply cap instead learns the smaller window and preserves the normal reply floor.
62
- * Thinking-only exhaustion keeps Pi's reserve and requires the branch's largest observed reply instead.
63
- * Resume, fork and /tree follow that branch's history; a new session has no inherited fallback. */
50
+ /** Models where a usable cached prefix is more valuable than an early cut. */
51
+ cacheSensitiveModels?: readonly string[];
52
+ /** provider/model with provider-native continuation; it keeps one length recovery per run, and only where a cut adds reply room. */
53
+ continuationModel?: string;
54
+ /** Host response reserve. `responseExact: true` uses it as declared. Otherwise the SDK
55
+ * keeps the catalogue maximum as a floor for existing callers. Standalone uses Pi’s soft reserve. */
64
56
  requestReserve?: (ctx: ExtensionContext) => {
65
57
  response: number;
66
58
  responseExact?: true;