pi-tuck 1.3.4 → 1.5.0

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 (48) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +67 -122
  3. package/dist/index.d.ts +1 -4
  4. package/dist/index.js +56 -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 +15 -20
  10. package/dist/src/compaction.js +236 -204
  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/footer.d.ts +37 -0
  15. package/dist/src/footer.js +91 -0
  16. package/dist/src/ledger.d.ts +6 -3
  17. package/dist/src/ledger.js +14 -7
  18. package/dist/src/llama-continuation.d.ts +8 -0
  19. package/dist/src/llama-continuation.js +179 -0
  20. package/dist/src/recall.js +8 -25
  21. package/dist/src/request-capacity.d.ts +11 -26
  22. package/dist/src/request-capacity.js +20 -57
  23. package/dist/src/run.d.ts +16 -7
  24. package/dist/src/run.js +53 -25
  25. package/dist/src/status.d.ts +9 -0
  26. package/dist/src/status.js +14 -9
  27. package/dist/src/tuck/core/format.js +1 -1
  28. package/dist/src/tuck/core/readable-content.d.ts +14 -0
  29. package/dist/src/tuck/core/readable-content.js +43 -0
  30. package/dist/src/tuck.d.ts +2 -1
  31. package/dist/src/tuck.js +92 -30
  32. package/index.ts +46 -10
  33. package/package.json +3 -1
  34. package/src/budget.ts +7 -12
  35. package/src/build-id.ts +1 -1
  36. package/src/compaction.ts +228 -194
  37. package/src/content-observations.ts +115 -0
  38. package/src/diagnostics.ts +1 -1
  39. package/src/footer.ts +111 -0
  40. package/src/ledger.ts +17 -10
  41. package/src/llama-continuation.ts +176 -0
  42. package/src/recall.ts +8 -20
  43. package/src/request-capacity.ts +18 -57
  44. package/src/run.ts +48 -22
  45. package/src/status.ts +20 -9
  46. package/src/tuck/core/format.ts +1 -1
  47. package/src/tuck/core/readable-content.ts +44 -0
  48. package/src/tuck.ts +79 -28
package/CHANGELOG.md CHANGED
@@ -3,6 +3,58 @@
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.5.0]
7
+
8
+ ### Added
9
+
10
+ - Footer: pi-tuck replaces Pi's footer in the terminal UI. Under the folder and branch line, a bar fills toward pi-tuck's trim point
11
+ (full means pi-tuck trims), with the context size, the trim point, the trim count once there is one, the cost when above $0, and the
12
+ model and thinking level; other extensions' statuses stay below. It turns yellow at 85% of the trim point instead of at Pi's 70% and
13
+ 90% of the window. Its figures are recomputed only after a reply, a trim, or a model or thinking change. `"footer": false` in `pi-tuck.json` keeps Pi's footer.
14
+ - Refusal and length-stop notices suggest `/tuck-incident next` to record the next trim for a bug report.
15
+
16
+ ### Changed
17
+
18
+ - `/tuck` says "trim" where it said "cut", the word the footer uses. The `cutAt` setting keeps its name.
19
+
20
+ ### Fixed
21
+
22
+ - `/tuck` no longer says the cut point adapts by itself: it names the default (the room less a 2% margin) and the trim point in tokens for
23
+ the current model.
24
+
25
+ ## [1.4.1]
26
+
27
+ ### Fixed
28
+
29
+ - The release workflow fetches full history, so the Part 6 reference test runs before publishing. 1.4.0 was tagged but never
30
+ published; 1.4.1 ships the same code.
31
+
32
+ ## [1.4.0]
33
+
34
+ ### Added
35
+
36
+ - Content lane: kept output, definition maps and plain-text thinking openings rank below kept reads and searches in the summary.
37
+
38
+ ### Changed
39
+
40
+ - Post-cut headroom: cut at the room by default, and carry no more native history than Pi keeps. The adaptive cut point is gone.
41
+
42
+ - 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.
43
+ - 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
44
+ out as before.
45
+ - Allow selected local models to defer early cuts.
46
+ - Support bounded native llama.cpp continuation for an explicitly configured and verified provider.
47
+
48
+ ### Fixed
49
+
50
+ - 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
51
+ 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
52
+ reply cap.
53
+ - Require standalone overflow recovery cuts to lower estimated input and combined request size when the failed request has a paired estimate.
54
+ - Stop inferring a smaller context window from an ambiguous length stop. Windows inferred by earlier versions no longer constrain requests.
55
+ - Reject invalid run transitions and discard pending cuts when their branch or model budget changes.
56
+ - Keep valid settings active when another field in `pi-tuck.json` is invalid.
57
+
6
58
  ## [1.3.4] - 2026-11-20
