@bismawy/pi-arnative 0.16.1 → 0.18.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.
Files changed (61) hide show
  1. package/README.md +25 -16
  2. package/extensions/index.ts +41 -0
  3. package/lib/active-clock.ts +91 -0
  4. package/lib/ansi.ts +40 -78
  5. package/lib/box.ts +49 -68
  6. package/lib/chatbox.ts +371 -0
  7. package/lib/color.ts +3 -31
  8. package/lib/compat.ts +0 -60
  9. package/lib/edit-diff.ts +199 -0
  10. package/{extensions → lib/features}/arnative.ts +96 -423
  11. package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -327
  12. package/{extensions → lib/features}/budget.ts +17 -242
  13. package/lib/features/footer.ts +2232 -0
  14. package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
  15. package/{extensions → lib/features}/model-heal.ts +5 -28
  16. package/lib/features/progress-group.ts +1691 -0
  17. package/{extensions → lib/features}/render-cache.ts +391 -218
  18. package/{extensions → lib/features}/timestamps.ts +18 -94
  19. package/{extensions → lib/features}/todos.ts +44 -158
  20. package/lib/features/tools.ts +1202 -0
  21. package/lib/features/ui-render-tweaks.ts +606 -0
  22. package/lib/features/usage.ts +786 -0
  23. package/lib/format.ts +22 -4
  24. package/lib/git-status.ts +164 -0
  25. package/lib/list-picker.ts +1 -127
  26. package/lib/model-heal.ts +70 -162
  27. package/lib/patch.ts +0 -63
  28. package/lib/preset-store.ts +17 -133
  29. package/lib/provider-store.ts +573 -0
  30. package/lib/provider.ts +52 -851
  31. package/lib/runtime.ts +209 -0
  32. package/lib/shortcuts.ts +8 -58
  33. package/lib/spinner.ts +88 -162
  34. package/lib/status-widget.ts +4 -30
  35. package/lib/todos.ts +20 -143
  36. package/lib/usage-pricing.ts +143 -0
  37. package/lib/usage-store.ts +44 -378
  38. package/package.json +48 -49
  39. package/themes/arnative-blossom.json +0 -0
  40. package/themes/arnative-crimson.json +0 -0
  41. package/themes/arnative-cyberpunk.json +0 -0
  42. package/themes/arnative-dracula.json +0 -0
  43. package/themes/arnative-earthy.json +0 -0
  44. package/themes/arnative-garden.json +0 -0
  45. package/themes/arnative-gruvbox.json +0 -0
  46. package/themes/arnative-lemonade.json +0 -0
  47. package/themes/arnative-magical.json +0 -0
  48. package/themes/arnative-matrix.json +0 -0
  49. package/themes/arnative-neutral.json +0 -0
  50. package/themes/arnative-nord.json +0 -0
  51. package/themes/arnative-zinc.json +0 -0
  52. package/themes/arnative.json +0 -0
  53. package/CHANGELOG.md +0 -683
  54. package/extensions/animations.ts +0 -242
  55. package/extensions/footer.ts +0 -2617
  56. package/extensions/tools.ts +0 -2231
  57. package/extensions/ui-render-tweaks.ts +0 -1005
  58. package/extensions/usage-export.ts +0 -283
  59. package/extensions/usage.ts +0 -1406
  60. package/lib/check.ts +0 -21
  61. package/themes/gen-themes.mjs +0 -715
@@ -32,21 +32,20 @@ import {
32
32
  type TuiMouseEvent,
33
33
  type TuiMouseEventResult,
34
34
  } from "@earendil-works/pi-tui";
