@bismawy/pi-arnative 0.16.1 → 0.18.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.
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 +1557 -0
  17. package/{extensions → lib/features}/render-cache.ts +113 -161
  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 +5 -6
  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
package/lib/model-heal.ts CHANGED
@@ -14,11 +14,9 @@
14
14
  * edited is remembered as manual and left alone.
15
15
  */
16
16
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
17
- import { execSync } from "node:child_process";
18
- import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
19
- import { tmpdir } from "node:os";
17
+ import { exec } from "node:child_process";
18
+ import { copyFileSync, existsSync, readFileSync } from "node:fs";
20
19
  import { join } from "node:path";
21
- import { assert, isMain } from "./check.ts";
22
20
  import {
23
21
  buildEffortMap,
24
22
  carriesRemap,
@@ -32,15 +30,15 @@ import {
32
30
  type CompatModel,
33
31
  type ModelMeta,
34
32
  } from "./compat.ts";
35
- import { loadChoice, saveChoice, writeAtomicSync } from "./preset-store.ts";
36
- import { levelToWire, loadModelsConfig, looseJsonParse, readAuthKey, saveModelsConfig, wireToLevel } from "./provider.ts";
33
+ import { loadChoice, saveChoice, writeJsonAtomicSync } from "./preset-store.ts";
34
+ import { levelToWire, loadModelsConfig, looseJsonParse, modelsPath, readAuthKey, saveModelsConfig, wireToLevel } from "./provider-store.ts";
37
35
 
38
36
  // ------------------------------------------------------------- setting
39
37
 
40
38
  export const MODEL_HEAL_CHOICES = ["Full", "Flags", "Off"] as const;
41
39
  export type ModelHealChoice = (typeof MODEL_HEAL_CHOICES)[number];
42
40
  export const MODEL_HEAL_KEY = "modelHeal";
43
- export const DEFAULT_MODEL_HEAL: ModelHealChoice = "Full";
41
+ const DEFAULT_MODEL_HEAL: ModelHealChoice = "Full";
44
42
 
45
43
  export const activeModelHeal = (): ModelHealChoice => loadChoice(MODEL_HEAL_KEY, MODEL_HEAL_CHOICES) ?? DEFAULT_MODEL_HEAL;
46
44
  export const setModelHeal = (choice: ModelHealChoice): void => saveChoice(MODEL_HEAL_KEY, choice);
@@ -59,7 +57,7 @@ export function autoCompatInstalled(): boolean {
59
57
  // --------------------------------------------------------------- types
60
58
 
61
59
  export type RtModel = CompatModel & { provider: string; id: string; thinkingLevelMap?: unknown };
62
- type Obj = Record<string, unknown>;
60
+ export type Obj = Record<string, unknown>;
63
61
 
64
62
  /** What a pass needs from the running session; injected so the self-check runs offline. */
65
63
  export interface HealDeps {
@@ -123,7 +121,7 @@ function edit(mutate: (cfg: Obj) => string[]): HealResult {
123
121
  const detail = mutate(cfg);
124
122
  if (detail.length === 0) return none();
125
123
  try {
126
- const path = join(getAgentDir(), "models.json");
124
+ const path = modelsPath();
127
125
  if (!backedUp && existsSync(path)) {
128
126
  if (!existsSync(`${path}.bak-model-heal`)) copyFileSync(path, `${path}.bak-model-heal`);
129
127
  backedUp = true;
@@ -254,7 +252,7 @@ export function healFlags(deps: HealDeps, only?: RtModel[], active?: RtModel): H
254
252
 
255
253
  // ---------------------------------------------------------------- state
256
254
 
257
- interface HealState {
255
+ export interface HealState {
258
256
  schema: 1;
259
257
  providers: Record<string, { signature: string; fetchedAt: number; failed?: boolean }>;
260
258
  sources: Record<string, { contextWindow?: number; maxTokens?: number; at: number }>;
@@ -283,7 +281,7 @@ function loadState(): HealState {
283
281
  function saveState(part: Partial<Omit<HealState, "schema">>): void {
284
282
  try {
285
283
  const state = { ...loadState(), ...part };
286
- writeAtomicSync(statePath(), `${JSON.stringify(state, null, 2)}\n`);
284
+ writeJsonAtomicSync(statePath(), state);
287
285
  } catch {
288
286
  // best effort: a lost stamp only costs one extra request next run
289
287
  }
@@ -291,17 +289,53 @@ function saveState(part: Partial<Omit<HealState, "schema">>): void {
291
289
 
292
290
  // ------------------------------------------------------------- channels
293
291
 
292
+ const SECRET_CMD_TIMEOUT_MS = 5_000;
293
+
294
294
  /** A models.json apiKey: "$VAR" env, "!cmd" shell output, else the literal. */
295
- function resolveSecret(value: unknown): string | undefined {
295
+ async function resolveSecret(value: unknown, signal?: AbortSignal): Promise<string | undefined> {
296
296
  if (typeof value !== "string" || !value) return undefined;
297
297
  if (value.startsWith("$")) return process.env[value.slice(1)]?.trim() || undefined;
298
298
  if (value.startsWith("!")) {
299
- try {
300
- // A hanging or prompting command must not freeze pi: give up after 5 s.
301
- return execSync(value.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5_000 }).trim() || undefined;
302
- } catch {
303
- return undefined;
304
- }
299
+ signal?.throwIfAborted();
300
+ const command = value.slice(1);
301
+ return await new Promise<string | undefined>((resolve, reject) => {
302
+ let settled = false;
303
+ const finish = (fn: () => void): void => {
304
+ if (settled) return;
305
+ settled = true;
306
+ signal?.removeEventListener("abort", onAbort);
307
+ fn();
308
+ };
309
+ const onAbort = (): void => {
310
+ try {
311
+ child.kill();
312
+ } catch {
313
+ // already exited
314
+ }
315
+ // Drop stdio refs so an aborted shell subchild cannot keep the event loop alive.
316
+ child.stdout?.destroy();
317
+ child.stderr?.destroy();
318
+ child.unref();
319
+ finish(() => reject(signal!.reason));
320
+ };
321
+ const child = exec(
322
+ command,
323
+ { encoding: "utf8", timeout: SECRET_CMD_TIMEOUT_MS, maxBuffer: 64 * 1024, windowsHide: true },
324
+ (error, stdout) => {
325
+ if (signal?.aborted) {
326
+ finish(() => reject(signal.reason));
327
+ return;
328
+ }
329
+ if (error) {
330
+ finish(() => resolve(undefined));
331
+ return;
332
+ }
333
+ finish(() => resolve(stdout.trim() || undefined));
334
+ },
335
+ );
336
+ child.stdin?.end();
337
+ signal?.addEventListener("abort", onAbort, { once: true });
338
+ });
305
339
  }
306
340
  return value;
307
341
  }
@@ -311,7 +345,7 @@ interface Channel {
311
345
  baseUrl: string;
312
346
  api: string;
313
347
  // Resolved on first use, so a !cmd key never runs for a channel the TTL skips.
314
- key: () => string | undefined;
348
+ key: (signal?: AbortSignal) => Promise<string | undefined>;
315
349
  headers: Record<string, string>;
316
350
  compat: Compat;
317
351
  ids: string[];
@@ -335,7 +369,12 @@ function channelsOf(cfg: Obj, deps: HealDeps): Channel[] {
335
369
  provider,
336
370
  baseUrl,
337
371
  api: lower(entry.api ?? merged[0]?.api),
338
- key: () => (key ??= { value: readAuthKey(provider) ?? resolveSecret(entry.apiKey) }).value,
372
+ key: async (signal?: AbortSignal) => {
373
+ if (key) return key.value;
374
+ const value = readAuthKey(provider) ?? (await resolveSecret(entry.apiKey, signal));
375
+ key = { value };
376
+ return value;
377
+ },
339
378
  headers,
340
379
  compat: { ...(isObj(entry.compat) ? entry.compat : {}), ...(merged[0]?.compat ?? {}) },
341
380
  ids: [...new Set([...stated, ...merged.map((m) => m.id)])].sort(),
@@ -344,11 +383,12 @@ function channelsOf(cfg: Obj, deps: HealDeps): Channel[] {
344
383
  return out;
345
384
  }
346
385
 
347
- async function fetchMeta(channel: Channel, fetchImpl: typeof fetch): Promise<Map<string, ModelMeta>> {
386
+ async function fetchMeta(channel: Channel, fetchImpl: typeof fetch, signal?: AbortSignal): Promise<Map<string, ModelMeta>> {
348
387
  const headers: Record<string, string> = { accept: "application/json", "accept-encoding": "identity", ...channel.headers };
349
- const key = channel.key();
388
+ const key = await channel.key(signal);
350
389
  if (key) headers.authorization = `Bearer ${key}`;
351
- const response = await fetchImpl(`${channel.baseUrl.replace(/\/+$/, "")}/models`, { headers, signal: AbortSignal.timeout(META_TIMEOUT_MS) });
390
+ const reqSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(META_TIMEOUT_MS)]) : AbortSignal.timeout(META_TIMEOUT_MS);
391
+ const response = await fetchImpl(`${channel.baseUrl.replace(/\/+$/, "")}/models`, { headers, signal: reqSignal });
352
392
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
353
393
  const text = await response.text();
354
394
  if (text.length > META_MAX_BYTES) throw new Error("response too large");
@@ -403,7 +443,7 @@ export async function healMeta(deps: HealDeps, force: boolean): Promise<HealResu
403
443
  const prev = state.providers[channel.provider];
404
444
  if (!force && metaFresh(prev, channel, signature, now)) continue;
405
445
  try {
406
- const meta = await fetchMeta(channel, deps.fetchImpl ?? fetch);
446
+ const meta = await fetchMeta(channel, deps.fetchImpl ?? fetch, deps.signal);
407
447
  deps.signal?.throwIfAborted();
408
448
  fetched.set(channel.provider, { meta, signature });
409
449
  } catch (error) {
@@ -534,7 +574,7 @@ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[
534
574
  try {
535
575
  supported = await probeEffort(
536
576
  { ...model, compat: { ...channel.compat, ...(model.compat ?? {}) } },
537
- { baseUrl: channel.baseUrl, key: channel.key(), headers: channel.headers, fetchImpl: deps.fetchImpl, signal: deps.signal, deadline },
577
+ { baseUrl: channel.baseUrl, key: await channel.key(deps.signal), headers: channel.headers, fetchImpl: deps.fetchImpl, signal: deps.signal, deadline },
538
578
  );
539
579
  } catch (error) {
540
580
  deps.signal?.throwIfAborted();
@@ -596,140 +636,8 @@ export function markRejectedLevel(deps: HealDeps, model: RtModel, level: string)
596
636
 
597
637
  // ----------------------------------------------------------- self-check
598
638
 
599
- if (isMain(import.meta.url)) {
600
- const dir = mkdtempSync(join(tmpdir(), "arnative-heal-"));
601
- const previous = process.env.PI_CODING_AGENT_DIR;
602
- process.env.PI_CODING_AGENT_DIR = dir;
603
- try {
604
- assert(getAgentDir() === dir, "the fixture redirects the agent dir");
605
- const file = join(dir, "models.json");
606
- const read = (): Record<string, Obj> => (JSON.parse(readFileSync(file, "utf8")) as Obj).providers as Record<string, Obj>;
607
- const modelIn = (provider: string, id: string): Obj => (read()[provider]!.models as Obj[]).find((m) => m.id === id)!;
608
- const relay = { api: "openai-completions", baseUrl: "https:\/\/relay.example/v1" };
609
- writeFileSync(
610
- file,
611
- JSON.stringify({
612
- providers: {
613
- relay: { ...relay, apiKey: "k", models: [{ id: "gpt-x" }, { id: "claude-sonnet-4-5" }, { id: "r1", reasoning: true }, { id: "pinned", reasoning: true, thinkingLevelMap: { off: null, minimal: null, low: null, medium: null, high: null, xhigh: "xhigh", max: null } }] },
614
- owned: { ...relay },
615
- },
616
- }),
617
- );
618
- const registry: RtModel[] = [
619
- { provider: "relay", id: "gpt-x", ...relay },
620
- { provider: "relay", id: "claude-sonnet-4-5", ...relay },
621
- { provider: "relay", id: "r1", reasoning: true, ...relay },
622
- { provider: "owned", id: "o1", ...relay },
623
- ];
624
- const deps: HealDeps = { models: () => registry, ownsModels: (p) => p === "owned" };
625
-
626
- const first = healFlags(deps);
627
- assert(first.changed && first.errors.length === 0, "the first flags pass writes");
628
- const relayCompat = read().relay!.compat as Obj;
629
- assert(relayCompat.supportsLongCacheRetention === false && relayCompat.sendSessionAffinityHeaders === true, "a channel-wide flag lands at provider level");
630
- assert(relayCompat.cacheControlFormat === undefined, "a flag only one sibling needs stays off the provider");
631
- const overrideCompat = (id: string): Obj => ((read().relay!.modelOverrides as Record<string, Obj>)[id]!.compat as Obj);
632
- assert(overrideCompat("claude-sonnet-4-5").cacheControlFormat === "anthropic", "and lands on that model override");
633
- const r1 = modelIn("relay", "r1");
634
- assert(isObj(r1.thinkingLevelMap) && overrideCompat("r1").supportsDeveloperRole === false, "a reasoning model gets a map and the developer-role opt-out");
635
- assert(read().owned!.compat === undefined && isObj((read().owned!.modelOverrides as Obj).o1), "an extension-owned provider is fixed through modelOverrides");
636
- assert(existsSync(`${file}.bak-model-heal`), "the first write keeps a backup");
637
- const pinned = modelIn("relay", "pinned").thinkingLevelMap as Obj;
638
- assert(pinned.minimal === "minimal" && pinned.medium === "medium" && pinned.xhigh === "xhigh" && pinned.max === null && !("off" in pinned), "an old single-pin map becomes a ceiling map");
639
-
640
- // The registry stays stale until refresh; a repeat must find nothing left to write.
641
- assert(!healFlags(deps).changed, "a repeated pass is a no-op");
642
-
643
- // An explicit value, even false, produces no suggestion, so nothing overwrites it.
644
- const explicit: RtModel = { provider: "relay", id: "gpt-x", ...relay, compat: { supportsLongCacheRetention: true, sendSessionAffinityHeaders: false } };
645
- assert(Object.keys(suggestCompat(explicit)).length === 0, "stated flags produce no suggestion");
646
-
647
- // Meta: a synced window and cap, an unloaded catalog id, the TTL, a later hand edit.
648
- const catalog = { data: [{ id: "gpt-x", context_length: 400_000, max_output_tokens: 32_000 }, { id: "unloaded", context_length: 9 }] };
649
- let calls = 0;
650
- const metaFetch = (async () => {
651
- calls++;
652
- return { ok: true, status: 200, text: async () => JSON.stringify(catalog) };
653
- }) as unknown as typeof fetch;
654
- const metaDeps: HealDeps = { ...deps, fetchImpl: metaFetch };
655
- const meta = await healMeta(metaDeps, false);
656
- assert(meta.changed && modelIn("relay", "gpt-x").contextWindow === 400_000 && modelIn("relay", "gpt-x").maxTokens === 32_000, "a catalog window and cap are synced");
657
- assert(!readFileSync(file, "utf8").includes("unloaded"), "a catalog id pi never loaded gets no entry");
658
- const callsAfterFirst = calls;
659
- await healMeta(metaDeps, false);
660
- assert(calls === callsAfterFirst, "a fresh signature inside the TTL costs no request");
661
-
662
- const edited = JSON.parse(readFileSync(file, "utf8")) as Obj;
663
- (((edited.providers as Record<string, Obj>).relay!.models as Obj[]).find((m) => m.id === "gpt-x")!).contextWindow = 200_000;
664
- writeFileSync(file, JSON.stringify(edited));
665
- await healMeta(metaDeps, true);
666
- assert(modelIn("relay", "gpt-x").contextWindow === 200_000, "a hand-edited window stays manual");
667
-
668
- // A write that fails must not stamp the state: the next run would read the unchanged
669
- // value as a hand edit and never sync it again. A directory at the temp path fails
670
- // the atomic write on every OS (EISDIR).
671
- const locked = JSON.parse(readFileSync(file, "utf8")) as Obj;
672
- (locked.providers as Record<string, Obj>).lock = { ...relay, models: [{ id: "m", contextWindow: 128_000 }] };
673
- writeFileSync(file, JSON.stringify(locked));
674
- const lockDeps: HealDeps = {
675
- models: () => [{ provider: "lock", id: "m", ...relay }],
676
- ownsModels: () => false,
677
- fetchImpl: (async () => ({ ok: true, status: 200, text: async () => JSON.stringify({ data: [{ id: "m", context_length: 400_000 }] }) })) as unknown as typeof fetch,
678
- };
679
- const blocker = file + "." + process.pid + ".tmp";
680
- mkdirSync(blocker);
681
- const failed = await healMeta(lockDeps, true);
682
- rmSync(blocker, { recursive: true, force: true });
683
- assert(!failed.changed && failed.errors.some((e) => e.startsWith("write failed")), "a failed write is reported");
684
- await healMeta(lockDeps, true);
685
- assert(modelIn("lock", "m").contextWindow === 400_000, "a failed write leaves no stamp, so the next run still syncs");
686
-
687
- // Effort: a relay that 400s medium remaps it upward; a shaped map is left alone.
688
- const effortFetch = (async (_url: string, init?: { body?: string }) => {
689
- const level = JSON.parse(init?.body ?? "{}").reasoning_effort as string;
690
- const ok = ["none", "minimal", "low", "high"].includes(level);
691
- return { status: ok ? 200 : 400, text: async () => (ok ? "" : "invalid reasoning_effort") };
692
- }) as unknown as typeof fetch;
693
- const r1Model: RtModel = { provider: "relay", id: "r1", reasoning: true, ...relay, thinkingLevelMap: { ...DEFAULT_THINKING_MAP } };
694
- const effort = await healEffort({ ...deps, fetchImpl: effortFetch }, true, [r1Model]);
695
- assert(effort.changed && (modelIn("relay", "r1").thinkingLevelMap as Obj).medium === null, "a rejected effort is marked unsupported, not remapped");
696
- const shaped = await healEffort({ ...deps, fetchImpl: effortFetch }, true, [{ ...r1Model, thinkingLevelMap: { medium: "high" } }]);
697
- assert(!shaped.changed, "a user-shaped map is never probed");
698
- const runtime = markRejectedLevel(deps, r1Model, "low");
699
- const afterRuntime = modelIn("relay", "r1").thinkingLevelMap as Obj;
700
- assert(runtime.changed && afterRuntime.low === null && afterRuntime.medium === null && afterRuntime.high === "high", "a level rejected at runtime is dropped and the rest stay");
701
- assert(!markRejectedLevel(deps, r1Model, "low").changed, "a level already dropped is a no-op");
702
- assert(!markRejectedLevel(deps, r1Model, "off").changed, "off is never dropped");
703
- assert((await healEffort({ ...deps, fetchImpl: effortFetch }, false, [{ ...r1Model, thinkingLevelMap: afterRuntime as Record<string, string | null> }])).errors.length === 0, "a runtime-dropped map stays probe-owned");
704
- assert(existsSync(join(dir, "arnative", "model-heal.json")), "state lives in the arnative folder");
705
- // The trigger runs meta and effort at once; neither save may drop the other's stamps.
706
- await Promise.all([healMeta(metaDeps, true), healEffort({ ...deps, fetchImpl: effortFetch }, true, [r1Model])]);
707
- const both = JSON.parse(readFileSync(join(dir, "arnative", "model-heal.json"), "utf8")) as HealState;
708
- assert(Object.keys(both.providers).length > 0 && Object.keys(both.efforts).length > 0, "concurrent passes keep both state sections");
709
-
710
- // A corrupt models.json is reported and left byte-for-byte as it was.
711
- writeFileSync(file, "{ broken");
712
- const corrupt = healFlags(deps);
713
- assert(!corrupt.changed && corrupt.errors.length === 1 && readFileSync(file, "utf8") === "{ broken", "a corrupt file is never rewritten");
714
-
715
- // Coexistence: pi-auto-compat in settings is detected in both package shapes.
716
- writeFileSync(join(dir, "settings.json"), JSON.stringify({ packages: ["npm:@bismawy/pi-arnative", { source: "npm:@bismawy/pi-auto-compat" }] }));
717
- assert(autoCompatInstalled(), "an installed pi-auto-compat is detected");
718
- writeFileSync(join(dir, "settings.json"), JSON.stringify({ packages: ["npm:@bismawy/pi-arnative"] }));
719
- assert(!autoCompatInstalled(), "and its removal too");
720
-
721
- // Mode: Full until chosen, every choice round-trips, and a junk value falls back to Full.
722
- assert(activeModelHeal() === "Full", "Full is the default mode");
723
- for (const choice of MODEL_HEAL_CHOICES) {
724
- setModelHeal(choice);
725
- assert(activeModelHeal() === choice, "the " + choice + " mode is saved");
726
- }
727
- saveChoice(MODEL_HEAL_KEY, "Sometimes");
728
- assert(activeModelHeal() === "Full", "an unknown saved mode reads as Full");
729
- } finally {
730
- if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR;
731
- else process.env.PI_CODING_AGENT_DIR = previous;
732
- rmSync(dir, { recursive: true, force: true });
733
- }
734
- console.log("model-heal.ts self-check OK");
735
- }
639
+ export const __test = {
640
+ isObj,
641
+ none,
642
+ edit,
643
+ };
package/lib/patch.ts CHANGED
@@ -47,66 +47,3 @@ export function originalOf<T extends AnyFn>(proto: Record<symbol | string, any>,
47
47
  export function patchOnce(proto: Record<symbol | string, any>, key: string, build: (original: AnyFn) => AnyFn): void {
48
48
  proto[key] = markPatched(build(originalOf(proto, key)));
49
49
  }
50
-
51
- // Self-check: `node lib/patch.ts`.
52
- import { assert, isMain } from "./check.ts";
53
- if (isMain(import.meta.url)) {
54
- const proto: any = { render(): string { return "pi"; } };
55
- const first = originalOf<() => string>(proto, "render");
56
- assert(first() === "pi", "the original is pi's own method");
57
- proto.render = markPatched(function (): string {
58
- return first();
59
- });
60
-
61
- // A reload: the slot holds OUR patch, and the second load must still see pi's method.
62
- const second = originalOf<() => string>(proto, "render");
63
- assert(second === first, "reload: the recorded original never becomes a previous patch");
64
- const reinstalled = markPatched(function (): string {
65
- return second();
66
- });
67
- proto.render = reinstalled;
68
- assert(proto.render() === "pi", "the reinstalled patch still calls pi, not itself");
69
- assert(proto.render !== first && proto.render === reinstalled, "the slot holds the newest patch");
70
- assert(proto[Symbol.for("pi-arnative.protoOriginals")].render === first, "originals stay on the prototype (outlive the module)");
71
-
72
- // A slot patched without bookkeeping cannot silently disable the patch.
73
- const lost: any = { render: markPatched(() => "x") };
74
- let threw = false;
75
- try {
76
- originalOf(lost, "render");
77
- } catch {
78
- threw = true;
79
- }
80
- assert(threw, "a marked slot with no recorded original fails loudly");
81
-
82
- // patchOnce: the one-call form, still reload-safe.
83
- const twice: any = { render(): string { return "pi"; } };
84
- patchOnce(twice, "render", (orig) => function (this: any): string {
85
- return `${orig.call(this)}!`;
86
- });
87
- patchOnce(twice, "render", (orig) => function (this: any): string {
88
- return `${orig.call(this)}?`;
89
- });
90
- assert(twice.render() === "pi?", "patchOnce: the second load patches pi's method again, not the first patch");
91
-
92
- // Instance vs prototype isolation: recording an original on a child object must never
93
- // overwrite its prototype's recorded original.
94
- class Parent {
95
- render(): string { return "parent"; }
96
- }
97
- patchOnce(Parent.prototype, "render", (orig) => function (this: any): string {
98
- return `[${orig.call(this)}]`;
99
- });
100
- const child = new Parent() as any;
101
- child.render = () => "stale-instance";
102
- patchOnce(child, "render", (orig) => function (this: any): string {
103
- return `(${orig.call(this)})`;
104
- });
105
- patchOnce(Parent.prototype, "render", (orig) => function (this: any): string {
106
- return `<${orig.call(this)}>`;
107
- });
108
- assert(new Parent().render() === "<parent>", "prototype original stays untouched when a child instance is patched");
109
- assert(child.render() === "(stale-instance)", "instance keeps its own recorded original");
110
-
111
- console.log("OK");
112
- }
@@ -9,11 +9,9 @@
9
9
  * Reads are memoised per process; every write re-reads the file and replaces it atomically
10
10
  * (temp file + rename), so concurrent pi sessions that write different keys keep both.
11
11
  */
12
- import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
13
- import { tmpdir } from "node:os";
12
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
14
13
  import { dirname, join } from "node:path";
15
14
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
16
- import { assert, isMain } from "./check.ts";
17
15
 
18
16
  export const HEADER_PRESET_KEY = "headerPreset";
19
17
  export const FOOTER_PRESET_KEY = "footerPreset";
@@ -32,6 +30,8 @@ export const RENDER_CACHE_KEY = "renderCache";
32
30
  export const PAYLOAD_LIMIT_KEY = "payloadLimit";
33
31
  /** Expanded `edit` diff layout: `"Split"` (default) or `"Unified"`. */
34
32
  export const EDIT_DIFF_KEY = "editDiff";
33
+ /** Tool transcript layout: `"Grouped"` (ADE phase progress box) or `"Classic"` (per-tool boxes). */
34
+ export const TOOL_LAYOUT_KEY = "toolLayout";
35
35
 
36
36
  // Resolved per call, not at import: the self-check points getAgentDir() at a fixture dir.
37
37
  // Everything pi-arnative writes lives in one folder (agent dir/arnative); the config moved
@@ -104,7 +104,7 @@ export function loadNumber(key: string, range: { min: number; max: number }): nu
104
104
  /** Reading order of `config.json`: the presets in the order the settings menu shows them,
105
105
  * then `layoutVersion`, then anything else (a key from another module or a newer version).
106
106
  * Times a user edits the file by hand or reads it back. */
107
- const KEY_ORDER = ["headerPreset", "footerPreset", "footerCost", "chatboxPreset", "chatboxPrompt", "chatboxDialog", "budgetDay", "budgetMonth", "budgetEnforce", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "payloadLimit", "modelHeal", "renderCache", "editDiff"];
107
+ const KEY_ORDER = ["headerPreset", "footerPreset", "footerCost", "chatboxPreset", "chatboxPrompt", "chatboxDialog", "budgetDay", "budgetMonth", "budgetEnforce", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "payloadLimit", "modelHeal", "renderCache", "editDiff", "toolLayout"];
108
108
 
109
109
  /** The record in {@link KEY_ORDER}; unknown keys keep the order they were written in. */
110
110
  function ordered(record: Record<string, unknown>): Record<string, unknown> {
@@ -145,6 +145,15 @@ export function writeAtomicSync(
145
145
  }
146
146
  }
147
147
 
148
+ /** Pretty-print JSON with a trailing newline and write it atomically. */
149
+ export function writeJsonAtomicSync(
150
+ path: string,
151
+ value: unknown,
152
+ rename: (from: string, to: string) => void = renameSync,
153
+ ): void {
154
+ writeAtomicSync(path, `${JSON.stringify(value, null, 2)}\n`, rename);
155
+ }
156
+
148
157
  /** Store a choice. Best effort: an unwritable agent dir must not break the TUI. */
149
158
  export function saveChoice(key: string, value: string, rename: (from: string, to: string) => void = renameSync): void {
150
159
  readConfig();
@@ -157,7 +166,7 @@ export function saveChoice(key: string, value: string, rename: (from: string, to
157
166
  if (record[key] === value) return;
158
167
  memo = { ...record, [key]: value };
159
168
  try {
160
- writeAtomicSync(configPath(), `${JSON.stringify(ordered(memo), null, 2)}\n`, rename);
169
+ writeJsonAtomicSync(configPath(), ordered(memo), rename);
161
170
  } catch {
162
171
  process.emitWarning("Arnative settings were not saved; the choice applies only to this session.", { code: "ARNATIVE_PRESET_SAVE" });
163
172
  }
@@ -210,131 +219,6 @@ export function resetPresetCache(): void {
210
219
  memo = null;
211
220
  }
212
221
 
213
- // Self-check: `node lib/preset-store.ts`
214
- if (isMain(import.meta.url)) {
215
- // The real agent dir must not decide pass/fail, and the test must not touch it.
216
- const fixture = mkdtempSync(join(tmpdir(), "arnative-preset-"));
217
- process.env.PI_CODING_AGENT_DIR = fixture;
218
-
219
- assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === undefined, "absent key reads as undefined");
220
- saveChoice(HEADER_PRESET_KEY, "b");
221
- saveChoice(FOOTER_PRESET_KEY, "a");
222
- assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "a saved choice reads back");
223
- assert(loadChoice(FOOTER_PRESET_KEY, ["a", "b"] as const) === "a", "a second key is stored without clobbering the first");
224
-
225
- // Another pi session writes its own key after this one loaded; a save must keep it.
226
- writeFileSync(join(fixture, "arnative", "config.json"), JSON.stringify({ headerPreset: "b", footerPreset: "a", other: "x" }), "utf8");
227
- saveChoice(FOOTER_PRESET_KEY, "b");
228
- resetPresetCache();
229
- assert(loadChoice("other", ["x"] as const) === "x", "a key written by another process survives a save");
230
-
231
- // The point of the file: the choice outlives the process (drop the in-memory copy).
232
- resetPresetCache();
233
- assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "the choice survives a restart (read from disk)");
234
-
235
- // A value no longer in the allowed set (renamed preset) falls back instead of breaking.
236
- saveChoice(HEADER_PRESET_KEY, "gone");
237
- assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === undefined, "an unknown stored value is rejected");
238
-
239
- // A corrupt file must not throw on the header's render path.
240
- writeFileSync(join(fixture, "arnative", "config.json"), "{not json", "utf8");
241
- resetPresetCache();
242
- assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === undefined, "a corrupt config file reads as empty");
243
- assert(readFileSync(join(fixture, "arnative", "config.json"), "utf8") === "{not json", "a corrupt config is left untouched — no stamp over it");
244
-
245
- // The flat pre-folder config is moved into the arnative folder on first read.
246
- const mig = mkdtempSync(join(tmpdir(), "arnative-preset-mig-"));
247
- process.env.PI_CODING_AGENT_DIR = mig;
248
- writeFileSync(join(mig, "arnative-config.json"), JSON.stringify({ headerPreset: "b" }), "utf8");
249
- resetPresetCache();
250
- assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "a legacy flat config is migrated and read");
251
- assert(existsSync(join(mig, "arnative", "config.json")), "the migrated config lives in the arnative folder");
252
- rmSync(mig, { recursive: true, force: true });
253
-
254
- // Layout stamp: the folder copy wins over a stale flat file a downgrade recreated,
255
- // the stale file is removed, and stamping merges into the config instead of replacing it.
256
- const stamp = mkdtempSync(join(tmpdir(), "arnative-preset-stamp-"));
257
- process.env.PI_CODING_AGENT_DIR = stamp;
258
- mkdirSync(join(stamp, "arnative"), { recursive: true });
259
- writeFileSync(join(stamp, "arnative", "config.json"), JSON.stringify({ headerPreset: "b" }), "utf8");
260
- writeFileSync(join(stamp, "arnative-config.json"), JSON.stringify({ headerPreset: "a" }), "utf8"); // stale, from a downgrade
261
- resetPresetCache();
262
- assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "the folder copy wins over the stale flat file");
263
- assert(!existsSync(join(stamp, "arnative-config.json")), "the stale flat config is removed");
264
- assert(loadChoice("layoutVersion", ["1"] as const) === "1", "the layout stamp is written on first read");
265
- const stamped = JSON.parse(readFileSync(join(stamp, "arnative", "config.json"), "utf8")) as Record<string, unknown>;
266
- assert(stamped.headerPreset === "b" && stamped.layoutVersion === "1", "stamping merges, it does not replace");
267
- rmSync(stamp, { recursive: true, force: true });
268
-
269
- // The startup record names every choice, including the ones still at their default.
270
- const profile = mkdtempSync(join(tmpdir(), "arnative-preset-profile-"));
271
- process.env.PI_CODING_AGENT_DIR = profile;
272
- resetPresetCache();
273
- ensureChoices({ headerPreset: "Arnative (Full)", footerPreset: "Arnative (Full)" });
274
- assert(loadChoice(HEADER_PRESET_KEY, ["Arnative (Full)"] as const) === "Arnative (Full)", "a default choice is written, not skipped");
275
- assert(loadChoice(FOOTER_PRESET_KEY, ["Arnative (Full)"] as const) === "Arnative (Full)", "every key in the batch is written");
276
- const profiled = readFileSync(join(profile, "arnative", "config.json"), "utf8");
277
- ensureChoices({ headerPreset: "Arnative (Full)", footerPreset: "Arnative (Full)" });
278
- assert(readFileSync(join(profile, "arnative", "config.json"), "utf8") === profiled, "a second record writes nothing");
279
-
280
- // The file keeps one key order whatever order the writes arrived in.
281
- const keyOrder = () => Object.keys(JSON.parse(readFileSync(join(profile, "arnative", "config.json"), "utf8")) as Record<string, unknown>);
282
- assert(
283
- keyOrder().join(",") === "headerPreset,footerPreset,layoutVersion",
284
- "known keys follow KEY_ORDER, layoutVersion after the presets: " + keyOrder().join(","),
285
- );
286
- saveChoice("spinnerPreset", "Circle Wave");
287
- saveChoice("zzz-other", "x");
288
- assert(
289
- keyOrder().join(",") === "headerPreset,footerPreset,spinnerPreset,layoutVersion,zzz-other",
290
- "a newly written key slots into place, an unknown one goes last: " + keyOrder().join(","),
291
- );
292
-
293
- // Windows: a running pi session can hold the file open, so the atomic replace fails
294
- // while the setting still has to land. The seam stands in for that rename.
295
- const locked = () => {
296
- throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" });
297
- };
298
- saveChoice(HEADER_PRESET_KEY, "b", locked);
299
- resetPresetCache();
300
- assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "a refused rename still writes the choice in place");
301
- saveChoice(FOOTER_PRESET_KEY, "a", locked);
302
- resetPresetCache();
303
- assert(loadChoice(FOOTER_PRESET_KEY, ["a", "b"] as const) === "a" && loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "the in-place write keeps the other keys");
304
- assert(!existsSync(join(profile, "arnative")) || readdirSync(join(profile, "arnative")).every((f) => !f.endsWith(".tmp")), "no temp file is left behind");
305
-
306
- writeFileSync(join(profile, "arnative", "config.json"), "{not json", "utf8");
307
- resetPresetCache();
308
- ensureChoices({ headerPreset: "b" });
309
- assert(readFileSync(join(profile, "arnative", "config.json"), "utf8") === "{not json", "the startup record leaves an unreadable config alone");
310
- rmSync(profile, { recursive: true, force: true });
311
-
312
- // loadNumber: amounts are stored as strings ("" = unset); anything that is not a finite
313
- // number in range reads as unset, so a hand-edited or corrupt value cannot become a cap.
314
- const nums = mkdtempSync(join(tmpdir(), "arnative-preset-num-"));
315
- process.env.PI_CODING_AGENT_DIR = nums;
316
- resetPresetCache();
317
- const range = { min: 0.01, max: 1_000_000 };
318
- saveChoice(BUDGET_DAY_KEY, "5");
319
- assert(loadNumber(BUDGET_DAY_KEY, range) === 5, "a stored amount parses");
320
- saveChoice(BUDGET_DAY_KEY, "7.50");
321
- assert(loadNumber(BUDGET_DAY_KEY, range) === 7.5, "a decimal amount parses");
322
- saveChoice(BUDGET_DAY_KEY, "abc");
323
- assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "a non-numeric amount reads as unset");
324
- saveChoice(BUDGET_DAY_KEY, "0");
325
- assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "below the range reads as unset");
326
- saveChoice(BUDGET_DAY_KEY, "2000000");
327
- assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "above the range reads as unset");
328
- saveChoice(BUDGET_DAY_KEY, "");
329
- assert(loadNumber(BUDGET_DAY_KEY, range) === undefined, "an empty amount reads as unset");
330
- writeFileSync(join(nums, "arnative", "config.json"), JSON.stringify({ [BUDGET_DAY_KEY]: 7 }), "utf8");
331
- resetPresetCache();
332
- assert(loadNumber(BUDGET_DAY_KEY, range) === 7, "a hand-edited numeric value is accepted");
333
- rmSync(nums, { recursive: true, force: true });
334
-
335
- process.env.PI_CODING_AGENT_DIR = fixture;
336
- resetPresetCache();
337
-
338
- rmSync(fixture, { recursive: true, force: true });
339
- console.log("preset-store.ts self-check OK");
340
- }
222
+ export const __test = {
223
+ KEY_ORDER,
224
+ };