pi-tuck 1.0.33 → 1.1.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,56 @@
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.1.1] - 2026-11-14
7
+
8
+ ### Fixed
9
+
10
+ - **A resumed session forgot what pi-tuck had learned about the provider's token counts.** pi-tuck saved its calibration only inside a
11
+ cut, so after quitting and resuming Pi before the next cut it counted at 1x again and could send a request the provider truncated or
12
+ refused, where native Pi succeeded. pi-tuck now saves a small private entry in the session when what a resume would learn changes (not
13
+ every turn) and reads it back on resume. The entry never reaches the model.
14
+ - **pi-tuck now stands down to native when it cannot do its job safely.** With an unknown context window (0, missing or not a number), a
15
+ Pi virtual model, or Pi's auto-compaction turned off, pi-tuck refused prompts that native Pi would have sent. It now does exactly what
16
+ native Pi does in these cases, and `/tuck` says `standing down:` with the reason.
17
+ - **Refusal, overflow and manual-cut notices were silent without a UI.** In `pi -p` and JSON runs they went nowhere, so a run could end
18
+ with no word. They now go to stderr, as the output-limit notice already did.
19
+ - **The semantic search status could claim "ready" when it was turned off or had failed.** Turning it on no longer overrides an off
20
+ setting for the project, platform or settings; a failed start says so; stopping it no longer leaves it marked ready. Status changes now
21
+ follow a fixed table of allowed moves.
22
+ - **A retry after a reply hit the output limit skipped a check** that a pending cut had really been saved in the session. It now runs
23
+ that check like every other path.
24
+
25
+ ### Release gates
26
+
27
+ - **Shipped without a live gate: replay matches 1.1.0.** 29 recordings, 13,946 requests: requests identical apart from noise also seen
28
+ between two runs of 1.1.0 (three recordings, re-run fresh: 0 differences), the same 1,971 cuts, 0 lost or dead tasks, clips 16 to 16.
29
+ - **Strict stress:** 318 cells, 0 findings, plus a new resumed-session suite (325 shapes, 830 reached resume cells, all passing; both
30
+ factor-1.25 truncation cells fixed). Lifecycle with 40 seeds. Tests and CI. The packed tarball loaded in the real installed Pi.
31
+
32
+ ## [1.1.0] - 2026-11-13
33
+
34
+ ### Added
35
+
36
+ - **A cut's summary now carries the files the session last read and has not changed since.** After a cut, agents often doubted what an
37
+ earlier read had shown and read the same file again, even though no edit had touched it. The summary now includes, after the Files
38
+ list, the newest whole read of each file that has no later write or edit, headed `read PATH (as recorded at #N; no write or edit
39
+ recorded since):`. It keeps at most 4 files, whole outputs only, within 20% of the summary's room and never more than 24,000
40
+ characters. When the summary is over its target these records are dropped first, oldest first. With no such reads the summary is
41
+ unchanged. Tool outputs are never touched.
42
+
43
+ ### Release gates
44
+
45
+ - **Shipped before its Tier 1, on a 5-task gate.** The Tier 1 runs after release against 1.0.33; if it fails, npm and installs go back
46
+ to 1.0.33.
47
+ - **5-task check against 1.0.31:** no breakage in 5 of 5; re-checks after a doubt 22 against 45; doubt moments 9 against 24; cuts 22
48
+ against 26; turns 305 against 384; all 5 solved on both. One heavy task went worse: 90 turns against 59, 9 cuts against 4, 3 doubts
49
+ against 1.
50
+ - **Replay against 1.0.33:** 13,946 requests. In every recording that differs, the first difference is the first summary carrying one of
51
+ these records; 11 of 29 never differ. 0 lost or dead tasks, clips 17 → 16, cuts 1,946 → 1,971 (larger summaries bring later cuts
52
+ sooner).
53
+ - **Strict stress, 313 cells:** 0 findings on Pi 1.2.0 and the newest Pi, including the large-session test. Tests and CI. The packed
54
+ tarball loaded in the real installed Pi 1.5.2.
55
+
6
56
  ## [1.0.33] - 2026-11-13
7
57
 
8
58
  ### Fixed
package/README.md CHANGED
@@ -64,8 +64,8 @@ Then start a new Pi session. That is all. pi-tuck takes over Pi's compaction, bo
64
64
 
65
65
  - Needs Pi 1.2.0 or later (tested on 1.2.0 and 1.4.0), on macOS or Linux. On an older Pi, pi-tuck stays off, Pi's own compaction runs, and pi-tuck says so once. Full features on macOS with Apple silicon; elsewhere, compaction and word recall.
