pi-tuck 1.1.0 → 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,32 @@
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
+
6
32
  ## [1.1.0] - 2026-11-13
7
33
 
8
34
  ### Added
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 = "4031a9c8a1371d6ed9eb73970d3b1f676181d9065a344501750ef711a9aaba4a";
1
+ export declare const BUILD_ID = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
@@ -1 +1 @@
1
- export const BUILD_ID = "4031a9c8a1371d6ed9eb73970d3b1f676181d9065a344501750ef711a9aaba4a";
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 = "4031a9c8a1371d6ed9eb73970d3b1f676181d9065a344501750ef711a9aaba4a";
3
+ export declare const DIAGNOSTIC_BUILD = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -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;
@@ -222,6 +222,18 @@ const SCORE_CHUNK = 1024;
222
222
  export function healDelayMs(attempts, integrity, delays = HEAL_DELAYS_MS, steady = HEAL_STEADY_MS) { return integrity ? steady : delays[attempts] ?? steady; }
223
223
  /** Errors that mean "the history moved or a slice ended; try again", not that the runtime failed. They do not make the state `unavailable`. */
224
224
  const CHURN = /indexing incomplete|history changed|source changed before|branch or source changed|cancelled/i;
225
+ const OFF_SETUP = ['off-settings', 'off-user', 'off-platform', 'off-project'];
226
+ /** Host policy is re-evaluated at session start; only a start may publish ready. */
227
+ export const SEMANTIC_SETUP_TRANSITIONS = {
228
+ 'off-settings': OFF_SETUP,
229
+ 'off-user': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
230
+ 'off-platform': [...OFF_SETUP, 'not-installed', 'starting'],
231
+ 'off-project': [...OFF_SETUP, 'not-installed', 'starting'],
232
+ 'not-installed': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
233
+ starting: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
234
+ failed: [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
235
+ ready: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
236
+ };
225
237
  /** Setup and operator wording have one owner; runtime indexing state remains separate. */
226
238
  export function semanticSetupMessage(setup, detail = {}) {
227
239
  switch (setup) {
@@ -597,7 +609,14 @@ export class SemanticRecallController {
597
609
  _timer;
598
610
  _error = null;
599
611
  get enabled() { return this._enabled; }
600
- set enabled(value) { this._enabled = value; this.touch(); }
612
+ set enabled(value) {
613
+ this._enabled = value;
614
+ if (!value && this.setup === 'ready') {
615
+ const reason = this.error ?? this.cleanupError;
616
+ this.setSetup(reason ? 'failed' : 'off-user', reason ? { stage: 'start', reason } : {});
617
+ }
618
+ this.touch();
619
+ }
601
620
  get current() { return this._current; }
602
621
  set current(value) { this._current = value; this.touch(); }
603
622
  get task() { return this._task; }
@@ -644,7 +663,14 @@ export class SemanticRecallController {
644
663
  }
645
664
  catch { } }); }
646
665
  /** A host that could not configure the runtime records why a requested start failed. The controller stays disabled and `lastError` carries the reason until the next `enable`. */
647
- setSetup(setup, detail = {}) { const announced = setup === 'ready' && this.setupDetail.announced; this.setup = setup; this.setupDetail = announced ? { ...detail, announced: true } : detail; this.touch(); }
666
+ setSetup(setup, detail = {}) {
667
+ if (!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes(setup))
668
+ return;
669
+ const announced = setup === 'ready' && this.setupDetail.announced;
670
+ this.setup = setup;
671
+ this.setupDetail = announced ? { ...detail, announced: true } : detail;
672
+ this.touch();
673
+ }
648
674
  /** Compatibility for hosts that already record an external start failure. */
649
675
  refuse(reason) { this.setSetup('failed', { stage: 'start', reason }); }
650
676
  setupNotice() { return semanticSetupNotice(this.setup, this.setupDetail); }
@@ -669,10 +695,31 @@ export class SemanticRecallController {
669
695
  const text = await readFile(path, 'utf8').catch((error) => { throw error.code === 'ENOENT' ? new Error('Semantic recall is not set up yet: pi-tuck sets it up when a session starts, unless pi-tuck.json turns it off') : error; });
670
696
  this.configure({ ...JSON.parse(text), ...(runtime?.nativeOwnerHelperPath === undefined ? {} : { nativeOwnerHelperPath: runtime.nativeOwnerHelperPath }) });
671
697
  }
672
- enable() { if (this.closing || this.joiningSearches || this.cleanupError)
673
- throw new Error('Semantic cleanup is unresolved; retry close before enable'); if (!this.config)
674
- throw new Error('Optional local semantic runtime is not configured'); this.setSetup('ready'); this.enabled = true; this.error = null; this.healReason = null; this.healAttempts = 0; this.cancelHeal(); if (this.provider && this.active)
675
- this.schedule(this.provider); }
698
+ enable() {
699
+ // Explicit opt-in can end off-user; project, platform and settings policy belongs to the host.
700
+ if (['off-user', 'not-installed', 'failed'].includes(this.setup))
701
+ this.setSetup('starting');
702
+ if (!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes('ready'))
703
+ return;
704
+ try {
705
+ if (this.closing || this.joiningSearches || this.cleanupError)
706
+ throw new Error('Semantic cleanup is unresolved; retry close before enable');
707
+ if (!this.config)
708
+ throw new Error('Optional local semantic runtime is not configured');
709
+ this.setSetup('ready');
710
+ this.enabled = true;
711
+ this.error = null;
712
+ this.healReason = null;
713
+ this.healAttempts = 0;
714
+ this.cancelHeal();
715
+ if (this.provider && this.active)
716
+ this.schedule(this.provider);
717
+ }
718
+ catch (error) {
719
+ this.setSetup('failed', { stage: 'start', reason: error instanceof Error ? error.message : String(error) });
720
+ throw error;
721
+ }
722
+ }
676
723
  status() { return { setup: this.setup, setupMessage: semanticSetupMessage(this.setup, this.setupDetail), enabled: this.enabled, configured: Boolean(this.config), cleanupError: this.cleanupError, state: (!this.enabled ? 'disabled' : this.healReason !== null || (this.error !== null && !CHURN.test(this.error)) ? 'unavailable' : this.task || this.timer ? 'preparing' : this.current?.complete ? 'ready' : 'waiting'), snapshotId: this.current?.id ?? null, throughEntryId: this.current?.throughEntryId ?? null, eligibleSources: this.current?.sources.length ?? 0, totalUnits: this.current?.units.length ?? 0, coveredUnits: this.current?.indexed.size ?? 0, indexingComplete: Boolean(this.current?.complete), lastError: this.error ?? this.healReason ?? semanticSetupMessage(this.setup, this.setupDetail), window: this.current ? windowCoverage(this.current) : null, recovery: this.healReason === null ? null : { attempts: this.healAttempts, integrity: this.healIntegrity, retryAt: this.healRetryAt === null ? null : new Date(this.healRetryAt).toISOString() }, operations: { ...this.operations }, limits: { keyword: 16000, broad: 20000 } }; }
677
724
  /** The existing model-facing coverage contract: setup metadata belongs to operator status, not the request. */
678
725
  requestCoverage() { const { setup, setupMessage, ...coverage } = this.status(); return coverage; }
@@ -5,6 +5,7 @@ export declare const LOADED_VERSION: string;
5
5
  export declare function statusText(input: {
6
6
  version: string;
7
7
  active: boolean;
8
+ compaction?: import('./compaction.js').CompactionState;
8
9
  branch: readonly {
9
10
  type: string;
10
11
  tokensBefore?: unknown;
@@ -15,6 +15,8 @@ export const LOADED_VERSION = (() => {
15
15
  export function statusText(input) {
16
16
  if (!input.active)
17
17
  return `pi-tuck ${input.version} is loaded but inactive in this host; Pi's own compaction runs.`;
18
+ if (input.compaction?.kind === 'standingDown')
19
+ return `pi-tuck ${input.version}: standing down: ${input.compaction.reason}; Pi's own compaction runs.`;
18
20
  const cuts = input.branch.filter(e => e.type === "compaction"), ours = cuts.filter(e => e.details?.compactor === "pi-tuck");
19
21
  const last = ours.at(-1), before = last?.tokensBefore, after = last?.details?.tokensAfter;
20
22
  const count = (n) => n.toLocaleString("en-US");
package/index.ts CHANGED
@@ -72,6 +72,7 @@ export default async function (pi: ExtensionAPI) {
72
72
  pi.on("session_start", (_event, ctx) => {
73
73
  const current = ++session;
74
74
  stderrSaid.clear();
75
+ if (handle.state?.(ctx).kind === "standingDown") return;
75
76
  if (settings.error) once(ctx, `pi-tuck: ${settings.error}; using the defaults.`, "warning");
76
77
  if (!appleSilicon)
77
78
  return announce(ctx, "off-platform");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history. Search by meaning on Apple silicon.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "4031a9c8a1371d6ed9eb73970d3b1f676181d9065a344501750ef711a9aaba4a";
1
+ export const BUILD_ID = "d2c1d18d69bb46f33f11ad8aeffc04ea0085035e24b1570b12d4039ae9ce3b5a";
package/src/compaction.ts CHANGED
@@ -56,6 +56,9 @@ class Refusal extends Error {}
56
56
  class CommitFault extends Error {}
57
57
  /** A refusal for want of room, which the user can remedy: it carries advice. */
58
58
  class CapacityError extends Refusal {}
59
+ function notify(ctx: ExtensionContext, message: string, level: "info" | "warning" | "error") {
60
+ try { if (ctx.hasUI === false) process.stderr.write(message + "\n"); else ctx.ui.notify(message, level); } catch { /* ended */ }
61
+ }
59
62
  /** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
60
63
  * likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
61
64
  export const refusalNotice = (message: string, factor: number): string =>
@@ -79,7 +82,8 @@ export const MEASURED_CALIBRATION: Readonly<Record<string, number>> = {};
79
82
  function initialWindow(key: string): number[] {
80
83
  try { const [provider, , id] = JSON.parse(key) as [string, string, string]; return [Math.min(MEASURED_CALIBRATION[`${provider}/${id}`] ?? 1, CALIBRATION_CEILING)]; } catch { return [1]; }
81
84
  }
82
- /** The calibration window a session starts with under accounting identity `key`: the newest compaction on the branch that carries this package's
85
+ export const CALIBRATION_RECEIPT = 'pi-tuck-calibration';
86
+ /** 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
83
87
  * receipt decides, and no older receipt is consulted. A receipt without the identity field (written before it existed) or from another identity gives `initialWindow`.
84
88
  * Otherwise its `calibrationWindow` (an array of 1..CALIBRATION_WINDOW finite numbers, oldest first) is the window, each entry clamped to
85
89
  * [0, CALIBRATION_CEILING]; without a valid one, the window is its `calibrationFactor` clamped to [1, CALIBRATION_CEILING] as one entry, else
@@ -88,10 +92,14 @@ function initialWindow(key: string): number[] {
88
92
  export function seedWindow(branch: readonly SessionEntry[], key: string): number[] {
89
93
  for (let i = branch.length; i--;) {
90
94
  const entry = branch[i]!;
91
- const receipt = entry.type === "compaction" ? (entry.details as { diagnosticReceipt?: { settings?: Partial<Receipt["settings"]> } | null } | undefined)?.diagnosticReceipt : undefined;
95
+ const receipt = entry.type === "custom" && entry.customType === CALIBRATION_RECEIPT ? { settings: entry.data as Partial<Receipt["settings"]> | undefined }
96
+ : entry.type === "compaction" ? (entry.details as { diagnosticReceipt?: { settings?: Partial<Receipt["settings"]> } | null } | undefined)?.diagnosticReceipt : undefined;
92
97
  if (receipt === undefined) continue;
93
98
  const { calibrationIdentity, calibrationFactor, calibrationWindow } = receipt?.settings ?? {}, stored: unknown = calibrationWindow;
94
- if (calibrationIdentity !== key) return initialWindow(key);
99
+ if (calibrationIdentity !== key) {
100
+ if (entry.type === "custom") continue; // Another model's new observation does not hide this model's last saved seed.
101
+ return initialWindow(key);
102
+ }
95
103
  if (Array.isArray(stored) && stored.length >= 1 && stored.length <= CALIBRATION_WINDOW && stored.every(n => typeof n === "number" && Number.isFinite(n)))
96
104
  return stored.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING));
97
105
  if (typeof calibrationFactor === "number" && Number.isFinite(calibrationFactor)) return [Math.min(Math.max(calibrationFactor, 1), CALIBRATION_CEILING)];
@@ -99,6 +107,15 @@ export function seedWindow(branch: readonly SessionEntry[], key: string): number
99
107
  }
100
108
  return initialWindow(key);
101
109
  }
110
+ export type CompactionState = { kind: "active" } | { kind: "standingDown"; reason: string };
111
+ /** Only evidenced prerequisites disable our request/summary transforms. A missing model keeps the existing explicit error. */
112
+ export function compactionState(model: { api: string; contextWindow?: number } | undefined, enabled: boolean): CompactionState {
113
+ const reason = !enabled ? "compaction is disabled" : model?.api === "pi-virtual" ? "pi-virtual model" : !model ? undefined
114
+ : model.contextWindow === undefined ? "context window is missing"
115
+ : !Number.isFinite(model.contextWindow) ? "context window is not finite"
116
+ : model.contextWindow <= 0 ? "context window is zero or negative" : undefined;
117
+ return reason ? { kind: "standingDown", reason } : { kind: "active" };
118
+ }
102
119
  export interface CompactionOptions {
103
120
  semanticRecall?: SemanticRecallController;
104
121
  /** Whether `tuck_search` exists: false where semantic recall cannot run (off Apple silicon), so the model is offered word recall only. */
@@ -186,7 +203,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
186
203
  } });
187
204
  pi.on("session_compact", (_event, ctx) => observe(ctx));
188
205
  // 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.
189
- pi.on("session_compact", (_event, ctx) => { semantic.indexAtCut(semanticProvider(ctx)); });
206
+ pi.on("session_compact", (_event, ctx) => { if (!standDown(ctx)) semantic.indexAtCut(semanticProvider(ctx)); });
190
207
  pi.on("session_shutdown", async () => { semanticRequest++; recorder.stop("session-shutdown"); await semantic.close(); await Promise.allSettled([...semanticPending]); });
191
208
  pi.on("session_start", () => { semanticRequest++; semanticTransition = semantic.close();void semanticTransition.catch(error => { options.fail?.(error); }); });
192
209
  pi.on("turn_end", (_event,ctx) => { semantic.schedule(semanticProvider(ctx)); });
@@ -223,7 +240,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
223
240
  }});
224
241
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
225
242
  const state = semantic.status();
226
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
243
+ 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");
227
244
  } });
228
245
  // Pi's native start/settled events bracket the run and its post-turn cuts.
229
246
  let run: Run | undefined;
@@ -234,6 +251,15 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
234
251
  const clips = () => run?.clips ?? emptyClips;
235
252
  const emptyClips = new Map<string, Clip>();
236
253
  const resetRun = () => { run = undefined; pending = undefined; };
254
+ const stateFor = (ctx: ExtensionContext) => compactionState(ctx.model, settingsFor().getCompactionSettings(ctx.model).enabled);
255
+ // A prerequisite can change with the model/settings; discard the old plan before returning control to native.
256
+ const standDown = (ctx: ExtensionContext) => {
257
+ if (stateFor(ctx).kind === "active") return false;
258
+ resetRun();
259
+ windowObservation = undefined;
260
+ lengthStop = false;
261
+ return true;
262
+ };
237
263
  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");
238
264
  let estimatedTokens = 0;
239
265
  // One serial request, one accounting identity; observations never certify new content. A new identity (the first request after a session
@@ -265,7 +291,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
265
291
  };
266
292
  });
