pi-tuck 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,25 @@
3
3
  All notable changes to pi-tuck. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [1.5.0]
7
+
8
+ ### Added
9
+
10
+ - Footer: pi-tuck replaces Pi's footer in the terminal UI. Under the folder and branch line, a bar fills toward pi-tuck's trim point
11
+ (full means pi-tuck trims), with the context size, the trim point, the trim count once there is one, the cost when above $0, and the
12
+ model and thinking level; other extensions' statuses stay below. It turns yellow at 85% of the trim point instead of at Pi's 70% and
13
+ 90% of the window. Its figures are recomputed only after a reply, a trim, or a model or thinking change. `"footer": false` in `pi-tuck.json` keeps Pi's footer.
14
+ - Refusal and length-stop notices suggest `/tuck-incident next` to record the next trim for a bug report.
15
+
16
+ ### Changed
17
+
18
+ - `/tuck` says "trim" where it said "cut", the word the footer uses. The `cutAt` setting keeps its name.
19
+
20
+ ### Fixed
21
+
22
+ - `/tuck` no longer says the cut point adapts by itself: it names the default (the room less a 2% margin) and the trim point in tokens for
23
+ the current model.
24
+
6
25
  ## [1.4.1]
7
26
 
8
27
  ### 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.5.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.5.0` or `pi install git:github.com/galyavin/pi-tuck@v1.5.0`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
@@ -29,17 +29,29 @@ 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
+
37
48
  ## Settings
38
49
 
39
50
  Optional settings go in `pi-tuck.json` in Pi's agent directory (`~/.pi/agent` by default, or `PI_CODING_AGENT_DIR`). Restart Pi to apply changes. The input room starts at the model's context window minus Pi's `compaction.reserveTokens`. Invalid JSON uses defaults. An invalid field uses its own default, with a notice when compaction is active.
40
51
 
41
52
  - **`cutAt`** is a fraction above 0 and at most 1. By default pi-tuck cuts at the room, less a 2% margin. An explicit value fixes a fraction of the room, subject to the same margin even at `1`.
42
53
  - **`cacheSensitiveModels`** lists exact `provider/model` identifiers. For these models, the cut point is the full room, taking precedence over `cutAt`. This delays early cuts that would discard a reusable prompt prefix.
54
+ - **`footer`** set to `false` keeps Pi's own footer.
43
55
  - **`llamaContinuation`** opts one reasoning model into a single extra request after a thinking-only response exhausts the full configured output allowance. In Pi's `models.json`, configure that model on a llama.cpp provider using the `openai-completions` API. Verify that the runtime and template support `continue_final_message: "reasoning_content"` and report reused prompt tokens through `prompt_progress`. Pi-tuck requires the first cache report to match the prefix within 15 seconds. The positive integer `extraTokens` caps the additional allowance within the remaining context. The positive integer `deadlineMs` covers both requests.
44
56
 
45
57
  ```json
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { installCompaction } from "./src/compaction.js";
5
5
  import { validCutAt } from "./src/budget.js";
6
6
  import { notify } from "./src/notify.js";
7
7
  import { cleanupLegacyFiles } from "./src/legacy-cleanup.js";
8
+ import { installFooter } from "./src/footer.js";
8
9
  export { installCompaction } from "./src/compaction.js";
9
10
  export { inspectIncident, readableIncident } from "./src/diagnostic-replay.js";
10
11
  /** Pi 1.2 added the run's custom message to before_agent_start so preflight can count it. */
@@ -36,6 +37,8 @@ export default async function (pi) {
36
37
  }
37
38
  const settings = readSettings(join(getAgentDir(), "pi-tuck.json"));
38
39
  const handle = await installCompaction(pi, { cutAt: settings.cutAt, cacheSensitiveModels: settings.cacheSensitiveModels, continuationModel: settings.llamaContinuation?.model });
40
+ if (settings.footer !== false)
41
+ installFooter(pi, ctx => handle.cutPoint(ctx));
39
42
  const continuation = settings.llamaContinuation;
40
43
  let continuationError;
41
44
  if (continuation) {
@@ -97,6 +100,10 @@ function readSettings(path) {
97
100
  settings.llamaContinuation = c;
98
101
  else if (c !== undefined)
99
102
  warnings.push(`${path} llamaContinuation requires a provider/model identifier in model, a positive safe integer extraTokens, and an integer deadlineMs from 1 to 2147483647; native continuation is off.`);
103
+ if (typeof value.footer === "boolean")
104
+ settings.footer = value.footer;
105
+ else if (value.footer !== undefined)
106
+ warnings.push(`${path} footer must be true or false; showing pi-tuck's footer.`);
100
107
  if (warnings.length)
