pi-tuck 1.4.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,34 @@
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.6.0]
7
+
8
+ ### Added
9
+
10
+ - Model config check: once per Pi start, in the background, for a model whose provider is defined in `models.json`, pi-tuck compares the
11
+ context window and thinking levels with the server's `/models` reply. With a UI it asks before changing `models.json` (dated backup,
12
+ only the reported fields; a file with comments gets the exact edit instead) and remembers a "no" in `pi-tuck.json` for that server
13
+ value. Without a UI it prints nothing; `/tuck` lists the findings.
14
+
15
+ ## [1.5.0]
16
+
17
+ ### Added
18
+
19
+ - Footer: pi-tuck replaces Pi's footer in the terminal UI. Under the folder and branch line, a bar fills toward pi-tuck's trim point
20
+ (full means pi-tuck trims), with the context size, the trim point, the trim count once there is one, the cost when above $0, and the
21
+ model and thinking level; other extensions' statuses stay below. It turns yellow at 85% of the trim point instead of at Pi's 70% and
22
+ 90% of the window. Its figures are recomputed only after a reply, a trim, or a model or thinking change. `"footer": false` in `pi-tuck.json` keeps Pi's footer.
23
+ - Refusal and length-stop notices suggest `/tuck-incident next` to record the next trim for a bug report.
24
+
25
+ ### Changed
26
+
27
+ - `/tuck` says "trim" where it said "cut", the word the footer uses. The `cutAt` setting keeps its name.
28
+
29
+ ### Fixed
30
+
31
+ - `/tuck` no longer says the cut point adapts by itself: it names the default (the room less a 2% margin) and the trim point in tokens for
32
+ the current model.
33
+
6
34
  ## [1.4.1]
7
35
 
8
36
  ### Fixed
package/README.md CHANGED
@@ -12,7 +12,7 @@ pi install npm:pi-tuck
12
12
 
13
13
  Start a new Pi process after installing or updating. pi-tuck handles automatic compaction and `/compact` by default. Run `/tuck` to see the loaded version, cut history, and active cut policy.
14
14
 
15
- This README describes pi-tuck 1.4.1. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.4.1` or `pi install git:github.com/galyavin/pi-tuck@v1.4.1`. To uninstall, run `pi remove` with the source you installed.
15
+ This README describes pi-tuck 1.6.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.6.0` or `pi install git:github.com/galyavin/pi-tuck@v1.6.0`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
@@ -29,17 +29,33 @@ Read the original by the hit's `entryId`, or use `{"index": 212}` to follow a `#
29
29
  | Command | Purpose |
30
30
  |---|---|
31
31
  | `/compact` | Request a cut. pi-tuck builds the summary from the session and ignores any appended instructions. |
32
- | `/tuck` | Inspect the loaded version, saved cuts, and cut point. |
32
+ | `/tuck` | Inspect the loaded version, saved trims, and trim point. |
33
33
  | `/tuck-incident on\|next\|off\|status` | Control diagnostic recording. The default directory is `~/.local/state/pi-tuck-incidents`. |
34
34
 
35
35
  Pi-tuck needs a supported Pi version and a nonvirtual model with a valid context window. Setting `"compaction": { "enabled": false }` in Pi's settings disables automatic compaction and makes pi-tuck stand down, including for `/compact` and recall. `/tuck` reports why a loaded compactor is standing down. Capacity notices go to stderr in headless runs.
36
36
 
37
+ ## Footer
38
+
39
+ In Pi's terminal UI, pi-tuck replaces Pi's footer. Under the folder and git branch, the bar fills toward pi-tuck's trim point, the number `/tuck` reports: a full bar means pi-tuck trims. Next to it are the context size and the trim point, the trim count once pi-tuck has trimmed, the cost when it is above $0, and the model with its thinking level. Other extensions' statuses stay below. The bar turns yellow at 85% of the trim point. A narrow terminal shows only the bar and the two sizes. Right after a trim, before the next reply, the size is the trim's own estimate, shown with `~`. When pi-tuck is not trimming for the model, the line shows the context against the window. `/tuck` shows the trim history.
40
+
41
+ ```text
42
+ ~/repo (main)
43
+ context ████████░░ 19k of 24k · 2 trims main · xhigh
44
+ ```
45
+
46
+ When pi-tuck stops a request or a reply ends at its length limit, the notice suggests `/tuck-incident next` to record the next trim for a bug report.
47
+
48
+ ## Model config check
49
+
50
+ Once per Pi start, in the background, pi-tuck reads the server's own model list (`{baseUrl}/models`, with Pi's auth for that provider) for the session's model, when that model's provider is defined in Pi's `models.json`. It compares the context window (`max_model_len`, `context_length`, `context_window` or `n_ctx`; never the training length `n_ctx_train`) and the thinking levels (`reasoning.efforts`, matched only by identical names) with `models.json`. In the terminal UI each difference is a yes/no question; yes backs up `models.json` next to it with the date in the name and changes only those fields (restart Pi to use them), and no is remembered in `pi-tuck.json` until the server reports a different value. A `models.json` with comments is not rewritten; pi-tuck shows the exact edit instead. Without a UI, nothing is printed: the findings go to the session and to `/tuck`. Tested with a server whose `/v1/models` entry reports `max_model_len` and `reasoning.efforts`; other servers, including llama.cpp's, are not verified yet.
51
+
37
52
  ## Settings
38
53
 
39
54
  Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by default, or `PI_CODING_AGENT_DIR`). Restart Pi to apply changes. The input room starts at the model's context window minus Pi's `compaction.reserveTokens`. Invalid JSON uses defaults. An invalid field uses its own default, with a notice when compaction is active.
40
55
 
41
56
  - **`cutAt`** is a fraction above 0 and at most 1. By default pi-tuck cuts at the room, less a 2% margin. An explicit value fixes a fraction of the room, subject to the same margin even at `1`.
42
57
  - **`cacheSensitiveModels`** lists exact `provider/model` identifiers. For these models, the cut point is the full room, taking precedence over `cutAt`. This delays early cuts that would discard a reusable prompt prefix.
58
+ - **`footer`** set to `false` keeps Pi's own footer.
43
59
  - **`llamaContinuation`** opts one reasoning model into a single extra request after a thinking-only response exhausts the full configured output allowance. In Pi's `models.json`, configure that model on a llama.cpp provider using the `openai-completions` API. Verify that the runtime and template support `continue_final_message: "reasoning_content"` and report reused prompt tokens through `prompt_progress`. Pi-tuck requires the first cache report to match the prefix within 15 seconds. The positive integer `extraTokens` caps the additional allowance within the remaining context. The positive integer `deadlineMs` covers both requests.
44
60
 
45
61
  ```json
package/dist/index.js CHANGED
@@ -5,6 +5,8 @@ import { installCompaction } from "./src/compaction.js";
5
5
  import { validCutAt } from "./src/budget.js";
6
6
  import { notify } from "./src/notify.js";
7
7
  import { cleanupLegacyFiles } from "./src/legacy-cleanup.js";
8
+ import { installFooter } from "./src/footer.js";
9
+ import { installConfigCheck } from "./src/config-check.js";
8
10
  export { installCompaction } from "./src/compaction.js";
9
11
  export { inspectIncident, readableIncident } from "./src/diagnostic-replay.js";
10
12
  /** Pi 1.2 added the run's custom message to before_agent_start so preflight can count it. */
@@ -36,6 +38,9 @@ export default async function (pi) {
36
38
  }
37
39
  const settings = readSettings(join(getAgentDir(), "pi-tuck.json"));
38
40
  const handle = await installCompaction(pi, { cutAt: settings.cutAt, cacheSensitiveModels: settings.cacheSensitiveModels, continuationModel: settings.llamaContinuation?.model });
41
+ if (settings.footer !== false)
42
+ installFooter(pi, ctx => handle.cutPoint(ctx));
43
+ installConfigCheck(pi, { agentDir: getAgentDir() });
39
44
  const continuation = settings.llamaContinuation;
40
45
  let continuationError;
41
46
  if (continuation) {
@@ -97,6 +102,10 @@ function readSettings(path) {
97
102
  settings.llamaContinuation = c;
98
103
  else if (c !== undefined)
99
104
  warnings.push(`${path} llamaContinuation requires a provider/model identifier in model, a positive safe integer extraTokens, and an integer deadlineMs from 1 to 2147483647; native continuation is off.`);
105
+ if (typeof value.footer === "boolean")
106
+ settings.footer = value.footer;
107
+ else if (value.footer !== undefined)
108
+ warnings.push(`${path} footer must be true or false; showing pi-tuck's footer.`);
100
109
  if (warnings.length)
101
110
  settings.error = warnings.join(" ");
102
111
  return settings;
@@ -1 +1 @@
1
- export declare const BUILD_ID = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
1
+ export declare const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
@@ -1 +1 @@
1
- export const BUILD_ID = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
1
+ export const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
@@ -7,6 +7,8 @@ import type { RecallPolicy } from "./recall.js";
7
7
  export declare const refusalNotice: (message: string, factor: number) => string;