267
293
  // 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.
268
- const learn = (value: number) => { ratios.push(value); if (ratios.length > CALIBRATION_WINDOW) ratios.shift(); factor = Math.max(1, ...ratios); };
294
+ const learn = (value: number, ctx: ExtensionContext) => {
295
+ ratios.push(value); if (ratios.length > CALIBRATION_WINDOW) ratios.shift(); factor = Math.max(1, ...ratios);
296
+ // Compare what a cold instance would seed (including the existing clamps). Stable windows write nothing.
297
+ if (!isDeepStrictEqual(seedWindow(ctx.sessionManager.getBranch(), identity), ratios.map(n => Math.min(Math.max(n, 0), CALIBRATION_CEILING))))
298
+ pi.appendEntry(CALIBRATION_RECEIPT, { calibrationIdentity: identity, calibrationWindow: [...ratios] });
299
+ };
269
300
  const corrected = (tokens: number, ctx: ExtensionContext) => { identityFor(ctx); return Math.ceil(tokens * factor); };
270
301
  const observeBudget = (rawTokens: number, ctx: ExtensionContext) => {
271
302
  if (options.observeBudget) options.observeBudget({ rawTokens, tokens: corrected(rawTokens, ctx), factor, ...limits(ctx), context: ctx });
@@ -278,6 +309,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
278
309
  };