35
- import type { BoxTheme } from "../lib/box.ts";
36
- import { BRAND, renderBoxLines } from "../lib/box.ts";
37
- import { getActiveTheme, setActiveTheme, softOf, softSecondaryOf, stripAnsi, themeOf } from "../lib/ansi.ts";
38
- import { capitalize, expandKeyName, modelDisplayParts } from "../lib/format.ts";
39
- import { SHORTCUT_NEW_SESSION, SHORTCUT_NEXT_TAB, SHORTCUT_RELOAD } from "../lib/shortcuts.ts";
40
- import { HEADER_PRESET_KEY as HEADER_PRESET_CONFIG_KEY, choiceSetting } from "../lib/preset-store.ts";
41
- import { formatTokens, getModelAllTimeUsage } from "../lib/usage-store.ts";
42
-
43
- import { patchOnce } from "../lib/patch.ts";
35
+ import { BRAND, renderBoxLines, type BoxTheme } from "../box.ts";
36
+ import { getActiveTheme, setActiveTheme, softOf, softSecondaryOf, stripAnsi, themeOf } from "../ansi.ts";
37
+ import { capitalize, expandKeyName, modelDisplayParts } from "../format.ts";
38
+ import { SHORTCUT_NEW_SESSION, SHORTCUT_NEXT_TAB, SHORTCUT_RELOAD } from "../shortcuts.ts";
39
+ import { HEADER_PRESET_KEY as HEADER_PRESET_CONFIG_KEY, choiceSetting } from "../preset-store.ts";
40
+ import { formatTokens, getModelAllTimeUsage } from "../usage-store.ts";
41
+ import { patchOnce } from "../patch.ts";
42
+ import { getRuntime } from "../runtime.ts";
44
43
  export type TabKey = "Model" | "Directory" | "Context" | "Skills" | "Extensions" | "Shortcut";
45
44
 
46
45
  // Tab order for the next-tab shortcut and for the menu line.
47
- export const TAB_ORDER: TabKey[] = ["Directory", "Model", "Context", "Skills", "Extensions", "Shortcut"];
46
+ const TAB_ORDER: TabKey[] = ["Directory", "Model", "Context", "Skills", "Extensions", "Shortcut"];
48
47
 