8
8
  /** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
9
9
  export declare const overflowNotice: (contextWindow: number, bound: number, learned: boolean) => string;
10
+ /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
11
+ export declare const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
10
12
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
11
13
  export declare const CALIBRATION_CEILING = 1.5;
12
14
  /** How many recent paired replies (and overflow bounds, and the seed while it is among them) the calibration factor is the maximum of. */
@@ -72,6 +74,7 @@ export interface CompactionOptions {
72
74
  export declare function installCompaction(pi: ExtensionAPI, options?: CompactionOptions): Promise<{
73
75
  close: () => Promise<void>;
74
76
  state: (ctx: ExtensionContext) => CompactionState;
77
+ cutPoint: (ctx: ExtensionContext) => number | undefined;
75
78
  inspectState: (ctx: ExtensionContext) => {
76
79
  run: Readonly<Run> | undefined;
77
80
  phase: "decided" | "claimed" | "expired" | "starting" | "admitted" | "failed" | "commit-failed" | undefined;
@@ -58,6 +58,8 @@ export const refusalNotice = (message, factor) => message + "; shorten the input
58
58
  /** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
59
59
  export const overflowNotice = (contextWindow, bound, learned) => `pi-tuck: the provider refused this request for context overflow. Using the configured ${contextWindow}-token window as the input limit gives a planning factor of ${bound.toFixed(2)}x.` +
60
60
  (learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
61
+ /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
62
+ export const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
61
63
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
62
64
  export const CALIBRATION_CEILING = 1.5;
63
65
  /** How many recent paired replies (and overflow bounds, and the seed while it is among them) the calibration factor is the maximum of. */
@@ -195,7 +197,7 @@ export async function installCompaction(pi, options = {}) {
195
197
  pi.on("session_compact", (_event, ctx) => observe(ctx));
196
198
  pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
197
199
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
198
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending }), "info");
200
+ ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx) }), "info");
199
201
  } });
200
202
  // Pi's native start/settled events bracket the run and its post-turn cuts.
201
203
  let run;
@@ -340,7 +342,7 @@ export async function installCompaction(pi, options = {}) {
340
342
  ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
341
343
  : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
342
344
  lengthStop = undefined;
343
- notify(ctx, kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message, "warning");
345
+ notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + INCIDENT_HINT, "warning");
344
346
  }