66
66
  - On macOS with Apple silicon, the first session also downloads a local search model in the background (about 390 MB, once), and says once when it is set up. Until it is ready, search works by keyword. See [Semantic search](#semantic-search).
67
- - Prefer GitHub? `pi install git:github.com/galyavin/pi-tuck@v1.0.27`.
68
- - To pin a version, add it: `pi install npm:pi-tuck@1.0.27`.
67
+ - Prefer GitHub? `pi install git:github.com/galyavin/pi-tuck@v1.1.0`.
68
+ - To pin a version, add it: `pi install npm:pi-tuck@1.1.0`.
69
69
 
70
70
  ## Uninstall
71
71
 
@@ -87,6 +87,7 @@ When context fills up, pi-tuck replaces the older turns with one summary. The su
87
87
 
88
88
  - **The dialogue and your prompts, ranked.** Since 1.0.18, one ranked list decides what a cut carries, across the summary and the kept tail together: the current prompt, whole; the openings of the first prompt and the newest answered prompts, sized to the room; the newest part of the conversation, kept as it is; the file and action lists below; and the rest of the conversation. Dropped turns and tool results are counted with index ranges that `tuck_recall` reads back. Clipped text says how to read it in full.
89
89
  - **The files.** Files the agent read, wrote or edited, newest first (up to 60), each with a pointer to read it back.
90
+ - **Kept reads** (1.1.0 and later). After the Files list, the summary carries the newest whole read of each file that has no later write or edit, headed `read PATH (as recorded at #N; no write or edit recorded since):`. It keeps at most 4 files, whole outputs only, within 20% of the summary's room and never more than 24,000 characters. When the summary is over its target, these records are dropped first, oldest first. With no such reads the summary is unchanged, and tool outputs are never touched. The header says only that no write or edit was recorded since the read; it does not say the file on disk is unchanged. After a cut, agents often doubted what an earlier read had shown and read the same file again, and this is meant to spare that. It has no effectiveness result yet; see Benchmarks.
90
91
  - **The action trail.** The agent's other tool calls, such as shell commands, newest first (up to 30). The output is left out. A pointer leads to it.
91
92
 
92
93
  Tool output stays in the session file, not in the summary. 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.
@@ -135,6 +136,11 @@ Known limits today:
135
136
  - A request above the room could be admitted and then refused, leaving the session stuck where native Pi would have sent (1.0.22 to 1.0.24; fixed in 1.0.25). pi-tuck checked its line in its own corrected token count, while Pi's reply cap uses Pi's own estimate, which is higher when the provider counts fewer tokens than pi-tuck's raw measure ([`CHANGELOG.md`](CHANGELOG.md) 1.0.25).
136
137
  - Near the 1.0.22 refusal line, replies were cut to a few hundred tokens (1.0.22; fixed in 1.0.23). 1.0.22 left only its reply floor and did not count Pi's 4,096-token margin on the reply cap ([`CHANGELOG.md`](CHANGELOG.md) 1.0.23).
137
138
  - Cost of the 1.0.22 change: between the room and the window, the reply reserve no longer cushions a wrong count. At a cold start an undercount can reach the provider. A provider that errors is caught and learned from; a server that truncates silently truncates, as it does for native Pi. With a setup above the room, cuts are forced and frequent, each freeing little, which beats a stranded session ([`CHANGELOG.md`](CHANGELOG.md) 1.0.22).
139
+ - Fixed in 1.0.33: a file read's recall number pointed at the read call, not at what the read returned. The summary lists each file the session read with a `tuck_recall` number, and that number brought back the call's arguments instead of the file's contents, so recalling a read cost a turn and showed nothing useful. It now brings back the read's output ([`CHANGELOG.md`](CHANGELOG.md) 1.0.33).
140
+ - Fixed in 1.0.32: background indexing never started at the cuts pi-tuck makes itself. Pi announces only its own compactions, so cuts pi-tuck saved after a tool round, at the end of a run, or before retrying a reply that hit the output limit started no indexing ([`CHANGELOG.md`](CHANGELOG.md) 1.0.32).
141
+ - Fixed in 1.0.31: input that arrived after a tool round had been checked, such as another extension's context or a newly enabled tool, could push the next request past the hard line, and the final check refused a request that pi-tuck could still cut. It now cuts at that check, carries the cut in that request, saves it at the next boundary, and refuses only when no cut can fit ([`CHANGELOG.md`](CHANGELOG.md) 1.0.31).
142
+ - Fixed in 1.0.29, when Pi's configured window was larger than the server's: a session could get stuck after one overflow, because pi-tuck mistook a cut Pi had saved for one Pi had failed to save. And a server that silently shrinks the reply to fit its real window went unnoticed, so pi-tuck answered fewer prompts than plain Pi. A reply that stops for length below the reply cap Pi sent is now read as the server's real window: pi-tuck learns it, keeps it for the model in the session, plans with the smaller window, and retries that turn once ([`CHANGELOG.md`](CHANGELOG.md) 1.0.29).
143
+ - 1.0.28 moved each piece of state that had several owners to one owner: the pending cut, the run, reply fit and semantic setup. Requests were unchanged. It also fixed a plan made for a prompt that another extension handled, which could still answer Pi's own compaction check before a later run and make a cut deeper than needed ([`CHANGELOG.md`](CHANGELOG.md) 1.0.28).
138
144
  - A run that a custom message started could lose that message after a cut in the middle of the run (fixed in 1.0.27). pi-tuck protected only a prompt the user typed, so a tool-loop cut in a run an extension started with a custom message kept the message neither whole nor quoted, and later requests lacked the instruction that started the run. Now such a message gets the same protection as a typed prompt: it is kept, or quoted whole in the summary, and the guard checks it. A custom message with no text has nothing to quote and stays unprotected ([`CHANGELOG.md`](CHANGELOG.md) 1.0.27).
139
145
  - A prompt's cut could reach a run it was not planned for (fixed in 1.0.24). pi-tuck plans a prompt's cut when the prompt arrives. When another extension handled that prompt, no run started, and the plan waited for the next run. A run started by a custom message carried a cut sized for the prompt that never ran, deeper than needed. After a move in the session tree (`/tree`), the plan was applied on the new branch, where its kept entry was not present, so the request lost the custom message that started the run, even on a branch that needed no cut ([`CHANGELOG.md`](CHANGELOG.md) 1.0.24).
140
146
  - Four `tuck_search` faults, fixed in 1.0.23: it said semantic recall was still indexing when the history was fully indexed; in the turn after a prompt's cut it ranked nothing ("nothing is out of view"); a keyword-search timeout on a very long history failed the whole search, where now the semantic results still answer; and the timeout message named a pattern instead of the history's size ([`CHANGELOG.md`](CHANGELOG.md) 1.0.23).
@@ -156,6 +162,7 @@ Each row says what was measured, under which conditions, and where the data is.
156
162
  | Pi's default compaction settings, 32k window, pi-tuck 1.0.10 candidate | Passed as registered: 0 dead tasks and 0 stuck sessions on 30 tasks, on a slow local server (27 of 30 tasks hit the 30-minute wall cap, and 2 had a first request the server never answered). 6 resolved. A counter written later, which counts a task with no token as dead, would count those 2. **The registered counter counts refusals and cannot see a task that began without its prompt**: in 8 of the 30 tasks (4, 8, 9, 10, 13, 14, 17, 21) a cut at the prompt kept no turn, none of the 8 resolved, and 6 ended with an empty patch. So the pass shows no refusal, not that every task began with its prompt. The 1.0.11 candidate on the same test had 7 of 30 such tasks, 1 resolved. Fixed in 1.0.12 | Candidate `a67ec30` of 1.0.10, `mac-studio/main`, window 32,768, output cap 16,384, Pi's default `reserveTokens` 16,384 and `keepRecentTokens` 20,000, one session of chain t06. One mid-run refusal (a round with 9,020 tokens of reasoning against the 16,384-token room). One session per arm, one model. In 12 of the 15 tasks across both arms the model's own first messages show it lacked the prompt; the other 3 are not clear from the records | [`benchmark/RESULTS-DEFAULTS-1010.md`](benchmark/RESULTS-DEFAULTS-1010.md) |
157
163
  | Pi's default compaction settings, 32k window, pi-tuck 1.0.8 | 28 of 30 tasks lost (tasks 3 to 30, each refused at its prompt); 1 resolved. Fails the pre-registered bar of 0 lost tasks | pi-tuck 1.0.8 (`86935e9`), `mac-studio/main`, window 32,768, output cap 16,384, `reserveTokens` 16,384 and `keepRecentTokens` 20,000 (larger than the room), one session of chain t06. One session, one model, one build: it shows that the failure occurs at these settings, not how often. Not comparable with other rows | [`benchmark/RESULTS-DEFAULTS.md`](benchmark/RESULTS-DEFAULTS.md) |
158
164
  | Tasks resolved, 32k window | Pi's built-in compaction 94 of 150; pi-tuck 120 of 150 (+17.3 points, 95% lower bound +10.7); observation masking 117 of 150 (pi-tuck +2.0, lower bound −2.7: no difference shown). Turns per task: 9.4 (built-in), 24.0 (pi-tuck), 11.9 (masking). Tokens per session: 6.10 M, 6.39 M, 7.02 M. Spend per arm for the five sessions: $0.87, $0.55, $0.94 | pi-tuck 1.0.5 (commit `aa30824`, the 1.0.5 code; 1.0.6 and 1.0.7 are not measured). DeepSeek V4.1 Flash pinned to one upstream, window 32,768, reserve 16,384, 5 chains of 30 SWE-bench Verified tasks, paired by task, one-sided bootstrap over tasks. **Limits:** only pi-tuck is held to the 16,384-token room (the built-in sent a request over it in 97 of 150 tasks, masking in 73, so the window is nominal for them). The difference by chain is +10.0, −3.3, +50.0, +16.7 and +13.3 points; leaving out chain t03 it is +9.2. The bootstrap resamples tasks, not chains. The pi-tuck arm ran at a different time from the others. One model, one window. pi-tuck refused to cut mid-run in 5 tasks, where one fresh tool result was larger than the room; they count as unresolved. In the same setup pi-tuck 1.0.3 resolved 72 of 150, with 52 dead tasks (tasks refused at their prompt after an earlier failure). In the pi-tuck arm of this row there was 1 dead task (t03 task 24: refused at its prompt with "Nothing to compact"; the next task ran normally), so this build missed the pre-registered acceptance bar of zero dead tasks by one task (the other part of the bar, no loss against 1.0.3 by more than 3 points, was met) | [`benchmark/RESULTS-32K-ACCEPT.md`](benchmark/RESULTS-32K-ACCEPT.md) |
165
+ | Kept reads (1.1.0): 5-task check against 1.0.31, and replay against 1.0.33 | No breakage in 5 of 5 tasks, and all 5 solved on both builds. Re-checks after a doubt 22 against 45; doubt moments 9 against 24; cuts 22 against 26; turns 305 against 384. One heavy task went worse: 90 turns against 59, 9 cuts against 4, 3 doubts against 1. Replay against 1.0.33: 13,946 requests, 0 lost or dead tasks, clips 17 to 16, cuts 1,946 to 1,971; in every recording that differs, the first difference is the first summary carrying a kept read, and 11 of 29 never differ | Five tasks, before the Tier 1. This is not an effectiveness result and no effectiveness claim is made for kept reads. The Tier 1 against 1.0.33 is still running; if it fails, npm and installs go back to 1.0.33. Strict stress: 0 findings in 313 cells on Pi 1.2.0 and the newest Pi | [`CHANGELOG.md`](CHANGELOG.md) 1.1.0 |
159
166
  | pi-tuck 1.0.18 against the recorded 1.0.16 arm, 81,920 window | Registered bar (Tier 1) met: both arms resolved the same 56 of 60 tasks (+0.0 points, one-sided 95% lower bound +0.0, against a bar of above −10); 0 lost tasks: dead tasks, mid-run refusals and dropped prompts are 0 in both arms, and the audit listed one candidate task (t06 task 21), which, with the two other candidate tasks that had a cut at a prompt (t06 task 8, t07 task 24), was read by hand and works on its own task. Readouts: turns per task 22.27 against 29.35, cuts 57 against 61, total tokens 40.3 M against 62.1 M. Against the recorded 1.0.13 arm of the adaptive gate, a different pair of runs a day apart, 1.0.18 is at 22.27 turns per task against 20.22 and 40.3 M tokens against 37.4 M | Pre-registered gate. pi-tuck 1.0.18 (`2d1f830`, tag `v1.0.18`), run from the unpacked npm tarball; its `src/` is byte-identical to `1ea1e1e`, the commit replay and the stress test measured, ran alone on chains t06 and t07 (60 tasks) against the recorded 1.0.16 arm; the arms did not run side by side, the base earlier the same day, so seconds are not compared. One model, one window, one run per arm. The resolved result is a bound, not a gain. The turn, cut and token readouts are reported, not claimed | [`benchmark/RESULTS-V1018.md`](benchmark/RESULTS-V1018.md) |
160
167
  | pi-tuck 1.0.16 against the recorded 1.0.13 arm, 81,920 window | Registered bar (Tier 1) met: resolved 56 of 60 against 55 (+1.7 points, one-sided 95% lower bound +0.0, against a bar of above −10); 0 lost tasks. Readouts: turns per task 29.35 against 20.22 (1.48 times on the 55 tasks both resolved, 95% interval 1.34 to 1.64), cuts 61 against 35, total tokens 62.1 M against 37.4 M | Pre-registered gate. pi-tuck 1.0.16 (`dee0eab`) ran alone on chains t06 and t07 (60 tasks) against the recorded 1.0.13 arm from the adaptive gate; the two arms did not run side by side, the base a day earlier, so seconds are not compared. One model, one window, one run per arm. The resolved result is a bound, not a gain. The cost readouts are reported, not claimed. 1.0.18 replaced this build's quote rules | [`benchmark/RESULTS-V1016.md`](benchmark/RESULTS-V1016.md) |
161
168
  | The adaptive cut point (1.0.13) against 1.0.12, 81,920 window | Registered bar (Tier 2) met: resolved 131 of 150 in both arms (+0.0 points, one-sided 95% lower bound −1.3, against a bar of above −5); 0 lost tasks in the candidate arm. The 0 counts dead tasks, tasks whose prompt was dropped at a cut, and tasks an audit found started without their prompt; all 11 tasks with a cut at a prompt, in both arms, were also read by hand, and in each the model's first messages work on that task | Pre-registered gate. pi-tuck 1.0.13 (`6f13685`) is the exact code the gate measured (`882f6f6`); only the version and the notes changed. It was measured against pi-tuck 1.0.12, `mac-studio/main` at xhigh, window 81,920, reserve 16,384, `keepRecentTokens` 20,000, 5 chains (t06 to t10) of 30 tasks, 150 paired tasks, one run per arm, one model throughout. The resolved result is a bound, not a gain. Turns, tokens and seconds are in the file and are not claimed here. Nothing about other windows, models or builds | [`benchmark/RESULTS-ADAPTIVE.md`](benchmark/RESULTS-ADAPTIVE.md) |
@@ -222,7 +229,7 @@ The first time a session starts, pi-tuck downloads what it needs, once, about 39
222
229
 
223
230
  Every file is pinned to a SHA-256 in [src/assets.ts](src/assets.ts) and checked before use. Everything goes to `~/.pi/agent/pi-tuck`; to remove it, delete that folder. Setup needs about 6.5 GB of free disk space while it runs, and uses 460 MB after. If it fails, for example offline, pi-tuck says so and tries again at the next session start. The first-time setup needs one interactive start: one-shot runs (`pi -p`) do not start the download. Since 1.0.21, a `pi -p` run starts semantic search when the runtime is already installed. If it is not installed, pi-tuck says so and starts no download. With no UI, an off or failing semantic recall, or a bad settings file, is written once per message per session to stderr, never into the model's context.
224
231
 
225
- Indexing starts in the background the first time a session uses `tuck_search`, and catches up after each compaction. Semantic search is off when Pi runs in a folder that contains Pi's agent folder, such as your home folder, because its own files live there. Open Pi in a project folder.
232
+ Since 1.0.32, at every cut pi-tuck indexes in the background what the cut moved out of view, so a first `tuck_search` finds it without embedding it then. One background indexer runs per machine at a time, holding a lock in the index folder, so several Pi sessions do not each load the encoder. A search never waits for that lock, the worker is given back once the window is indexed, and the cut itself never waits for indexing. Semantic search is off when Pi runs in a folder that contains Pi's agent folder, such as your home folder, because its own files live there. Open Pi in a project folder.
226
233
 
227
234
  ## Use from code
228
235
 
package/dist/index.js CHANGED
@@ -92,6 +92,8 @@ export default async function (pi) {
92
92
  pi.on("session_start", (_event, ctx) => {
93
93
  const current = ++session;
94
94
  stderrSaid.clear();
95
+ if (handle.state?.(ctx).kind === "standingDown")
96
+ return;
95
97
  if (settings.error)
96
98
  once(ctx, `pi-tuck: ${settings.error}; using the defaults.`, "warning");
97
99
  if (!appleSilicon)
@@ -1 +1 @@
1
- export declare const BUILD_ID = "ca81d2cebd530b421127fa0090adc48f14b9532bc7195141dcc4ced449c8f791";
1
+ export declare const BUILD_ID = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
@@ -1 +1 @@
1
- export const BUILD_ID = "ca81d2cebd530b421127fa0090adc48f14b9532bc7195141dcc4ced449c8f791";
1
+ export const BUILD_ID = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
@@ -17,13 +17,25 @@ export declare const CALIBRATION_WINDOW = 32;
17
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
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
19
  export declare const MEASURED_CALIBRATION: Readonly<Record<string, number>>;
20
- /** The calibration window a session starts with under accounting identity `key`: the newest compaction on the branch that carries this package's
20
+ 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
21
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`.
22
23
  * Otherwise its `calibrationWindow` (an array of 1..CALIBRATION_WINDOW finite numbers, oldest first) is the window, each entry clamped to
23
24
  * [0, CALIBRATION_CEILING]; without a valid one, the window is its `calibrationFactor` clamped to [1, CALIBRATION_CEILING] as one entry, else
24
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
25
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. */
26
27
  export declare function seedWindow(branch: readonly SessionEntry[], key: string): number[];
28
+ export type CompactionState = {
29
+ kind: "active";
30
+ } | {
31
+ kind: "standingDown";
32
+ reason: string;
33
+ };
34
+ /** Only evidenced prerequisites disable our request/summary transforms. A missing model keeps the existing explicit error. */
35
+ export declare function compactionState(model: {
36
+ api: string;
37
+ contextWindow?: number;
38
+ } | undefined, enabled: boolean): CompactionState;
27
39
  export interface CompactionOptions {
28
40
  semanticRecall?: SemanticRecallController;
29
41
  /** Whether `tuck_search` exists: false where semantic recall cannot run (off Apple silicon), so the model is offered word recall only. */
@@ -167,4 +179,5 @@ export declare function installCompaction(pi: ExtensionAPI, options?: Compaction
167
179
  };
168
180
  };
169
181
  };
182
+ state: (ctx: ExtensionContext) => CompactionState;
170
183
  }>;
@@ -55,6 +55,15 @@ class CommitFault extends Error {
55
55
  /** A refusal for want of room, which the user can remedy: it carries advice. */
56
56
  class CapacityError extends Refusal {
57
57
  }
58
+ function notify(ctx, message, level) {
59
+ try {
60
+ if (ctx.hasUI === false)
61
+ process.stderr.write(message + "\n");
62
+ else
63
+ ctx.ui.notify(message, level);
64
+ }
65
+ catch { /* ended */ }
66
+ }
58
67
  /** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
59
68
  * likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
60
69
  export const refusalNotice = (message, factor) => message + "; shorten the input, use a model with a larger window, or lower Pi's compaction.reserveTokens, then retry." +
@@ -82,7 +91,8 @@ function initialWindow(key) {
82
91
  return [1];
83
92
  }
84
93
  }
85
- /** The calibration window a session starts with under accounting identity `key`: the newest compaction on the branch that carries this package's
94
+ export const CALIBRATION_RECEIPT = 'pi-tuck-calibration';
95
+ /** 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
86
96
  * receipt decides, and no older receipt is consulted. A receipt without the identity field (written before it existed) or from another identity gives `initialWindow`.
87
97
  * Otherwise its `calibrationWindow` (an array of 1..CALIBRATION_WINDOW finite numbers, oldest first) is the window, each entry clamped to
88
98
  * [0, CALIBRATION_CEILING]; without a valid one, the window is its `calibrationFactor` clamped to [1, CALIBRATION_CEILING] as one entry, else
@@ -91,12 +101,16 @@ function initialWindow(key) {
91
101
  export function seedWindow(branch, key) {
92
102
  for (let i = branch.length; i--;) {
93
103
  const entry = branch[i];
94
- const receipt = entry.type === "compaction" ? entry.details?.diagnosticReceipt : undefined;
104
+ const receipt = entry.type === "custom" && entry.customType === CALIBRATION_RECEIPT ? { settings: entry.data }
105
+ : entry.type === "compaction" ? entry.details?.diagnosticReceipt : undefined;
95
106
  if (receipt === undefined)
96
107
  continue;
97
108
  const { calibrationIdentity, calibrationFactor, calibrationWindow } = receipt?.settings ?? {}, stored = calibrationWindow;
98
- if (calibrationIdentity !== key)
109
+ if (calibrationIdentity !== key) {
110
+ if (entry.type === "custom")
111
+ continue; // Another model's new observation does not hide this model's last saved seed.
99
112
  return initialWindow(key);
113
+ }
100
114
  if (Array.isArray(stored) && stored.length >= 1 && stored.length <= CALIBRATION_WINDOW && stored.every(n => typeof n === "number" && Number.isFinite(n)))
101
115
  return stored.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING));
102
116
  if (typeof calibrationFactor === "number" && Number.isFinite(calibrationFactor))
@@ -105,6 +119,14 @@ export function seedWindow(branch, key) {
105
119
  }
106
120
  return initialWindow(key);
107
121
  }
122
+ /** Only evidenced prerequisites disable our request/summary transforms. A missing model keeps the existing explicit error. */
123
+ export function compactionState(model, enabled) {
124
+ const reason = !enabled ? "compaction is disabled" : model?.api === "pi-virtual" ? "pi-virtual model" : !model ? undefined
125
+ : model.contextWindow === undefined ? "context window is missing"
126
+ : !Number.isFinite(model.contextWindow) ? "context window is not finite"
127
+ : model.contextWindow <= 0 ? "context window is zero or negative" : undefined;
128
+ return reason ? { kind: "standingDown", reason } : { kind: "active" };
129
+ }
108
130
  export async function installCompaction(pi, options = {}) {
109
131
  const piMath = await loadPiRequestMath();
110
132
  const piMargin = options.requestReserve ? 0 : await piContextSafetyMargin(piMath);
@@ -174,7 +196,8 @@ export async function installCompaction(pi, options = {}) {
174
196
  } });
175
197
  pi.on("session_compact", (_event, ctx) => observe(ctx));
176
198
  // A saved cut moves entries out of view: index them now, in the background, even for a session that has not searched or whose worker the idle limit stopped.
177
- pi.on("session_compact", (_event, ctx) => { semantic.indexAtCut(semanticProvider(ctx)); });
199
+ pi.on("session_compact", (_event, ctx) => { if (!standDown(ctx))
200
+ semantic.indexAtCut(semanticProvider(ctx)); });
178
201
  pi.on("session_shutdown", async () => { semanticRequest++; recorder.stop("session-shutdown"); await semantic.close(); await Promise.allSettled([...semanticPending]); });
179
202
  pi.on("session_start", () => { semanticRequest++; semanticTransition = semantic.close(); void semanticTransition.catch(error => { options.fail?.(error); }); });
180
203
  pi.on("turn_end", (_event, ctx) => { semantic.schedule(semanticProvider(ctx)); });
@@ -226,7 +249,7 @@ export async function installCompaction(pi, options = {}) {
226
249
  } });
