@bismawy/pi-arnative 0.11.1 → 0.13.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.
@@ -15,6 +15,7 @@
15
15
  * the `→` marker and `·` separators, selected text in soft.
16
16
  */
17
17
  import {
18
+ AssistantMessageComponent,
18
19
  CompactionSummaryMessageComponent,
19
20
  ExtensionSelectorComponent,
20
21
  getMarkdownTheme,
@@ -45,7 +46,7 @@ import { contrast, oklchToRgb, parseOklch, toHex } from "../lib/color.ts";
45
46
  import { expandKeyName } from "../lib/format.ts";
46
47
  import { patchOnce } from "../lib/patch.ts";
47
48
 
48
- type ActiveTheme = { fg(color: string, text: string): string; bg?(color: string, text: string): string } | null;
49
+ type ActiveTheme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; italic?(text: string): string } | null;
49
50
  const activeTheme = () => getActiveTheme<Exclude<ActiveTheme, null>>();
50
51
 
51
52
  // Hide pi's built-in "Reloading keybindings, extensions, skills..." box
@@ -208,6 +209,15 @@ export default function uiRenderTweaks(pi: ExtensionAPI) {
208
209
  pi.on("session_start", async (_event, ctx) => {
209
210
  const th = themeOf<Exclude<ActiveTheme, null>>(ctx);
210
211
  if (th) setActiveTheme(th);
212
+ clearThinkingTicker();
213
+ });
214
+
215
+ pi.on("agent_end", async () => {
216
+ clearThinkingTicker();
217
+ });
218
+
219
+ pi.on("session_shutdown", async () => {
220
+ clearThinkingTicker();
211
221
  });
212
222
 
213
223
  // 4. `pi-jev-eye-review` contract message: use our own border box.
@@ -271,6 +281,7 @@ if (InteractiveMode?.prototype) {
271
281
  if (InteractiveMode?.prototype) {
272
282
  const proto = InteractiveMode.prototype as unknown as {
273
283
  setExtensionWidget(key: string, content: unknown, options?: { placement?: string }): void;
284
+ renderWidgets?(): void;
274
285
  };
275
286
  patchOnce(proto, "setExtensionWidget", (origSetWidget) => function (
276
287
  this: typeof proto,
@@ -278,6 +289,8 @@ if (InteractiveMode?.prototype) {
278
289
  content: unknown,
279
290
  options?: { placement?: string },
280
291
  ) {
292
+ const ui = (this as unknown as { ui?: { requestRender(): void } }).ui;
293
+ if (ui) thinkingState.ui = ui;
281
294
  if (Array.isArray(content) && content.every((line) => typeof line === "string")) {
282
295
  const rows = content as string[];
283
296
  content = (_tui: unknown, th: Parameters<typeof statusRows>[0]) => ({
@@ -294,6 +307,13 @@ if (InteractiveMode?.prototype) {
294
307
  }
295
308
  return origSetWidget.call(this, key, content, options);
296
309
  });
310
+ if (typeof proto.renderWidgets === "function") {
311
+ patchOnce(proto, "renderWidgets", (origRenderWidgets) => function (this: typeof proto) {
312
+ const ui = (this as unknown as { ui?: { requestRender(): void } }).ui;
313
+ if (ui) thinkingState.ui = ui;
314
+ return origRenderWidgets.call(this);
315
+ });
316
+ }
297
317
  }
298
318
 
299
319
  export class JevReviewBoxComponent implements Component {
@@ -393,6 +413,224 @@ if (CompactionSummaryMessageComponent?.prototype) {
393
413
  });
394
414
  }
395
415
 
416
+ // 8. Hidden thinking label (`AssistantMessageComponent`): pi renders plain `Thinking...`
417
+ // in `thinkingText`. Arnative replaces pi's default `"Thinking..."` label with `\uec21`
418
+ // in `accent`, `Thinking...` in `dim`, and animates `.` -> `..` -> `...` while that
419
+ // thinking run is actively streaming. Finished or non-default labels stay static.
420
+ export const THINKING_ICON = "\uec21";
421
+ export const THINKING_DOTS = [".", "..", "..."] as const;
422
+ export const THINKING_DOT_MS = 400;
423
+
424
+ const THINKING_STATE_KEY = Symbol.for("pi-arnative.thinkingLabelState");
425
+ type ThinkingState = {
426
+ ui: { requestRender(): void } | null;
427
+ active: Set<object>;
428
+ starts: WeakMap<object, number[]>;
429
+ finished: WeakMap<object, Array<string | undefined>>;
430
+ timer: ReturnType<typeof setInterval> | null;
431
+ };
432
+ const thinkingState = ((globalThis as Record<symbol, unknown>)[THINKING_STATE_KEY] ??= {
433
+ ui: null,
434
+ active: new Set<object>(),
435
+ starts: new WeakMap<object, number[]>(),
436
+ finished: new WeakMap<object, Array<string | undefined>>(),
437
+ timer: null,
438
+ }) as ThinkingState;
439
+
440
+ function stopThinkingTicker(): void {
441
+ if (thinkingState.timer) {
442
+ clearInterval(thinkingState.timer);
443
+ thinkingState.timer = null;
444
+ }
445
+ }
446
+
447
+ export function clearThinkingTicker(): void {
448
+ thinkingState.active.clear();
449
+ thinkingState.starts = new WeakMap<object, number[]>();
450
+ thinkingState.finished = new WeakMap<object, Array<string | undefined>>();
451
+ stopThinkingTicker();
452
+ }
453
+
454
+ // Clear any leftover timer on module reload so old closures never keep ticking.
455
+ clearThinkingTicker();
456
+
457
+ function syncThinkingTicker(): void {
458
+ if (thinkingState.active.size === 0) {
459
+ stopThinkingTicker();
460
+ return;
461
+ }
462
+ if (thinkingState.timer) return;
463
+ thinkingState.timer = setInterval(() => {
464
+ if (thinkingState.active.size === 0) {
465
+ stopThinkingTicker();
466
+ return;
467
+ }
468
+ thinkingState.ui?.requestRender?.();
469
+ }, THINKING_DOT_MS);
470
+ thinkingState.timer.unref?.();
471
+ }
472
+
473
+ export function thinkingDotsAt(now: number, startMs: number): string {
474
+ const elapsed = Math.max(0, now - startMs);
475
+ const step = Math.floor(elapsed / THINKING_DOT_MS) % THINKING_DOTS.length;
476
+ return THINKING_DOTS[step]!;
477
+ }
478
+
479
+ // A finished run states what it did and how long it took, so the collapsed block stops
480
+ // claiming to be thinking once the answer has started. Seconds below a minute, then
481
+ // `Xm Ys`; a run always lasts at least one second, never `0s`.
482
+ export function formatThinkingElapsed(ms: number): string {
483
+ const total = Math.max(1, Math.round(ms / 1000));
484
+ if (total < 60) return `${total}s`;
485
+ const minutes = Math.floor(total / 60);
486
+ const seconds = total % 60;
487
+ return seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`;
488
+ }
489
+
490
+ export function formatThinkingLabel(
491
+ th: { fg(color: string, text: string): string; italic?(text: string): string } | null,
492
+ dots = "...",
493
+ finished?: string,
494
+ ): string {
495
+ const icon = th ? th.fg("dim", THINKING_ICON) : THINKING_ICON;
496
+ const label = finished ?? `Thinking${dots}`;
497
+ const styledLabel = th ? (th.italic ? th.italic(th.fg("dim", label)) : th.fg("dim", label)) : label;
498
+ return `${icon} ${styledLabel}`;
499
+ }
500
+
501
+ export function activeThinkingRunIndex(
502
+ message: { content?: Array<{ type?: string; text?: string; thinking?: string }> } | undefined,
503
+ isStreaming: boolean,
504
+ ): number | null {
505
+ if (!isStreaming || !Array.isArray(message?.content)) return null;
506
+ let runIdx = -1;
507
+ let lastVisibleKind: "thinking" | "other" | null = null;
508
+ for (let i = 0; i < message.content.length; i++) {
509
+ const block = message.content[i];
510
+ if (!block) continue;
511
+ if (block.type === "thinking") {
512
+ let hasText = false;
513
+ for (; i < message.content.length; i++) {
514
+ const b = message.content[i];
515
+ if (b?.type !== "thinking") break;
516
+ if (typeof b.thinking === "string" && b.thinking.trim()) hasText = true;
517
+ }
518
+ i--;
519
+ if (hasText) {
520
+ runIdx++;
521
+ lastVisibleKind = "thinking";
522
+ }
523
+ } else if ((block.type === "text" && typeof block.text === "string" && block.text.trim()) || block.type === "toolCall") {
524
+ lastVisibleKind = "other";
525
+ }
526
+ }
527
+ return lastVisibleKind === "thinking" && runIdx >= 0 ? runIdx : null;
528
+ }
529
+
530
+ export class ThinkingLabelComponent implements Component {
531
+ private inner: Text;
532
+ private isActive: boolean;
533
+ private startMs: number | undefined;
534
+ private finished: string | undefined;
535
+ private getTheme: () => ActiveTheme;
536
+
537
+ constructor(
538
+ padX: number,
539
+ isActive: boolean,
540
+ startMs: number | undefined,
541
+ getTheme: () => ActiveTheme,
542
+ finished?: string,
543
+ ) {
544
+ this.isActive = isActive;
545
+ this.startMs = startMs;
546
+ this.finished = finished;
547
+ this.getTheme = getTheme;
548
+ this.inner = new Text(this.labelText(), padX, 0);
549
+ }
550
+
551
+ private labelText(): string {
552
+ const dots = this.isActive ? thinkingDotsAt(Date.now(), this.startMs ?? Date.now()) : "...";
553
+ return formatThinkingLabel(this.getTheme(), dots, this.isActive ? undefined : this.finished);
554
+ }
555
+
556
+ invalidate(): void {
557
+ this.inner.invalidate();
558
+ }
559
+
560
+ render(width: number): string[] {
561
+ this.inner.setText(this.labelText());
562
+ return this.inner.render(width);
563
+ }
564
+ }
565
+
566
+ function isPlainTextComponent(c: unknown): boolean {
567
+ if (!c || typeof c !== "object") return false;
568
+ const ctorName = (c as { constructor?: { name?: string } }).constructor?.name;
569
+ if (ctorName === "Text") return true;
570
+ return "text" in c && typeof (c as { text?: unknown }).text === "string" && !("theme" in c);
571
+ }
572
+
573
+ export function patchThinkingInAssistantMessage(comp: {
574
+ contentContainer?: { children?: unknown[] };
575
+ lastMessage?: { content?: Array<{ type?: string; text?: string; thinking?: string }> };
576
+ isStreaming?: boolean;
577
+ hiddenThinkingLabel?: string;
578
+ outputPad?: number;
579
+ }): boolean {
580
+ const th = activeTheme();
581
+ if (!th || (comp.hiddenThinkingLabel ?? "Thinking...") !== "Thinking...") {
582
+ thinkingState.active.delete(comp);
583
+ syncThinkingTicker();
584
+ return false;
585
+ }
586
+ const activeRunIdx = activeThinkingRunIndex(comp.lastMessage, Boolean(comp.isStreaming));
587
+ const children = comp.contentContainer?.children ?? [];
588
+ const starts = thinkingState.starts.get(comp) ?? [];
589
+ const finished = thinkingState.finished.get(comp) ?? [];
590
+ let runIdx = 0;
591
+ let anyActive = false;
592
+ let anyReplaced = false;
593
+ for (const child of children) {
594
+ if (!child || typeof child !== "object" || !("child" in child) || !("onMouse" in child)) continue;
595
+ const region = child as { child: unknown };
596
+ if (isPlainTextComponent(region.child)) {
597
+ const isActive = activeRunIdx === runIdx;
598
+ if (isActive) {
599
+ anyActive = true;
600
+ starts[runIdx] ??= Date.now();
601
+ } else if (starts[runIdx] !== undefined && finished[runIdx] === undefined) {
602
+ // The run just ended: keep how long it took, so the settled label reads
603
+ // `Thought for 3s` instead of claiming to still think.
604
+ finished[runIdx] = `Thought for ${formatThinkingElapsed(Date.now() - starts[runIdx]!)}`;
605
+ }
606
+ region.child = new ThinkingLabelComponent(
607
+ comp.outputPad ?? 1,
608
+ isActive,
609
+ starts[runIdx],
610
+ activeTheme,
611
+ finished[runIdx],
612
+ );
613
+ anyReplaced = true;
614
+ }
615
+ runIdx++;
616
+ }
617
+ thinkingState.starts.set(comp, starts);
618
+ thinkingState.finished.set(comp, finished);
619
+ if (anyActive) thinkingState.active.add(comp);
620
+ else thinkingState.active.delete(comp);
621
+ syncThinkingTicker();
622
+ return anyReplaced;
623
+ }
624
+
625
+ if (AssistantMessageComponent?.prototype?.updateContent) {
626
+ const proto = AssistantMessageComponent.prototype as any;
627
+ patchOnce(proto, "updateContent", (origUpdateContent) => function (this: any, message: unknown, isStreaming?: boolean) {
628
+ const res = origUpdateContent.call(this, message, isStreaming);
629
+ patchThinkingInAssistantMessage(this);
630
+ return res;
631
+ });
632
+ }
633
+
396
634
  // Self-check: `node extensions/ui-render-tweaks.ts`
397
635
  if (isMain(import.meta.url)) {
398
636
  // reload box fully hidden (not line by line)
@@ -713,5 +951,39 @@ if (isMain(import.meta.url)) {
713
951
  expLines[0].startsWith("╭") && expLines[expLines.length - 1].startsWith("╰") && expLines.some((l: string) => l.includes("Language follows the user")),
714
952
  "contract message expanded: border box with the full content",
715
953
  );
954
+
955
+ // Thinking label: accent \uec21 + dim Thinking... + animated . -> .. -> ... while active streaming
956
+ assert(thinkingDotsAt(0, 0) === "." && thinkingDotsAt(400, 0) === ".." && thinkingDotsAt(800, 0) === "..." && thinkingDotsAt(1200, 0) === ".", "thinking dots loop . -> .. -> ...");
957
+ const tLabel = formatThinkingLabel(
958
+ { fg: (c, t) => `[${c}]${t}[/${c}]`, italic: (t) => `<i>${t}</i>` },
959
+ "..",
960
+ );
961
+ assert(tLabel === "[dim]\uec21[/dim] <i>[dim]Thinking..[/dim]</i>", "thinking label paints icon dim and label dim italic");
962
+ const doneLabel = formatThinkingLabel(
963
+ { fg: (c, t) => `[${c}]${t}[/${c}]`, italic: (t) => `<i>${t}</i>` },
964
+ "...",
965
+ "Thought for 3s",
966
+ );
967
+ assert(doneLabel === "[dim]\uec21[/dim] <i>[dim]Thought for 3s[/dim]</i>", "a finished run states Thought for Ns, same dim italic paint");
968
+ assert(formatThinkingElapsed(0) === "1s" && formatThinkingElapsed(2999) === "3s", "a short run counts in whole seconds, never 0s");
969
+ assert(formatThinkingElapsed(60_000) === "1m" && formatThinkingElapsed(83_000) === "1m 23s", "a long run adds minutes");
970
+
971
+ const fakeThinkingMsg = { role: "assistant", content: [{ type: "thinking", thinking: "pondering" }], stopReason: "stop", usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, api: "openai-completions", provider: "test", model: "test", timestamp: 0 };
972
+ const activeComp = new AssistantMessageComponent(undefined, true, getMarkdownTheme(), "Thinking...", 1);
973
+ activeComp.updateContent(fakeThinkingMsg as any, true);
974
+ const stripOsc = (s: string) => stripAnsi(s.replace(/\x1b\][^\x07]*\x07/g, "")).trim();
975
+ const activeLines = activeComp.render(60).map(stripOsc);
976
+ assert(activeLines.some((l) => l.startsWith("\uec21 Thinking.")), "streaming hidden thinking renders \\uec21 Thinking.(. / .. / ...)");
977
+ assert(activeThinkingRunIndex(fakeThinkingMsg, true) === 0, "active thinking run is detected while streaming");
978
+ assert(activeThinkingRunIndex({ content: [{ type: "thinking", thinking: "x" }, { type: "text", text: "done" }] }, true) === null, "thinking stops animating once answer text begins");
979
+
980
+ activeComp.updateContent(fakeThinkingMsg as any, false);
981
+ const doneLines = activeComp.render(60).map(stripOsc);
982
+ assert(
983
+ doneLines.some((l) => l.startsWith("\uec21 Thought for ")),
984
+ "a finished hidden thinking run settles on \uec21 Thought for Ns, not Thinking...",
985
+ );
986
+ clearThinkingTicker();
987
+
716
988
  console.log("ui-render-tweaks.ts self-check OK");
717
989
  }
@@ -521,10 +521,13 @@ export class UsageModalComponent implements Component {
521
521
  const isSelected = actualIdx === this.selectedIndex;
522
522
 
523
523
  // Provider and project group rows sit on the plain text color, and the rows beneath
524
- // them are dim. The cursor paints any row the soft accent, and the expand arrow alone
525
- // carries the accent so the eye can find the tree.
524
+ // them are dim — including the providers nested under a project. The cursor paints
525
+ // any row the soft accent, and the expand arrow alone carries the accent so the eye
526
+ // can find the tree.
526
527
  const plain = (s: string) => th.fg("text", s);
527
- const resting = item.type === "model" || item.type === "price" ? dim : plain;
528
+ const nested =
529
+ item.type === "model" || item.type === "price" || (this.view === "project" && item.type === "provider");
530
+ const resting = nested ? dim : plain;
528
531
  const paintName = isSelected ? accSoft : resting;
529
532
  const paintVal = isSelected ? accSoft : resting;
530
533
  const isPrice = item.type === "price";
@@ -1071,19 +1074,20 @@ if (isMain(import.meta.url)) {
1071
1074
  new UsageModalComponent(strictTheme, () => {}, () => {}, "off").render(120).length > 0,
1072
1075
  "a theme without the soft tokens still renders the rows",
1073
1076
  );
1074
- // Project view: the project group row sits on plain text like a provider group row, and the
1075
- // expand arrow carries the accent.
1077
+ // Project view: the project group row sits on plain text like a provider group row, its
1078
+ // folder content (the providers under it) on dim, and the expand arrow carries the accent.
1076
1079
  const taggedProject = new UsageModalComponent(taggedTheme, () => {}, () => {}, "off");
1077
1080
  taggedProject.handleInput("v");
1078
1081
  const projectLines = taggedProject.render(260);
1079
1082
  assert(projectLines.some((l) => /<accent>[▸▾]/.test(l)), "the expand arrow carries the accent");
1080
1083
  assert(
1081
- projectLines.some((l) => /│<\/>\s{3,5}<text>/.test(l)),
1082
- "a provider row under a project sits on plain text, indented like a model row",
1084
+ projectLines.some((l) => /│<\/>\s{3,5}<dim>/.test(l)),
1085
+ "a provider row under a project sits on dim text, indented like a model row",
1083
1086
  );
1084
1087
  taggedProject.handleInput("j");
1085
1088
  const selectedLines = taggedProject.render(260);
1086
1089
  assert(selectedLines.some((l) => l.includes("<text>unknown")), "the project label sits on plain text");
1090
+ assert(!projectLines.some((l) => /│<\/>\s{3,5}<text>/.test(l)), "no provider under a project keeps the plain text color");
1087
1091
  assert(selectedLines.some((l) => /<accentSoft>\w/.test(l)), "the selected provider row takes the soft accent");
1088
1092
  // Shared chrome (per `renderScreen`): title accent+bold, description muted, legend dim.
1089
1093
  // `taggedTheme.bold` is identity, so only the accent wrapper shows here; the bold half is
@@ -74,6 +74,8 @@ interface ListPickerHooks {
74
74
  /** Description re-read on every render, so the line under the title can follow screen
75
75
  * state (the model list shows the API flavor `a` switched to). */
76
76
  description?: () => string;
77
+ /** Optional status block rendered above the row list (separated by a blank line). */
78
+ summary?: (width: number) => string[];
77
79
  // What the rows are ("models"): shows a filter line under the description, the way
78
80
  // vision-watcher filters its model list. Slash focuses it, Enter keeps it, Esc clears it.
79
81
  search?: string;
@@ -205,8 +207,11 @@ export class ListPicker implements Component {
205
207
 
206
208
  private move(delta: number): void {
207
209
  const shown = this.shown;
208
- const next = Math.min(shown.length - 1, Math.max(0, this.selected + delta));
209
- if (next === this.selected || next < 0) return;
210
+ if (shown.length === 0) return;
211
+ // Wrap at both ends, matching the /jev-eye picker: the top row steps up to the
212
+ // last row and the last row steps down to the top, so a held key never sticks.
213
+ const next = (this.selected + delta + shown.length) % shown.length;
214
+ if (next === this.selected) return;
210
215
  this.selected = next;
211
216
  if (!this.livePreview) {
212
217
  this.hooks.requestRender();
@@ -295,6 +300,8 @@ export class ListPicker implements Component {
295
300
  const line = this.typing ? this.field.render(Math.max(1, width - 4)) : [truncateToWidth(idle, width - 4, "")];
296
301
  body.unshift(...line, "");
297
302
  }
303
+ const summary = this.hooks.summary?.(Math.max(1, width - 4));
304
+ if (summary && summary.length > 0) body.unshift(...summary.map((line) => truncateToWidth(line, width - 4, "")), "");
298
305
  return renderScreen(
299
306
  th,
300
307
  width,
@@ -444,9 +451,14 @@ if (isMain(import.meta.url)) {
444
451
  scrolled.handleInput("\x1b[B");
445
452
  const frameNext = scrolled.render(50);
446
453
  assert(frameNext.length === frame.length && countItems(frameNext) === 10, "the frame height stays constant while scrolling inside the list");
447
- for (let i = 0; i < 20; i++) scrolled.handleInput("\x1b[B");
454
+ for (let i = 0; i < 9; i++) scrolled.handleInput("\x1b[B");
448
455
  frame = scrolled.render(50);
449
456
  assert(frame.some((l) => l.includes("→ m24")) && frame.some((l) => l.includes("↑ 15 more")) && !frame.some((l) => l.includes("↓")), "the bottom of the list announces only what is above");
457
+ // Wrap at both edges, matching the /jev-eye picker: a held key never sticks.
458
+ scrolled.handleInput("\x1b[B");
459
+ assert(scrolled.render(50).some((l) => l.includes("→ m0")), "↓ at the last row wraps to the top");
460
+ scrolled.handleInput("\x1b[A");
461
+ assert(scrolled.render(50).some((l) => l.includes("→ m24")), "↑ at the top row wraps to the last row");
450
462
  const short = new ListPicker(fakeTheme, nameRows(["a", "b"]), "a", { preview: quiet, revert: quiet, done: quiet, requestRender: quiet }, { title: screenTitle("Test"), description: "d", legend: "l" }, false, undefined, 10);
451
463
  assert(!short.render(50).some((l) => l.includes("more")), "a short list shows no scroll indicators");
452
464
 
@@ -497,5 +509,9 @@ if (isMain(import.meta.url)) {
497
509
  filtered.handleInput("\x1b");
498
510
  assert(hits.join().endsWith("done"), "a second Esc, outside typing, leaves the screen");
499
511
 
512
+ const summarized = new ListPicker(fakeTheme, nameRows(["a", "b"]), "a", { preview: quiet, revert: quiet, done: quiet, requestRender: quiet, summary: () => ["Box · a"] }, { title: "T", description: "d", legend: "l" }, false);
513
+ const sumLines = summarized.render(40).map(plain);
514
+ assert(sumLines.some((l) => l.includes("Box · a")) && sumLines.indexOf(sumLines.find((l) => l.includes("Box · a"))!) < sumLines.indexOf(sumLines.find((l) => l.includes("→ a"))!), "summary renders above the picker rows");
515
+
500
516
  console.log("list-picker.ts self-check OK");
501
517
  }
package/lib/model-heal.ts CHANGED
@@ -88,11 +88,9 @@ const errText = (error: unknown): string => (error instanceof Error ? error.mess
88
88
  export const DEFAULT_THINKING_MAP = { low: "low", medium: "medium", high: "high", xhigh: "xhigh" };
89
89
 
90
90
  const HOUR_MS = 60 * 60 * 1000;
91
- const META_TTL_MS = 6 * HOUR_MS;
92
91
  const META_FAILURE_TTL_MS = HOUR_MS;
93
92
  const META_TIMEOUT_MS = 8000;
94
93
  const META_MAX_BYTES = 2 * 1024 * 1024;
95
- const EFFORT_TTL_MS = 24 * HOUR_MS;
96
94
  const EFFORT_FAILURE_TTL_MS = HOUR_MS;
97
95
  const EFFORT_BUDGET_MS = 2 * 60 * 1000;
98
96
 
@@ -243,7 +241,9 @@ export function healFlags(deps: HealDeps, only?: RtModel[], active?: RtModel): H
243
241
  const atProvider = assignCompat(entry, shared);
244
242
  if (atProvider.length) detail.push(`${m.provider}: compat += ${atProvider.join(", ")}`);
245
243
  if (Object.keys(own).length) {
246
- const { slot, label } = modelSlot(entry, m.id, owned);
244
+ // Keep per-model compat in modelOverrides so external catalog syncs (e.g. Magpie)
245
+ // rewriting models[] cannot strip healed flags and re-trigger heals.
246
+ const { slot, label } = modelSlot(entry, m.id, true);
247
247
  const atModel = assignCompat(slot, own);
248
248
  if (atModel.length) detail.push(`${m.provider} ${label}: compat += ${atModel.join(", ")}`);
249
249
  }
@@ -374,8 +374,23 @@ function readForPass(): Obj | undefined {
374
374
 
375
375
  let metaInFlight = false;
376
376
 
377
+ /** True when a channel's cached catalog still covers all current model ids at the same
378
+ * endpoint (or a failed fetch is still inside its 1h cooldown). */
379
+ function metaFresh(prev: HealState["providers"][string] | undefined, channel: Channel, signature: string, now: number): boolean {
380
+ if (!prev) return false;
381
+ if (prev.failed) return prev.signature === signature && now - prev.fetchedAt < META_FAILURE_TTL_MS;
382
+ try {
383
+ const parsed = JSON.parse(prev.signature) as { baseUrl?: string; ids?: string[] };
384
+ if (parsed.baseUrl !== channel.baseUrl || !Array.isArray(parsed.ids)) return false;
385
+ const known = new Set(parsed.ids);
386
+ return channel.ids.every((id) => known.has(id));
387
+ } catch {
388
+ return false;
389
+ }
390
+ }
391
+
377
392
  /** contextWindow / maxTokens from each channel's catalog. A non-forced run skips a channel
378
- * fetched within the TTL whose baseUrl and model ids are unchanged. */
393
+ * whose endpoint and current model ids are already cached locally, retrying failures after 1h. */
379
394
  export async function healMeta(deps: HealDeps, force: boolean): Promise<HealResult> {
380
395
  if (metaInFlight) return none();
381
396
  metaInFlight = true;
@@ -390,7 +405,7 @@ export async function healMeta(deps: HealDeps, force: boolean): Promise<HealResu
390
405
  deps.signal?.throwIfAborted();
391
406
  const signature = JSON.stringify({ baseUrl: channel.baseUrl, ids: channel.ids });
392
407
  const prev = state.providers[channel.provider];
393
- if (!force && prev?.signature === signature && now - prev.fetchedAt < (prev.failed ? META_FAILURE_TTL_MS : META_TTL_MS)) continue;
408
+ if (!force && metaFresh(prev, channel, signature, now)) continue;
394
409
  try {
395
410
  const meta = await fetchMeta(channel, deps.fetchImpl ?? fetch);
396
411
  deps.signal?.throwIfAborted();
@@ -463,11 +478,20 @@ export async function healMeta(deps: HealDeps, force: boolean): Promise<HealResu
463
478
 
464
479
  let effortInFlight = false;
465
480
 
481
+ const EFFORT_KEYS = THINKING_LEVELS.filter((l) => l !== "off");
466
482
  const sameMap = (a: Record<string, string | null> | undefined, b: Record<string, string | null> | undefined): boolean =>
467
- THINKING_LEVELS.every((l) => a?.[l] === b?.[l]);
483
+ EFFORT_KEYS.every((l) => a?.[l] === b?.[l]);
468
484
 
469
485
  const mapOf = (m: RtModel): Record<string, string | null> | undefined => (isObj(m.thinkingLevelMap) ? (m.thinkingLevelMap as Record<string, string | null>) : undefined);
470
486
 
487
+ function findEffort(efforts: HealState["efforts"], provider: string, id: string): HealState["efforts"][string] | undefined {
488
+ const exact = efforts[modelKey(provider, id)];
489
+ if (exact) return exact;
490
+ const wanted = `${lower(provider)}\0${lower(id)}`;
491
+ for (const [k, v] of Object.entries(efforts)) if (k.toLowerCase() === wanted) return v;
492
+ return undefined;
493
+ }
494
+
471
495
  /** Probe the reasoning efforts each relay accepts and remap rejected levels. A map the user
472
496
  * shaped (a remap or a null) is theirs and never probed, not even when forced. */
473
497
  export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[]): Promise<HealResult> {
@@ -488,13 +512,14 @@ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[
488
512
  const pending = (only ?? deps.models()).filter((m) => {
489
513
  const channel = m?.provider ? channels.get(lower(m.provider)) : undefined;
490
514
  if (!channel || !isEffortProbeable(m, channel.compat)) return false;
491
- const prev = state.efforts[modelKey(m.provider, m.id)];
515
+ const prev = findEffort(state.efforts, m.provider, m.id);
492
516
  // A shaped map (a null or a remap) is the user's unless the probe wrote it. A map an
493
- // older probe wrote (nearest-effort remaps) is redone now, not after the TTL.
517
+ // older probe wrote with nearest-effort remaps is redone once, not on a timer.
494
518
  const probeWrote = prev !== undefined && sameMap(mapOf(m), prev.map);
495
519
  if (carriesRemap(mapOf(m)) && !probeWrote) return false;
496
- if (force || !prev || (probeWrote && !prev.failed && prev.exact !== true)) return true;
497
- if (now - prev.at >= (prev.failed ? EFFORT_FAILURE_TTL_MS : EFFORT_TTL_MS)) return true;
520
+ if (force || !prev) return true;
521
+ if (probeWrote && !prev.failed && prev.exact !== true && carriesRemap(prev.map)) return true;
522
+ if (prev.failed) return now - prev.at >= EFFORT_FAILURE_TTL_MS;
498
523
  return !sameMap(mapOf(m), prev.map);
499
524
  });
500
525
  if (pending.length === 0) return none();
@@ -607,9 +632,10 @@ if (isMain(import.meta.url)) {
607
632
  const relayCompat = read().relay!.compat as Obj;
608
633
  assert(relayCompat.supportsLongCacheRetention === false && relayCompat.sendSessionAffinityHeaders === true, "a channel-wide flag lands at provider level");
609
634
  assert(relayCompat.cacheControlFormat === undefined, "a flag only one sibling needs stays off the provider");
610
- assert((modelIn("relay", "claude-sonnet-4-5").compat as Obj).cacheControlFormat === "anthropic", "and lands on that model");
635
+ const overrideCompat = (id: string): Obj => ((read().relay!.modelOverrides as Record<string, Obj>)[id]!.compat as Obj);
636
+ assert(overrideCompat("claude-sonnet-4-5").cacheControlFormat === "anthropic", "and lands on that model override");
611
637
  const r1 = modelIn("relay", "r1");
612
- assert(isObj(r1.thinkingLevelMap) && (r1.compat as Obj).supportsDeveloperRole === false, "a reasoning model gets a map and the developer-role opt-out");
638
+ assert(isObj(r1.thinkingLevelMap) && overrideCompat("r1").supportsDeveloperRole === false, "a reasoning model gets a map and the developer-role opt-out");
613
639
  assert(read().owned!.compat === undefined && isObj((read().owned!.modelOverrides as Obj).o1), "an extension-owned provider is fixed through modelOverrides");
614
640
  assert(existsSync(`${file}.bak-model-heal`), "the first write keeps a backup");
615
641
  const pinned = modelIn("relay", "pinned").thinkingLevelMap as Obj;
package/lib/patch.ts CHANGED
@@ -29,7 +29,13 @@ export function markPatched<T extends AnyFn>(fn: T): T {
29
29
 
30
30
  /** pi's own method for `key`, recorded once per prototype and returned on every load. */
31
31
  export function originalOf<T extends AnyFn>(proto: Record<symbol | string, any>, key: string): T {
32
- const originals = (proto[ORIGINALS_KEY] ??= {} as Record<string, Marked>);
32
+ // Own property only: an instance without its own map must never read or mutate its
33
+ // prototype's recorded originals across reloads.
34
+ let originals = Object.hasOwn(proto, ORIGINALS_KEY) ? (proto[ORIGINALS_KEY] as Record<string, Marked>) : undefined;
35
+ if (!originals) {
36
+ originals = {};
37
+ Object.defineProperty(proto, ORIGINALS_KEY, { value: originals, configurable: true });
38
+ }
33
39
  const current: Marked | undefined = proto[key];
34
40
  if (current && !current[PATCHED_KEY]) originals[key] = current;
35
41
  const original = originals[key];
@@ -83,5 +89,24 @@ if (isMain(import.meta.url)) {
83
89
  });
84
90
  assert(twice.render() === "pi?", "patchOnce: the second load patches pi's method again, not the first patch");
85
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
+
86
111
  console.log("OK");
87
112
  }
@@ -19,10 +19,15 @@ export const HEADER_PRESET_KEY = "headerPreset";
19
19
  export const FOOTER_PRESET_KEY = "footerPreset";
20
20
  /** Footer cost cell: `"on"`/`"off"`, absent reads as off. */
21
21
  export const FOOTER_COST_KEY = "footerCost";
22
+ export const CHATBOX_PRESET_KEY = "chatboxPreset";
23
+ export const CHATBOX_PROMPT_KEY = "chatboxPrompt";
24
+ export const CHATBOX_DIALOG_KEY = "chatboxDialog";
22
25
  /** Budget guardrail — day/month caps are amount strings (`"5"`, `""` = unset), enforce is `"on"`/`"off"`. */
23
26
  export const BUDGET_DAY_KEY = "budgetDay";
24
27
  export const BUDGET_MONTH_KEY = "budgetMonth";
25
28
  export const BUDGET_ENFORCE_KEY = "budgetEnforce";
29
+ /** Transcript render cache: `"On"` / `"Off"`, absent reads as `"On"`. */
30
+ export const RENDER_CACHE_KEY = "renderCache";
26
31
 
27
32
  // Resolved per call, not at import: the self-check points getAgentDir() at a fixture dir.
28
33
  // Everything pi-arnative writes lives in one folder (agent dir/arnative); the config moved
@@ -90,7 +95,7 @@ export function loadNumber(key: string, range: { min: number; max: number }): nu
90
95
  /** Reading order of `config.json`: the presets in the order the settings menu shows them,
91
96
  * then `layoutVersion`, then anything else (a key from another module or a newer version).
92
97
  * Times a user edits the file by hand or reads it back. */
93
- const KEY_ORDER = ["headerPreset", "footerPreset", "footerCost", "budgetDay", "budgetMonth", "budgetEnforce", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "modelHeal"];
98
+ const KEY_ORDER = ["headerPreset", "footerPreset", "footerCost", "chatboxPreset", "chatboxPrompt", "chatboxDialog", "budgetDay", "budgetMonth", "budgetEnforce", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "modelHeal", "renderCache"];
94
99
 
95
100
  /** The record in {@link KEY_ORDER}; unknown keys keep the order they were written in. */
96
101
  function ordered(record: Record<string, unknown>): Record<string, unknown> {
@@ -55,24 +55,13 @@ 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
58
  /**
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.
59
+ * State what the last change did, as a transcript notify (like pi-jev-eye) instead of the
60
+ * widget slot above the editor: the widget covered the prompt, while a scrollback line
61
+ * stays visible without blocking anything. A UI without notify (RPC/headless) is left alone.
68
62
  */
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?.();
63
+ export function announce(ui: { notify?(message: string, type?: string): void } | undefined, message: string): void {
64
+ ui?.notify?.("[arnative] " + message, "info");
76
65
  }
77
66
 
78
67
  if (isMain(import.meta.url)) {