345
347
  finally {
346
348
  resetRun();
@@ -376,6 +378,18 @@ export async function installCompaction(pi, options = {}) {
376
378
  const preservePrefix = (ctx) => ctx.model !== undefined &&
377
379
  options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
378
380
  const decisionBand = (ctx, room) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
381
+ /** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
382
+ const cutPoint = (ctx) => {
383
+ if (!active() || !ctx.model || stateFor(ctx).kind !== "active")
384
+ return undefined;
385
+ try {
386
+ const band = decisionBand(ctx, limits(ctx).room);
387
+ return band > 0 ? band : undefined;
388
+ }
389
+ catch {
390
+ return undefined;
391
+ }
392
+ };
379
393
  const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
380
394
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
381
395
  const measureFor = (ctx) => (messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
@@ -498,9 +512,9 @@ export async function installCompaction(pi, options = {}) {
498
512
  finally {
499
513
  try {
500
514
  if (!receipted)
501
- notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
515
+ notify(ctx, (fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
502
516
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
503
- : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error");
517
+ : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`) + INCIDENT_HINT, "error");
504
518
  }
505
519
  finally {
506
520
  ctx.abort();
@@ -1375,7 +1389,7 @@ export async function installCompaction(pi, options = {}) {
1375
1389
  fail(error, ctx);
1376
1390
  }
1377
1391
  });
1378
- return { close: async () => { recorder.stop("caller-close"); }, state: stateFor, inspectState: (ctx) => ({ run: run, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending }) };
1392
+ return { close: async () => { recorder.stop("caller-close"); }, state: stateFor, cutPoint, inspectState: (ctx) => ({ run: run, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending }) };
1379
1393
  }
1380
1394
  function checkedInput(raw) { if (!Check(RecallInput, raw))
1381
1395
  throw new Error("Invalid recall input"); return structuredClone(raw); }
@@ -0,0 +1,54 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ /**
3
+ * The models.json check: once per Pi process, in the background at session start, for a model of a provider defined in models.json,
4
+ * read the server's own model list and compare the context window and the thinking levels with the config. With a UI each difference
5
+ * is a yes/no question; yes edits only the reported fields (after a dated backup), no is remembered in pi-tuck.json for that server
6
+ * value. Without a UI nothing is printed: the findings go to the session and to /tuck. It changes nothing the model sees.
7
+ */
8
+ export declare const CONFIG_CHECK_ENTRY = "pi-tuck-config-check";
9
+ type Map = Partial<Record<string, string | null>>;
10
+ /** What the server says about one model. Window from the first of these it reports; never n_ctx_train (the training length). */
11
+ export interface ServerModel {
12
+ window?: number;
13
+ efforts?: string[];
14
+ }
15
+ export declare function serverModel(body: unknown, id: string): ServerModel | undefined;
16
+ export interface Finding {
17
+ kind: "window" | "thinking";
18
+ /** The server value a "no" is remembered against. */
19
+ server: string;
20
+ question: string;
21
+ /** The fields to set on the model in models.json. */
22
+ patch: {
23
+ contextWindow?: number;
24
+ thinkingLevelMap?: Map;
25
+ };
26
+ }
27
+ /** The differences between the config and the server; the thinking levels only for a reasoning model whose server lists efforts. */
28
+ export declare function findings(model: {
29
+ contextWindow: number;
30
+ reasoning?: boolean;
31
+ thinkingLevelMap?: Map;
32
+ }, server: ServerModel): Finding[];
33
+ /** JSON with // and /* comments removed outside strings (Pi accepts comments in models.json). */
34
+ export declare function stripComments(text: string): string;
35
+ /** The exact edit, for a models.json Pi accepts but pi-tuck will not rewrite (it has comments). */
36
+ export declare const editText: (path: string, provider: string, id: string, patch: Finding["patch"]) => string;
37
+ /** Apply the accepted fields: back up models.json next to it, then write only those fields. Says what to tell the operator. */
38
+ export declare function applyPatch(path: string, provider: string, id: string, patch: Finding["patch"], now?: Date): {
39
+ outcome: "updated" | "edit shown" | "unchanged";
40
+ text: string;
41
+ };
42
+ /** Remembered "no" answers in pi-tuck.json: {"configCheck": {"provider/model": {"window": "272000", "thinking": "high,xhigh"}}}. */
43
+ export declare function declined(settingsPath: string): Record<string, Partial<Record<Finding["kind"], string>>>;
44
+ export declare function rememberNo(settingsPath: string, ref: string, finding: Finding): void;
45
+ export interface CheckDeps {
46
+ agentDir: string;
47
+ fetch?: typeof fetch;
48
+ now?: () => Date;
49
+ }
50
+ /** One check of the session's model. Resolves when done; never throws. */
51
+ export declare function checkModel(pi: Pick<ExtensionAPI, "appendEntry">, ctx: ExtensionContext, deps: CheckDeps): Promise<void>;
52
+ /** Run the check once per Pi process, in the background: session start never waits for it. */
53
+ export declare function installConfigCheck(pi: ExtensionAPI, deps: CheckDeps): void;
54
+ export {};
@@ -0,0 +1,196 @@
1
+ import { copyFileSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ /**
4
+ * The models.json check: once per Pi process, in the background at session start, for a model of a provider defined in models.json,
5
+ * read the server's own model list and compare the context window and the thinking levels with the config. With a UI each difference
6
+ * is a yes/no question; yes edits only the reported fields (after a dated backup), no is remembered in pi-tuck.json for that server
7
+ * value. Without a UI nothing is printed: the findings go to the session and to /tuck. It changes nothing the model sees.
8
+ */
9
+ export const CONFIG_CHECK_ENTRY = "pi-tuck-config-check";
10
+ /** Pi's thinking levels that a server can list; "off" is never a server effort. */
11
+ const LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"];
12
+ export function serverModel(body, id) {
13
+ const data = body?.data;
14
+ const entry = Array.isArray(data) ? data.find(m => m?.id === id) : undefined;
15
+ if (!entry)
16
+ return undefined;
17
+ const window = ["max_model_len", "context_length", "context_window", "n_ctx"].map(k => entry[k]).find(v => Number.isSafeInteger(v) && v > 0);
18
+ const raw = entry.reasoning?.efforts;
19
+ const efforts = Array.isArray(raw) && raw.every(e => typeof e === "string") ? raw : undefined;
20
+ return { window, efforts };
21
+ }
22
+ const k = (n) => n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`;
23
+ /** The differences between the config and the server; the thinking levels only for a reasoning model whose server lists efforts. */
24
+ export function findings(model, server) {
25
+ const out = [];
26
+ const w = server.window, c = model.contextWindow;
27
+ if (w !== undefined && w !== c)
28
+ out.push({ kind: "window", server: String(w), patch: { contextWindow: w }, question: w > c
29
+ ? `Server allows ${k(w)}, config says ${k(c)}. Use ${k(w)}?`
30
+ : `Config says ${k(c)}, but the server allows only ${k(w)}: requests past ${k(w)} will fail. Use ${k(w)}?` });
31
+ if (model.reasoning && server.efforts) {
32
+ const map = {};
33
+ for (const level of LEVELS) {
34
+ const want = server.efforts.includes(level) ? level : null;
35
+ if (model.thinkingLevelMap?.[level] !== want)
36
+ map[level] = want;
37
+ }
38
+ const on = LEVELS.filter(l => typeof model.thinkingLevelMap?.[l] === "string").join(", ") || "none";
39
+ if (Object.keys(map).length)
40
+ out.push({ kind: "thinking", server: server.efforts.join(","), patch: { thinkingLevelMap: map },
41
+ question: `Server thinking levels: ${server.efforts.join(", ") || "none"}; config enables: ${on}. Match the server?` });
42
+ }
43
+ return out;
44
+ }
45
+ /** JSON with // and /* comments removed outside strings (Pi accepts comments in models.json). */
46
+ export function stripComments(text) {
47
+ let out = "", i = 0, str = false;
48
+ while (i < text.length) {
49
+ const ch = text[i], next = text[i + 1];
50
+ if (str) {
51
+ out += ch;
52
+ if (ch === "\\") {
53
+ out += next ?? "";
54
+ i += 2;
55
+ continue;
56
+ }
57
+ if (ch === '"')
58
+ str = false;
59
+ i++;
60
+ continue;
61
+ }
62
+ if (ch === '"') {
63
+ str = true;
64
+ out += ch;
65
+ i++;
66
+ continue;
67
+ }
68
+ if (ch === "/" && next === "/") {
69
+ while (i < text.length && text[i] !== "\n")
70
+ i++;
71
+ continue;
72
+ }
73
+ if (ch === "/" && next === "*") {
74
+ const end = text.indexOf("*/", i + 2);
75
+ i = end < 0 ? text.length : end + 2;
76
+ continue;
77
+ }
78
+ out += ch;
79
+ i++;
80
+ }
81
+ return out;
82
+ }
83
+ const stamp = (d) => d.toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
84
+ /** The exact edit, for a models.json Pi accepts but pi-tuck will not rewrite (it has comments). */
85
+ export const editText = (path, provider, id, patch) => `In ${path}, provider "${provider}", model "${id}": ` + Object.entries(patch.thinkingLevelMap ?? {}).map(([l, v]) => `set thinkingLevelMap.${l} to ${JSON.stringify(v)}`)
86
+ .concat(patch.contextWindow === undefined ? [] : [`set contextWindow to ${patch.contextWindow}`]).join("; ") + ".";
87
+ /** Apply the accepted fields: back up models.json next to it, then write only those fields. Says what to tell the operator. */
88
+ export function applyPatch(path, provider, id, patch, now = new Date()) {
89
+ const text = readFileSync(path, "utf8");
90
+ let file;
91
+ try {
92
+ file = JSON.parse(text);
93
+ }
94
+ catch {
95
+ return { outcome: "edit shown", text: `pi-tuck: ${path} has comments, so pi-tuck did not change it. ${editText(path, provider, id, patch)} Then restart Pi.` };
96
+ }
97
+ const model = file.providers?.[provider]?.models?.find(m => m.id === id);
98
+ if (!model)
99
+ return { outcome: "unchanged", text: `pi-tuck: ${provider}/${id} is no longer in ${path}; nothing changed.` };
100
+ if (patch.contextWindow !== undefined)
101
+ model.contextWindow = patch.contextWindow;
102
+ if (patch.thinkingLevelMap)
103
+ model.thinkingLevelMap = { ...model.thinkingLevelMap, ...patch.thinkingLevelMap };
104
+ const backup = `${path}.before-pi-tuck-${stamp(now)}`;
105
+ copyFileSync(path, backup);
106
+ writeFileSync(path, JSON.stringify(file, null, 2) + "\n");
107
+ return { outcome: "updated", text: `pi-tuck: updated ${path} (backup ${backup}). Restart Pi to use it.` };
108
+ }
109
+ /** Remembered "no" answers in pi-tuck.json: {"configCheck": {"provider/model": {"window": "272000", "thinking": "high,xhigh"}}}. */
110
+ export function declined(settingsPath) {
111
+ try {
112
+ const value = JSON.parse(readFileSync(settingsPath, "utf8"));
113
+ return value.configCheck && typeof value.configCheck === "object" ? value.configCheck : {};
114
+ }
115
+ catch {
116
+ return {};
117
+ }
118
+ }
119
+ export function rememberNo(settingsPath, ref, finding) {
120
+ let value = {};
121
+ try {
122
+ value = JSON.parse(readFileSync(settingsPath, "utf8"));
123
+ }
124
+ catch (error) {
125
+ if (error.code !== "ENOENT")
126
+ return; // an unreadable pi-tuck.json is left alone
127
+ }
128
+ const all = { ...declined(settingsPath) };
129
+ all[ref] = { ...all[ref], [finding.kind]: finding.server };
130
+ writeFileSync(settingsPath, JSON.stringify({ ...value, configCheck: all }, null, 2) + "\n");
131
+ }
132
+ /** One check of the session's model. Resolves when done; never throws. */
133
+ export async function checkModel(pi, ctx, deps) {
134
+ try {
135
+ const model = ctx.model, registry = ctx.modelRegistry;
136
+ if (!model || typeof registry?.getApiKeyAndHeaders !== "function")
137
+ return;
138
+ const modelsPath = join(deps.agentDir, "models.json"), settingsPath = join(deps.agentDir, "pi-tuck.json");
139
+ let file;
140
+ try {
141
+ file = JSON.parse(stripComments(readFileSync(modelsPath, "utf8")));
142
+ }
143
+ catch {
144
+ return;
145
+ }
146
+ const provider = file.providers?.[model.provider];
147
+ if (typeof provider?.baseUrl !== "string" || !provider.models?.some(m => m.id === model.id))
148
+ return;
149
+ const auth = await registry.getApiKeyAndHeaders(model);
150
+ if (!auth.ok)
151
+ return;
152
+ const base = (auth.baseUrl ?? model.baseUrl ?? provider.baseUrl).replace(/\/+$/, "");
153
+ const headers = { ...(auth.apiKey ? { Authorization: `Bearer ${auth.apiKey}` } : {}), ...auth.headers };
154
+ const response = await (deps.fetch ?? fetch)(`${base}/models`, { headers, signal: AbortSignal.timeout(10_000) });
155
+ if (!response.ok)
156
+ return;
157
+ const server = serverModel(await response.json(), model.id);
158
+ if (!server)
159
+ return;
160
+ const ref = `${model.provider}/${model.id}`, no = declined(settingsPath)[ref] ?? {};
161
+ const open = findings(model, server).filter(f => no[f.kind] !== f.server);
162
+ if (!open.length)
163
+ return;
164
+ const lines = open.map(f => f.question.replace(/\?$/, "."));
165
+ if (!ctx.hasUI) {
166
+ pi.appendEntry(CONFIG_CHECK_ENTRY, { model: ref, lines, outcome: "not asked (no UI)" });
167
+ return;
168
+ }
169
+ const accepted = [];
170
+ for (const f of open) {
171
+ if (await ctx.ui.confirm(`pi-tuck: ${ref} in models.json`, f.question))
172
+ accepted.push(f);
173
+ else
174
+ rememberNo(settingsPath, ref, f);
175
+ }
176
+ let outcome = "declined";
177
+ if (accepted.length) {
178
+ const patch = Object.assign({}, ...accepted.map(f => f.patch));
179
+ const told = applyPatch(modelsPath, model.provider, model.id, patch, deps.now?.());
180
+ ctx.ui.notify(told.text, told.outcome === "updated" ? "info" : "warning");
181
+ outcome = told.outcome;
182
+ }
183
+ pi.appendEntry(CONFIG_CHECK_ENTRY, { model: ref, lines, outcome });
184
+ }
185
+ catch { /* a server that does not answer, or an ended session: no check */ }
186
+ }
187
+ /** Run the check once per Pi process, in the background: session start never waits for it. */
188
+ export function installConfigCheck(pi, deps) {
189
+ let done = false;
190
+ pi.on("session_start", (_event, ctx) => {
191
+ if (done)
192
+ return;
193
+ done = true;
194
+ void checkModel(pi, ctx, deps);
195
+ });
196
+ }
@@ -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 = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
3
+ export declare const DIAGNOSTIC_BUILD = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -0,0 +1,37 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ /**
3
+ * pi-tuck's footer in place of Pi's: the folder and branch line, then how full the context is against pi-tuck's trim point (a full bar
4
+ * means pi-tuck trims), the trim count once there is one, the cost when there is one, and the model; other extensions' statuses below. The figures are computed only after
5
+ * a reply, a trim, or a model or thinking change, and cached; a render reads the cache and Pi's own cached branch and statuses. It reads;
6
+ * it changes nothing the model sees.
7
+ */
8
+ export interface FooterFigures {
9
+ /** Context tokens as Pi reports them, or the last trim's size (estimated) right after a trim, before the next reply. */
10
+ tokens: number | null;
11
+ estimated: boolean;
12
+ /** pi-tuck's trim point in tokens (the band), when pi-tuck is active for this model. */
13
+ cut: number | undefined;
14
+ /** pi-tuck trims on this branch so far. */
15
+ cuts: number;
16
+ window: number;
17
+ cost: number;
18
+ model: string;
19
+ pwd: string;
20
+ session: string | undefined;
21
+ }
22
+ /** The part of Pi's theme the footer uses. */
23
+ export interface FooterTheme {
24
+ fg(color: "dim" | "warning", text: string): string;
25
+ }
26
+ /** Context at or above this share of the trim point shows in the warning color. */
27
+ export declare const NEAR_CUT = 0.85;
28
+ /** Pi's compact token format (its footer's formatTokens). */
29
+ export declare const formatTokens: (n: number) => string;
30
+ /** Everything a render needs, from the session as it is now. The one place the footer reads the session. */
31
+ export declare function footerFigures(ctx: ExtensionContext, cutPoint: number | undefined, thinking: string | undefined): FooterFigures;
32
+ /** A bar of `cells` cells that fills toward the trim point: full means pi-tuck trims. */
33
+ export declare function gauge(f: Pick<FooterFigures, "tokens" | "cut">, cells: number): string;
34
+ /** The footer's lines at this width, from the cached figures. Dim when healthy; the bar and size turn yellow near the trim point. */
35
+ export declare function footerLines(f: FooterFigures, width: number, theme: FooterTheme, branch: string | null, statuses: ReadonlyMap<string, string>): string[];
36
+ /** Replace Pi's footer while a UI is present. `cutPoint` is the compactor's own trim point (the number `/tuck` shows). */
37
+ export declare function installFooter(pi: ExtensionAPI, cutPoint: (ctx: ExtensionContext) => number | undefined): void;
@@ -0,0 +1,91 @@
1
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+ import { tuckCuts } from "./status.js";
3
+ /** Context at or above this share of the trim point shows in the warning color. */
4
+ export const NEAR_CUT = 0.85;
5
+ const BAR = 10;
6
+ /** Pi's compact token format (its footer's formatTokens). */
7
+ export const formatTokens = (n) => n < 1000 ? `${n}` : n < 10_000 ? `${(n / 1000).toFixed(1)}k` : n < 1_000_000 ? `${Math.round(n / 1000)}k`
8
+ : n < 10_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : `${Math.round(n / 1_000_000)}M`;
9
+ const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
10
+ /** Everything a render needs, from the session as it is now. The one place the footer reads the session. */
11
+ export function footerFigures(ctx, cutPoint, thinking) {
12
+ let cost = 0;
13
+ // As Pi's footer: cost from all entries (every branch), including usage carried by summaries and tool results.
14
+ for (const entry of ctx.sessionManager.getEntries())
15
+ cost += num((entry.type === "message" ? entry.message?.usage : entry.usage)?.cost?.total);
16
+ const ours = tuckCuts(ctx.sessionManager.getBranch()), usage = ctx.getContextUsage();
17
+ let tokens = usage?.tokens ?? null, estimated = false;
18
+ // Pi does not know the context size between a trim and the next reply; pi-tuck's trim recorded what it left.
19
+ const after = ours.at(-1)?.details?.tokensAfter;
20
+ if (tokens === null && typeof after === "number") {
21
+ tokens = after;
22
+ estimated = true;
23
+ }
24
+ const home = process.env.HOME || process.env.USERPROFILE;
25
+ const pwd = home && (ctx.cwd === home || ctx.cwd.startsWith(home + "/") || ctx.cwd.startsWith(home + "\\")) ? "~" + ctx.cwd.slice(home.length) : ctx.cwd;
26
+ const model = ctx.model ? ctx.model.reasoning ? `${ctx.model.id} · ${thinking && thinking !== "off" ? thinking : "thinking off"}` : ctx.model.id : "no-model";
27
+ return { tokens, estimated, cut: cutPoint, cuts: ours.length, window: usage?.contextWindow ?? ctx.model?.contextWindow ?? 0, cost, model, pwd, session: ctx.sessionManager.getSessionName?.() };
28
+ }
29
+ /** A bar of `cells` cells that fills toward the trim point: full means pi-tuck trims. */
30
+ export function gauge(f, cells) {
31
+ const filled = f.cut && f.cut > 0 ? Math.min(cells, Math.max(0, Math.round((f.tokens ?? 0) / f.cut * cells))) : 0;
32
+ return "█".repeat(filled) + "░".repeat(cells - filled);
33
+ }
34
+ /** The footer's lines at this width, from the cached figures. Dim when healthy; the bar and size turn yellow near the trim point. */
35
+ export function footerLines(f, width, theme, branch, statuses) {
36
+ const dim = (s) => theme.fg("dim", s);
37
+ const near = f.tokens !== null && f.cut !== undefined && f.tokens >= f.cut * NEAR_CUT;
38
+ const hot = (s) => theme.fg(near ? "warning" : "dim", s);
39
+ const size = f.tokens === null ? "?" : (f.estimated ? "~" : "") + formatTokens(f.tokens);
40
+ // Against the trim point; with no trim point (pi-tuck off, or no window), against the window when Pi knows it.
41
+ const of = f.cut ?? (f.window > 0 ? f.window : undefined);
42
+ const amount = (f.cut === undefined ? "" : `${gauge(f, BAR)} `) + size + (of === undefined ? "" : ` of ${formatTokens(of)}`);
43
+ const cost = f.cost > 0 ? ` · $${f.cost.toFixed(f.cost < 0.01 ? 3 : 2)}` : "";
44
+ const trims = f.cuts > 0 ? ` · ${f.cuts} trim${f.cuts === 1 ? "" : "s"}` : "";
45
+ const wide = dim("context ") + hot(amount) + dim(trims + cost);
46
+ const room = width - visibleWidth(wide) - visibleWidth(f.model);
47
+ // The whole line when it fits, else only the bar and the sizes.
48
+ const stats = room >= 2 ? wide + dim(" ".repeat(room) + f.model) : truncateToWidth(hot(amount), width, dim("..."));
49
+ const pwd = f.pwd + (branch ? ` (${branch})` : "") + (f.session ? ` • ${f.session}` : "");
50
+ const lines = [truncateToWidth(dim(pwd), width, dim("...")), stats];
51
+ if (statuses.size > 0)
52
+ lines.push(truncateToWidth([...statuses.entries()].sort(([a], [b]) => a.localeCompare(b))
53
+ .map(([, text]) => text.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim()).join(" "), width, dim("...")));
54
+ return lines;
55
+ }
56
+ /** Replace Pi's footer while a UI is present. `cutPoint` is the compactor's own trim point (the number `/tuck` shows). */
57
+ export function installFooter(pi, cutPoint) {
58
+ let figures;
59
+ let redraw;
60
+ const refresh = (ctx) => {
61
+ if (!ctx.hasUI)
62
+ return;
63
+ try {
64
+ figures = footerFigures(ctx, cutPoint(ctx), pi.getThinkingLevel?.());
65
+ redraw?.();
66
+ }
67
+ catch { /* an ended session keeps the last figures */ }
68
+ };
69
+ const show = (ctx) => {
70
+ if (!ctx.hasUI)
71
+ return;
72
+ refresh(ctx);
73
+ try {
74
+ ctx.ui.setFooter((tui, theme, data) => {
75
+ redraw = () => tui.requestRender();
76
+ const unsubscribe = data.onBranchChange(() => tui.requestRender());
77
+ return {
78
+ render: (width) => figures ? footerLines(figures, width, theme, data.getGitBranch(), data.getExtensionStatuses()) : [],
79
+ invalidate: () => { },
80
+ dispose: () => { unsubscribe(); redraw = undefined; },
81
+ };
82
+ });
83
+ }
84
+ catch { /* a host without a footer keeps its own */ }
85
+ };
86
+ pi.on("session_start", (_event, ctx) => show(ctx));
87
+ // After a reply, a trim, a tree move, or a model or thinking change. pi-tuck saves its trims as turn_end and agent_before_settle entries,
88
+ // which Pi appends after every handler has run; the next turn_start and agent_settled come after both the reply and the trim are saved.
89
+ for (const event of ["turn_start", "agent_settled", "session_compact", "session_tree", "model_select", "thinking_level_select"])
90
+ pi.on(event, (_event, ctx) => refresh(ctx));
91
+ }
@@ -1,6 +1,11 @@
1
1
  export declare const CONTINUATION_CACHE_MISS = "Native continuation stopped because the server could not reuse the unfinished response without rebuilding context.";
2
2
  /** The version of the package this code was loaded from: the open session keeps it until Pi restarts, whatever is installed since. */
3
3
  export declare const LOADED_VERSION: string;
4
+ /** pi-tuck's own cuts on a branch: what `/tuck` and the footer count. */
5
+ export declare const tuckCuts: <E extends {
6
+ type: string;
7
+ details?: unknown;
8
+ }>(branch: readonly E[]) => E[];
4
9
  /** `/tuck`: what an operator needs to know in words, from what is already recorded. It reads; it changes nothing the model sees. */
5
10
  export declare function statusText(input: {
6
11
  version: string;
@@ -16,4 +21,6 @@ export declare function statusText(input: {
16
21
  pending?: boolean;
17
22
  cutAt: number | undefined;
18
23
  cacheSensitive?: boolean;
24
+ /** The trim point in tokens for the current model, the footer's full bar; absent when it cannot be computed. */
25
+ cutPoint?: number;
19
26
  }): string;
@@ -12,27 +12,34 @@ export const LOADED_VERSION = (() => {
12
12
  return "unknown";
13
13
  }
14
14
  })();
15
+ /** pi-tuck's own cuts on a branch: what `/tuck` and the footer count. */
16
+ export const tuckCuts = (branch) => branch.filter(e => e.type === "compaction" && e.details?.compactor === "pi-tuck");
15
17
  /** `/tuck`: what an operator needs to know in words, from what is already recorded. It reads; it changes nothing the model sees. */
16
18
  export function statusText(input) {
17
19
  if (!input.active)
18
20
  return `pi-tuck ${input.version} is inactive in this host.`;
19
21
  if (input.compaction?.kind === 'standingDown')
20
22
  return `pi-tuck ${input.version} is standing down (${input.compaction.reason}). Pi controls compaction.`;
21
- const cuts = input.branch.filter(e => e.type === "compaction"), ours = cuts.filter(e => e.details?.compactor === "pi-tuck");
23
+ const cuts = input.branch.filter(e => e.type === "compaction"), ours = tuckCuts(input.branch);
22
24
  const last = ours.at(-1), before = last?.tokensBefore, after = last?.details?.tokensAfter;
23
25
  const count = (n) => n.toLocaleString("en-US");
24
- const cutLine = ours.length === 0 ? input.pending ? "Cuts: none saved yet in this session." : "Cuts: none yet in this session. Recall becomes available after the first pi-tuck cut on this branch."
25
- : `Cuts: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
26
+ const cutLine = ours.length === 0 ? input.pending ? "Trims: none saved yet in this session." : "Trims: none yet in this session. Recall becomes available after the first pi-tuck trim on this branch."
27
+ : `Trims: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
26
28
  const native = cuts.length - ours.length;
29
+ const now = input.cutPoint === undefined ? "" : ` (about ${count(input.cutPoint)} tokens with this model)`;
30
+ const check = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-config-check").at(-1)?.data;
31
+ const checkLines = Array.isArray(check?.lines) ? [`models.json check for ${String(check.model)} (${String(check.outcome)}):`, ...check.lines.map(line => ` ${String(line)}`)] : [];
27
32
  const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
28
33
  entry.data?.kind === "retry").length;
29
34
  return [
30
35
  `pi-tuck ${input.version} (the version this session loaded; restart Pi after an update).`,
31
36
  cutLine,
32
37
  ...(retries ? [`Capacity retries on this branch: ${retries}.`] : []),
33
- ...(input.pending ? ["A cut is pending: requests already carry it; the first boundary saves it."] : []),
34
- ...(native > 0 ? [`Pi's own compaction cut ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
35
- input.cacheSensitive ? "Cut point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined ? "Cut point: adapts by itself." : `Cut point: cutAt ${input.cutAt} of the room, subject to the standard margin. Remove cutAt from pi-tuck.json to let it adapt.`,
38
+ ...(input.pending ? ["A trim is pending: requests already carry it; the first boundary saves it."] : []),
39
+ ...(native > 0 ? [`Pi's own compaction ran ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
40
+ input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
41
+ ? `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
36
42
  "Search: by keyword.",
43
+ ...checkLines,
37
44
  ].join("\n");
38
45
  }
package/index.ts CHANGED
@@ -6,6 +6,8 @@ import { validCutAt } from "./src/budget";
6
6
  import { notify } from "./src/notify";
7
7
  import type { LlamaContinuation } from "./src/llama-continuation";
8
8
  import { cleanupLegacyFiles } from "./src/legacy-cleanup";
9
+ import { installFooter } from "./src/footer";
10
+ import { installConfigCheck } from "./src/config-check";
9
11
 
10
12
  export type { CompactionOptions } from "./src/compaction";
11
13
  export { installCompaction } from "./src/compaction";
@@ -34,6 +36,8 @@ export default async function (pi: ExtensionAPI) {
34
36
  }
35
37
  const settings = readSettings(join(getAgentDir(), "pi-tuck.json"));
36
38
  const handle = await installCompaction(pi, { cutAt: settings.cutAt, cacheSensitiveModels: settings.cacheSensitiveModels, continuationModel: settings.llamaContinuation?.model });
39
+ if (settings.footer !== false) installFooter(pi, ctx => handle.cutPoint(ctx));
40
+ installConfigCheck(pi, { agentDir: getAgentDir() });
37
41
  const continuation = settings.llamaContinuation;
38
42
  let continuationError: string | undefined;
39
43
  if (continuation) {
@@ -62,7 +66,7 @@ export default async function (pi: ExtensionAPI) {
62
66
  });
63
67
  }
64
68
 
65
- type Settings = { cutAt?: number; cacheSensitiveModels?: string[]; llamaContinuation?: LlamaContinuation; error?: string };
69
+ type Settings = { cutAt?: number; cacheSensitiveModels?: string[]; llamaContinuation?: LlamaContinuation; footer?: boolean; error?: string };
66
70
  const modelRef = (value: unknown) => typeof value === "string" && /^[^/]+\/.+/.test(value);
67
71
  function readSettings(path: string): Settings {
68
72
  let text: string;
@@ -82,6 +86,8 @@ function readSettings(path: string): Settings {
82
86
  if (c && modelRef(c.model) && Number.isSafeInteger(c.extraTokens) && c.extraTokens > 0 &&
83
87
  Number.isSafeInteger(c.deadlineMs) && c.deadlineMs > 0 && c.deadlineMs <= 2_147_483_647) settings.llamaContinuation = c;
84
88
  else if (c !== undefined) warnings.push(`${path} llamaContinuation requires a provider/model identifier in model, a positive safe integer extraTokens, and an integer deadlineMs from 1 to 2147483647; native continuation is off.`);
89
+ if (typeof value.footer === "boolean") settings.footer = value.footer;
90
+ else if (value.footer !== undefined) warnings.push(`${path} footer must be true or false; showing pi-tuck's footer.`);
85
91
  if (warnings.length) settings.error = warnings.join(" ");
86
92
  return settings;
87
93
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.4.1",
3
+ "version": "1.6.0",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -59,11 +59,13 @@
59
59
  "peerDependencies": {
60
60
  "@earendil-works/pi-ai": ">=1.2.0",
61
61
  "@earendil-works/pi-coding-agent": ">=1.2.0",
62
+ "@earendil-works/pi-tui": ">=1.2.0",
62
63
  "typebox": "*"
63
64
  },
64
65
  "devDependencies": {
65
66
  "@earendil-works/pi-ai": "1.4.0",
66
67
  "@earendil-works/pi-coding-agent": "1.4.0",
68
+ "@earendil-works/pi-tui": "1.4.0",
67
69
  "@types/node": "24.10.1",
68
70
  "typebox": "1.3.27",
69
71
  "typescript": "5.9.3",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
1
+ export const BUILD_ID = "724e52323e3ef4f1359322bf874dc8d069782f67d505ea6217c3f00a71c52166";
package/src/compaction.ts CHANGED
@@ -61,6 +61,8 @@ export const refusalNotice = (message: string, factor: number): string =>
61
61
  export const overflowNotice = (contextWindow: number, bound: number, learned: boolean): string =>
62
62
  `pi-tuck: the provider refused this request for context overflow. Using the configured ${contextWindow}-token window as the input limit gives a planning factor of ${bound.toFixed(2)}x.` +
63
63
  (learned ? " pi-tuck added this estimate to its calibration." : " This exceeds the calibration ceiling, so the factor is unchanged.");
64
+ /** Appended to the operator notices at the failure points pi-tuck detects (refusals, length stops), so a report can carry a record. */
65
+ export const INCIDENT_HINT = "\npi-tuck: something went wrong - run /tuck-incident next to record it for a bug report.";
64
66
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
65
67
  export const CALIBRATION_CEILING = 1.5;
66
68
  /** How many recent paired replies (and overflow bounds, and the seed while it is among them) the calibration factor is the maximum of. */
@@ -203,7 +205,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
203
205
  pi.on("session_compact", (_event, ctx) => observe(ctx));
204
206
  pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
205
207
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
206
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending }), "info");
208
+ ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, cacheSensitive: preservePrefix(ctx), pending: view(ctx).pending, cutPoint: cutPoint(ctx) }), "info");
207
209
  } });