279
310
  pi.on("message_end", (event, ctx) => {
280
311
  if (event.message.role !== "assistant") return;
312
+ if (standDown(ctx)) return;
281
313
  const responseMessage = event.message;
282
314
  if (recorder.enabled && !recorder.waitingForCut) recorder.measureInline(() => {
283
315
  if (!responseMessage.content.some(b => b.type === "thinking")) recorder.capture("response-actions", "native-public-message-end", responseMessage);
@@ -298,8 +330,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
298
330
  if (overflow) {
299
331
  const window = contextWindow(ctx), bound = (window + 1) / paired.tokens;
300
332
  const learned = bound <= CALIBRATION_CEILING;
301
- ctx.ui.notify(overflowNotice(window, bound, learned), "warning");
302
- if (learned) learn(bound);
333
+ notify(ctx, overflowNotice(window, bound, learned), "warning");
334
+ if (learned) learn(bound, ctx);
303
335
  return;
304
336
  }
305
337
  const usage = message.usage;
@@ -318,9 +350,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
318
350
  // A request that was answered cannot have held more than the model's window, so a report above it describes something that never happened.
319
351
  // 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
320
352
  // 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.
321
- if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio)) learn(ratio);
353
+ if (input > 0 && input <= ctx.model.contextWindow && Number.isSafeInteger(input) && Number.isFinite(ratio)) learn(ratio, ctx);
322
354
  });