227
250
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
228
251
  const state = semantic.status();
229
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
252
+ ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
230
253
  } });
231
254
  // Pi's native start/settled events bracket the run and its post-turn cuts.
232
255
  let run;
@@ -237,6 +260,16 @@ export async function installCompaction(pi, options = {}) {
237
260
  const clips = () => run?.clips ?? emptyClips;
238
261
  const emptyClips = new Map();
239
262
  const resetRun = () => { run = undefined; pending = undefined; };
263
+ const stateFor = (ctx) => compactionState(ctx.model, settingsFor().getCompactionSettings(ctx.model).enabled);
264
+ // A prerequisite can change with the model/settings; discard the old plan before returning control to native.
265
+ const standDown = (ctx) => {
266
+ if (stateFor(ctx).kind === "active")
267
+ return false;
268
+ resetRun();
269
+ windowObservation = undefined;
270
+ lengthStop = false;
271
+ return true;
272
+ };
240
273
  const promptRefusal = () => new Refusal("Prompt check failed: the whole starting prompt cannot fit after cutting to the band and room, shrinking the summary and clipping fresh results. Shorten the prompt or choose a model with a larger context window, then retry");
241
274
  let estimatedTokens = 0;
242
275
  // One serial request, one accounting identity; observations never certify new content. A new identity (the first request after a session
@@ -275,8 +308,15 @@ export async function installCompaction(pi, options = {}) {
275
308
  };
276
309
  });
