@bismawy/pi-arnative 0.10.1 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +6 -1
- package/extensions/arnative.ts +76 -23
- package/extensions/budget.ts +665 -0
- package/extensions/footer.ts +409 -26
- package/extensions/usage-export.ts +292 -0
- package/extensions/usage.ts +424 -147
- package/lib/compat.ts +36 -10
- package/lib/list-picker.ts +2 -2
- package/lib/model-heal.ts +12 -4
- package/lib/preset-store.ts +49 -5
- package/lib/provider.ts +36 -5
- package/lib/shortcuts.ts +12 -7
- package/lib/status-widget.ts +20 -0
- package/lib/usage-store.ts +913 -312
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -10,6 +10,40 @@
|
|
|
10
10
|
|
|
11
11
|
## [Unreleased]
|
|
12
12
|
|
|
13
|
+
## [0.11.1] - 2026-11-13
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
- **A reselect keeps the thinking levels a probe paid for.** Selecting or re-probing a provider's models reserialized every `auto` model through `mergeLevels`, which carried only its level, so `wireModels` dropped the stored `thinkingLevelMap` and the model went back to offering every level. `mergeLevels` now carries the probed map with the level, and the reselect path is pinned in the provider self-check (`lib/provider.ts`, `mergeLevels`).
|
|
17
|
+
|
|
18
|
+
## [0.11.0] - 2026-11-13
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
- **Spend is exported as a Prometheus textfile.** On `turn_end` — at most one write per 60 s, and only when the rendered text differs from the last one written, so an idle session never touches the file — the usage summary is rendered as a Prometheus exposition and atomically written (temp file + rename, Windows `EPERM` in-place fallback) to `~/.pi/agent/arnative/usage.prom`: `arnative_cost_billed_total` (billed only, never estimates), `arnative_cost_estimated_total`, `arnative_cost_today` / `arnative_cost_30d` (the day buckets), `arnative_tokens_total{provider,model,kind}`, `arnative_sessions_total` and `arnative_usage_last_change_timestamp_seconds`, each with `# HELP`/`# TYPE`. No network, no credentials: point a textfile collector at the folder (`node_exporter --collector.textfile.directory=~/.pi/agent/arnative`) and the gauges land in Grafana next to the infra metrics; `PI_ARNATIVE_EXPORT=0` disables the export. A failed write is swallowed, never thrown into the session (`extensions/usage-export.ts`, `renderProm`, `exportProm`, `writePromFile`; pinned in the usage-export self-check and in `test/usage-export.test.ts`).
|
|
22
|
+
- **Warn-only budget guardrail on the next turn.** `/arnative` → **Budget** sets a day and/or a 30-day cap on billed spend (read from the usage cache's day buckets, `totals.today` / `last30d`: the footer band through the 5s memo, the gate through a forced scan so it never decides on a stale total) and an enforce switch that ships **off**. The footer cost cell turns amber at 80% of a cap and red at 100%. The gate is `pi.on("input")`: over a cap with enforce on, the next turn is stopped before any token is bought (`{ action: "handled" }` plus an error notify); with enforce off it notifies once per session and lets the turn through. It never blocks a `source === "extension"` input, never blocks when the spend is unknown (no day buckets), and the whole handler fails open — any error returns `continue`. Only billed spend can cross a cap — a cap computed from a catalog estimate would enforce $0 on an unpriced model — while an estimate still counts towards the 80% warning, so a provider that reports no billed total is not silently ignored (`UsageDayWindow.estimated`). New `config.json` keys `budgetDay` / `budgetMonth` (amount strings, `""` = unset) and `budgetEnforce` (`"on"`/`"off"`), read through the new `loadNumber` and recorded in the startup profile (`extensions/budget.ts`, `budgetState`, `spendNow`, `budgetLevelNow`, `openBudget`, the `input` gate; `lib/preset-store.ts`, `loadNumber`, `KEY_ORDER`; `extensions/arnative.ts`, the Budget row; `extensions/footer.ts`, `costCell`/`getUsage` band painting; pinned in the budget, preset-store, footer and arnative self-checks and in `test/budget.test.ts`, `test/profile.test.ts`).
|
|
23
|
+
- **The Budget screen shows the spend it guards.** `/arnative` → **Budget** now opens a dashboard: one line per window, `Today · $0.42 of $1.00 ███░░ 42% · OK`, with `30d` under it on the same column grid, so a cap is read next to the bar it fills. A dim `Total · $0.07 est.` line states the estimate the caps ignore. The bars fill from billed plus estimated spend, while the level keeps the guardrail rule (only billed spend can reach a cap, an estimate still counts towards the 80% warning), and the three rows below, `Day cap`, `30d cap` and `Enforce`, keep their notes and stay the only way to set a cap (`extensions/budget.ts`, `BudgetModalComponent`, `budgetWindows`; pinned in the budget self-check).
|
|
24
|
+
- **The footer cost cell also shows the burn rate, and the cache cell colours its recent hit rate.** With the cost cell on (`/arnative` → Footers → `[c]`), the cell appends `$/h` — cost divided by *active* hours of the footer clock (idle pauses excluded, not wall-clock), so the cost per active hour is visible without opening `/usage`: `$0.42 ($1.80/h)`, opened by the footer `·` divider so the dollar icon reads as its own group next to the token cells. The rate is hidden below five minutes of active time (dividing a two-minute clock prints nonsense), when the session has no cost, and below 80 terminal columns, and it carries the `~` whenever estimated cost feeds it, like the estimated part of the cell. Separately, the cache cell's colour now follows a recent window — the last 10 assistant messages, the session's first two always skipped because turn 1 is a cold cache — while the `pi …%` text stays session-wide: ≥70% keeps the soft tier, 40–70% turns amber (`warning` slot, accent when the theme has none), below 40% turns red (`error`). It is a passive colour only, never a notification, and no config key was added (`extensions/footer.ts`, `costCell`, `getUsage`, `cacheHitBand`, `CACHE_WINDOW_MSGS`, `RATE_MIN_ACTIVE_MS`, `RATE_MIN_WIDTH`; pinned in the footer self-check and in `test/footer-rate.test.ts`).
|
|
25
|
+
- **The footer counts subagent and nested-tool spend, and `/usage` stops counting it twice.** pi attaches a tool execution's own usage to the tool result (`ToolResultMessage.usage`), not to any assistant message, so the footer's `↑↓` cells and cost cell under-reported a fan-out workflow. `getUsage`/`lastUsageOf` now sum tool-result usage too, attributed to a synthetic `tool` provider with the tool name as the model (`tool · subagent`) — never to the parent's provider/model. The `/usage` scan deliberately does **not** read it: pi-subagents writes each child run as `<project>/<parent id>/<run id>/run-N/session.jsonl` *inside* the sessions tree, and the run's transcript under `<project>/subagent-artifacts/`, so the recursive scan was already counting every child's assistant messages — and counting both the child file and the parent's tool result billed the same tokens twice. `scanSessionFiles` now reads the parent session files plus each child run's `session.jsonl`, and never a `subagent-artifacts/` transcript — which also removes the pre-existing double count of those transcripts from every `/usage` total. The usage cache is now v9: an item written by the build that also stored tool-result rows is re-parsed once, so those rows cannot be counted a second time next to the child's own file. `piCacheHit()`'s denominator (`input + cacheRead`) includes child tokens on purpose: the `↑` cell is total spend, so the hit rate is measured against the same total (`lib/usage-store.ts`, `scanSessionFiles`, `childSessionFiles`, `SUBAGENT_ARTIFACTS_DIR`, `TOOL_PROVIDER`; `extensions/footer.ts`, `getUsage`, `lastUsageOf`, `attributionOf`; pinned in the usage-store and footer self-checks and in `test/usage-store.test.ts`).
|
|
26
|
+
- **`/usage` can group by project and answer "what did I spend today".** The usage cache is now v7: each session file's rollup also keeps day buckets (keyed `YYYY-MM-DD` in **UTC**, so the cache does not depend on the machine's timezone) and the session's `cwd` (read from the file's first line on a whole-file parse, kept from the cache on a tail parse, so a grown file never re-reads its head; a file with no cwd counts under `unknown`). A pre-v6 cache entry is re-parsed once from its file and re-saved in the new shape. The summary gains `projects` (one row per cwd, same fields as a provider row, with the providers seen in that project) and `totals.today`/`last7d`/`last30d` from the day buckets. In the dashboard, `v` cycles the view Provider → Project → Provider on the same column grid, and a dim `today $x · 7d $y · 30d $z` line sits under the Total band when the cache holds buckets; the legend advertises `[v] View` only where it is handled (`lib/usage-store.ts`, `collectUsageSummary`, `foldInto`, `encodeDiskItem`/`decodeDiskItem`; `extensions/usage.ts`, `UsageModalComponent`, `cycleView`; `lib/shortcuts.ts`, `legendUsage`; pinned in the usage-store and usage self-checks and in `test/usage-store.test.ts`).
|
|
27
|
+
- **The footer can show what the session cost, off by default.** `/arnative` → **Footers** → `[c]` adds a cost cell to the metrics row: the sum of pi's per-message `cost.total` over the branch, so it follows the live stream the way the token cells do (same 2s scan cache, same in-place delta on a streaming tick). A session where no provider reported a billed total is prefixed `~`, because `cost.total` is then the catalog estimate — the same promise `/usage` makes; a session with no cost at all shows no cell rather than `-`. The switch is a command, not a preview: the legend states its state and `Esc`/`←` leave it on, only the preset preview reverts. Stored as `footerCost` (`"on"`/`"off"`, absent reads as off) and recorded in the profile at `session_start` (`extensions/footer.ts`, `activeFooterCost`, `setFooterCost`, `costCell`; `lib/preset-store.ts`, `FOOTER_COST_KEY`; `extensions/arnative.ts`, `footersPickerText`; pinned in the footer and arnative self-checks and in `test/profile.test.ts`).
|
|
28
|
+
|
|
29
|
+
- **A change notice sits above the editor.** After a menu commits a change (theme, header, footer, animation, auto-compact, model heal, budget row, provider save/delete/rename/key) one line above the chat input states what changed and clears itself after six seconds. It uses the `aboveEditor` widget slot under the key `arnative-notice`, so a later change replaces the line instead of stacking, and a headless session is left alone (`lib/status-widget.ts`, `announce`; `extensions/arnative.ts`, the pickers' `done` hooks; `extensions/budget.ts`, `change`; `lib/provider.ts`, the provider writes).
|
|
30
|
+
|
|
31
|
+
### Fixed
|
|
32
|
+
- **A cache item is never trusted while it is missing something.** A v4 rollup and a pre-v8 row are now stamped below the current version, so the scan re-parses their file once instead of trusting sums that carry no day buckets and no billed split; an item whose `r` is empty (a session with no assistant message) is a current item, not an old one, so it is no longer re-read on every start. A corrupt timestamp on one line is dropped instead of throwing `RangeError` out of the whole scan, which used to take `/usage` and the Model tab down with it. The Prometheus export forces its scan (the 5s memo could otherwise export the turn *before* the one that just ended, then hold that number for the 60s throttle), also exports `kind="cache_write"`, and flushes on `session_shutdown` (`lib/usage-store.ts`, `decodeDiskItem`, `entryOfLine`, `tsOf`, `windowOf`; `extensions/usage-export.ts`, `exportProm`; `extensions/footer.ts`, the cache band only colours pi's own rate, never a cache-stats plugin's).
|
|
33
|
+
- **Cost numbers no longer blend billed and estimated, and cache writes are priced.** `models.json` rates now carry `cacheWrite` (pi's own catalog prices it, `Usage.cost.cacheWrite`), so every `~` estimate counts cache writes, and the price table is memoized on `models.json`'s stat — one `statSync` per call instead of a `readFileSync` on every footer frame. The usage cache is now v8: its rows also store `cacheWrite` and the billed split of `cost`, and a pre-v8 entry is re-parsed once from its file. `cost` everywhere (the `/usage` rows, the Total band, the day windows) is the provider-billed total only; catalog totals and price-table reconstructions live in `estimatedCost` and are always shown with a `~`. The footer cost cell renders `$0.42`, `~$0.42` or `$0.30 + ~$0.12` — one billed message no longer strips the `~` from a sum that still contains estimates — and `/usage` names both sources under the Total band (`$0.30 billed + ~$0.12 estimated (models.json)`). `v` in `/usage` now also cycles to a Prices view: every provider+model in `models.json` with its `$/1M` in / out / cache-read / cache-write rates, sorted by input rate, with a used model that has neither a rate nor a reported cost marked `unpriced` (a built-in model reports its own cost, so it is priced even though `models.json` has no entry for it) (`lib/usage-store.ts`, `loadPriceTable`, `estimateCost`, `entryOfLine`, `providerStatsOf`, `decodeDiskItem`/`encodeDiskItem`; `extensions/footer.ts`, `costCell`, `getUsage`; `extensions/usage.ts`, `UsageModalComponent` Prices view; pinned in the usage-store, footer and usage self-checks and in `test/usage-store.test.ts`).
|
|
34
|
+
- Footer usage caching now separates session managers and branch leaves. Switching equal-length branches shows their own totals while streaming updates retain the cached prefix.
|
|
35
|
+
- Effort probes use the declared Responses or Chat Completions protocol, including its reasoning payload and token-limit fields. Responses-only providers can now report accepted thinking levels.
|
|
36
|
+
- Effort probes stop pending requests, remaining levels, and retry waits on cancellation. Model heal enforces its probe deadline without recording cancellation or budget exhaustion as model failures.
|
|
37
|
+
- Preset saves now compare against the current disk value and preserve invalid profiles. Unsaved choices emit a warning.
|
|
38
|
+
- Usage Reset now clears model/provider statistics without moving session files or removing them from `/resume`. A persistent baseline excludes earlier messages, counts new messages in existing sessions, and supports Undo while the dashboard remains open. Existing `usage-trash` files stay untouched.
|
|
39
|
+
|
|
40
|
+
### Fixed
|
|
41
|
+
- **Usage stops showing `unknown` for projects it can read.** A cache written before the cwd field existed still carried the current version number, so the scan trusted it and every old session landed under `unknown`. The cache is now v10, an item counts as current only when it carries the cwd marker, and a re-parse that starts at the reset baseline reads the file's first line for the cwd instead of skipping it (`lib/usage-store.ts`, `CACHE_VERSION`, `headCwd`, `encodeDiskItem`; pinned in the usage-store self-check and in `test/usage-store.test.ts`).
|
|
42
|
+
|
|
43
|
+
### Changed
|
|
44
|
+
- **Enter says Select, each footer names one exit, and Budget changes on Space.** The shared menu legend read `[Enter] Open` while the pickers read `Select`; it now says `Select` everywhere. The Footers legend drops the duplicate `[←] Back` and renames `[Esc] Revert` to `[Esc] Back`, because both keys already ran the same `back()`. The Budget screen moves its change action to Space (`[↑↓] Move [Space] Change [Esc] Back`) and Enter no longer changes a row; it stops calling Esc `Close` when it returns to `/arnative`. The Thinking list spells its number keys as `[0-6] Set level`, the provider delete prompt uses the arnative box instead of pi's stock confirm, and the Usage description names the active view, with its legend reading `[Space/Click] Show/Hide` and `[v] Next: <view>` stating where the key leads (`lib/shortcuts.ts`, `LEGEND_ROOT`/`LEGEND_MOVE`; `extensions/arnative.ts`, `footersPickerText`; `extensions/budget.ts`, `BUDGET_PICKER_TEXT`; `lib/provider.ts`, `THINKING_LEGEND`, `deleteProviderFlow`; `extensions/usage.ts`, the dashboard description; pinned in the list-picker, shortcuts, arnative, budget and usage self-checks).
|
|
45
|
+
- **The Usage dashboard drops two summary lines and groups the price table.** The Total row now shows the catalog estimate (`~$2.93`) when no provider reported a billed total, instead of a bare `-`. The `today · 7d · 30d` line and the separate estimate line under it are gone, and the detail line writes `$2.93 est.` without a second `~`. In the Prices view, models sit under their provider like the Provider view, the group row stays blank, and the rate columns gained a space. Rows follow the menu palette: a group row (provider or project) uses the plain text color, model and price rows are dim, the expand arrow is accent, and the selected row takes the soft accent. Project and Prices keep that same two-level shape: one group row, then its indented rows (`softOf` derives it from the theme accent, so a theme without the `accentSoft` token still renders; `extensions/usage.ts`, `UsageModalComponent`, `buildFlatRows`, the row and Total renderers; pinned in the usage self-check).
|
|
46
|
+
|
|
13
47
|
## [0.10.0] - 2026-11-08
|
|
14
48
|
|
|
15
49
|
### Added
|
package/README.md
CHANGED
|
@@ -20,6 +20,8 @@ pi-arnative replaces pi’s default terminal chrome with a unified visual interf
|
|
|
20
20
|
- Working Spinners: 18 animated presets with live picker preview and optional `[g]` gradient sweep.
|
|
21
21
|
- Transcript Clock: Per-message timestamps with clean bubble backgrounds.
|
|
22
22
|
- Usage Dashboard: Real-time token counts and cost tracking across local sessions via `/usage`.
|
|
23
|
+
- Budget Guardrails: `/arnative` → Budget sets UTC day and rolling 30-day caps on billed spend, draws each window as a spend-vs-cap bar, turns the footer cost cell amber at 80% and red at 100%, and can stop the next turn when enforce is on.
|
|
24
|
+
- Prometheus Textfile Export: On every `turn_end` (at most one write per minute, and only when the numbers changed) the usage summary is written as an exposition file to `~/.pi/agent/arnative/usage.prom` — point a textfile collector at that folder (`node_exporter --collector.textfile.directory=~/.pi/agent/arnative`) and the spend lands in Grafana next to the infra metrics; set `PI_ARNATIVE_EXPORT=0` to turn it off.
|
|
23
25
|
- Custom Providers: Interactive `/providers` wizard to probe endpoints, pick models, set thinking levels, edit the base URL, provider id or API key, and save OpenAI-, Anthropic-, Gemini-, or Ollama-compatible channels to `models.json` and `auth.json`.
|
|
24
26
|
- Model Heal: Background sync (`/model-heal`) that fills missing compat flags, `/models` token limits, and accepted reasoning effort levels in `models.json`.
|
|
25
27
|
- Auto-compact: Automatic context compaction after a turn settles using smart window tiers or a fixed token budget.
|
|
@@ -30,6 +32,7 @@ pi-arnative replaces pi’s default terminal chrome with a unified visual interf
|
|
|
30
32
|
Saved to `~/.pi/agent/arnative/config.json` via `/arnative`:
|
|
31
33
|
|
|
32
34
|
- **Headers & Footers:** `Arnative (Full)` (default), `Arnative (Minimal)` (footer only; click head text or press `ctrl+alt+m` to toggle), or `Pi (system)`.
|
|
35
|
+
- **Footer cost:** off by default. Press `[c]` in the Footers picker to add the session's cost (`$0.42`, `~$0.42` when no provider reported a billed total) to the metrics row; the choice is stored as `footerCost` in `config.json`.
|
|
33
36
|
- **Animations:** 18 presets (`Arnative` default, `Pi (system)`, and alphabetical variants). Press `[g]` in the picker to toggle the Google gradient sweep.
|
|
34
37
|
- **Auto-compact:** Off by default. **Smart** tiers trigger near ~200k tokens (`≥768k→20%`, `≥384k→40%`, `≥192k→80%`, `<192k→pi core`), or pick a fixed budget (`100k` to `400k`).
|
|
35
38
|
- **Model heal:** **Full** (default: offline compat flags, `GET /models` limits with a 6h TTL, reasoning effort probe with a 24h TTL, and a failed fetch of either retried after 1h), **Flags** (offline only), or **Off**. Hand-edited fields are never overwritten. `/model-heal` forces every pass, warns that thinking probes can use paid tokens, and shows the stage it is in.
|
|
@@ -71,12 +74,14 @@ module deleted here is pruned from the installed copy (a stale entry point would
|
|
|
71
74
|
| `ctrl+alt+k` · `alt+k` | Scroll task list up |
|
|
72
75
|
| Click `[show]` / `[hide]` · `ctrl+o` | Toggle tool output box |
|
|
73
76
|
| `←` / `Esc` | Step back to parent menu / close active screen |
|
|
74
|
-
| `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Auto-compact, Model heal, Providers, Usage) |
|
|
77
|
+
| `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Auto-compact, Model heal, Providers, Usage, Budget) |
|
|
75
78
|
| `/usage` | Token & cost dashboard |
|
|
76
79
|
| `/todos` | Full task list recap |
|
|
77
80
|
| `/providers` | Custom provider manager |
|
|
78
81
|
| `/model-heal` | Run `models.json` heal passes now |
|
|
79
82
|
|
|
83
|
+
In Usage, `R` resets all model/provider statistics after confirmation. Session files stay unchanged and remain available through `/resume`. New messages count from the reset, including messages in existing sessions. The baseline persists in `~/.pi/agent/arnative/usage-baseline.json`; `U` undoes the latest reset while that dashboard remains open. Files from earlier resets in `usage-trash` stay untouched.
|
|
84
|
+
|
|
80
85
|
<details>
|
|
81
86
|
<summary><b>Keybindings & Platform Notes</b></summary>
|
|
82
87
|
|
package/extensions/arnative.ts
CHANGED
|
@@ -7,9 +7,10 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { bindSetModel } from "../lib/provider.ts";
|
|
9
9
|
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
-
import { visibleWidth, type AutocompleteItem } from "@earendil-works/pi-tui";
|
|
10
|
+
import { visibleWidth, matchesKey, type AutocompleteItem } from "@earendil-works/pi-tui";
|
|
11
11
|
import { stripAnsi } from "../lib/ansi.ts";
|
|
12
12
|
import { screenTitle } from "../lib/box.ts";
|
|
13
|
+
import { announce } from "../lib/status-widget.ts";
|
|
13
14
|
import { assert, isMain } from "../lib/check.ts";
|
|
14
15
|
import { markedLabels, ROW_DIVIDER } from "../lib/format.ts";
|
|
15
16
|
import { SPINNER_GRADIENT_KEY, SPINNER_PRESET_KEY, SPINNER_PRESETS, type SpinnerPreset } from "../lib/spinner.ts";
|
|
@@ -23,8 +24,9 @@ import {
|
|
|
23
24
|
setSpinnerGradient,
|
|
24
25
|
setSpinnerPreset,
|
|
25
26
|
} from "./animations.ts";
|
|
26
|
-
import { FOOTER_PRESET_KEY, HEADER_PRESET_KEY, ensureChoices } from "../lib/preset-store.ts";
|
|
27
|
-
import { FOOTER_PRESETS, activeFooterPreset, setFooterPreset, type FooterPreset } from "./footer.ts";
|
|
27
|
+
import { FOOTER_COST_KEY, FOOTER_PRESET_KEY, HEADER_PRESET_KEY, BUDGET_DAY_KEY, BUDGET_ENFORCE_KEY, BUDGET_MONTH_KEY, ensureChoices } from "../lib/preset-store.ts";
|
|
28
|
+
import { FOOTER_PRESETS, activeFooterCost, activeFooterPreset, setFooterCost, setFooterPreset, type FooterPreset } from "./footer.ts";
|
|
29
|
+
import { activeBudgetDay, activeBudgetEnforce, activeBudgetMonth, openBudget } from "./budget.ts";
|
|
28
30
|
import { HEADER_PRESETS, activeHeaderPreset, setHeaderPreset, type HeaderPreset } from "./section-headers.ts";
|
|
29
31
|
import {
|
|
30
32
|
AUTO_COMPACT_CHOICES,
|
|
@@ -36,6 +38,7 @@ import {
|
|
|
36
38
|
import { cancelManualHeal, healNow } from "./model-heal.ts";
|
|
37
39
|
import { MODEL_HEAL_CHOICES, MODEL_HEAL_KEY, activeModelHeal, setModelHeal, type ModelHealChoice } from "../lib/model-heal.ts";
|
|
38
40
|
import { LIST_LEGEND_LIVE, LIST_LEGEND_MOVE, LIST_LEGEND_ROOT, ListPicker, nameRows, rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
|
|
41
|
+
import { BACK_KEY_LABEL } from "../lib/shortcuts.ts";
|
|
39
42
|
import { openProviders } from "../lib/provider.ts";
|
|
40
43
|
import { openUsage } from "./usage.ts";
|
|
41
44
|
import { SHORTCUT_OPEN_ARNATIVE } from "../lib/shortcuts.ts";
|
|
@@ -56,7 +59,7 @@ export function menuRows(menus: Pick<ArnativeMenu, "label" | "description">[]):
|
|
|
56
59
|
/** Title of the settings menu, derived from `screenTitle` so the format lives in one place. */
|
|
57
60
|
export const MENU_TITLE = screenTitle("Settings");
|
|
58
61
|
/** One-line description under the menu title. */
|
|
59
|
-
export const MENU_DESC = "Themes, headers, footers, animations, auto-compact, providers, usage";
|
|
62
|
+
export const MENU_DESC = "Themes, headers, footers, animations, auto-compact, providers, usage, budget";
|
|
60
63
|
|
|
61
64
|
const THEMES_PICKER_TEXT: ListPickerText = {
|
|
62
65
|
title: screenTitle("Themes"),
|
|
@@ -96,7 +99,11 @@ const openThemes = async (ctx: ExtensionCommandContext): Promise<boolean | void>
|
|
|
96
99
|
revert: () => {
|
|
97
100
|
if (current) ctx.ui.setTheme(current);
|
|
98
101
|
},
|
|
99
|
-
done: () =>
|
|
102
|
+
done: () => {
|
|
103
|
+
const applied = ctx.ui.theme.name;
|
|
104
|
+
announce(ctx.ui, applied ? `Theme: ${applied}.` : "Theme changed.");
|
|
105
|
+
done(false);
|
|
106
|
+
},
|
|
100
107
|
back: () => {
|
|
101
108
|
// Back drops the live preview, then reports upward so the menu reopens.
|
|
102
109
|
// Guarded like `revert`: `theme.name` is optional, and `setTheme(undefined)`
|
|
@@ -110,11 +117,14 @@ const openThemes = async (ctx: ExtensionCommandContext): Promise<boolean | void>
|
|
|
110
117
|
return goBack === true;
|
|
111
118
|
};
|
|
112
119
|
|
|
113
|
-
|
|
120
|
+
/** The Footers screen copy. The legend states the cost switch's live value, like the
|
|
121
|
+
* Animations screen does for the gradient — a constant legend would advertise the value
|
|
122
|
+
* the screen opened with. */
|
|
123
|
+
const footersPickerText = (): ListPickerText => ({
|
|
114
124
|
title: screenTitle("Footers"),
|
|
115
125
|
description: "Selection applies live — custom footer or built-in.",
|
|
116
|
-
legend:
|
|
117
|
-
};
|
|
126
|
+
legend: `[↑↓] Preview [c] Cost ${activeFooterCost() ? "on" : "off"} [Enter] Select [Esc] Back`,
|
|
127
|
+
});
|
|
118
128
|
|
|
119
129
|
const openFooters = async (ctx: ExtensionCommandContext): Promise<boolean | void> => {
|
|
120
130
|
const opened = activeFooterPreset();
|
|
@@ -122,7 +132,7 @@ const openFooters = async (ctx: ExtensionCommandContext): Promise<boolean | void
|
|
|
122
132
|
if (ctx.mode !== "tui") {
|
|
123
133
|
// No custom components (RPC/headless): fall back to the blocking picker.
|
|
124
134
|
const labels = markedLabels(FOOTER_PRESETS, opened);
|
|
125
|
-
const pick = await ctx.ui.select(
|
|
135
|
+
const pick = await ctx.ui.select(footersPickerText().title, labels);
|
|
126
136
|
if (pick === undefined) return;
|
|
127
137
|
const name = FOOTER_PRESETS[labels.indexOf(pick)]!;
|
|
128
138
|
setFooterPreset(name, ctx);
|
|
@@ -138,15 +148,26 @@ const openFooters = async (ctx: ExtensionCommandContext): Promise<boolean | void
|
|
|
138
148
|
{
|
|
139
149
|
preview: (name) => setFooterPreset(name as FooterPreset, ctx),
|
|
140
150
|
revert: () => setFooterPreset(opened, ctx),
|
|
141
|
-
done: () =>
|
|
151
|
+
done: () => {
|
|
152
|
+
announce(ctx.ui, `Footer: ${activeFooterPreset()}.`);
|
|
153
|
+
done(false);
|
|
154
|
+
},
|
|
142
155
|
back: () => {
|
|
143
156
|
// Back drops the live preview, then reports upward so the menu reopens.
|
|
144
157
|
if (activeFooterPreset() !== opened) setFooterPreset(opened, ctx);
|
|
145
158
|
done(true);
|
|
146
159
|
},
|
|
160
|
+
// `[c]` is a switch, not a preview: the user asked for it and the legend states
|
|
161
|
+
// its state, so Esc and `←` leave it on. Only the preset preview reverts.
|
|
162
|
+
press: (keyData) => {
|
|
163
|
+
if (!matchesKey(keyData, "c")) return;
|
|
164
|
+
setFooterCost(!activeFooterCost());
|
|
165
|
+
tui.requestRender();
|
|
166
|
+
},
|
|
167
|
+
legend: () => footersPickerText().legend,
|
|
147
168
|
requestRender: () => tui.requestRender(),
|
|
148
169
|
},
|
|
149
|
-
|
|
170
|
+
footersPickerText(),
|
|
150
171
|
true,
|
|
151
172
|
ctx.thinkingLevel,
|
|
152
173
|
),
|
|
@@ -182,7 +203,10 @@ const openHeaders = async (ctx: ExtensionCommandContext): Promise<boolean | void
|
|
|
182
203
|
{
|
|
183
204
|
preview: (name) => setHeaderPreset(name as HeaderPreset, ctx),
|
|
184
205
|
revert: () => setHeaderPreset(opened, ctx),
|
|
185
|
-
done: () =>
|
|
206
|
+
done: () => {
|
|
207
|
+
announce(ctx.ui, `Header: ${activeHeaderPreset()}.`);
|
|
208
|
+
done(false);
|
|
209
|
+
},
|
|
186
210
|
back: () => {
|
|
187
211
|
// Back drops the live preview, then reports upward so the menu reopens.
|
|
188
212
|
if (activeHeaderPreset() !== opened) setHeaderPreset(opened, ctx);
|
|
@@ -226,7 +250,10 @@ const openAnimations = async (ctx: ExtensionCommandContext): Promise<boolean | v
|
|
|
226
250
|
{
|
|
227
251
|
preview: (name) => setSpinnerPreset(name as SpinnerPreset),
|
|
228
252
|
revert: () => setSpinnerPreset(opened),
|
|
229
|
-
done: () =>
|
|
253
|
+
done: () => {
|
|
254
|
+
announce(ctx.ui, `Animation: ${activeSpinnerPreset()}.`);
|
|
255
|
+
done(false);
|
|
256
|
+
},
|
|
230
257
|
back: () => {
|
|
231
258
|
// Back restores the preset it opened with, then reports upward.
|
|
232
259
|
if (activeSpinnerPreset() !== opened) setSpinnerPreset(opened);
|
|
@@ -303,6 +330,7 @@ const openAutoCompact = async (ctx: ExtensionCommandContext): Promise<boolean |
|
|
|
303
330
|
revert: () => {},
|
|
304
331
|
done: () => {
|
|
305
332
|
setAutoCompact(AUTO_COMPACT_CHOICES[picker.index]!);
|
|
333
|
+
announce(ctx.ui, `Auto-compact: ${AUTO_COMPACT_CHOICES[picker.index]}.`);
|
|
306
334
|
done(false);
|
|
307
335
|
},
|
|
308
336
|
cancel: () => done(false),
|
|
@@ -369,7 +397,10 @@ const openModelHeal = async (ctx: ExtensionCommandContext): Promise<boolean | vo
|
|
|
369
397
|
revert: () => {},
|
|
370
398
|
done: () => {
|
|
371
399
|
if (picker.index === MODEL_HEAL_CHOICES.length) runNow = true;
|
|
372
|
-
else
|
|
400
|
+
else {
|
|
401
|
+
setModelHeal(MODEL_HEAL_CHOICES[picker.index]!);
|
|
402
|
+
announce(ctx.ui, `Model heal: ${MODEL_HEAL_CHOICES[picker.index]}.`);
|
|
403
|
+
}
|
|
373
404
|
done(false);
|
|
374
405
|
},
|
|
375
406
|
cancel: () => done(false),
|
|
@@ -436,6 +467,12 @@ export const MENUS: ArnativeMenu[] = [
|
|
|
436
467
|
description: "open the token & cost dashboard (same as /usage)",
|
|
437
468
|
open: openUsage,
|
|
438
469
|
},
|
|
470
|
+
{
|
|
471
|
+
value: "budget",
|
|
472
|
+
label: "Budget",
|
|
473
|
+
description: "warn-only spend caps on today / 30d; enforce on blocks the next turn",
|
|
474
|
+
open: openBudget,
|
|
475
|
+
},
|
|
439
476
|
];
|
|
440
477
|
|
|
441
478
|
/** The settings menu and the loop that gives `←` its meaning: a screen returning `true`
|
|
@@ -527,7 +564,7 @@ export function shouldApplyDefaultTheme(
|
|
|
527
564
|
* set without starting a session. */
|
|
528
565
|
export function registerCommands(pi: Pick<ExtensionAPI, "registerCommand">): void {
|
|
529
566
|
pi.registerCommand("arnative", {
|
|
530
|
-
description: "Arnative settings menu: themes, headers, footers, animations, auto-compact, model heal, providers, usage",
|
|
567
|
+
description: "Arnative settings menu: themes, headers, footers, animations, auto-compact, model heal, providers, usage, budget",
|
|
531
568
|
getArgumentCompletions: arnativeCompletions,
|
|
532
569
|
handler: arnativeHandler,
|
|
533
570
|
});
|
|
@@ -545,10 +582,14 @@ export function recordProfile(): void {
|
|
|
545
582
|
ensureChoices({
|
|
546
583
|
[HEADER_PRESET_KEY]: activeHeaderPreset(),
|
|
547
584
|
[FOOTER_PRESET_KEY]: activeFooterPreset(),
|
|
585
|
+
[FOOTER_COST_KEY]: activeFooterCost() ? "on" : "off",
|
|
548
586
|
[SPINNER_PRESET_KEY]: activeSpinnerPreset(),
|
|
549
587
|
[SPINNER_GRADIENT_KEY]: activeSpinnerGradient() ? "on" : "off",
|
|
550
588
|
[AUTO_COMPACT_KEY]: activeAutoCompact(),
|
|
551
589
|
[MODEL_HEAL_KEY]: activeModelHeal(),
|
|
590
|
+
[BUDGET_DAY_KEY]: activeBudgetDay() === undefined ? "" : String(activeBudgetDay()),
|
|
591
|
+
[BUDGET_MONTH_KEY]: activeBudgetMonth() === undefined ? "" : String(activeBudgetMonth()),
|
|
592
|
+
[BUDGET_ENFORCE_KEY]: activeBudgetEnforce() ? "on" : "off",
|
|
552
593
|
});
|
|
553
594
|
}
|
|
554
595
|
|
|
@@ -583,10 +624,10 @@ if (isMain(import.meta.url)) {
|
|
|
583
624
|
assert(rowText(labels[0]!) === "Themes · arnative themes only (all themes: /settings → Theme)", "menu row text format");
|
|
584
625
|
assert(labels[0]!.label === "Themes" && labels[0]!.note === "arnative themes only (all themes: /settings → Theme)", "menu row keeps label and note apart");
|
|
585
626
|
assert(MENU_TITLE === "Settings - Arnative\u2819", `the menu title is the pinned string, got ${MENU_TITLE}`);
|
|
586
|
-
assert(MENU_DESC === "Themes, headers, footers, animations, auto-compact, providers, usage", `the menu description is the pinned string, got ${MENU_DESC}`);
|
|
627
|
+
assert(MENU_DESC === "Themes, headers, footers, animations, auto-compact, providers, usage, budget", `the menu description is the pinned string, got ${MENU_DESC}`);
|
|
587
628
|
// Every menu row is reachable and the description names them all, so a new screen cannot
|
|
588
629
|
// be added to MENUS and forgotten in the copy a user reads first.
|
|
589
|
-
assert(MENUS.length ===
|
|
630
|
+
assert(MENUS.length === 9, "nine settings screens");
|
|
590
631
|
{
|
|
591
632
|
const values = MENUS.map((m) => m.value);
|
|
592
633
|
assert(values.indexOf("heal") === values.indexOf("compact") + 1, "Model heal row sits right after Auto-compact");
|
|
@@ -594,7 +635,7 @@ if (isMain(import.meta.url)) {
|
|
|
594
635
|
assert(heal.map((r) => r.label).join(",") === "Full,Flags,Off,Run now", "Model heal rows: three modes then Run now");
|
|
595
636
|
assert(heal.filter((r) => r.chosen).map((r) => r.label).join(",") === "Flags", "Model heal marks only the saved mode");
|
|
596
637
|
}
|
|
597
|
-
for (const label of ["Themes", "Headers", "Footers", "Animations", "Auto-compact", "Providers", "Usage"]) {
|
|
638
|
+
for (const label of ["Themes", "Headers", "Footers", "Animations", "Auto-compact", "Providers", "Usage", "Budget"]) {
|
|
598
639
|
assert(MENUS.some((m) => m.label === label), `MENUS carries the ${label} screen`);
|
|
599
640
|
}
|
|
600
641
|
assert(/^Settings - Arnative/.test(MENU_TITLE), "title follows `<setting> - <extension>`");
|
|
@@ -625,11 +666,22 @@ if (isMain(import.meta.url)) {
|
|
|
625
666
|
assert([...registered.keys()].join(",") === "arnative,providers", "two commands: /arnative and /providers");
|
|
626
667
|
assert(typeof registered.get("providers")!.handler === "function", "/providers has a handler");
|
|
627
668
|
assert(MENUS.some((m) => m.value === "providers"), "/providers routes to a menu row that exists");
|
|
669
|
+
assert(
|
|
670
|
+
registered.get("arnative")!.description === "Arnative settings menu: themes, headers, footers, animations, auto-compact, model heal, providers, usage, budget",
|
|
671
|
+
"the /arnative command description names every screen: " + registered.get("arnative")!.description,
|
|
672
|
+
);
|
|
628
673
|
}
|
|
629
674
|
// Usage is reachable from /arnative even though it is a dashboard, not a setting.
|
|
630
675
|
assert(MENUS.some((m) => m.value === "usage"), "usage menu registered");
|
|
631
676
|
assert(arnativeCompletions("us")![0]!.value === "usage", "usage menu has completions");
|
|
632
677
|
assert(typeof MENUS.find((m) => m.value === "usage")!.open === "function", "the usage row opens the dashboard");
|
|
678
|
+
// The Budget row: warn-only caps, enforce on blocks the next turn.
|
|
679
|
+
assert(MENUS.some((m) => m.value === "budget" && typeof m.open === "function"), "budget menu registered");
|
|
680
|
+
assert(arnativeCompletions("b")![0]!.value === "budget", "budget menu has completions");
|
|
681
|
+
assert(
|
|
682
|
+
rowText(labels[labels.length - 1]!) === "Budget · warn-only spend caps on today / 30d; enforce on blocks the next turn",
|
|
683
|
+
"the budget row text is pinned: " + rowText(labels[labels.length - 1]!),
|
|
684
|
+
);
|
|
633
685
|
|
|
634
686
|
// The /arnative picker lists the package's family only; everything else (system, dark,
|
|
635
687
|
// light, a theme of the user's own) stays in /settings → Theme.
|
|
@@ -674,8 +726,8 @@ if (isMain(import.meta.url)) {
|
|
|
674
726
|
|
|
675
727
|
// `←` reports upward instead of closing on a screen with a parent, reverting the live
|
|
676
728
|
// preview first; the root menu has nothing behind it and omits the key.
|
|
677
|
-
assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter]
|
|
678
|
-
assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter]
|
|
729
|
+
assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Select [Esc] Close", "root menu legend omits ←");
|
|
730
|
+
assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Select [Esc] Back", "submenu legend advertises Esc Back");
|
|
679
731
|
assert(LIST_LEGEND_LIVE === "[↑↓] Preview [Enter] Select [Esc] Back", "live legend advertises Esc Back");
|
|
680
732
|
let backs = 0;
|
|
681
733
|
let backReverts = 0;
|
|
@@ -713,8 +765,8 @@ if (isMain(import.meta.url)) {
|
|
|
713
765
|
cancel: () => { menuCancelled = true; },
|
|
714
766
|
requestRender: () => {},
|
|
715
767
|
}, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_ROOT }, false);
|
|
716
|
-
// 80 columns: the description names
|
|
717
|
-
//
|
|
768
|
+
// 80 columns: the description names the screens (a tripwire — a screen added to MENUS must
|
|
769
|
+
// be added to the copy too), and that one-liner no longer fits 60.
|
|
718
770
|
const menuLines = mainPicker.render(80);
|
|
719
771
|
assert(menuLines.some((l) => l.includes(MENU_TITLE)), "the main menu renders its title");
|
|
720
772
|
assert(menuLines.some((l) => l.includes("[Esc] Close") && !l.includes("←")), "the root menu legend renders without a back key");
|
|
@@ -805,12 +857,13 @@ if (isMain(import.meta.url)) {
|
|
|
805
857
|
|
|
806
858
|
// Footers reuses the same picker too.
|
|
807
859
|
assert(FOOTER_PRESETS[0] === "Pi (system)", "built-in footer preset is listed first");
|
|
808
|
-
const footerPicker = new ListPicker(fakeTheme, nameRows(FOOTER_PRESETS), "Pi (system)", { preview: () => {}, revert: () => {}, done: () => {}, requestRender: () => {} },
|
|
860
|
+
const footerPicker = new ListPicker(fakeTheme, nameRows(FOOTER_PRESETS), "Pi (system)", { preview: () => {}, revert: () => {}, done: () => {}, requestRender: () => {} }, footersPickerText());
|
|
809
861
|
const footerLines = footerPicker.render(50);
|
|
810
862
|
assert(footerLines.some((l) => l.includes(screenTitle("Footers"))), "footers picker title");
|
|
811
863
|
assert(footerLines.some((l) => l.includes("→ Pi (system)")), "footers picker cursors the active preset");
|
|
812
864
|
assert(footerLines.some((l) => l.includes("Arnative (Minimal)")), "footers picker lists the minimal preset");
|
|
813
865
|
assert(footerLines.filter((l) => l.includes("Arnative (")).length === 2, "both arnative footer presets are selectable");
|
|
866
|
+
assert(/\[c\] Cost (on|off)/.test(footersPickerText().legend), "footers legend advertises the cost switch and its live state");
|
|
814
867
|
|
|
815
868
|
// Animations picker: "Pi (system)" carries a note AND renders "(system)" in dim
|
|
816
869
|
const animPicker = new ListPicker(
|