@bismawy/pi-arnative 0.10.0 → 0.11.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/lib/compat.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * Two things ride along with the same probe: the real `contextWindow`/`maxTokens`, and
8
8
  * (on demand) which `reasoning_effort` names the channel accepts.
9
9
  */
10
+ import { setTimeout as sleep } from "node:timers/promises";
10
11
  import { assert, isMain } from "./check.ts";
11
12
 
12
13
  export type Compat = Record<string, unknown>;
@@ -254,6 +255,8 @@ export interface EffortProbeOptions {
254
255
  key?: string;
255
256
  headers?: Record<string, string>;
256
257
  fetchImpl?: typeof fetch;
258
+ signal?: AbortSignal;
259
+ deadline?: number;
257
260
  /** Called after each level, for a progress row. */
258
261
  onLevel?: (level: string, accepted: boolean | undefined, index: number) => void;
259
262
  }
@@ -265,47 +268,70 @@ function isParamRejection(status: number, body: string): boolean {
265
268
  return REJECTION_RE.test(body);
266
269
  }
267
270
 
268
- const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
269
-
270
271
  /** Every effort name the channel accepts, found with one tiny completion per level.
271
272
  * `[]` means nothing answered — never call that "nothing supported". */
272
273
  export async function probeEffort(model: CompatModel, options: EffortProbeOptions): Promise<string[]> {
273
274
  const fetchImpl = options.fetchImpl ?? fetch;
274
- const url = `${options.baseUrl.replace(/\/+$/, "")}/chat/completions`;
275
+ const responses = lower(model.api) === "openai-responses";
276
+ const url = `${options.baseUrl.replace(/\/+$/, "")}/${responses ? "responses" : "chat/completions"}`;
275
277
  const headers: Record<string, string> = { "content-type": "application/json", accept: "application/json", ...options.headers };
276
278
  if (options.key) headers.authorization = `Bearer ${options.key}`;
277
279
  const accepted: string[] = [];
278
-
280
+ const signal = AbortSignal.any([
281
+ ...(options.signal ? [options.signal] : []),
282
+ ...(options.deadline !== undefined ? [AbortSignal.timeout(Math.max(1, options.deadline - Date.now()))] : []),
283
+ ]);
284
+ const checkStopped = (): void => {
285
+ signal.throwIfAborted();
286
+ if (options.deadline !== undefined && Date.now() >= options.deadline) {
287
+ throw new DOMException("Effort probe budget exhausted", "TimeoutError");
288
+ }
289
+ };
279
290
  for (const [index, level] of EFFORT_RANK.entries()) {
280
- const body = JSON.stringify({
291
+ checkStopped();
292
+ const body = JSON.stringify(responses ? {
293
+ model: model.id,
294
+ input: [{ role: "user", content: [{ type: "input_text", text: "ping" }] }],
295
+ ...(model.compat?.supportsMaxOutputTokens === false ? {} : { max_output_tokens: PROBE_TOKENS }),
296
+ stream: false,
297
+ store: false,
298
+ reasoning: { effort: level },
299
+ } : {
281
300
  model: model.id,
282
301
  messages: [{ role: "user", content: "ping" }],
283
- max_tokens: PROBE_TOKENS,
302
+ [model.compat?.maxTokensField === "max_completion_tokens" ? "max_completion_tokens" : "max_tokens"]: PROBE_TOKENS,
284
303
  stream: false,
285
304
  ...(thinkingPayload(model.compat ?? {}, true) ?? {}),
286
305
  reasoning_effort: level,
287
306
  });
288
307
  let verdict: boolean | undefined;
289
- // Two attempts per level: a first 400 can be an upstream flake, a second confirms it.
290
308
  for (let attempt = 0; attempt < 2 && verdict === undefined; attempt++) {
309
+ checkStopped();
291
310
  let status: number;
292
311
  let text: string;
293
312
  try {
294
- const response = await fetchImpl(url, { method: "POST", headers, body, signal: AbortSignal.timeout(LEVEL_TIMEOUT_MS) });
313
+ const response = await fetchImpl(url, { method: "POST", headers, body, signal: AbortSignal.any([signal, AbortSignal.timeout(LEVEL_TIMEOUT_MS)]) });
295
314
  status = response.status;
296
315
  text = (await response.text()).slice(0, 4000);
297
316
  } catch {
317
+ checkStopped();
298
318
  break; // network/timeout: inconclusive
299
319
  }
320
+ checkStopped();
300
321
  if (status < 300) {
301
322
  verdict = true;
302
323
  break;
303
324
  }
304
325
  if (status === 429) {
305
- await sleep(RETRY_PAUSE_MS);
326
+ try {
327
+ await sleep(RETRY_PAUSE_MS, undefined, { signal });
328
+ } catch (error) {
329
+ checkStopped();
330
+ throw error;
331
+ }
306
332
  continue;
307
333
  }
308
- if (!isParamRejection(status, text)) break; // 401/403/5xx without a hint: unknown
334
+ if (!isParamRejection(status, text)) break;
309
335
  verdict = false;
310
336
  }
311
337
  if (verdict) accepted.push(level);
@@ -386,8 +386,8 @@ export class InputPicker implements Component, Focusable {
386
386
 
387
387
  // Self-check: `node lib/list-picker.ts`
388
388
  if (isMain(import.meta.url)) {
389
- assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Open [Esc] Close", "root legend pinned, no ← behind the root menu");
390
- assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Open [Esc] Back", "move legend pinned: Esc is Back where a parent exists");
389
+ assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Select [Esc] Close", "root legend pinned, no ← behind the root menu");
390
+ assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Select [Esc] Back", "move legend pinned: Esc is Back where a parent exists");
391
391
  assert(LIST_LEGEND_LIVE === "[↑↓] Preview [Enter] Select [Esc] Back", "live legend pinned: Esc drops the preview and steps out");
392
392
  const fakeTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
393
393
  const quiet = (): void => undefined;
package/lib/model-heal.ts CHANGED
@@ -69,6 +69,7 @@ export interface HealDeps {
69
69
  * models.json, so only `modelOverrides` reaches the merged model. */
70
70
  ownsModels: (provider: string) => boolean;
71
71
  fetchImpl?: typeof fetch;
72
+ signal?: AbortSignal;
72
73
  }
73
74
 
74
75
  export interface HealResult {
@@ -88,6 +89,7 @@ export const DEFAULT_THINKING_MAP = { low: "low", medium: "medium", high: "high"
88
89
 
89
90
  const HOUR_MS = 60 * 60 * 1000;
90
91
  const META_TTL_MS = 6 * HOUR_MS;
92
+ const META_FAILURE_TTL_MS = HOUR_MS;
91
93
  const META_TIMEOUT_MS = 8000;
92
94
  const META_MAX_BYTES = 2 * 1024 * 1024;
93
95
  const EFFORT_TTL_MS = 24 * HOUR_MS;
@@ -254,7 +256,7 @@ export function healFlags(deps: HealDeps, only?: RtModel[], active?: RtModel): H
254
256
 
255
257
  interface HealState {
256
258
  schema: 1;
257
- providers: Record<string, { signature: string; fetchedAt: number }>;
259
+ providers: Record<string, { signature: string; fetchedAt: number; failed?: boolean }>;
258
260
  sources: Record<string, { contextWindow?: number; maxTokens?: number; at: number }>;
259
261
  efforts: Record<string, { at: number; map: Record<string, string | null>; failed?: boolean; exact?: boolean }>;
260
262
  }
@@ -385,15 +387,22 @@ export async function healMeta(deps: HealDeps, force: boolean): Promise<HealResu
385
387
  const errors: string[] = [];
386
388
  const fetched = new Map<string, { meta: Map<string, ModelMeta>; signature: string }>();
387
389
  for (const channel of channelsOf(cfg, deps)) {
390
+ deps.signal?.throwIfAborted();
388
391
  const signature = JSON.stringify({ baseUrl: channel.baseUrl, ids: channel.ids });
389
392
  const prev = state.providers[channel.provider];
390
- if (!force && prev?.signature === signature && now - prev.fetchedAt < META_TTL_MS) continue;
393
+ if (!force && prev?.signature === signature && now - prev.fetchedAt < (prev.failed ? META_FAILURE_TTL_MS : META_TTL_MS)) continue;
391
394
  try {
392
- fetched.set(channel.provider, { meta: await fetchMeta(channel, deps.fetchImpl ?? fetch), signature });
395
+ const meta = await fetchMeta(channel, deps.fetchImpl ?? fetch);
396
+ deps.signal?.throwIfAborted();
397
+ fetched.set(channel.provider, { meta, signature });
393
398
  } catch (error) {
399
+ deps.signal?.throwIfAborted();
394
400
  errors.push(`${channel.provider}: ${errText(error)}`);
401
+ state.providers[channel.provider] = { signature, fetchedAt: Date.now(), failed: true };
395
402
  }
396
403
  }
404
+ // A failed endpoint needs a cooldown even when no catalog answered.
405
+ if (errors.length > 0) saveState({ providers: state.providers });
397
406
  if (fetched.size === 0) return { changed: false, detail: [], errors };
398
407
 
399
408
  const byProvider = groupByProvider(deps.models());
@@ -484,9 +493,9 @@ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[
484
493
  // older probe wrote (nearest-effort remaps) is redone now, not after the TTL.
485
494
  const probeWrote = prev !== undefined && sameMap(mapOf(m), prev.map);
486
495
  if (carriesRemap(mapOf(m)) && !probeWrote) return false;
487
- if (force || !prev || (probeWrote && prev.exact !== true)) return true;
496
+ if (force || !prev || (probeWrote && !prev.failed && prev.exact !== true)) return true;
488
497
  if (now - prev.at >= (prev.failed ? EFFORT_FAILURE_TTL_MS : EFFORT_TTL_MS)) return true;
489
- return JSON.stringify(mapOf(m) ?? {}) !== JSON.stringify(prev.map); // edited since: respect it
498
+ return !sameMap(mapOf(m), prev.map);
490
499
  });
491
500
  if (pending.length === 0) return none();
492
501
 
@@ -494,15 +503,25 @@ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[
494
503
  const answered: { model: RtModel; supported: string[] }[] = [];
495
504
  const deadline = now + EFFORT_BUDGET_MS;
496
505
  for (const model of pending) {
506
+ deps.signal?.throwIfAborted();
497
507
  if (Date.now() >= deadline) {
498
508
  errors.push(`${model.provider}: probe budget exhausted`);
499
509
  break;
500
510
  }
501
511
  const channel = channels.get(lower(model.provider))!;
502
- const supported = await probeEffort(
503
- { ...model, compat: { ...channel.compat, ...(model.compat ?? {}) } },
504
- { baseUrl: channel.baseUrl, key: channel.key(), headers: channel.headers, fetchImpl: deps.fetchImpl },
505
- );
512
+ let supported: string[];
513
+ try {
514
+ supported = await probeEffort(
515
+ { ...model, compat: { ...channel.compat, ...(model.compat ?? {}) } },
516
+ { baseUrl: channel.baseUrl, key: channel.key(), headers: channel.headers, fetchImpl: deps.fetchImpl, signal: deps.signal, deadline },
517
+ );
518
+ } catch (error) {
519
+ deps.signal?.throwIfAborted();
520
+ if (!(error instanceof Error) || error.name !== "TimeoutError" || Date.now() < deadline) throw error;
521
+ errors.push(`${model.provider}: probe budget exhausted`);
522
+ break;
523
+ }
524
+ deps.signal?.throwIfAborted();
506
525
  if (supported.length === 0) {
507
526
  // Stamped as failed so the next run waits the short TTL instead of re-sending.
508
527
  errors.push(`${model.provider}/${model.id}: no level answered (not patched)`);
@@ -17,6 +17,12 @@ import { assert, isMain } from "./check.ts";
17
17
 
18
18
  export const HEADER_PRESET_KEY = "headerPreset";
19
19
  export const FOOTER_PRESET_KEY = "footerPreset";
20
+ /** Footer cost cell: `"on"`/`"off"`, absent reads as off. */
21
+ export const FOOTER_COST_KEY = "footerCost";
22
+ /** Budget guardrail — day/month caps are amount strings (`"5"`, `""` = unset), enforce is `"on"`/`"off"`. */
23
+ export const BUDGET_DAY_KEY = "budgetDay";
24
+ export const BUDGET_MONTH_KEY = "budgetMonth";
25
+ export const BUDGET_ENFORCE_KEY = "budgetEnforce";
20
26
 
21
27
  // Resolved per call, not at import: the self-check points getAgentDir() at a fixture dir.
22
28
  // Everything pi-arnative writes lives in one folder (agent dir/arnative); the config moved
@@ -72,10 +78,19 @@ export function loadChoice<T extends string>(key: string, allowed: readonly T[])
72
78
  return typeof value === "string" && (allowed as readonly string[]).includes(value) ? (value as T) : undefined;
73
79
  }
74
80
 
81
+ /** The stored value for `key` as a finite number in `[min, max]`, or undefined when absent, empty,
82
+ * unparsable or out of range. Amounts are stored as strings (`"5"`, `""` = unset) because
83
+ * `loadChoice` only accepts strings from an allowed set, so numbers get their own reader. */
84
+ export function loadNumber(key: string, range: { min: number; max: number }): number | undefined {
85
+ const raw = readConfig()[key];
86
+ const n = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() !== "" ? Number(raw) : NaN;
87
+ return Number.isFinite(n) && n >= range.min && n <= range.max ? n : undefined;
88
+ }
89
+
75
90
  /** Reading order of `config.json`: the presets in the order the settings menu shows them,
76
91
  * then `layoutVersion`, then anything else (a key from another module or a newer version).
77
92
  * Times a user edits the file by hand or reads it back. */
78
- const KEY_ORDER = ["headerPreset", "footerPreset", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "modelHeal"];
93
+ const KEY_ORDER = ["headerPreset", "footerPreset", "footerCost", "budgetDay", "budgetMonth", "budgetEnforce", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "modelHeal"];
79
94
 
80
95
  /** The record in {@link KEY_ORDER}; unknown keys keep the order they were written in. */
81
96
  function ordered(record: Record<string, unknown>): Record<string, unknown> {
@@ -87,9 +102,15 @@ function ordered(record: Record<string, unknown>): Record<string, unknown> {
87
102
 
88
103
  /** Store a choice. Best effort: an unwritable agent dir must not break the TUI. */
89
104
  export function saveChoice(key: string, value: string, rename: (from: string, to: string) => void = renameSync): void {
90
- if (readConfig()[key] === value) return;
91
- // Re-read: another pi session may have written its own key since this one loaded.
92
- memo = { ...readDisk().record, [key]: value };
105
+ readConfig();
106
+ const { parsed, record } = readDisk();
107
+ if (!parsed && existsSync(configPath())) {
108
+ process.emitWarning("Arnative settings were not saved: config.json is unreadable or invalid.", { code: "ARNATIVE_PRESET_SAVE" });
109
+ return;
110
+ }
111
+ memo = record;
112
+ if (record[key] === value) return;
113
+ memo = { ...record, [key]: value };
93
114
  try {
94
115
  const path = configPath();
95
116
  const tmp = `${path}.${process.pid}.tmp`;
@@ -108,7 +129,7 @@ export function saveChoice(key: string, value: string, rename: (from: string, to
108
129
  rmSync(tmp, { force: true });
109
130
  }
110
131
  } catch {
111
- // ignore: the choice still applies for this session
132
+ process.emitWarning("Arnative settings were not saved; the choice applies only to this session.", { code: "ARNATIVE_PRESET_SAVE" });
112
133
  }
113
134
  }
114
135
 
@@ -227,6 +248,29 @@ if (isMain(import.meta.url)) {
227
248
  assert(readFileSync(join(profile, "arnative", "config.json"), "utf8") === "{not json", "the startup record leaves an unreadable config alone");
228
249
  rmSync(profile, { recursive: true, force: true });
229
250
 
251
+ // loadNumber: amounts are stored as strings ("" = unset); anything that is not a finite
252
+ // number in range reads as unset, so a hand-edited or corrupt value cannot become a cap.
253
+ const nums = mkdtempSync(join(tmpdir(), "arnative-preset-num-"));
254
+ process.env.PI_CODING_AGENT_DIR = nums;
255
+ resetPresetCache();
256
+ const range = { min: 0.01, max: 1_000_000 };
257
+ saveChoice(BUDGET_DAY_KEY, "5");
258
+ assert(loadNumber(BUDGET_DAY_KEY, range) === 5, "a stored amount parses");
259
+ saveChoice(BUDGET_DAY_KEY, "7.50");
260
+ assert(loadNumber(BUDGET_DAY_KEY, range) === 7.5, "a decimal amount parses");
261
+ saveChoice(BUDGET_DAY_KEY, "abc");
262
+ assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "a non-numeric amount reads as unset");
263
+ saveChoice(BUDGET_DAY_KEY, "0");
264
+ assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "below the range reads as unset");
265
+ saveChoice(BUDGET_DAY_KEY, "2000000");
266
+ assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "above the range reads as unset");
267
+ saveChoice(BUDGET_DAY_KEY, "");
268
+ assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "an empty amount reads as unset");
269
+ writeFileSync(join(nums, "arnative", "config.json"), JSON.stringify({ [BUDGET_DAY_KEY]: 7 }), "utf8");
270
+ resetPresetCache();
271
+ assert(loadNumber(BUDGET_DAY_KEY, range) === 7, "a hand-edited numeric value is accepted");
272
+ rmSync(nums, { recursive: true, force: true });
273
+
230
274
  process.env.PI_CODING_AGENT_DIR = fixture;
231
275
  resetPresetCache();
232
276
 
package/lib/provider.ts CHANGED
@@ -16,7 +16,7 @@ import { assert, isMain } from "../lib/check.ts";
16
16
  import { buildEffortMap, isEffortProbeable, mergeMeta, parseModelMeta, probeEffort, suggestCompat, type Compat, type ModelMeta } from "./compat.ts";
17
17
  import { screenTitle, type ScreenText } from "../lib/box.ts";
18
18
  import { stripAnsi } from "../lib/ansi.ts";
19
- import { statusRows } from "./status-widget.ts";
19
+ import { announce, statusRows } from "./status-widget.ts";
20
20
  import { INPUT_LEGEND, InputPicker, LIST_LEGEND_MOVE, ListPicker, rowText, type ListRow } from "./list-picker.ts";
21
21
 
22
22
  // ---------------------------------------------------------------- flavors
@@ -720,12 +720,36 @@ const addProviderFlow = async (ctx: ExtensionCommandContext): Promise<void> => {
720
720
  return;
721
721
  }
722
722
  ctx.ui.notify(`[arnative] Provider saved: ${name} (${FLAVOR_LABELS[flavor]}, ${picked.length} models, ${levelsSummary(entry.models)}). Open /model to pick one.`, "info");
723
+ announce(ctx.ui, `Provider saved: ${name} (${picked.length} models).`);
723
724
  };
724
725
 
725
726
  const deleteProviderFlow = async (ctx: ExtensionCommandContext, name: string): Promise<void> => {
726
- if (!(await ctx.ui.confirm("Delete provider", `${name}? The stored key goes with it.`))) return;
727
+ const confirmed =
728
+ ctx.mode === "tui"
729
+ ? await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
730
+ let picker: ListPicker;
731
+ picker = new ListPicker(
732
+ theme,
733
+ [{ label: "No" }, { label: "Yes" }],
734
+ "No",
735
+ {
736
+ preview: () => {},
737
+ revert: () => {},
738
+ done: () => done(picker.index === 1),
739
+ cancel: () => done(false),
740
+ requestRender: () => tui.requestRender(),
741
+ },
742
+ { title: screenTitle("Delete provider"), description: `${name}? The stored key goes with it.`, legend: LIST_LEGEND_MOVE },
743
+ false,
744
+ ctx.thinkingLevel,
745
+ );
746
+ return picker;
747
+ })
748
+ : await ctx.ui.confirm("Delete provider", `${name}? The stored key goes with it.`);
749
+ if (confirmed !== true) return;
727
750
  try {
728
751
  ctx.ui.notify(deleteProviderNamed(name) ? `[arnative] Deleted ${name}.` : `[arnative] ${name} was already gone.`, "info");
752
+ announce(ctx.ui, `Provider deleted: ${name}.`);
729
753
  } catch (error) {
730
754
  ctx.ui.notify(`[arnative] Not deleted: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
731
755
  }
@@ -753,11 +777,13 @@ export const bindSetModel = (fn: SetModel): void => {
753
777
  /** Load models.json into the running session. A registry refresh alone is not enough: pi keeps
754
778
  * the session model object (and its thinkingLevelMap) until the model is picked again, so
755
779
  * /thinking kept offering the old levels even after /reload. */
756
- export async function reloadCurrentModel(ctx: { modelRegistry?: RegistryRef; model?: ModelRef }, setModel: SetModel | undefined = setSessionModel): Promise<boolean> {
780
+ export async function reloadCurrentModel(ctx: { modelRegistry?: RegistryRef; model?: ModelRef }, setModel: SetModel | undefined = setSessionModel, signal?: AbortSignal): Promise<boolean> {
781
+ signal?.throwIfAborted();
757
782
  const registry = ctx.modelRegistry;
758
783
  if (!registry) return false;
759
- await registry.refresh({ allowNetwork: false });
760
784
  const current = ctx.model;
785
+ await registry.refresh({ allowNetwork: false });
786
+ signal?.throwIfAborted();
761
787
  if (!current) return true;
762
788
  const fresh = registry.find(current.provider, current.id);
763
789
  if (!fresh || fresh === current) return true;
@@ -820,7 +846,7 @@ const probeModelsFlow = async (ctx: ExtensionCommandContext, name: string, entry
820
846
  await saveModelsNamed(ctx, name, mergeLevels(entry, picked, result.meta));
821
847
  };
822
848
 
823
- const THINKING_LEGEND = "[/] Filter [Space] Off/auto [0-6] Levels [p] Probe [a/r] All auto/off [Enter] Save [Esc] Back";
849
+ const THINKING_LEGEND = "[/] Filter [Space] Off/auto [0-6] Set level [p] Probe [a/r] All auto/off [Enter] Save [Esc] Back";
824
850
  // minimal … max: the efforts a map can offer; off is pi's own switch, not an effort.
825
851
  const EFFORT_LEVELS = THINKING_LEVELS.slice(1);
826
852
 
@@ -1099,6 +1125,7 @@ const editNameFlow = async (ctx: ExtensionCommandContext, name: string): Promise
1099
1125
  return name;
1100
1126
  }
1101
1127
  ctx.ui.notify(`[arnative] Renamed ${name} → ${value}. Open /model to refresh.`, "info");
1128
+ announce(ctx.ui, `Provider renamed: ${name} → ${value}.`);
1102
1129
  return value;
1103
1130
  };
1104
1131
 
@@ -1116,6 +1143,7 @@ const editKeyFlow = async (ctx: ExtensionCommandContext, name: string, entry: Pr
1116
1143
  return;
1117
1144
  }
1118
1145
  ctx.ui.notify(`[arnative] ${name}: API key replaced (${keyHint(value)}). Open /model to refresh.`, "info");
1146
+ announce(ctx.ui, `API key replaced: ${name} (${keyHint(value)}).`);
1119
1147
  };
1120
1148
 
1121
1149
  /** The Edit menu: one field per row, each write immediate. Returns the provider id to keep
package/lib/shortcuts.ts CHANGED
@@ -78,18 +78,20 @@ export const UNDO_USAGE = keySet("U", "shift+u");
78
78
  const legend = (...pairs: [string, string][]): string => pairs.map(([key, action]) => `[${key}] ${action}`).join(" ");
79
79
 
80
80
  /** Root `/arnative` menu: nothing behind it, so Esc closes. */
81
- export const LEGEND_ROOT = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"], [CANCEL.label, "Close"]);
81
+ export const LEGEND_ROOT = legend([MOVE.label, "Move"], [CHOOSE.label, "Select"], [CANCEL.label, "Close"]);
82
82
  /** Move-and-open list inside a submenu (the provider list, the provider actions): Esc steps
83
83
  * back to the screen above, exactly like ←. */
84
- export const LEGEND_MOVE = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"], [CANCEL.label, "Back"]);
84
+ export const LEGEND_MOVE = legend([MOVE.label, "Move"], [CHOOSE.label, "Select"], [CANCEL.label, "Back"]);
85
85
  /** Live-preview list: moving applies, Enter keeps, Esc drops the preview and steps out. */
86
86
  export const LEGEND_LIVE = legend([MOVE.label, "Preview"], [CHOOSE.label, "Select"], [CANCEL.label, "Back"]);
87
87
  /** A list you only read (the `/todos` recap): moving changes nothing, so there is no Open. */
88
88
  export const LEGEND_READ_ONLY = legend([MOVE.label, "Move"], [CANCEL.label, "Close"]);
89
89
  /** The usage dashboard. `reset` adds the key that deletes history, so a screen without
90
- * that key never advertises it; `undo` appears only while a reset can be undone. */
91
- export function legendUsage(width: number, opts: { reset?: boolean; undo?: boolean } = {}): string {
92
- const pairs: [string, string][] = [[MOVE.label, "Move"], [RANGE.label, "Range"], ["Click", "Open/close"]];
90
+ * that key never advertises it; `undo` appears only while a reset can be undone. `v` cycles
91
+ * the Provider → Project → Prices views, handled on every view; `next` names the view that
92
+ * key would show, so the legend states the destination instead of the generic word View. */
93
+ export function legendUsage(width: number, opts: { reset?: boolean; undo?: boolean; next?: string } = {}): string {
94
+ const pairs: [string, string][] = [[MOVE.label, "Move"], [RANGE.label, "Range"], ["Space/Click", "Show/Hide"], ["v", opts.next ? `Next: ${opts.next}` : "View"]];
93
95
  if (opts.reset) pairs.push([CANCEL.label, "Back"], [RESET_USAGE.label, "Reset"]);
94
96
  if (opts.undo) pairs.push([UNDO_USAGE.label, "Undo"]);
95
97
  if (!opts.reset) pairs.push([CANCEL.label, "Back"]);
@@ -130,7 +132,7 @@ if (isMain(import.meta.url)) {
130
132
  assert(!matchesBack("h"), "a bare letter is not the back key");
131
133
  // The legends are built from the same keys the handlers match, so a key cannot be
132
134
  // advertised on one screen and handled on none.
133
- assert(LEGEND_MOVE === "[↑↓] Move [Enter] Open [Esc] Back", `submenu legend pinned, got ${LEGEND_MOVE}`);
135
+ assert(LEGEND_MOVE === "[↑↓] Move [Enter] Select [Esc] Back", `submenu legend pinned, got ${LEGEND_MOVE}`);
134
136
  assert(LEGEND_READ_ONLY === "[↑↓] Move [Esc] Close", `read-only legend pinned, got ${LEGEND_READ_ONLY}`);
135
137
  assert(
136
138
  LEGEND_LIVE === `[↑↓] Preview [Enter] Select [${CANCEL.label}] Back`,
@@ -142,8 +144,11 @@ if (isMain(import.meta.url)) {
142
144
  assert(CANCEL.matches("\x1b"), "[Esc] matches escape");
143
145
  assert(!CANCEL.matches("\x1b[D"), "[Esc] is not the ← byte sequence");
144
146
  assert(legendUsage(120).includes("[Esc] Back"), "a wide usage legend advertises Esc Back");
145
- assert(legendUsage(120).includes("[Click] Open/close"), "a wide usage legend advertises the mouse");
147
+ assert(legendUsage(140).includes("[Space/Click] Show/Hide"), "a wide usage legend advertises Space and the mouse");
148
+ assert(legendUsage(120).includes("[v] View"), "a wide usage legend advertises the view key the dashboard handles");
149
+ assert(legendUsage(120, { next: "Project" }).includes("[v] Next: Project"), "the legend names the view the key would show");
146
150
  assert(legendUsage(20) === "[Esc] Back", "a narrow usage legend degrades to the one key that still fits");
151
+ assert(!legendUsage(20).includes("[v]"), "the narrow usage legend drops the view key with the rest");
147
152
  assert(legendUsage(160, { reset: true }).includes("[R] Reset"), "a reset-capable dashboard advertises R Reset");
148
153
  assert(!legendUsage(160).includes("Reset"), "the read-only dashboard does not advertise a key it lacks");
149
154
  assert(RESET_USAGE.matches("R") && !RESET_USAGE.matches("r"), "a capital R is shift+r, not r");
@@ -55,6 +55,26 @@ export function statusRows(th: FgTheme, rows: string[], width = Number.POSITIVE_
55
55
  return Number.isFinite(width) ? lines.map((line) => truncateToWidth(line, width, "")) : lines;
56
56
  }
57
57
 
58
+ /** Key for the one-line change notice above the editor. */
59
+ export const NOTICE_KEY = "arnative-notice";
60
+ /** How long a change notice stays before it clears itself. */
61
+ export const NOTICE_MS = 6_000;
62
+ let noticeTimer: ReturnType<typeof setTimeout> | undefined;
63
+
64
+ /**
65
+ * State what the last change did, in the status slot above the editor, and clear it after
66
+ * {@link NOTICE_MS}. The next change replaces the line instead of stacking. A UI without
67
+ * widgets (RPC/headless) is left alone.
68
+ */
69
+ export function announce(ui: { setWidget?(key: string, content: string[] | undefined): void } | undefined, message: string): void {
70
+ if (!ui?.setWidget) return;
71
+ ui.setWidget(NOTICE_KEY, [message]);
72
+ if (noticeTimer) clearTimeout(noticeTimer);
73
+ noticeTimer = setTimeout(() => ui.setWidget?.(NOTICE_KEY, undefined), NOTICE_MS);
74
+ // Do not hold the process open just to hide a notice.
75
+ (noticeTimer as { unref?(): void }).unref?.();
76
+ }
77
+
58
78
  if (isMain(import.meta.url)) {
59
79
  const tag = (color: string, text: string) => `<${color}>${text}</${color}>`;
60
80
  assert(