277
310
  // The factor is max(1, the last CALIBRATION_WINDOW paired ratios, overflow bounds and seed): it rises at once and a stale high ratio ages out.
278
- const learn = (value) => { ratios.push(value); if (ratios.length > CALIBRATION_WINDOW)
279
- ratios.shift(); factor = Math.max(1, ...ratios); };
311
+ const learn = (value, ctx) => {
312
+ ratios.push(value);
313
+ if (ratios.length > CALIBRATION_WINDOW)
314
+ ratios.shift();
315
+ factor = Math.max(1, ...ratios);
316
+ // Compare what a cold instance would seed (including the existing clamps). Stable windows write nothing.
317
+ if (!isDeepStrictEqual(seedWindow(ctx.sessionManager.getBranch(), identity), ratios.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING))))
318
+ pi.appendEntry(CALIBRATION_RECEIPT, { calibrationIdentity: identity, calibrationWindow: [...ratios] });
319
+ };
280
320
  const corrected = (tokens, ctx) => { identityFor(ctx); return Math.ceil(tokens * factor); };
281
321
  const observeBudget = (rawTokens, ctx) => {
282
322
  if (options.observeBudget)
@@ -291,6 +331,8 @@ export async function installCompaction(pi, options = {}) {
291
331
  pi.on("message_end", (event, ctx) => {
292
332
  if (event.message.role !== "assistant")
293
333
  return;
334
+ if (standDown(ctx))
335
+ return;
294
336
  const responseMessage = event.message;
295
337
  if (recorder.enabled && !recorder.waitingForCut)
296
338
  recorder.measureInline(() => {
@@ -316,9 +358,9 @@ export async function installCompaction(pi, options = {}) {
316
358
  if (overflow) {
317
359
  const window = contextWindow(ctx), bound = (window + 1) / paired.tokens;
318
360
  const learned = bound <= CALIBRATION_CEILING;
319
- ctx.ui.notify(overflowNotice(window, bound, learned), "warning");
361
+ notify(ctx, overflowNotice(window, bound, learned), "warning");
320
362
  if (learned)
321
- learn(bound);
363
+ learn(bound, ctx);
322
364
  return;
323
365
  }
324
366
  const usage = message.usage;
@@ -340,9 +382,11 @@ export async function installCompaction(pi, options = {}) {
340
382
  // Learning from one sets the factor for the requests after it: a 60,000-token cache read reported in a 32,768-token window made a
341
383
  // 6,000-token prompt refuse. The overflow branch above learns from a refusal, where the count is a lower bound, and the ceiling is unchanged.
342
384
  if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio))
343
- learn(ratio);
385
+ learn(ratio, ctx);
344
386
  });
345
- pi.on("turn_end", event => {
387
+ pi.on("turn_end", (event, ctx) => {
388
+ if (standDown(ctx))
389
+ return;
346
390
  if (windowObservation?.message !== event.message)
347
391
  return;
348
392
  const observation = windowObservation;
@@ -353,29 +397,24 @@ export async function installCompaction(pi, options = {}) {
353
397
  // The operator's length-stop notice is decided at settle and is not attempt state: a run reset before then (a tree move inside another
354
398
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
355
399
  let lengthStop = false;
356
- pi.on("agent_start", () => { run ??= createRun("admitted"); run.phase = "admitted"; run.thinkingRetryPending = false; lengthStop = false; pending = undefined; });
400
+ pi.on("agent_start", (_event, ctx) => { if (standDown(ctx))
401
+ return; run ??= createRun("admitted"); run.phase = "admitted"; run.thinkingRetryPending = false; lengthStop = false; pending = undefined; });
357
402
  pi.on("message_end", event => { if (event.message.role === "assistant")
358
403
  lengthStop = event.message.stopReason === "length"; });
359
404
  pi.on("agent_settled", (_event, ctx) => {
360
405
  try {
361
- if (!lengthStop || !active())
406
+ if (standDown(ctx) || !lengthStop || !active())
362
407
  return;
363
408
  lengthStop = false;
364
409
  const message = "pi-tuck: the last reply stopped at the model's output limit and may be cut off. Ask the agent to continue.";
365
- try {
366
- if (ctx.hasUI === false)
367
- process.stderr.write(message + "\n");
368
- else
369
- ctx.ui.notify(message, "warning");
370
- }
371
- catch { /* ended */ }
410
+ notify(ctx, message, "warning");
372
411
  }
373
412
  finally {
374
413
  resetRun();
375
414
  }
376
415
  });
377
416
  const active = () => options.active?.() ?? true;
378
- const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings());
417
+ const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings?.());
379
418
  // The one reserve decision; every consumer takes its room from limits. Standalone starts at Pi's native cut point. Once a reply did
380
419
  // not fit (a length stop with text/tools, or a refusal pi-ai classes as a context overflow), hold the catalogue maximum too. A thinking-only
381
420
  // length stop uses branchReplyFloor's observed output instead; reserving the catalogue maximum would strand setups above the room.
@@ -492,7 +531,7 @@ export async function installCompaction(pi, options = {}) {
492
531
  recorder.stop("native-attempt-failed");
493
532
  // Every refusal says why, once per attempt: a capacity error with what the user can change, a cut Pi failed to commit with what that
494
533
  // means for the session, anything else as it is (an attempt that ended with no word looked like a hang).
495
- const previous = failure(), notify = !previous;
534
+ const previous = failure(), shouldNotify = !previous;
496
535
  const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
497
536
  const receipted = run?.refusalReceipted;
498
537
  resetRun();
@@ -509,8 +548,8 @@ export async function installCompaction(pi, options = {}) {
509
548
  }
510
549
  finally {
511
550
  try {
512
- if (notify)
513
- ctx.ui.notify(fault instanceof CapacityError ? refusalNotice(fault.message, factor) : fault instanceof CommitFault
551
+ if (shouldNotify)
552
+ notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, factor) : fault instanceof CommitFault
514
553
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
515
554
  : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error");
516
555
  }
@@ -610,6 +649,8 @@ export async function installCompaction(pi, options = {}) {
610
649
  } });
611
650
  pi.on("session_before_compact", (event, ctx) => {
612
651
  try {
652
+ if (standDown(ctx))
653
+ return;
613
654
  if (!active())
614
655
  return { cancel: true };
615
656
  if (event.signal.aborted || ctx.signal?.aborted) {
@@ -633,7 +674,7 @@ export async function installCompaction(pi, options = {}) {
633
674
  // pi-tuck's summary is built from the session itself, so text after /compact cannot steer it. The operator asked for a cut: make the one
634
675
  // plain /compact makes and say the text was not used, rather than cancel (which Pi shows as an error, with no cut).
635
676
  if (event.customInstructions?.trim())
636
- ctx.ui.notify("pi-tuck: /compact ignores the text after it, since pi-tuck builds its summary from the session itself. Cutting as plain /compact does.", "info");
677
+ notify(ctx, "pi-tuck: /compact ignores the text after it, since pi-tuck builds its summary from the session itself. Cutting as plain /compact does.", "info");
637
678
  const { response, room } = limits(ctx);
638
679
  const retain = operatorManual || run?.phase === "admitted";
639
680
  // A cut Pi asks for (an operator's /compact, Pi's threshold or overflow recovery) charges what the request must carry whatever is
@@ -684,7 +725,7 @@ export async function installCompaction(pi, options = {}) {
684
725
  if (decision.kind === "none" || decision.kind === "defer")
685
726
  return { cancel: true };
686
727
  recorder.stop("no-cut");
687
- ctx.ui.notify(decision.message, "warning");
728
+ notify(ctx, decision.message, "warning");
688
729
  if (operatorManual)
689
730
  receipt("refusal", decision.message, ctx);
690
731
  if (!operatorManual)
@@ -700,15 +741,15 @@ export async function installCompaction(pi, options = {}) {
700
741
  }
701
742
  }
702
743
  });
703
- pi.on("session_before_tree", (event) => event.preparation.userWantsSummary ? { cancel: true } : undefined);
744
+ pi.on("session_before_tree", (event, ctx) => !standDown(ctx) && event.preparation.userWantsSummary ? { cancel: true } : undefined);
704
745
  pi.on("session_start", () => { resetRun(); recorder.stop("session-transition"); proposalId = undefined; commitFault = undefined; estimatedTokens = 0; identity = ""; factor = 1; learnedContextWindow = undefined; windowObservation = undefined; });
705
- const historyToolsEnabled = (ctx) => view(ctx).hasTuckCut;
746
+ const historyToolsEnabled = (ctx) => stateFor(ctx).kind === "active" && view(ctx).hasTuckCut;
706
747
  const syncHistoryTools = (ctx) => { if (active())
707
748
  applyHistoryTools(pi, historyToolsEnabled(ctx)); };
708
749
  pi.on("session_start", (_event, ctx) => syncHistoryTools(ctx));
709
750
  // A plan decided on `input` is for the branch it was decided on: moving in the tree leaves it planned for another branch, whose kept entry
710
751
  // may not be on this one.
711
- pi.on("session_tree", (_event, ctx) => { resetRun(); windowObservation = undefined; learnedContextWindow = seedContextWindow(ctx.sessionManager.getBranch(), identityFor(ctx)); syncHistoryTools(ctx); });
752
+ pi.on("session_tree", (_event, ctx) => { resetRun(); windowObservation = undefined; identity = ""; identityFor(ctx); syncHistoryTools(ctx); });
712
753
  pi.on("session_compact", (_event, ctx) => { if (run?.phase !== "admitted")
713
754
  syncHistoryTools(ctx); });
714
755
  pi.on("turn_start", (_event, ctx) => syncHistoryTools(ctx));
@@ -759,6 +800,8 @@ export async function installCompaction(pi, options = {}) {
759
800
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
760
801
  // Pi's defaults on a 32k window). Each request of the run carries the cut, and the run's first boundary saves it.
761
802
  const preflight = (ctx, incomingPart, incomingMessages, observedPrompt, tools, hostSnapshot) => {
803
+ if (standDown(ctx))
804
+ return;
762
805
  run.cut.clear();
763
806
  const branchLength = ctx.sessionManager.getBranch().length;
764
807
  if (!active())
@@ -820,6 +863,8 @@ export async function installCompaction(pi, options = {}) {
820
863
  run.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, branchLength);
821
864
  };
822
865
  pi.on("before_agent_start", async (event, ctx) => {
866
+ if (standDown(ctx))
867
+ return;
823
868
  // A decided plan is for the prompt `input` saw. A run that a custom message starts is not that run (another extension handled the
824
869
  // input, so no run started for it): plan afresh.
825
870
  const prompted = run?.phase === "decided" && event.messageType !== "custom";
@@ -854,6 +899,8 @@ export async function installCompaction(pi, options = {}) {
854
899
  // handlers have run. Pi's prepareRequest has not yet snapshotted executable tools. A first cut discovered in context_with_system
855
900
  // would be too late for that snapshot, even if its declarations were repaired there, so make the late prompt decision here.
856
901
  pi.on("message_end", (event, ctx) => {
902
+ if (standDown(ctx))
903
+ return;
857
904
  if (event.message.role !== "user" || !active() || run?.phase !== "admitted" || view(ctx).pending)
858
905
  return;
859
906
  try {
@@ -1051,8 +1098,10 @@ export async function installCompaction(pi, options = {}) {
1051
1098
  // Pi's later native length recovery from retrying it independently. The stored message and its output usage stay on the branch.
1052
1099
  const entries = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries),
1053
1100
  { type: "context_edit", targetId: event.messageEntryId, replacement: null }];
1054
- if (run.thinkingRetryPending)
1101
+ if (run.thinkingRetryPending) {
1102
+ markBoundary(entries);
1055
1103
  return { entries, continue: false };
1104
+ }
1056
1105
  const preview = liveCut.view(ctx, entries).session;
1057
1106
  const view = Object.create(ctx, { sessionManager: { value: preview } });
1058
1107
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
@@ -1069,9 +1118,11 @@ export async function installCompaction(pi, options = {}) {
1069
1118
  clips().set(id, clip);
1070
1119
  const { room, hardLine } = limits(view);
1071
1120
  run.thinkingRetryPending = true;
1072
- return { entries: [...entries, { type: "custom", customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
1073
- stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: false,
1074
- piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }], continue: true };
1121
+ const drafts = [...entries, { type: "custom", customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
1122
+ stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: false,
1123
+ piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }];
1124
+ markBoundary(drafts);
1125
+ return { entries: drafts, continue: true };
1075
1126
  }
1076
1127
  if (decision.kind !== "cut")
1077
1128
  throw new CapacityError(clampMessage);
@@ -1099,6 +1150,8 @@ export async function installCompaction(pi, options = {}) {
1099
1150
  };
1100
1151
  pi.on("turn_end", (event, ctx) => {
1101
1152
  try {
1153
+ if (standDown(ctx))
1154
+ return;
1102
1155
  if (!active() || run?.phase !== "admitted")
1103
1156
  return;
1104
1157
  if ((thinkingOnlyLength(event.message) || serverClipped.has(event.message)) && !failure() && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
@@ -1195,6 +1248,8 @@ export async function installCompaction(pi, options = {}) {
1195
1248
  };
1196
1249
  pi.on("context", (event, ctx) => {
1197
1250
  try {
1251
+ if (standDown(ctx))
1252
+ return;
1198
1253
  if (!active())
1199
1254
  return;
1200
1255
  run?.prompt?.id(ctx.sessionManager.getBranch());
@@ -1214,6 +1269,8 @@ export async function installCompaction(pi, options = {}) {
1214
1269
  }
1215
1270
  });
1216
1271
  pi.on("session_compact_failed", (event, ctx) => {
1272
+ if (standDown(ctx))
1273
+ return;
1217
1274
  // This compactor's own refusal of a Pi threshold ask (the gate, or an opportunistic cut that cannot reach the band) reaches here as a
1218
1275
  // threshold compaction cancelled and not from an extension: no event for the recorder.
1219
1276
  if (event.reason === "threshold" && event.aborted && !event.fromExtension)
@@ -1233,6 +1290,8 @@ export async function installCompaction(pi, options = {}) {
1233
1290
  fail(new (event.fromExtension ? CommitFault : Error)(event.errorMessage ?? "Compaction failed"), ctx);
1234
1291
  });
1235
1292
  pi.on("agent_before_settle", (event, ctx) => {
1293
+ if (standDown(ctx))
1294
+ return;
1236
1295
  if (run?.pendingBoundaryCommit) {
1237
1296
  if (event.outcome === "error") {
1238
1297
  try {
@@ -1262,6 +1321,8 @@ export async function installCompaction(pi, options = {}) {
1262
1321
  }
1263
1322
  });
1264
1323
  pi.on("context_with_system", (event, ctx) => {
1324
+ if (standDown(ctx))
1325
+ return;
1265
1326
  // Reaching the next request boundary proves native commit returned, not durable storage.
1266
1327
  if (run) {
1267
1328
  run.pendingBoundaryCommit = false;
@@ -1321,7 +1382,7 @@ export async function installCompaction(pi, options = {}) {
1321
1382
  fail(error, ctx);
1322
1383
  }
1323
1384
  });
1324
- return { close: async () => { semanticRequest++; recorder.stop("caller-close"); await semantic.close(); await Promise.allSettled([...semanticPending]); }, semanticRecall: semantic, setSemanticEnabled, semanticStatus };
1385
+ return { close: async () => { semanticRequest++; recorder.stop("caller-close"); await semantic.close(); await Promise.allSettled([...semanticPending]); }, semanticRecall: semantic, setSemanticEnabled, semanticStatus, state: stateFor };
1325
1386
  }
1326
1387
  function checkedInput(raw) { if (!Check(RecallInput, raw))
1327
1388
  throw new Error("Invalid recall input"); return structuredClone(raw); }
@@ -1,6 +1,6 @@
1
1
  import { type RecallPolicy } from './recall.js';
2
2
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
3
- export declare const DIAGNOSTIC_BUILD = "ca81d2cebd530b421127fa0090adc48f14b9532bc7195141dcc4ced449c8f791";
3
+ export declare const DIAGNOSTIC_BUILD = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -0,0 +1,4 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import type { TranscriptRecord } from "./tuck/core/transcript.js";
3
+ /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
4
+ export declare function keptReadCandidates(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
@@ -0,0 +1,40 @@
1
+ import { isTextOnly, textOf } from "./tuck/core/content.js";
2
+ import { extractPath } from "./tuck/core/tool-args.js";
3
+ /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
4
+ export function keptReadCandidates(entries, indices, resolvable) {
5
+ const reads = new Map(), mutations = new Map();
6
+ let order = 0;
7
+ for (const entry of entries) {
8
+ if (entry.type !== "message" || entry.message.role !== "assistant")
9
+ continue;
10
+ for (const block of entry.message.content) {
11
+ if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) ||
12
+ !block.arguments || typeof block.arguments !== "object")
13
+ continue;
14
+ const path = extractPath(block.arguments);
15
+ if (!path || /[\r\n]/u.test(path))
16
+ continue;
17
+ order++;
18
+ if (block.name === "read")
19
+ reads.set(block.id, { path, order });
20
+ else
21
+ mutations.set(path, order);
22
+ }
23
+ }
24
+ const seen = new Set(), records = [];
25
+ for (let at = entries.length - 1; at >= 0; at--) {
26
+ const entry = entries[at];
27
+ if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content))
28
+ continue;
29
+ const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
30
+ if (!read || seen.has(read.path) || (mutations.get(read.path) ?? -1) > read.order)
31
+ continue;
32
+ const text = textOf(entry.message.content);
33
+ if (!text.length || sourceIndex === undefined || !resolvable(entry))
34
+ continue;
35
+ seen.add(read.path);
36
+ records.push({ kind: "section", title: "Kept-read", sourceIndex,
37
+ text: `read ${read.path} (as recorded at #${sourceIndex}; no write or edit recorded since):\n${text}` });
38
+ }
39
+ return records;
40
+ }
@@ -133,6 +133,8 @@ export declare const MAX_INDEX_UNITS = 8000;
133
133
  export declare function healDelayMs(attempts: number, integrity: boolean, delays?: readonly number[], steady?: number): number;
134
134
  export type SemanticState = 'disabled' | 'unavailable' | 'preparing' | 'ready' | 'waiting';
135
135
  export type SemanticSetup = 'off-settings' | 'off-user' | 'not-installed' | 'off-platform' | 'off-project' | 'starting' | 'failed' | 'ready';
136
+ /** Host policy is re-evaluated at session start; only a start may publish ready. */
137
+ export declare const SEMANTIC_SETUP_TRANSITIONS: Readonly<Record<SemanticSetup, readonly SemanticSetup[]>>;
136
138
  interface SetupDetail {
137
139
  installed?: boolean;
138
140
  reason?: string;