7
59
 
8
60
  ### Fixed
package/README.md CHANGED
@@ -1,154 +1,87 @@
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.5.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.5.0` or `pi install git:github.com/galyavin/pi-tuck@v1.5.0`. 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 trims, and trim 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.
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.
100
36
 
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.
37
+ ## Footer
102
38
 
103
- ## Settings
104
-
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
+ In Pi's terminal UI, pi-tuck replaces Pi's footer. Under the folder and git branch, the bar fills toward pi-tuck's trim point, the number `/tuck` reports: a full bar means pi-tuck trims. Next to it are the context size and the trim point, the trim count once pi-tuck has trimmed, the cost when it is above $0, and the model with its thinking level. Other extensions' statuses stay below. The bar turns yellow at 85% of the trim point. A narrow terminal shows only the bar and the two sizes. Right after a trim, before the next reply, the size is the trim's own estimate, shown with `~`. When pi-tuck is not trimming for the model, the line shows the context against the window. `/tuck` shows the trim history.
106
40
 
107
- ```json
108
- { "cutAt": 0.8 }
41
+ ```text
42
+ ~/repo (main)
43
+ context ████████░░ 19k of 24k · 2 trims main · xhigh
109
44
  ```
110
45
 
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.
46
+ When pi-tuck stops a request or a reply ends at its length limit, the notice suggests `/tuck-incident next` to record the next trim for a bug report.
114
47
 
115
- ## Small windows
48
+ ## Settings
116
49
 
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.
50
+ 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.
122
51
 
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:
52
+ - **`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`.
53
+ - **`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.
54
+ - **`footer`** set to `false` keeps Pi's own footer.
55
+ - **`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.
124
56
 
125
57
  ```json
126
- { "providers": { "openrouter": { "compat": { "openRouterRouting": { "only": ["your-upstream"], "allow_fallbacks": false } } } } }
58
+ {
59
+ "cacheSensitiveModels": ["my-provider/my-model"],
60
+ "llamaContinuation": {
61
+ "model": "my-provider/my-model",
62
+ "extraTokens": 4096,
63
+ "deadlineMs": 5400000
64
+ }
65
+ }
127
66
  ```
128
67
 
129
- The details are in [`docs/small-windows.md`](docs/small-windows.md).
68
+ ## Output exhaustion and small windows
130
69
 
131
- ## Known limits
70
+ - 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.
71
+ - 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.
72
+ - 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.
132
73
 
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.
74
+ When using OpenRouter, you can pin an upstream in Pi's `models.json` if upstreams count context differently.
138
75
 
139
- Fixed problems are in [`CHANGELOG.md`](CHANGELOG.md).
140
-
141
- ## Uninstall
142
-
143
- ```sh
144
- pi remove npm:pi-tuck
76
+ ```json
77
+ { "providers": { "openrouter": { "compat": { "openRouterRouting": { "only": ["your-upstream"], "allow_fallbacks": false } } } } }
145
78
  ```
146
79
 
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.
80
+ 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
81
 
149
82
  ## Use from code
150
83
 
151
- Hosts that embed Pi through its SDK can use the package:
84
+ Hosts that embed Pi through its SDK can import the compactor directly.
152
85
 
153
86
  ```ts
154
87
  import { installCompaction } from "pi-tuck";
@@ -156,23 +89,35 @@ import { installCompaction } from "pi-tuck";
156
89
  const handle = await installCompaction(pi);
157
90
  ```
158
91
 
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.
92
+ 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
93
 
161
94
  ## Development
162
95
 
96
+ From the repository root, install the locked dependencies and run the checks.
97
+
163
98
  ```sh