101
108
  settings.error = warnings.join(" ");
102
109
  return settings;
@@ -1 +1 @@
1
- export declare const BUILD_ID = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
1
+ export declare const BUILD_ID = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
@@ -1 +1 @@
1
- export const BUILD_ID = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
1
+ export const BUILD_ID = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
@@ -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); }
@@ -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 = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
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,31 @@ 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)`;
27
30
  const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
28
31
  entry.data?.kind === "retry").length;
29
32
  return [
30
33
  `pi-tuck ${input.version} (the version this session loaded; restart Pi after an update).`,
31
34
  cutLine,
32
35
  ...(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.`,
36
+ ...(input.pending ? ["A trim is pending: requests already carry it; the first boundary saves it."] : []),
37
+ ...(native > 0 ? [`Pi's own compaction ran ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
38
+ input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
39
+ ? `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
40
  "Search: by keyword.",
37
41
  ].join("\n");
38
42
  }
package/index.ts CHANGED
@@ -6,6 +6,7 @@ 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";
9
10
 
10
11
  export type { CompactionOptions } from "./src/compaction";
11
12
  export { installCompaction } from "./src/compaction";
@@ -34,6 +35,7 @@ export default async function (pi: ExtensionAPI) {
34
35
  }
35
36
  const settings = readSettings(join(getAgentDir(), "pi-tuck.json"));
36
37
  const handle = await installCompaction(pi, { cutAt: settings.cutAt, cacheSensitiveModels: settings.cacheSensitiveModels, continuationModel: settings.llamaContinuation?.model });
38
+ if (settings.footer !== false) installFooter(pi, ctx => handle.cutPoint(ctx));
37
39
  const continuation = settings.llamaContinuation;
38
40
  let continuationError: string | undefined;
39
41
  if (continuation) {
@@ -62,7 +64,7 @@ export default async function (pi: ExtensionAPI) {
62
64
  });
63
65
  }
64
66
 
65
- type Settings = { cutAt?: number; cacheSensitiveModels?: string[]; llamaContinuation?: LlamaContinuation; error?: string };
67
+ type Settings = { cutAt?: number; cacheSensitiveModels?: string[]; llamaContinuation?: LlamaContinuation; footer?: boolean; error?: string };
66
68
  const modelRef = (value: unknown) => typeof value === "string" && /^[^/]+\/.+/.test(value);
67
69
  function readSettings(path: string): Settings {
68
70
  let text: string;
@@ -82,6 +84,8 @@ function readSettings(path: string): Settings {
82
84
  if (c && modelRef(c.model) && Number.isSafeInteger(c.extraTokens) && c.extraTokens > 0 &&
83
85
  Number.isSafeInteger(c.deadlineMs) && c.deadlineMs > 0 && c.deadlineMs <= 2_147_483_647) settings.llamaContinuation = c;
84
86
  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.`);
87
+ if (typeof value.footer === "boolean") settings.footer = value.footer;
88
+ else if (value.footer !== undefined) warnings.push(`${path} footer must be true or false; showing pi-tuck's footer.`);
85
89
  if (warnings.length) settings.error = warnings.join(" ");
86
90
  return settings;
87
91
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.4.1",
3
+ "version": "1.5.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 = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
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); }
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,28 @@ 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)`;
33
40
  const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
34
41
  (entry.data as { kind?: unknown } | null | undefined)?.kind === "retry").length;
35
42
  return [
36
43
  `pi-tuck ${input.version} (the version this session loaded; restart Pi after an update).`,
37
44
  cutLine,
38
45
  ...(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.`,
46
+ ...(input.pending ? ["A trim is pending: requests already carry it; the first boundary saves it."] : []),
47
+ ...(native > 0 ? [`Pi's own compaction ran ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
48
+ input.cacheSensitive ? "Trim point: preserves the active prefix while the reply reserve fits." : input.cutAt === undefined
49
+ ? `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
50
  "Search: by keyword.",
43
51
  ].join("\n");
44
52
  }