323
- pi.on("turn_end", event => {
355
+ pi.on("turn_end", (event, ctx) => {
356
+ if (standDown(ctx)) return;
324
357
  if (windowObservation?.message !== event.message) return;
325
358
  const observation = windowObservation; windowObservation = undefined;
326
359
  pi.appendEntry(WINDOW_RECEIPT, { calibrationIdentity: observation.identity, learnedContextWindow: observation.window,
@@ -329,18 +362,18 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
329
362
  // 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
330
363
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
331
364
  let lengthStop = false;
332
- pi.on("agent_start", () => { run ??= createRun("admitted"); run.phase = "admitted"; run.thinkingRetryPending = false; lengthStop = false; pending = undefined; });
365
+ pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= createRun("admitted"); run.phase = "admitted"; run.thinkingRetryPending = false; lengthStop = false; pending = undefined; });
333
366
  pi.on("message_end", event => { if (event.message.role === "assistant") lengthStop = event.message.stopReason === "length"; });
334
367
  pi.on("agent_settled", (_event, ctx) => {
335
368
  try {
336
- if (!lengthStop || !active()) return;
369
+ if (standDown(ctx) || !lengthStop || !active()) return;
337
370
  lengthStop = false;
338
371
  const message = "pi-tuck: the last reply stopped at the model's output limit and may be cut off. Ask the agent to continue.";
339
- try { if (ctx.hasUI === false) process.stderr.write(message + "\n"); else ctx.ui.notify(message, "warning"); } catch { /* ended */ }
372
+ notify(ctx, message, "warning");
340
373
  } finally { resetRun(); }
341
374
  });
342
375
  const active = () => options.active?.() ?? true;
343
- const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings());
376
+ const settingsFor = () => options.settings ?? SettingsManager.inMemory(pi.getSettings?.());
344
377
  // The one reserve decision; every consumer takes its room from limits. Standalone starts at Pi's native cut point. Once a reply did
345
378
  // 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
346
379
  // length stop uses branchReplyFloor's observed output instead; reserving the catalogue maximum would strand setups above the room.
@@ -450,7 +483,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
450
483
  recorder.stop("native-attempt-failed");
451
484
  // 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
452
485
  // means for the session, anything else as it is (an attempt that ended with no word looked like a hang).
453
- const previous = failure(), notify = !previous;
486
+ const previous = failure(), shouldNotify = !previous;
454
487
  const fault = previous instanceof CommitFault ? previous : error instanceof Error ? error : new Error(String(error));
455
488
  const receipted = run?.refusalReceipted;
456
489
  resetRun();
@@ -461,7 +494,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
461
494
  if (!receipted) receipt("refusal", fault.message, ctx);
462
495
  options.fail?.(error);
463
496
  } finally {
464
- try { if (notify) ctx.ui.notify(fault instanceof CapacityError ? refusalNotice(fault.message, factor) : fault instanceof CommitFault
497
+ try { if (shouldNotify) notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, factor) : fault instanceof CommitFault
465
498
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
466
499
  : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error"); }
467
500
  finally { ctx.abort(); }
@@ -533,6 +566,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
533
566
 
534
567
  pi.on("session_before_compact", (event, ctx) => {
535
568
  try {
569
+ if (standDown(ctx)) return;
536
570
  if (!active()) return { cancel: true };
537
571
  if (event.signal.aborted || ctx.signal?.aborted) { recorder.stop("cut-cancelled"); return { cancel: true }; }
538
572
  // Pi checks its own threshold after a prompt's input and before the run starts: the prompt's cut, planned with the prompt counted,
@@ -550,7 +584,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
550
584
  access();
551
585
  // 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
552
586
  // plain /compact makes and say the text was not used, rather than cancel (which Pi shows as an error, with no cut).
553
- if (event.customInstructions?.trim()) 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");
587
+ if (event.customInstructions?.trim()) 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");
554
588
  const { response, room } = limits(ctx);
555
589
  const retain = operatorManual || run?.phase === "admitted";
556
590
  // A cut Pi asks for (an operator's /compact, Pi's threshold or overflow recovery) charges what the request must carry whatever is
@@ -602,7 +636,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
602
636
  // An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
603
637
  if (decision.kind === "none" || decision.kind === "defer") return { cancel: true };
604
638
  recorder.stop("no-cut");
605
- ctx.ui.notify(decision.message, "warning");
639
+ notify(ctx, decision.message, "warning");
606
640
  if (operatorManual) receipt("refusal", decision.message, ctx);
607
641
  if (!operatorManual) fail(new (decision.capacity ? CapacityError : Refusal)(decision.message), ctx);
608
642
  return { cancel: true };
@@ -610,14 +644,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
610
644
  try { fail(error, ctx); } finally { return { cancel: true }; }
611
645
  }
612
646
  });
613
- pi.on("session_before_tree", (event) => event.preparation.userWantsSummary ? { cancel: true } : undefined);
647
+ pi.on("session_before_tree", (event, ctx) => !standDown(ctx) && event.preparation.userWantsSummary ? { cancel: true } : undefined);
614
648
  pi.on("session_start", () => { resetRun(); recorder.stop("session-transition"); proposalId = undefined; commitFault = undefined; estimatedTokens = 0; identity = ""; factor = 1; learnedContextWindow = undefined; windowObservation = undefined; });
615
- const historyToolsEnabled = (ctx: ExtensionContext) => view(ctx).hasTuckCut;
649
+ const historyToolsEnabled = (ctx: ExtensionContext) => stateFor(ctx).kind === "active" && view(ctx).hasTuckCut;
616
650
  const syncHistoryTools = (ctx: ExtensionContext) => { if (active()) applyHistoryTools(pi, historyToolsEnabled(ctx)); };
617
651
  pi.on("session_start", (_event, ctx) => syncHistoryTools(ctx));
618
652
  // 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
619
653
  // may not be on this one.
620
- pi.on("session_tree", (_event, ctx) => { resetRun(); windowObservation = undefined; learnedContextWindow = seedContextWindow(ctx.sessionManager.getBranch(), identityFor(ctx)); syncHistoryTools(ctx); });
654
+ pi.on("session_tree", (_event, ctx) => { resetRun(); windowObservation = undefined; identity = ""; identityFor(ctx); syncHistoryTools(ctx); });
621
655
  pi.on("session_compact", (_event, ctx) => { if (run?.phase !== "admitted") syncHistoryTools(ctx); });
622
656
  pi.on("turn_start", (_event, ctx) => syncHistoryTools(ctx));
623
657
  pi.on("agent_settled", (_event, ctx) => syncHistoryTools(ctx));
@@ -661,6 +695,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
661
695
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
662
696
  // Pi's defaults on a 32k window). Each request of the run carries the cut, and the run's first boundary saves it.
663
697
  const preflight = (ctx: ExtensionContext, incomingPart: number, incomingMessages: Messages, observedPrompt: string, tools: readonly string[], hostSnapshot?: Messages) => {
698
+ if (standDown(ctx)) return;
664
699
  run!.cut.clear();
665
700
  const branchLength = ctx.sessionManager.getBranch().length;
666
701
  if (!active()) return;
@@ -719,6 +754,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
719
754
  run!.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, branchLength);
720
755
  };
721
756
  pi.on("before_agent_start", async (event, ctx) => {
757
+ if (standDown(ctx)) return;
722
758
  // A decided plan is for the prompt `input` saw. A run that a custom message starts is not that run (another extension handled the
723
759
  // input, so no run started for it): plan afresh.
724
760
  const prompted = run?.phase === "decided" && event.messageType !== "custom";
@@ -747,6 +783,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
747
783
  // handlers have run. Pi's prepareRequest has not yet snapshotted executable tools. A first cut discovered in context_with_system
748
784
  // would be too late for that snapshot, even if its declarations were repaired there, so make the late prompt decision here.
749
785
  pi.on("message_end", (event, ctx) => {
786
+ if (standDown(ctx)) return;
750
787
  if (event.message.role !== "user" || !active() || run?.phase !== "admitted" || view(ctx).pending) return;
751
788
  try {
752
789
  access();
@@ -928,7 +965,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
928
965
  // Pi's later native length recovery from retrying it independently. The stored message and its output usage stay on the branch.
929
966
  const entries: SessionBoundaryDraft[] = [...(atBoundary(event, ctx, "run-end", false)?.entries ?? event.entries),
930
967
  { type: "context_edit", targetId: event.messageEntryId, replacement: null }];
931
- if (run!.thinkingRetryPending) return { entries, continue: false };
968
+ if (run!.thinkingRetryPending) { markBoundary(entries); return { entries, continue: false }; }
932
969
  const preview = liveCut.view(ctx, entries).session;
933
970
  const view: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
934
971
  const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
@@ -943,9 +980,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
943
980
  clips().clear(); for (const [id, clip] of previousClips) clips().set(id, clip);
944
981
  const { room, hardLine } = limits(view);
945
982
  run!.thinkingRetryPending = true;
946
- return { entries: [...entries, { type: "custom" as const, customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
983
+ const drafts = [...entries, { type: "custom" as const, customType: "pi-tuck-capacity", data: { kind: "retry", stoppedReplyEntryId: event.messageEntryId,
947
984
  stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: false,
948
- piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }], continue: true };
985
+ piEstimateTokens: asIsCheck.estimate, piCap: asIsCheck.cap, room, hardLine, buildId: BUILD_ID } }];
986
+ markBoundary(drafts);
987
+ return { entries: drafts, continue: true };
949
988
  }
950
989
  if (decision.kind !== "cut") throw new CapacityError(clampMessage);
951
990
  const messages = projectedRequest(decision.plan.messages, view, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true);
@@ -971,6 +1010,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
971
1010
  };
972
1011
  pi.on("turn_end", (event, ctx) => {
973
1012
  try {
1013
+ if (standDown(ctx)) return;
974
1014
  if (!active() || run?.phase !== "admitted") return;
975
1015
  if ((thinkingOnlyLength(event.message) || serverClipped.has(event.message)) && !failure() && !ctx.signal?.aborted && settingsFor().getCompactionSettings(ctx.model).enabled)
976
1016
  return retryLength(event, ctx);
@@ -1061,6 +1101,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1061
1101
  };
1062
1102
  pi.on("context", (event, ctx) => {
1063
1103
  try {
1104
+ if (standDown(ctx)) return;
1064
1105
  if (!active()) return;
1065
1106
  run?.prompt?.id(ctx.sessionManager.getBranch());
1066
1107
  // Before a cut, Pi owns the whole request, including its object identities and system-message serialization.
@@ -1070,6 +1111,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1070
1111
  } catch (error) { try { fail(error, ctx); } finally { return historyToolsEnabled(ctx) ? { messages: [] } : undefined; } }
1071
1112
  });
1072
1113
  pi.on("session_compact_failed", (event, ctx) => {
1114
+ if (standDown(ctx)) return;
1073
1115
  // 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
1074
1116
  // threshold compaction cancelled and not from an extension: no event for the recorder.
1075
1117
  if (event.reason === "threshold" && event.aborted && !event.fromExtension) return;
@@ -1084,6 +1126,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1084
1126
  if (active() && !event.aborted) fail(new (event.fromExtension ? CommitFault : Error)(event.errorMessage ?? "Compaction failed"), ctx);
1085
1127
  });
1086
1128
  pi.on("agent_before_settle", (event, ctx) => {
1129
+ if (standDown(ctx)) return;
1087
1130
  if (run?.pendingBoundaryCommit) {
1088
1131
  if (event.outcome === "error") {
1089
1132
  try { if (!boundarySaved(ctx)) throw new Error("Boundary receipt absent from the session file"); }
@@ -1100,6 +1143,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1100
1143
  } catch (error) { fail(error, ctx); }
1101
1144
  });
1102
1145
  pi.on("context_with_system", (event, ctx) => {
1146
+ if (standDown(ctx)) return;
1103
1147
  // Reaching the next request boundary proves native commit returned, not durable storage.
1104
1148
  if (run) { run.pendingBoundaryCommit = false; run.pendingBoundaryReceipts = []; }
1105
1149
  pending = undefined;
@@ -1148,7 +1192,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1148
1192
 
1149
1193
  } catch (error) { fail(error, ctx); }
1150
1194
  });
1151
- return {close:async()=>{semanticRequest++;recorder.stop("caller-close");await semantic.close();await Promise.allSettled([...semanticPending]);}, semanticRecall:semantic, setSemanticEnabled, semanticStatus};
1195
+ return {close:async()=>{semanticRequest++;recorder.stop("caller-close");await semantic.close();await Promise.allSettled([...semanticPending]);}, semanticRecall:semantic, setSemanticEnabled, semanticStatus, state: stateFor};
1152
1196
  }
1153
1197
 
1154
1198
  function checkedInput(raw: unknown) { if (!Check(RecallInput, raw)) throw new Error("Invalid recall input"); return structuredClone(raw); }
@@ -140,6 +140,18 @@ export function healDelayMs(attempts:number,integrity:boolean,delays:readonly nu
140
140
  const CHURN=/indexing incomplete|history changed|source changed before|branch or source changed|cancelled/i;
141
141
  export type SemanticState='disabled'|'unavailable'|'preparing'|'ready'|'waiting';
142
142
  export type SemanticSetup = 'off-settings' | 'off-user' | 'not-installed' | 'off-platform' | 'off-project' | 'starting' | 'failed' | 'ready';
143
+ const OFF_SETUP: readonly SemanticSetup[] = ['off-settings', 'off-user', 'off-platform', 'off-project'];
144
+ /** Host policy is re-evaluated at session start; only a start may publish ready. */
145
+ export const SEMANTIC_SETUP_TRANSITIONS: Readonly<Record<SemanticSetup, readonly SemanticSetup[]>> = {
146
+ 'off-settings': OFF_SETUP,
147
+ 'off-user': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
148
+ 'off-platform': [...OFF_SETUP, 'not-installed', 'starting'],
149
+ 'off-project': [...OFF_SETUP, 'not-installed', 'starting'],
150
+ 'not-installed': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
151
+ starting: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
152
+ failed: [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
153
+ ready: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
154
+ };
143
155
  interface SetupDetail { installed?: boolean; reason?: string; stage?: 'setup' | 'start'; notice?: string; announced?: boolean }
144
156
  /** Setup and operator wording have one owner; runtime indexing state remains separate. */
145
157
  export function semanticSetupMessage(setup: SemanticSetup, detail: SetupDetail = {}): string | null {
@@ -283,7 +295,11 @@ export class SemanticRecallController {
283
295
  // The fields below decide `status().state`; their setters announce a change to `onStateChange` listeners.
284
296
  private setup: SemanticSetup = 'off-user'; private setupDetail: SetupDetail = {};
285
297
  private _enabled=false;private _current?:Snapshot;private _task?:Promise<void>;private _timer?:ReturnType<typeof setTimeout>;private _error:string|null=null;
286
- private get enabled(){return this._enabled;}private set enabled(value:boolean){this._enabled=value;this.touch();}
298
+ private get enabled(){return this._enabled;}private set enabled(value:boolean){
299
+ this._enabled=value;
300
+ if(!value&&this.setup==='ready'){const reason=this.error??this.cleanupError;this.setSetup(reason?'failed':'off-user',reason?{stage:'start',reason}:{});}
301
+ this.touch();
302
+ }
287
303
  private get current(){return this._current;}private set current(value:Snapshot|undefined){this._current=value;this.touch();}
288
304
  private get task(){return this._task;}private set task(value:Promise<void>|undefined){this._task=value;this.touch();}
289
305
  private get timer(){return this._timer;}private set timer(value:ReturnType<typeof setTimeout>|undefined){this._timer=value;this.touch();}
@@ -303,7 +319,10 @@ export class SemanticRecallController {
303
319
  onStateChange(listener:(state:SemanticState,reason:string|null)=>void):()=>void{this.listeners.add(listener);return()=>{this.listeners.delete(listener);};}
304
320
  private touch(){if(this.announcing)return;this.announcing=true;queueMicrotask(()=>{this.announcing=false;const {state,lastError}=this.status(),key=state+'\0'+(lastError??'');if(key===this.announced)return;this.announced=key;for(const listener of [...this.listeners])try{listener(state,lastError);}catch{}});}
305
321
  /** A host that could not configure the runtime records why a requested start failed. The controller stays disabled and `lastError` carries the reason until the next `enable`. */
306
- setSetup(setup: SemanticSetup, detail: SetupDetail = {}) { const announced = setup === 'ready' && this.setupDetail.announced; this.setup = setup; this.setupDetail = announced ? { ...detail, announced: true } : detail; this.touch(); }
322
+ setSetup(setup: SemanticSetup, detail: SetupDetail = {}) {
323
+ if(!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes(setup))return;
324
+ const announced = setup === 'ready' && this.setupDetail.announced; this.setup = setup; this.setupDetail = announced ? { ...detail, announced: true } : detail; this.touch();
325
+ }
307
326
  /** Compatibility for hosts that already record an external start failure. */
308
327
  refuse(reason:string){this.setSetup('failed', { stage: 'start', reason });}
309
328
  setupNotice(){return semanticSetupNotice(this.setup, this.setupDetail);}
@@ -312,7 +331,13 @@ export class SemanticRecallController {
312
331
  * optional override is a current-process verified dependency, not Task data. */
313
332
  async configureExternal(project:string,selectedPath=runtimeConfigPath(defaultRoot()),runtime?:{nativeOwnerHelperPath?:string}){const path=resolve(selectedPath);outsideProject(project,path,'configuration');if(runtime?.nativeOwnerHelperPath!==undefined)outsideProject(project,runtime.nativeOwnerHelperPath,'runtime');const text=await readFile(path,'utf8').catch((error:NodeJS.ErrnoException)=>{throw error.code==='ENOENT'?new Error('Semantic recall is not set up yet: pi-tuck sets it up when a session starts, unless pi-tuck.json turns it off'):error;});
314
333
  this.configure({...JSON.parse(text) as SemanticRecallConfig,...(runtime?.nativeOwnerHelperPath===undefined?{}:{nativeOwnerHelperPath:runtime.nativeOwnerHelperPath})});}
315
- enable(){if(this.closing||this.joiningSearches||this.cleanupError)throw new Error('Semantic cleanup is unresolved; retry close before enable');if(!this.config)throw new Error('Optional local semantic runtime is not configured');this.setSetup('ready');this.enabled=true;this.error=null;this.healReason=null;this.healAttempts=0;this.cancelHeal();if(this.provider&&this.active)this.schedule(this.provider);}
334
+ enable(){
335
+ // Explicit opt-in can end off-user; project, platform and settings policy belongs to the host.
336
+ if(['off-user','not-installed','failed'].includes(this.setup))this.setSetup('starting');
337
+ if(!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes('ready'))return;
338
+ try{if(this.closing||this.joiningSearches||this.cleanupError)throw new Error('Semantic cleanup is unresolved; retry close before enable');if(!this.config)throw new Error('Optional local semantic runtime is not configured');this.setSetup('ready');this.enabled=true;this.error=null;this.healReason=null;this.healAttempts=0;this.cancelHeal();if(this.provider&&this.active)this.schedule(this.provider);}
339
+ catch(error){this.setSetup('failed',{stage:'start',reason:error instanceof Error?error.message:String(error)});throw error;}
340
+ }
316
341
  status(){return{setup:this.setup,setupMessage:semanticSetupMessage(this.setup,this.setupDetail),enabled:this.enabled,configured:Boolean(this.config),cleanupError:this.cleanupError,state:(!this.enabled?'disabled':this.healReason!==null||(this.error!==null&&!CHURN.test(this.error))?'unavailable':this.task||this.timer?'preparing':this.current?.complete?'ready':'waiting') as SemanticState,snapshotId:this.current?.id??null,throughEntryId:this.current?.throughEntryId??null,eligibleSources:this.current?.sources.length??0,totalUnits:this.current?.units.length??0,coveredUnits:this.current?.indexed.size??0,indexingComplete:Boolean(this.current?.complete),lastError:this.error??this.healReason??semanticSetupMessage(this.setup,this.setupDetail),window:this.current?windowCoverage(this.current):null,recovery:this.healReason===null?null:{attempts:this.healAttempts,integrity:this.healIntegrity,retryAt:this.healRetryAt===null?null:new Date(this.healRetryAt).toISOString()},operations:{...this.operations},limits:{keyword:16000,broad:20000}};}
317
342
  /** The existing model-facing coverage contract: setup metadata belongs to operator status, not the request. */
318
343
  requestCoverage(){const {setup,setupMessage,...coverage}=this.status();return coverage;}
package/src/status.ts CHANGED
@@ -15,6 +15,7 @@ export const LOADED_VERSION: string = (() => {
15
15
  export function statusText(input: {
16
16
  version: string;
17
17
  active: boolean;
18
+ compaction?: import('./compaction').CompactionState;
18
19
  branch: readonly { type: string; tokensBefore?: unknown; details?: unknown; customType?: unknown; data?: unknown }[];
19
20
  pending?: boolean;
20
21
  cutAt: number | undefined;
@@ -22,6 +23,7 @@ export function statusText(input: {
22
23
  semantic: { state: SemanticState; lastError: string | null };
23
24
  }): string {
24
25
  if (!input.active) return `pi-tuck ${input.version} is loaded but inactive in this host; Pi's own compaction runs.`;
26
+ if (input.compaction?.kind === 'standingDown') return `pi-tuck ${input.version}: standing down: ${input.compaction.reason}; Pi's own compaction runs.`;
25
27
  const cuts = input.branch.filter(e => e.type === "compaction"), ours = cuts.filter(e => (e.details as { compactor?: unknown } | null | undefined)?.compactor === "pi-tuck");
26
28
  const last = ours.at(-1), before = last?.tokensBefore, after = (last?.details as { tokensAfter?: unknown } | undefined)?.tokensAfter;
27
29
  const count = (n: number) => n.toLocaleString("en-US");