164
- npm install
165
- npm run check # types
166
- npm test # unit tests (Vitest)
167
- npm run build # dist/ for the library export
99
+ npm ci
100
+ npm run build
101
+ npm run check
102
+ npm test
168
103
  ```
169
104
 
170
- [`CHANGELOG.md`](CHANGELOG.md) lists the changes. GitHub Actions publishes releases with npm trusted publishing and provenance.
105
+ 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.
106
+
107
+ - The extension entry point reads settings and registers the optional provider adapter. [Entry point](index.ts) · [Continuation adapter](src/llama-continuation.ts)
108
+ - Session hooks plan cuts for Pi to commit. [Compaction hooks](src/compaction.ts) · [Reply budgeting and Pi's clamp](src/request-capacity.ts)
109
+ - The summary compiler renders the cut. Recall reads eligible source entries from the branch. [Summary compiler](src/tuck.ts) · [Recall](src/recall.ts)
110
+
111
+ See [Contributing](CONTRIBUTING.md) for stress tests and [the changelog](CHANGELOG.md) for release changes.
112
+
113
+ ## Benchmarks
171
114
 
172
- ## Credits
115
+ - **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)
116
+ - **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)
117
+ - **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
118
 
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).
119
+ The [benchmark index](benchmark/README.md) records the models, versions, plans, and scope of each result.
175
120
 
176
- ## License
121
+ ## Credits and license
177
122
 
178
- MIT
123
+ 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
@@ -5,12 +5,10 @@ import { installCompaction } from "./src/compaction.js";
5
5
  import { validCutAt } from "./src/budget.js";
6
6
  import { notify } from "./src/notify.js";
7
7
  import { cleanupLegacyFiles } from "./src/legacy-cleanup.js";
8
+ import { installFooter } from "./src/footer.js";
8
9
  export { installCompaction } from "./src/compaction.js";
9
10
  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). */
11
+ /** Pi 1.2 added the run's custom message to before_agent_start so preflight can count it. */
14
12
  export const PI_FLOOR = "1.2.0";
15
13
  /** Whether a Pi version is at or above the floor. A version that does not parse is taken as supported. */
16
14
  export function piSupported(version) {
@@ -38,17 +36,41 @@ export default async function (pi) {
38
36
  return;
39
37
  }
40
38
  const settings = readSettings(join(getAgentDir(), "pi-tuck.json"));
41
- const handle = await installCompaction(pi, { cutAt: settings.cutAt });
39
+ const handle = await installCompaction(pi, { cutAt: settings.cutAt, cacheSensitiveModels: settings.cacheSensitiveModels, continuationModel: settings.llamaContinuation?.model });
40
+ if (settings.footer !== false)
41
+ installFooter(pi, ctx => handle.cutPoint(ctx));
42
+ const continuation = settings.llamaContinuation;
43
+ let continuationError;
44
+ if (continuation) {
45
+ try {
46
+ const [{ getApiProvider }, { llamaContinuationStream }] = await Promise.all([
47
+ import("@earendil-works/pi-ai/compat"), import("./src/llama-continuation.js"),
48
+ ]);
49
+ const native = getApiProvider("openai-completions")?.streamSimple;
50
+ if (!native)
51
+ throw new Error("Pi's Chat Completions provider is unavailable");
52
+ pi.registerProvider(continuation.model.split("/")[0], {
53
+ api: "openai-completions",
54
+ streamSimple: llamaContinuationStream(continuation, native),
55
+ });
56
+ }
57
+ catch (error) {
58
+ continuationError = `pi-tuck: native continuation unavailable: ${String(error)}`;
59
+ }
60
+ }
42
61
  let said = false;
43
62
  pi.on("session_start", async (_event, ctx) => {
44
63
  await cleanupLegacyFiles(ctx);
45
64
  if (handle.state?.(ctx).kind === "standingDown")
46
65
  return;
66
+ if (continuationError)
67
+ notify(ctx, continuationError, "warning");
47
68
  if (settings.error && !said) {
48
- said = notify(ctx, `pi-tuck: ${settings.error}; using the defaults.`, "warning");
69
+ said = notify(ctx, `pi-tuck: ${settings.error}`, "warning");
49
70
  }
50
71
  });
51
72
  }
73
+ const modelRef = (value) => typeof value === "string" && /^[^/]+\/.+/.test(value);
52
74
  function readSettings(path) {
53
75
  let text;
54
76
  try {
@@ -57,12 +79,36 @@ function readSettings(path) {
57
79
  catch {
58
80
  return {};
59
81
  }
82
+ const cutAtHint = `${path} should be a JSON object like {"cutAt": 0.8}, with cutAt a number above 0 and at most 1`;
60
83
  try {
61
84
  const value = JSON.parse(text);
62
- if (value && typeof value === "object" &&
63
- (value.cutAt === undefined || validCutAt(value.cutAt)))
64
- return { cutAt: value.cutAt };
85
+ if (value && typeof value === "object" && !Array.isArray(value)) {
86
+ const settings = {};
87
+ const warnings = [];
88
+ if (value.cutAt === undefined || validCutAt(value.cutAt))
89
+ settings.cutAt = value.cutAt;
90
+ else
91
+ warnings.push(`${cutAtHint}; using the default cut point.`);
92
+ const models = value.cacheSensitiveModels;
93
+ if (Array.isArray(models) && models.every(modelRef))
94
+ settings.cacheSensitiveModels = models;
95
+ else if (models !== undefined)
96
+ warnings.push(`${path} cacheSensitiveModels must be an array of provider/model identifiers; ignoring that setting.`);
97
+ const c = value.llamaContinuation;
98
+ if (c && modelRef(c.model) && Number.isSafeInteger(c.extraTokens) && c.extraTokens > 0 &&
99
+ Number.isSafeInteger(c.deadlineMs) && c.deadlineMs > 0 && c.deadlineMs <= 2_147_483_647)
100
+ settings.llamaContinuation = c;
101
+ else if (c !== undefined)
102
+ 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.`);
103
+ if (typeof value.footer === "boolean")
104
+ settings.footer = value.footer;
105
+ else if (value.footer !== undefined)
106
+ warnings.push(`${path} footer must be true or false; showing pi-tuck's footer.`);
107
+ if (warnings.length)
108
+ settings.error = warnings.join(" ");
109
+ return settings;
110
+ }
65
111
  }