208
210
  // Pi's native start/settled events bracket the run and its post-turn cuts.
209
211
  let run: Run | undefined;
@@ -318,7 +320,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
318
320
  ? "pi-tuck: the model exhausted its output allowance before producing an answer or tool call. The unfinished response is saved in the session."
319
321
  : "pi-tuck: the last reply ended with a length stop and may be cut off. Ask the agent to continue.";
320
322
  lengthStop = undefined;
321
- notify(ctx, kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message, "warning");
323
+ notify(ctx, (kind === "thinking" && cacheMiss ? `${message} ${CONTINUATION_CACHE_MISS}` : message) + INCIDENT_HINT, "warning");
322
324
  } finally { resetRun(); }
323
325
  });
324
326
  const active = () => options.active?.() ?? true;
@@ -351,6 +353,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
351
353
  const preservePrefix = (ctx: ExtensionContext) => ctx.model !== undefined &&
352
354
  options.cacheSensitiveModels?.includes(`${ctx.model.provider}/${ctx.model.id}`);
353
355
  const decisionBand = (ctx: ExtensionContext, room: number) => preservePrefix(ctx) ? room : bandOf(room, cutAt);
356
+ /** The cut point in tokens, for the operator (`/tuck`, the footer): the band the triggers use, from the same limits. Reads only. */
357
+ const cutPoint = (ctx: ExtensionContext): number | undefined => {
358
+ if (!active() || !ctx.model || stateFor(ctx).kind !== "active") return undefined;
359
+ try { const band = decisionBand(ctx, limits(ctx).room); return band > 0 ? band : undefined; } catch { return undefined; }
360
+ };
354
361
  const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