49
- export const SECTION_ICONS: Record<TabKey, string> = {
48
+ const SECTION_ICONS: Record<TabKey, string> = {
50
49
  Model: "\uf1b2",
51
50
  Directory: "\uf07b",
52
51
  Context: "\udb84\uddd7",
@@ -63,11 +62,8 @@ export const HEADER_BRAND = `Arnative${BRAND}`;
63
62
 
64
63
  export type Themeish = { fg?(color: string, text: string): string; bg?(color: string, text: string): string } | null;
65
64
 
66
- const MODEL_SNAPSHOT_KEY = Symbol.for("pi-arnative.currentModel");
67
- const THINKING_SNAPSHOT_KEY = Symbol.for("pi-arnative.currentThinking");
68
-
69
65
  // First theme color that the theme really defines
70
- export function fgFirst(th: Themeish, names: string[], text: string): string {
66
+ function fgFirst(th: Themeish, names: string[], text: string): string {
71
67
  if (!th?.fg) return text;
72
68
  for (const name of names) {
73
69
  try {
@@ -89,7 +85,7 @@ export function fgFirst(th: Themeish, names: string[], text: string): string {
89
85
  * the same tint from the resolved accent; a theme that genuinely defines `accentSoft`
90
86
  * still wins first.
91
87
  */
92
- export function softFirst(th: Themeish, fallbacks: string[], text: string): string {
88
+ function softFirst(th: Themeish, fallbacks: string[], text: string): string {
93
89
  return softOnTier(softOf(th as never), th, fallbacks, text);
94
90
  }
95
91
 
@@ -98,7 +94,7 @@ export function softFirst(th: Themeish, fallbacks: string[], text: string): stri
98
94
  * counts). Same colour language as the footer: marks take `accent`, their text takes the
99
95
  * soft border-accent tier, so a header line and the footer under it agree.
100
96
  */
101
- export function softLabelFirst(th: Themeish, fallbacks: string[], text: string): string {
97
+ function softLabelFirst(th: Themeish, fallbacks: string[], text: string): string {
102
98
  return softOnTier(softSecondaryOf(th as never), th, fallbacks, text);
103
99
  }
104
100
 
@@ -123,7 +119,7 @@ export function sectionBodyOf(child: any): string | null {
123
119
  }
124
120
 
125
121
  /** Text of a themed text line, whichever pi version built it (pi 0.99 defers it to `build`). */
126
- export function themedTextOf(child: any): string {
122
+ function themedTextOf(child: any): string {
127
123
  if (typeof child?.build === "function") return String(child.build());
128
124
  const direct = child?.text ?? child?.content;
129
125
  if (typeof direct === "string" && direct !== "") return direct;
@@ -156,7 +152,7 @@ export function deviceUser(): string {
156
152
  return u || "there";
157
153
  }
158
154
 
159
- export function readVersion(dir: string): string | null {
155
+ function readVersion(dir: string): string | null {
160
156
  try {
161
157
  const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")) as { version?: unknown };
162
158
  return typeof pkg.version === "string" && pkg.version !== "" ? pkg.version : null;
@@ -287,7 +283,7 @@ export function extensionTabItems(expanded: string, agentDir: string, cwd: strin
287
283
  // Arnative build actually running: package.json one level above this extension file.
288
284
  // Reading the module's own package beats reading the npm-installed copy, which lags
289
285
  // behind whenever the local clone (or a hand-copied extensions/) is what pi loaded.
290
- const ARNATIVE_VERSION = readVersion(fileURLToPath(new URL("..", import.meta.url)));
286
+ const ARNATIVE_VERSION = readVersion(fileURLToPath(new URL("../..", import.meta.url)));
291
287
 
292
288
  export function extractItemsFromBody(body: string): string[] {
293
289
  const plain = stripAnsi(body).trim();
@@ -306,7 +302,7 @@ export function extractItemsFromBody(body: string): string[] {
306
302
 
307
303
  // Cheatsheet for the Shortcut tab. Mirrors README "Shortcuts" plus the bindings the
308
304
  // extensions themselves own (footer.ts). Kept as plain text so the data line can wrap it.
309
- export const SHORTCUTS: string[] = [
305
+ const SHORTCUTS: string[] = [
310
306
  "[Esc] Interrupt",
311
307
  "[Ctrl+c/d] Exit",
312
308
  "[/] Commands",
@@ -321,7 +317,7 @@ export function wrapCommaItems(items: string[], maxWidth: number): string[] {
321
317
  return wrapTokens(items, maxWidth, ", ", ",");
322
318
  }
323
319
 
324
- export function wrapTokens(items: string[], maxWidth: number, sep = " ", trailing = ""): string[] {
320
+ function wrapTokens(items: string[], maxWidth: number, sep = " ", trailing = ""): string[] {
325
321
  const lines: string[] = [];
326
322
  let cur = "";
327
323
  for (const item of items) {
@@ -398,17 +394,13 @@ export function buildLogoLines(th: Themeish): string[] {
398
394
 
399
395
 
400
396
  // Singleton store for loaded resources
401
- const STORE_KEY = Symbol.for("pi-arnative.resourceStore");
402
- export const tabStore: Map<TabKey, string[]> =
403
- (globalThis as Record<symbol, Map<TabKey, string[]>>)[STORE_KEY] ??
404
- new Map<TabKey, string[]>([
405
- ["Model", []],
406
- ["Directory", []],
407
- ["Context", []],
408
- ["Skills", []],
409
- ["Extensions", []],
410
- ]);
411
- (globalThis as Record<symbol, Map<TabKey, string[]>>)[STORE_KEY] = tabStore;
397
+ export const tabStore: Map<TabKey, string[]> = (getRuntime().resourceStore ??= new Map<TabKey, string[]>([
398
+ ["Model", []],
399
+ ["Directory", []],
400
+ ["Context", []],
401
+ ["Skills", []],
402
+ ["Extensions", []],
403
+ ])) as Map<TabKey, string[]>;
412
404
 
413
405
  // Header preset chosen through `/arnative headers`. "Arnative (Full)" = this extension's
414
406
  // header; "Pi (system)" = pi's built-in header. The picker lives in arnative.ts, so the
@@ -422,7 +414,7 @@ const headerPreset = choiceSetting(HEADER_PRESET_CONFIG_KEY, HEADER_PRESETS, DEF
422
414
  export const activeHeaderPreset = (): HeaderPreset => headerPreset.get();
423
415
 
424
416
  /** Hand the header slot to the active preset: arnative's box, or pi's built-in ("Pi (system)"). */
425
- export function applyHeaderPreset(ctx: ExtensionContext): void {
417
+ function applyHeaderPreset(ctx: ExtensionContext): void {
426
418
  if (activeHeaderPreset() === "Pi (system)") {
427
419
  ctx.ui?.setHeader?.(undefined);
428
420
  } else {
@@ -446,15 +438,12 @@ export function resourcesListingShown(current?: boolean): boolean {
446
438
  return countsKnown;
447
439
  }
448
440
 
449
- // The installed header instance. globalThis-backed because `/reload` re-imports the
450
- // extension modules and arnative.ts imports this file, so two copies can coexist.
451
- const HEADER_INSTANCE_KEY = Symbol.for("pi-arnative.headerInstance");
441
+ // The installed header instance on RuntimeState so `/reload` keeps it reachable.
452
442
  function headerInstance(): ArnativeHeader | null {
453
- return (globalThis as Record<symbol, ArnativeHeader | undefined>)[HEADER_INSTANCE_KEY] ?? null;
443
+ return (getRuntime().headerInstance as ArnativeHeader | null) ?? null;
454
444
  }
455
445
  function setHeaderInstance(instance: ArnativeHeader | null): void {
456
- if (instance) (globalThis as Record<symbol, ArnativeHeader>)[HEADER_INSTANCE_KEY] = instance;
457
- else delete (globalThis as Record<symbol, ArnativeHeader | undefined>)[HEADER_INSTANCE_KEY];
446
+ getRuntime().headerInstance = instance;
458
447
  }
459
448
 
460
449
  // Model name formatted exactly like in the footer: Gemini 3.8 Flash (Antigravity), Deepseek V4.1 Flash (Yarz), etc.
@@ -465,9 +454,8 @@ export function formatModelDisplayName(model?: { id?: string; name?: string; pro
465
454
 
466
455
  // Full working directory for the Directory tab. ctx.cwd is authoritative; the
467
456
  // snapshot survives header re-creation when ctx is missing.
468
- const CWD_SNAPSHOT_KEY = Symbol.for("pi-arnative.lastCwd");
469
- export function getCwd(ctx?: { cwd?: string }): string {
470
- return ctx?.cwd || (globalThis as Record<symbol, any>)[CWD_SNAPSHOT_KEY] || "";
457
+ function getCwd(ctx?: { cwd?: string }): string {
458
+ return ctx?.cwd || getRuntime().lastCwd || "";
471
459
  }
472
460
 
473
461
  export class ArnativeHeader implements Component {
@@ -497,7 +485,7 @@ export class ArnativeHeader implements Component {
497
485
  setExpanded(_expanded: boolean): void {}
498
486
 
499
487
  getTabsData(width: number): Array<{ key: TabKey; name: string; icon: string; count: number; label: string }> {
500
- const modelObj = this.ctx?.model ?? (globalThis as Record<symbol, any>)[MODEL_SNAPSHOT_KEY];
488
+ const modelObj = (this.ctx?.model ?? getRuntime().currentModel) as { id?: string; name?: string; provider?: string } | undefined;
501
489
  // Tab row stays compact: the Directory tab shows just its name, the full path
502
490
  // lives in the content line below.
503
491
  const dirLabel = "Directory";
@@ -689,9 +677,9 @@ export class ArnativeHeader implements Component {
689
677
  // 3. Active tab data (left-aligned, neatly wrapped, soft)
690
678
  let activeItems: string[] = [];
691
679
  if (this.activeTab === "Model") {
692
- const modelObj = this.ctx?.model ?? (globalThis as Record<symbol, any>)[MODEL_SNAPSHOT_KEY];
680
+ const modelObj = (this.ctx?.model ?? getRuntime().currentModel) as { id?: string; name?: string; provider?: string } | undefined;
693
681
  const fullName = formatModelDisplayName(modelObj);
694
- const thLvl = this.ctx?.thinkingLevel ?? (globalThis as Record<symbol, any>)[THINKING_SNAPSHOT_KEY];
682
+ const thLvl = (this.ctx?.thinkingLevel ?? getRuntime().currentThinking) as string | undefined;
695
683
  const thinkLevel = thLvl && thLvl !== "off" ? capitalize(thLvl) : "Off";
696
684
  const sep = fgFirst(th, ["dim"], " · ");
697
685
  // Model name in soft, its "(Provider)" tail dim.
@@ -878,9 +866,10 @@ export default function (pi: ExtensionAPI) {
878
866
  });
879
867
 
880
868
  pi.on("turn_start", async (_event, ctx) => {
881
- (globalThis as Record<symbol, any>)[MODEL_SNAPSHOT_KEY] = ctx.model;
882
- (globalThis as Record<symbol, any>)[THINKING_SNAPSHOT_KEY] = ctx.thinkingLevel;
883
- if (ctx.cwd) (globalThis as Record<symbol, any>)[CWD_SNAPSHOT_KEY] = ctx.cwd;
869
+ const rt = getRuntime();
870
+ rt.currentModel = ctx.model;
871
+ rt.currentThinking = ctx.thinkingLevel;
872
+ if (ctx.cwd) rt.lastCwd = ctx.cwd;
884
873
  });
885
874
 
886
875
  pi.on("turn_end", async () => {
@@ -9,14 +9,12 @@
9
9
  * only, Off = nothing. While pi-auto-compat is installed this module defers to it and says so
10
10
  * once, so two healers never write models.json at the same time.
11
11
  */
12
- import { bindSetModel, reloadCurrentModel } from "../lib/provider.ts";
12
+ import { bindSetModel, reloadCurrentModel } from "../provider.ts";
13
+ import { modelsPath } from "../provider-store.ts";
13
14
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
14
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
15
15
  import { type FSWatcher, watch } from "node:fs";
16
- import { join } from "node:path";
17
- import { assert, isMain } from "../lib/check.ts";
18
- import { REJECTION_RE } from "../lib/compat.ts";
19
- import { activeModelHeal, autoCompatInstalled, healEffort, healFlags, healMeta, markRejectedLevel, type HealDeps, type HealResult, type ModelHealChoice, type RtModel } from "../lib/model-heal.ts";
16
+ import { REJECTION_RE } from "../compat.ts";
17
+ import { activeModelHeal, autoCompatInstalled, healEffort, healFlags, healMeta, markRejectedLevel, type HealDeps, type HealResult, type ModelHealChoice, type RtModel } from "../model-heal.ts";
20
18
 
21
19
  // Nerd Font md-shield-sync (U+F06DE), written as a code point so the source stays ASCII.
22
20
  const HEAL_ICON = String.fromCodePoint(0xf06de);
@@ -149,7 +147,7 @@ export default function registerModelHeal(pi: ExtensionAPI): void {
149
147
  stopWatcher();
150
148
  try {
151
149
  // A pass's own write fires this too; the re-run finds nothing to change.
152
- watcher = watch(join(getAgentDir(), "models.json"), { persistent: false }, () => {
150
+ watcher = watch(modelsPath(), { persistent: false }, () => {
153
151
  if (timer) clearTimeout(timer);
154
152
  timer = setTimeout(() => {
155
153
  timer = undefined;
@@ -297,24 +295,3 @@ function registerCommands(pi: ExtensionAPI, runNow: (args: string, ctx: Extensio
297
295
  // Migration alias: keeps the old habit working once pi-auto-compat is uninstalled.
298
296
  if (!autoCompatInstalled()) pi.registerCommand("auto-compat", { description: description + " (alias of /model-heal)", handler: runNow });
299
297
  }
300
-
301
- if (isMain(import.meta.url)) {
302
- assert(isRejectedParam({ role: "assistant", provider: "r", model: "m", errorMessage: "400 invalid reasoning_effort" }), "a rejected effort triggers a re-probe");
303
- assert(!isRejectedParam({ role: "assistant", provider: "r", model: "m", errorMessage: "401 unauthorized" }), "an auth failure costs no probe");
304
- assert(!isRejectedParam({ role: "user", provider: "r", model: "m", errorMessage: "bad request" }), "only assistant messages count");
305
- assert(!isRejectedParam(undefined), "no message, no probe");
306
- assert(isEffortRejection({ role: "assistant", provider: "r", model: "m", errorMessage: "400 invalid reasoning_effort: medium" }), "an effort rejection drops the level");
307
- assert(!isEffortRejection({ role: "assistant", provider: "r", model: "m", errorMessage: "400 bad request: context too long" }), "a plain 400 keeps the map");
308
- assert(healAllowed("Flags", "Full", false) && healAllowed("Full", "Full", false), "Full runs every pass");
309
- assert(healAllowed("Flags", "Flags", false) && !healAllowed("Full", "Flags", false), "Flags runs only the offline pass");
310
- assert(!healAllowed("Flags", "Off", false) && !healAllowed("Full", "Off", false), "Off runs nothing");
311
- assert(!healAllowed("Flags", "Full", true) && !healAllowed("Flags", "Flags", true), "an installed pi-auto-compat owns the file");
312
- assert(deferNotice("Full", true) && deferNotice("Flags", true), "the hand-over notice shows while heal is wanted");
313
- assert(!deferNotice("Off", true) && !deferNotice("Full", false), "and stays quiet when Off or nothing to defer to");
314
- const owned = depsFor({ modelRegistry: { getAll: () => [{ provider: "x", id: "a" }, null], getRegisteredProviderConfig: (p: string) => (p === "ext" ? { refreshModels: () => [] } : undefined) } });
315
- assert(owned.models().length === 1, "non-object registry entries are dropped");
316
- assert(owned.ownsModels("ext") && !owned.ownsModels("x"), "an extension list with refreshModels owns its models");
317
- const throwing = depsFor({ modelRegistry: { getRegisteredProviderConfig: () => { throw new Error("stale"); } } });
318
- assert(!throwing.ownsModels("x") && throwing.models().length === 0, "a stale registry reads as empty");
319
- console.log("model-heal extension self-check OK");
320
- }