66
112
  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` };
113
+ return { error: `${cutAtHint}; using the defaults.` };
68
114
  }
@@ -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 = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
@@ -1 +1 @@
1
- export const BUILD_ID = "6a84733ab75ecf863fe77c6dd6d0a91602a8a0d353a785c3fdb34585f42637a2";
1
+ export const BUILD_ID = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
@@ -3,27 +3,21 @@ 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;
10
+ /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
11
+ export declare const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
12
12
  /** 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
13
  export declare const CALIBRATION_CEILING = 1.5;
14
14
  /** How many recent paired replies (and overflow bounds, and the seed while it is among them) the calibration factor is the maximum of. */
15
15
  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
16
  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. */
17
+ /** Read the newest applicable calibration receipt on the branch for `key` ([provider, api, id]). A custom
18
+ * observation for another identity is skipped. A compaction receipt for another or missing identity resets
19
+ * the seed to [1]. A matching receipt supplies its recent ratios clamped to [0, CALIBRATION_CEILING],
20
+ * or its legacy factor clamped to [1, CALIBRATION_CEILING]. Without a usable seed, start at [1]. */
27
21
  export declare function seedWindow(branch: readonly SessionEntry[], key: string): number[];
28
22
  export type CompactionState = {
29
23
  kind: "active";
@@ -55,12 +49,12 @@ export interface CompactionOptions {
55
49
  * 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
50
  * owns cut targets; standalone final capacity admission uses the branch reply floor. If omitted, the band adapts to the last cut. */
57
51
  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. */
52
+ /** Models where a usable cached prefix is more valuable than an early cut. */
53
+ cacheSensitiveModels?: readonly string[];
54
+ /** provider/model with provider-native continuation; it keeps one length recovery per run, and only where a cut adds reply room. */
55
+ continuationModel?: string;
56
+ /** Host response reserve. `responseExact: true` uses it as declared. Otherwise the SDK
57
+ * keeps the catalogue maximum as a floor for existing callers. Standalone uses Pi’s soft reserve. */
64
58
  requestReserve?: (ctx: ExtensionContext) => {
65
59
  response: number;
66
60
  responseExact?: true;
@@ -80,6 +74,7 @@ export interface CompactionOptions {
80
74
  export declare function installCompaction(pi: ExtensionAPI, options?: CompactionOptions): Promise<{
81
75
  close: () => Promise<void>;
82
76
  state: (ctx: ExtensionContext) => CompactionState;
77
+ cutPoint: (ctx: ExtensionContext) => number | undefined;
83
78
  inspectState: (ctx: ExtensionContext) => {
84
79
  run: Readonly<Run> | undefined;
85
80
  phase: "decided" | "claimed" | "expired" | "starting" | "admitted" | "failed" | "commit-failed" | undefined;