355
362
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
356
363
  const measureFor = (ctx: ExtensionContext) => (messages: Messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
@@ -459,9 +466,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
459
466
  if (!receipted) receipt("refusal", fault.message, ctx);
460
467
  options.fail?.(error);
461
468
  } finally {
462
- try { if (!receipted) notify(ctx, fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
469
+ try { if (!receipted) notify(ctx, (fault instanceof CapacityError ? refusalNotice(fault.message, calibration.factor) : fault instanceof CommitFault
463
470
  ? `pi-tuck: ${fault.message}; the session holds a cut its file may lack, so start a new session.`
464
- : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`, "error"); }
471
+ : `pi-tuck could not plan this request (${fault.message}); the next prompt is planned afresh.`) + INCIDENT_HINT, "error"); }
465
472
  finally { ctx.abort(); }
466
473
  }
467
474
  };
@@ -1214,7 +1221,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1214
1221
 
1215
1222
  } catch (error) { fail(error, ctx); }
1216
1223
  });
1217
- return {close:async()=>{recorder.stop("caller-close");}, state: stateFor, inspectState: (ctx: ExtensionContext) => ({ run: run as Readonly<Run> | undefined, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending })};
1224
+ return {close:async()=>{recorder.stop("caller-close");}, state: stateFor, cutPoint, inspectState: (ctx: ExtensionContext) => ({ run: run as Readonly<Run> | undefined, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending })};
1218
1225
  }
1219
1226
 
1220
1227
  function checkedInput(raw: unknown) { if (!Check(RecallInput, raw)) throw new Error("Invalid recall input"); return structuredClone(raw); }
@@ -0,0 +1,162 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { copyFileSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ /**
6
+ * The models.json check: once per Pi process, in the background at session start, for a model of a provider defined in models.json,
7
+ * read the server's own model list and compare the context window and the thinking levels with the config. With a UI each difference
8
+ * is a yes/no question; yes edits only the reported fields (after a dated backup), no is remembered in pi-tuck.json for that server
9
+ * value. Without a UI nothing is printed: the findings go to the session and to /tuck. It changes nothing the model sees.
10
+ */
11
+ export const CONFIG_CHECK_ENTRY = "pi-tuck-config-check";
12
+ /** Pi's thinking levels that a server can list; "off" is never a server effort. */
13
+ const LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"] as const;
14
+ type Map = Partial<Record<string, string | null>>;
15
+
16
+ /** What the server says about one model. Window from the first of these it reports; never n_ctx_train (the training length). */
17
+ export interface ServerModel { window?: number; efforts?: string[] }
18
+ export function serverModel(body: unknown, id: string): ServerModel | undefined {
19
+ const data = (body as { data?: unknown } | null)?.data;
20
+ const entry = Array.isArray(data) ? data.find(m => (m as { id?: unknown } | null)?.id === id) as Record<string, unknown> | undefined : undefined;
21
+ if (!entry) return undefined;
22
+ const window = ["max_model_len", "context_length", "context_window", "n_ctx"].map(k => entry[k]).find(v => Number.isSafeInteger(v) && (v as number) > 0) as number | undefined;
23
+ const raw = (entry.reasoning as { efforts?: unknown } | null | undefined)?.efforts;
24
+ const efforts = Array.isArray(raw) && raw.every(e => typeof e === "string") ? raw as string[] : undefined;
25
+ return { window, efforts };
26
+ }
27
+
28
+ export interface Finding {
29
+ kind: "window" | "thinking";
30
+ /** The server value a "no" is remembered against. */
31
+ server: string;
32
+ question: string;
33
+ /** The fields to set on the model in models.json. */
34
+ patch: { contextWindow?: number; thinkingLevelMap?: Map };
35
+ }
36
+ const k = (n: number) => n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`;
37
+
38
+ /** The differences between the config and the server; the thinking levels only for a reasoning model whose server lists efforts. */
39
+ export function findings(model: { contextWindow: number; reasoning?: boolean; thinkingLevelMap?: Map }, server: ServerModel): Finding[] {
40
+ const out: Finding[] = [];
41
+ const w = server.window, c = model.contextWindow;
42
+ if (w !== undefined && w !== c) out.push({ kind: "window", server: String(w), patch: { contextWindow: w }, question: w > c
43
+ ? `Server allows ${k(w)}, config says ${k(c)}. Use ${k(w)}?`
44
+ : `Config says ${k(c)}, but the server allows only ${k(w)}: requests past ${k(w)} will fail. Use ${k(w)}?` });
45
+ if (model.reasoning && server.efforts) {
46
+ const map: Map = {};
47
+ for (const level of LEVELS) {
48
+ const want = server.efforts.includes(level) ? level : null;
49
+ if (model.thinkingLevelMap?.[level] !== want) map[level] = want;
50
+ }
51
+ const on = LEVELS.filter(l => typeof model.thinkingLevelMap?.[l] === "string").join(", ") || "none";
52
+ if (Object.keys(map).length) out.push({ kind: "thinking", server: server.efforts.join(","), patch: { thinkingLevelMap: map },
53
+ question: `Server thinking levels: ${server.efforts.join(", ") || "none"}; config enables: ${on}. Match the server?` });
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /** JSON with // and /* comments removed outside strings (Pi accepts comments in models.json). */
59
+ export function stripComments(text: string): string {
60
+ let out = "", i = 0, str = false;
61
+ while (i < text.length) {
62
+ const ch = text[i]!, next = text[i + 1];
63
+ if (str) { out += ch; if (ch === "\\") { out += next ?? ""; i += 2; continue; } if (ch === '"') str = false; i++; continue; }
64
+ if (ch === '"') { str = true; out += ch; i++; continue; }
65
+ if (ch === "/" && next === "/") { while (i < text.length && text[i] !== "\n") i++; continue; }
66
+ if (ch === "/" && next === "*") { const end = text.indexOf("*/", i + 2); i = end < 0 ? text.length : end + 2; continue; }
67
+ out += ch; i++;
68
+ }
69
+ return out;
70
+ }
71
+
72
+ type ModelsFile = { providers?: Record<string, { baseUrl?: unknown; models?: { id?: unknown }[] }> };
73
+ const stamp = (d: Date) => d.toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
74
+ /** The exact edit, for a models.json Pi accepts but pi-tuck will not rewrite (it has comments). */
75
+ export const editText = (path: string, provider: string, id: string, patch: Finding["patch"]) =>
76
+ `In ${path}, provider "${provider}", model "${id}": ` + Object.entries(patch.thinkingLevelMap ?? {}).map(([l, v]) => `set thinkingLevelMap.${l} to ${JSON.stringify(v)}`)
77
+ .concat(patch.contextWindow === undefined ? [] : [`set contextWindow to ${patch.contextWindow}`]).join("; ") + ".";
78
+
79
+ /** Apply the accepted fields: back up models.json next to it, then write only those fields. Says what to tell the operator. */
80
+ export function applyPatch(path: string, provider: string, id: string, patch: Finding["patch"], now = new Date()): { outcome: "updated" | "edit shown" | "unchanged"; text: string } {
81
+ const text = readFileSync(path, "utf8");
82
+ let file: ModelsFile;
83
+ try { file = JSON.parse(text) as ModelsFile; } catch {
84
+ return { outcome: "edit shown", text: `pi-tuck: ${path} has comments, so pi-tuck did not change it. ${editText(path, provider, id, patch)} Then restart Pi.` };
85
+ }
86
+ const model = file.providers?.[provider]?.models?.find(m => m.id === id) as Record<string, unknown> | undefined;
87
+ if (!model) return { outcome: "unchanged", text: `pi-tuck: ${provider}/${id} is no longer in ${path}; nothing changed.` };
88
+ if (patch.contextWindow !== undefined) model.contextWindow = patch.contextWindow;
89
+ if (patch.thinkingLevelMap) model.thinkingLevelMap = { ...(model.thinkingLevelMap as Map | undefined), ...patch.thinkingLevelMap };
90
+ const backup = `${path}.before-pi-tuck-${stamp(now)}`;
91
+ copyFileSync(path, backup);
92
+ writeFileSync(path, JSON.stringify(file, null, 2) + "\n");
93
+ return { outcome: "updated", text: `pi-tuck: updated ${path} (backup ${backup}). Restart Pi to use it.` };
94
+ }
95
+
96
+ /** Remembered "no" answers in pi-tuck.json: {"configCheck": {"provider/model": {"window": "272000", "thinking": "high,xhigh"}}}. */
97
+ export function declined(settingsPath: string): Record<string, Partial<Record<Finding["kind"], string>>> {
98
+ try {
99
+ const value = JSON.parse(readFileSync(settingsPath, "utf8")) as { configCheck?: unknown };
100
+ return value.configCheck && typeof value.configCheck === "object" ? value.configCheck as Record<string, Partial<Record<Finding["kind"], string>>> : {};
101
+ } catch { return {}; }
102
+ }
103
+ export function rememberNo(settingsPath: string, ref: string, finding: Finding): void {
104
+ let value: Record<string, unknown> = {};
105
+ try { value = JSON.parse(readFileSync(settingsPath, "utf8")) as Record<string, unknown>; } catch (error) {
106
+ if ((error as { code?: unknown }).code !== "ENOENT") return; // an unreadable pi-tuck.json is left alone
107
+ }
108
+ const all = { ...declined(settingsPath) };
109
+ all[ref] = { ...all[ref], [finding.kind]: finding.server };
110
+ writeFileSync(settingsPath, JSON.stringify({ ...value, configCheck: all }, null, 2) + "\n");
111
+ }
112
+
113
+ export interface CheckDeps { agentDir: string; fetch?: typeof fetch; now?: () => Date }
114
+
115
+ /** One check of the session's model. Resolves when done; never throws. */
116
+ export async function checkModel(pi: Pick<ExtensionAPI, "appendEntry">, ctx: ExtensionContext, deps: CheckDeps): Promise<void> {
117
+ try {
118
+ const model = ctx.model, registry = ctx.modelRegistry as { getApiKeyAndHeaders?: (m: unknown) => Promise<{ ok: boolean; apiKey?: string; headers?: Record<string, string>; baseUrl?: string }> } | undefined;
119
+ if (!model || typeof registry?.getApiKeyAndHeaders !== "function") return;
120
+ const modelsPath = join(deps.agentDir, "models.json"), settingsPath = join(deps.agentDir, "pi-tuck.json");
121
+ let file: ModelsFile;
122
+ try { file = JSON.parse(stripComments(readFileSync(modelsPath, "utf8"))) as ModelsFile; } catch { return; }
123
+ const provider = file.providers?.[model.provider];
124
+ if (typeof provider?.baseUrl !== "string" || !provider.models?.some(m => m.id === model.id)) return;
125
+ const auth = await registry.getApiKeyAndHeaders(model);
126
+ if (!auth.ok) return;
127
+ const base = (auth.baseUrl ?? model.baseUrl ?? provider.baseUrl).replace(/\/+$/, "");
128
+ const headers: Record<string, string> = { ...(auth.apiKey ? { Authorization: `Bearer ${auth.apiKey}` } : {}), ...auth.headers };
129
+ const response = await (deps.fetch ?? fetch)(`${base}/models`, { headers, signal: AbortSignal.timeout(10_000) });
130
+ if (!response.ok) return;
131
+ const server = serverModel(await response.json(), model.id);
132
+ if (!server) return;
133
+ const ref = `${model.provider}/${model.id}`, no = declined(settingsPath)[ref] ?? {};
134
+ const open = findings(model as never, server).filter(f => no[f.kind] !== f.server);
135
+ if (!open.length) return;
136
+ const lines = open.map(f => f.question.replace(/\?$/, "."));
137
+ if (!ctx.hasUI) { pi.appendEntry(CONFIG_CHECK_ENTRY, { model: ref, lines, outcome: "not asked (no UI)" }); return; }
138
+ const accepted: Finding[] = [];
139
+ for (const f of open) {
140
+ if (await ctx.ui.confirm(`pi-tuck: ${ref} in models.json`, f.question)) accepted.push(f);
141
+ else rememberNo(settingsPath, ref, f);
142
+ }
143
+ let outcome = "declined";
144
+ if (accepted.length) {
145
+ const patch = Object.assign({}, ...accepted.map(f => f.patch)) as Finding["patch"];
146
+ const told = applyPatch(modelsPath, model.provider, model.id, patch, deps.now?.());
147
+ ctx.ui.notify(told.text, told.outcome === "updated" ? "info" : "warning");
148
+ outcome = told.outcome;
149
+ }
150
+ pi.appendEntry(CONFIG_CHECK_ENTRY, { model: ref, lines, outcome });
151
+ } catch { /* a server that does not answer, or an ended session: no check */ }
152
+ }
153
+
154
+ /** Run the check once per Pi process, in the background: session start never waits for it. */
155
+ export function installConfigCheck(pi: ExtensionAPI, deps: CheckDeps): void {
156
+ let done = false;
157
+ pi.on("session_start", (_event, ctx) => {
158
+ if (done) return;
159
+ done = true;
160
+ void checkModel(pi, ctx, deps);
161
+ });
162
+ }
package/src/footer.ts ADDED
@@ -0,0 +1,111 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { tuckCuts } from "./status.js";
4
+
5
+ /**
6
+ * pi-tuck's footer in place of Pi's: the folder and branch line, then how full the context is against pi-tuck's trim point (a full bar
7
+ * means pi-tuck trims), the trim count once there is one, the cost when there is one, and the model; other extensions' statuses below. The figures are computed only after
8
+ * a reply, a trim, or a model or thinking change, and cached; a render reads the cache and Pi's own cached branch and statuses. It reads;
9
+ * it changes nothing the model sees.
10
+ */
11
+ export interface FooterFigures {
12
+ /** Context tokens as Pi reports them, or the last trim's size (estimated) right after a trim, before the next reply. */
13
+ tokens: number | null;
14
+ estimated: boolean;
15
+ /** pi-tuck's trim point in tokens (the band), when pi-tuck is active for this model. */
16
+ cut: number | undefined;
17
+ /** pi-tuck trims on this branch so far. */
18
+ cuts: number;
19
+ window: number;
20
+ cost: number;
21
+ model: string;
22
+ pwd: string;
23
+ session: string | undefined;
24
+ }
25
+ /** The part of Pi's theme the footer uses. */
26
+ export interface FooterTheme { fg(color: "dim" | "warning", text: string): string }
27
+ /** Context at or above this share of the trim point shows in the warning color. */
28
+ export const NEAR_CUT = 0.85;
29
+ const BAR = 10;
30
+
31
+ /** Pi's compact token format (its footer's formatTokens). */
32
+ export const formatTokens = (n: number): string => n < 1000 ? `${n}` : n < 10_000 ? `${(n / 1000).toFixed(1)}k` : n < 1_000_000 ? `${Math.round(n / 1000)}k`
33
+ : n < 10_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : `${Math.round(n / 1_000_000)}M`;
34
+
35
+ type Usage = { cost?: { total?: unknown } };
36
+ const num = (value: unknown) => typeof value === "number" && Number.isFinite(value) ? value : 0;
37
+
38
+ /** Everything a render needs, from the session as it is now. The one place the footer reads the session. */
39
+ export function footerFigures(ctx: ExtensionContext, cutPoint: number | undefined, thinking: string | undefined): FooterFigures {
40
+ let cost = 0;
41
+ // As Pi's footer: cost from all entries (every branch), including usage carried by summaries and tool results.
42
+ for (const entry of ctx.sessionManager.getEntries() as readonly { type: string; usage?: Usage; message?: { usage?: Usage } }[])
43
+ cost += num((entry.type === "message" ? entry.message?.usage : entry.usage)?.cost?.total);
44
+ const ours = tuckCuts(ctx.sessionManager.getBranch() as readonly { type: string; details?: unknown }[]), usage = ctx.getContextUsage();
45
+ let tokens = usage?.tokens ?? null, estimated = false;
46
+ // Pi does not know the context size between a trim and the next reply; pi-tuck's trim recorded what it left.
47
+ const after = (ours.at(-1)?.details as { tokensAfter?: unknown } | undefined)?.tokensAfter;
48
+ if (tokens === null && typeof after === "number") { tokens = after; estimated = true; }
49
+ const home = process.env.HOME || process.env.USERPROFILE;
50
+ const pwd = home && (ctx.cwd === home || ctx.cwd.startsWith(home + "/") || ctx.cwd.startsWith(home + "\\")) ? "~" + ctx.cwd.slice(home.length) : ctx.cwd;
51
+ const model = ctx.model ? ctx.model.reasoning ? `${ctx.model.id} · ${thinking && thinking !== "off" ? thinking : "thinking off"}` : ctx.model.id : "no-model";
52
+ return { tokens, estimated, cut: cutPoint, cuts: ours.length, window: usage?.contextWindow ?? ctx.model?.contextWindow ?? 0, cost, model, pwd, session: ctx.sessionManager.getSessionName?.() };
53
+ }
54
+
55
+ /** A bar of `cells` cells that fills toward the trim point: full means pi-tuck trims. */
56
+ export function gauge(f: Pick<FooterFigures, "tokens" | "cut">, cells: number): string {
57
+ const filled = f.cut && f.cut > 0 ? Math.min(cells, Math.max(0, Math.round((f.tokens ?? 0) / f.cut * cells))) : 0;
58
+ return "█".repeat(filled) + "░".repeat(cells - filled);
59
+ }
60
+
61
+ /** The footer's lines at this width, from the cached figures. Dim when healthy; the bar and size turn yellow near the trim point. */
62
+ export function footerLines(f: FooterFigures, width: number, theme: FooterTheme, branch: string | null, statuses: ReadonlyMap<string, string>): string[] {
63
+ const dim = (s: string) => theme.fg("dim", s);
64
+ const near = f.tokens !== null && f.cut !== undefined && f.tokens >= f.cut * NEAR_CUT;
65
+ const hot = (s: string) => theme.fg(near ? "warning" : "dim", s);
66
+ const size = f.tokens === null ? "?" : (f.estimated ? "~" : "") + formatTokens(f.tokens);
67
+ // Against the trim point; with no trim point (pi-tuck off, or no window), against the window when Pi knows it.
68
+ const of = f.cut ?? (f.window > 0 ? f.window : undefined);
69
+ const amount = (f.cut === undefined ? "" : `${gauge(f, BAR)} `) + size + (of === undefined ? "" : ` of ${formatTokens(of)}`);
70
+ const cost = f.cost > 0 ? ` · $${f.cost.toFixed(f.cost < 0.01 ? 3 : 2)}` : "";
71
+ const trims = f.cuts > 0 ? ` · ${f.cuts} trim${f.cuts === 1 ? "" : "s"}` : "";
72
+ const wide = dim("context ") + hot(amount) + dim(trims + cost);
73
+ const room = width - visibleWidth(wide) - visibleWidth(f.model);
74
+ // The whole line when it fits, else only the bar and the sizes.
75
+ const stats = room >= 2 ? wide + dim(" ".repeat(room) + f.model) : truncateToWidth(hot(amount), width, dim("..."));
76
+ const pwd = f.pwd + (branch ? ` (${branch})` : "") + (f.session ? ` • ${f.session}` : "");
77
+ const lines = [truncateToWidth(dim(pwd), width, dim("...")), stats];
78
+ if (statuses.size > 0) lines.push(truncateToWidth([...statuses.entries()].sort(([a], [b]) => a.localeCompare(b))
79
+ .map(([, text]) => text.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim()).join(" "), width, dim("...")));
80
+ return lines;
81
+ }
82
+
83
+ /** Replace Pi's footer while a UI is present. `cutPoint` is the compactor's own trim point (the number `/tuck` shows). */
84
+ export function installFooter(pi: ExtensionAPI, cutPoint: (ctx: ExtensionContext) => number | undefined): void {
85
+ let figures: FooterFigures | undefined;
86
+ let redraw: (() => void) | undefined;
87
+ const refresh = (ctx: ExtensionContext) => {
88
+ if (!ctx.hasUI) return;
89
+ try { figures = footerFigures(ctx, cutPoint(ctx), pi.getThinkingLevel?.()); redraw?.(); } catch { /* an ended session keeps the last figures */ }
90
+ };
91
+ const show = (ctx: ExtensionContext) => {
92
+ if (!ctx.hasUI) return;
93
+ refresh(ctx);
94
+ try {
95
+ ctx.ui.setFooter((tui, theme, data) => {
96
+ redraw = () => tui.requestRender();
97
+ const unsubscribe = data.onBranchChange(() => tui.requestRender());
98
+ return {
99
+ render: (width: number) => figures ? footerLines(figures, width, theme, data.getGitBranch(), data.getExtensionStatuses()) : [],
100
+ invalidate: () => {},
101
+ dispose: () => { unsubscribe(); redraw = undefined; },
102
+ };
103
+ });
104
+ } catch { /* a host without a footer keeps its own */ }
105
+ };
106
+ pi.on("session_start", (_event, ctx) => show(ctx));
107
+ // After a reply, a trim, a tree move, or a model or thinking change. pi-tuck saves its trims as turn_end and agent_before_settle entries,
108
+ // which Pi appends after every handler has run; the next turn_start and agent_settled come after both the reply and the trim are saved.
109
+ for (const event of ["turn_start", "agent_settled", "session_compact", "session_tree", "model_select", "thinking_level_select"] as const)
110
+ pi.on(event as "turn_start", (_event, ctx) => refresh(ctx));
111
+ }
package/src/status.ts CHANGED
@@ -12,6 +12,10 @@ export const LOADED_VERSION: string = (() => {
12
12
  } catch { return "unknown"; }
13
13
  })();
14
14
 
15
+ /** pi-tuck's own cuts on a branch: what `/tuck` and the footer count. */
16
+ export const tuckCuts = <E extends { type: string; details?: unknown }>(branch: readonly E[]): E[] =>
17
+ branch.filter(e => e.type === "compaction" && (e.details as { compactor?: unknown } | null | undefined)?.compactor === "pi-tuck");
18
+
15
19
  /** `/tuck`: what an operator needs to know in words, from what is already recorded. It reads; it changes nothing the model sees. */
16
20
  export function statusText(input: {
17
21
  version: string;
@@ -21,24 +25,31 @@ export function statusText(input: {
21
25
  pending?: boolean;
22
26
  cutAt: number | undefined;
23
27
  cacheSensitive?: boolean;
28
+ /** The trim point in tokens for the current model, the footer's full bar; absent when it cannot be computed. */
29
+ cutPoint?: number;
24
30
  }): string {
25
31
  if (!input.active) return `pi-tuck ${input.version} is inactive in this host.`;
26
32
  if (input.compaction?.kind === 'standingDown') return `pi-tuck ${input.version} is standing down (${input.compaction.reason}). Pi controls compaction.`;
27
- const cuts = input.branch.filter(e => e.type === "compaction"), ours = cuts.filter(e => (e.details as { compactor?: unknown } | null | undefined)?.compactor === "pi-tuck");
33
+ const cuts = input.branch.filter(e => e.type === "compaction"), ours = tuckCuts(input.branch);
28
34
  const last = ours.at(-1), before = last?.tokensBefore, after = (last?.details as { tokensAfter?: unknown } | undefined)?.tokensAfter;
29
35
  const count = (n: number) => n.toLocaleString("en-US");
30
- const cutLine = ours.length === 0 ? input.pending ? "Cuts: none saved yet in this session." : "Cuts: none yet in this session. Recall becomes available after the first pi-tuck cut on this branch."
31
- : `Cuts: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
36
+ const cutLine = ours.length === 0 ? input.pending ? "Trims: none saved yet in this session." : "Trims: none yet in this session. Recall becomes available after the first pi-tuck trim on this branch."
37
+ : `Trims: ${ours.length} by pi-tuck in this session` + (typeof before === "number" && typeof after === "number" ? `, the last from ${count(before)} to ${count(after)} tokens.` : ".");
32
38
  const native = cuts.length - ours.length;
39
+ const now = input.cutPoint === undefined ? "" : ` (about ${count(input.cutPoint)} tokens with this model)`;
40
+ const check = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-config-check").at(-1)?.data as { model?: unknown; lines?: unknown; outcome?: unknown } | undefined;
41
+ const checkLines = Array.isArray(check?.lines) ? [`models.json check for ${String(check!.model)} (${String(check!.outcome)}):`, ...check!.lines.map(line => ` ${String(line)}`)] : [];
33
42
  const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
34
43
  (entry.data as { kind?: unknown } | null | undefined)?.kind === "retry").length;
35
44
  return [
36
45
  `pi-tuck ${input.version} (the version this session loaded; restart Pi after an update).`,
37
46
  cutLine,
38
47
  ...(retries ? [`Capacity retries on this branch: ${retries}.`] : []),
39
- ...(input.pending ? ["A cut is pending: requests already carry it; the first boundary saves it."] : []),
40
- ...(native > 0 ? [`Pi's own compaction cut ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
41
- input.cacheSensitive ? "Cut point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined ? "Cut point: adapts by itself." : `Cut point: cutAt ${input.cutAt} of the room, subject to the standard margin. Remove cutAt from pi-tuck.json to let it adapt.`,
48
+ ...(input.pending ? ["A trim is pending: requests already carry it; the first boundary saves it."] : []),
49
+ ...(native > 0 ? [`Pi's own compaction ran ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
50
+ input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
51
+ ? `Trim point: the room less a 2% margin${now}.` : `Trim point: cutAt ${input.cutAt} of the room, subject to the standard margin${now}. Remove cutAt from pi-tuck.json to use the default.`,
42
52
  "Search: by keyword.",
53
+ ...checkLines,
43
54
  ].join("\n");
44
55
  }