@bismawy/pi-arnative 0.12.0 → 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.
@@ -30,6 +30,7 @@ import {
30
30
  saveChoice,
31
31
  } from "../lib/preset-store.ts";
32
32
  import { formatCost } from "./usage.ts";
33
+ import { isByteLimitedModel, wireBytesSnapshot } from "./autocompact.ts";
33
34
  import { budgetLevelNow } from "./budget.ts";
34
35
  import { EDITOR_KEY, activeSpinnerGradient, activeSpinnerPreset } from "./animations.ts";
35
36
  import { spinnerPainter } from "../lib/spinner.ts";
@@ -854,36 +855,29 @@ export function overlayOutsideDialogOnWidgetLines(lines: readonly string[], widt
854
855
 
855
856
  const OUTSIDE_HOOK_KEY = Symbol.for("pi-arnative.outsideDialogHook");
856
857
  const ABOVE_WRAPPED_KEY = Symbol.for("pi-arnative.aboveWidgetWrapped");
858
+ const ABOVE_MODE_KEY = Symbol.for("pi-arnative.aboveWidgetMode");
857
859
 
858
860
  function installAboveEditorHook(widgetContainer: { render?: (w: number) => string[] } | undefined, mode: unknown): void {
859
861
  if (!widgetContainer || typeof widgetContainer.render !== "function") return;
860
- if ((widgetContainer as unknown as Record<symbol, boolean>)[ABOVE_WRAPPED_KEY]) return;
861
- (widgetContainer as unknown as Record<symbol, boolean>)[ABOVE_WRAPPED_KEY] = true;
862
- const origRender = widgetContainer.render;
863
- widgetContainer.render = function (this: unknown, width: number): string[] {
864
- if (activeChatboxPreset() === "Arnative") {
865
- trimLeadingSpacerAboveWidget(this as { children?: Array<{ constructor?: { name?: string }; render?(w: number): string[] }> });
866
- }
867
- const lines = origRender.call(this, width);
862
+ const box = widgetContainer as Record<symbol, unknown> & { render: (w: number) => string[] };
863
+ box[ABOVE_MODE_KEY] = mode;
864
+ if (box[ABOVE_WRAPPED_KEY]) return;
865
+ box[ABOVE_WRAPPED_KEY] = true;
866
+ const ownOrig = Object.hasOwn(box, "render") ? box.render : null;
867
+ box.render = function (this: Record<symbol, unknown>, width: number): string[] {
868
+ // Delegate to the live prototype render when not overridden on the instance so `/reload`
869
+ // changes to Container.prototype.render still apply without touching prototype originals.
870
+ const baseRender = ownOrig ?? (Object.getPrototypeOf(this) as { render: (w: number) => string[] }).render;
871
+ const lines = baseRender.call(this, width);
868
872
  try {
869
873
  const hook = (globalThis as Record<symbol, ((l: string[], w: number, m: unknown) => string[]) | undefined>)[OUTSIDE_HOOK_KEY];
870
- return hook ? hook(lines, width, mode) : lines;
874
+ return hook ? hook(lines, width, this[ABOVE_MODE_KEY]) : lines;
871
875
  } catch {
872
876
  return lines;
873
877
  }
874
878
  };
875
879
  }
876
880
 
877
- export function trimLeadingSpacerAboveWidget(
878
- widgetContainer: { children?: Array<{ constructor?: { name?: string }; render?(w: number): string[] }> } | undefined,
879
- ): boolean {
880
- const children = widgetContainer?.children;
881
- if (!Array.isArray(children) || children.length === 0) return false;
882
- if (children[0]?.constructor?.name !== "Spacer") return false;
883
- children.shift();
884
- return true;
885
- }
886
-
887
881
  if (InteractiveMode?.prototype) {
888
882
  const modeProto = InteractiveMode.prototype as unknown as {
889
883
  renderWidgetContainer?: (container: unknown, widgets: unknown, spacerWhenEmpty: boolean, leadingSpacer: boolean) => void;
@@ -901,17 +895,11 @@ if (InteractiveMode?.prototype) {
901
895
  installAboveEditorHook(container as { render?: (w: number) => string[] }, this);
902
896
  }
903
897
  orig.call(this, container, widgets, spacerWhenEmpty, leadingSpacer);
904
- if (container && container === this.widgetContainerAbove && activeChatboxPreset() === "Arnative") {
905
- trimLeadingSpacerAboveWidget(container as { children?: Array<{ constructor?: { name?: string }; render?(w: number): string[] }> });
906
- }
907
898
  });
908
899
  }
909
900
  if (typeof modeProto.showStatusIndicator === "function") {
910
901
  patchOnce(modeProto, "showStatusIndicator", (orig) => function (this: any, indicator: unknown): void {
911
902
  installAboveEditorHook(this.widgetContainerAbove, this);
912
- if (activeChatboxPreset() === "Arnative") {
913
- trimLeadingSpacerAboveWidget(this.widgetContainerAbove);
914
- }
915
903
  orig.call(this, indicator);
916
904
  });
917
905
  }
@@ -1128,7 +1116,8 @@ export const RATE_MIN_WIDTH = 80;
1128
1116
  * is hidden below RATE_MIN_ACTIVE_MS of active time and below RATE_MIN_WIDTH columns.
1129
1117
  * `bandPaint` paints the whole cell (icon and text) when a budget cap is near or over —
1130
1118
  * amber at `warn`, red at `over` (see `budgetLevelNow`); without it the icon keeps `acc` and
1131
- * the text `soft`. */
1119
+ * the text `soft`. The rate suffix is secondary information, so it renders `dim` (or the band
1120
+ * paint when a cap is active, keeping the alert one colour). */
1132
1121
  export function costCell(
1133
1122
  costBilled: number,
1134
1123
  costEstimated: number,
@@ -1136,24 +1125,31 @@ export function costCell(
1136
1125
  soft: (t: string) => string,
1137
1126
  width: number = RATE_MIN_WIDTH,
1138
1127
  bandPaint?: (t: string) => string,
1128
+ dim?: (t: string) => string,
1139
1129
  ): string {
1140
1130
  if (!(costBilled > 0) && !(costEstimated > 0)) return "";
1141
1131
  const parts: string[] = [];
1142
1132
  if (costBilled > 0) parts.push(formatCost(costBilled));
1143
1133
  if (costEstimated > 0) parts.push(`~${formatCost(costEstimated)}`);
1144
- let text = parts.join(" + ");
1134
+ const text = parts.join(" + ");
1135
+ let rate = "";
1145
1136
  const activeMs = clock.total();
1146
1137
  if (activeMs >= RATE_MIN_ACTIVE_MS && width >= RATE_MIN_WIDTH) {
1147
- const rate = (costBilled + costEstimated) / (activeMs / 3_600_000);
1148
- text += ` (${costEstimated > 0 ? "~" : ""}${formatCost(rate)}/h)`;
1138
+ const perHour = (costBilled + costEstimated) / (activeMs / 3_600_000);
1139
+ rate = `(${costEstimated > 0 ? "~" : ""}${formatCost(perHour)}/h)`;
1149
1140
  }
1150
- return `${(bandPaint ?? acc)("\uf155")} ${(bandPaint ?? soft)(text)}`;
1141
+ const cell = `${(bandPaint ?? acc)("\uf155")} ${(bandPaint ?? soft)(text)}`;
1142
+ return rate ? `${cell} ${(bandPaint ?? dim ?? soft)(rate)}` : cell;
1151
1143
  }
1152
1144
 
1153
1145
  // 2s cache + branch length: the footer renders on every poke/stream tick, so
1154
1146
  // without this every frame rescans the whole branch (O(N) per frame).
1155
1147
  export function getUsage(
1156
- ctx: { sessionManager: { getBranch(): readonly unknown[] }; getContextUsage(): { tokens: number | null; contextWindow: number; percent: number | null } | undefined },
1148
+ ctx: {
1149
+ sessionManager: { getBranch(): readonly unknown[] };
1150
+ getContextUsage(): { tokens: number | null; contextWindow: number; percent: number | null } | undefined;
1151
+ model?: { id?: string; provider?: string };
1152
+ },
1157
1153
  acc: (t: string) => string,
1158
1154
  soft: (t: string) => string,
1159
1155
  /** Off by default: the cost cell is opt-in (`/arnative` → Footers → `[c]`). */
@@ -1239,10 +1235,10 @@ export function getUsage(
1239
1235
  if (read > 0) parts.push(`${acc("\uf49b")} ${soft(formatTokens(read))}`);
1240
1236
  const u = ctx.getContextUsage();
1241
1237
  if (u && u.percent !== null && u.tokens !== null) {
1242
- parts.push(`${acc("\udb81\udfaf")} ${soft(`${u.percent.toFixed(1)}%/${formatTokens(u.contextWindow)}`)}`);
1238
+ parts.push(`${acc("\ueb85")} ${soft(`${u.percent.toFixed(1)}%/${formatTokens(u.contextWindow)}`)}`);
1243
1239
  }
1244
1240
  if (showCost) {
1245
- const cell = costCell(costBilled, costEstimated, acc, soft, width, bandPaint);
1241
+ const cell = costCell(costBilled, costEstimated, acc, soft, width, bandPaint, dim);
1246
1242
  // The dollar icon opens a new group, so it takes the same divider the footer uses
1247
1243
  // between cells; the token and context parts stay a space apart.
1248
1244
  if (cell) parts.push(parts.length > 0 ? `${dim("·")} ${cell}` : cell);
@@ -1608,6 +1604,20 @@ export default function (pi: ExtensionAPI) {
1608
1604
  for (const [k, s] of statuses) {
1609
1605
  if (k !== "mcp" && k !== "pi-cache-stats") groups.push(cleanStatus(s));
1610
1606
  }
1607
+ // Payload pressure sits beside the extension statuses: the right rows
1608
+ // already carry speed, cache, tokens and cost. The denominator is the shed
1609
+ // trigger from the snapshot (900KB), not the 1MB proxy wall: showing /1MB
1610
+ // understated pressure by 10 points right before the trim starts.
1611
+ const wire = wireBytesSnapshot();
1612
+ if (wire && wire.bytes > 0 && isByteLimitedModel(ctx.model)) {
1613
+ // Under a 1 MB wall the label keeps the approved shape `0.74MB/900KB`: the
1614
+ // payload in MB, the ceiling in KB. A bigger wall scales both to MB so the
1615
+ // ceiling stays readable instead of printing 14336KB.
1616
+ const label = wire.limit >= 1024 * 1024
1617
+ ? `${(wire.bytes / 1024 / 1024).toFixed(2)}MB/${(wire.limit / 1024 / 1024).toFixed(2)}MB`
1618
+ : `${(wire.bytes / 1024 / 1024).toFixed(2)}MB/${Math.round(wire.limit / 1024)}KB`;
1619
+ groups.push(`${acc("\udb80\udd93")} ${secondarySoft(label)}`);
1620
+ }
1611
1621
 
1612
1622
  let usageStr = "";
1613
1623
  try {
@@ -2415,12 +2425,6 @@ if (isMain(import.meta.url)) {
2415
2425
  assert(outNotice.length === 3 && outNotice[0] === "" && outNotice[1] === ` ${dStatus} \ueb1b Chatbox: Arnative.` && outNotice[2] === "", "Outside dialog sits on the left with the notice beside it and 1 blank line below");
2416
2426
  const outTodos = overlayOutsideDialogOnWidgetLines(["", "\u256d" + "\u2500".repeat(58) + "\u256e", "\u2570" + "\u2500".repeat(58) + "\u256f"], 60, dStatus);
2417
2427
  assert(outTodos.length === 5 && outTodos[0] === "" && outTodos[1] === ` ${dStatus}` && outTodos[2] === "" && outTodos[3]!.startsWith("\u256d"), "Outside dialog leaves 1 blank line above and below when Todos is visible");
2418
- const fakeAbove = { children: [{ constructor: { name: "Spacer" }, render: () => [""] }, { render: () => ["\u256d\u2500\u256e", "\u2570\u2500\u256f"] }] };
2419
- assert(trimLeadingSpacerAboveWidget(fakeAbove) === true && fakeAbove.children.length === 1, "leading Spacer above boxed widget (e.g. Todos) is trimmed cleanly");
2420
- const fakePlainAbove = { children: [{ constructor: { name: "Spacer" }, render: () => [""] }, { render: () => ["plain status"] }] };
2421
- assert(trimLeadingSpacerAboveWidget(fakePlainAbove) === true && fakePlainAbove.children.length === 1, "leading Spacer above notice widget is trimmed cleanly");
2422
- const fakeEmptyAbove = { children: [{ constructor: { name: "Spacer" }, render: () => [""] }] };
2423
- assert(trimLeadingSpacerAboveWidget(fakeEmptyAbove) === true && fakeEmptyAbove.children.length === 0, "leading Spacer when widgetContainerAbove is empty is trimmed cleanly");
2424
2428
 
2425
2429
  const scrollBorder = renderChatboxScrollBorder("\u2191", 3, 24, (t) => `<bdr>${t}</bdr>`, (t) => `<pri>${t}</pri>`);
2426
2430
  assert(scrollBorder.includes("<pri>↑ 3 more</pri>") && visibleWidth(stripAnsi(scrollBorder.replace(/<\/?(bdr|pri)>/g, ""))) === 24, "chatbox scroll border paints N more in primary at exact width");
@@ -34,8 +34,9 @@ interface AssistantMessage {
34
34
  errorMessage?: string;
35
35
  }
36
36
 
37
+ /** models.json watcher debounce: batch rapid writes (a heal pass re-reading its own write). */
37
38
  const DEBOUNCE_MS = 800;
38
- const WIDGET_MS = 10_000;
39
+
39
40
 
40
41
  const registryOf = (ctx: unknown): RegistryLike | undefined => (ctx as { modelRegistry?: RegistryLike } | undefined)?.modelRegistry;
41
42
 
@@ -83,28 +84,18 @@ export default function registerModelHeal(pi: ExtensionAPI): void {
83
84
  bindSetModel((model) => pi.setModel(model as never));
84
85
  let watcher: FSWatcher | undefined;
85
86
  let timer: ReturnType<typeof setTimeout> | undefined;
86
- let widgetTimer: ReturnType<typeof setTimeout> | undefined;
87
87
  let deferNoticeShown = false;
88
88
 
89
89
  // ctx getters throw once the session was replaced or reloaded, and deferred callbacks
90
- // (timer, watcher, network passes) can outlive it: capture ui while live, guard dismissal.
90
+ // (timer, watcher, network passes) can outlive it: capture ui while live, guard access.
91
91
  function notify(ctx: ExtensionContext, lines: string[]): void {
92
- let ui: ExtensionContext["ui"] | undefined;
93
92
  try {
94
- ui = ctx.ui;
95
- ui?.setWidget?.("model-heal", lines.map((line) => HEAL_ICON + " model-heal: " + line));
93
+ // Transcript notify, like pi-jev-eye: the widget slot above the input box steals focus
94
+ // from the prompt, while a scrollback line stays visible without covering anything.
95
+ ctx.ui?.notify(lines.map((line) => "[arnative] model-heal: " + line).join("\n"), "info");
96
96
  } catch {
97
97
  return;
98
98
  }
99
- if (widgetTimer) clearTimeout(widgetTimer);
100
- widgetTimer = setTimeout(() => {
101
- widgetTimer = undefined;
102
- try {
103
- ui?.setWidget?.("model-heal", undefined);
104
- } catch {
105
- // session replaced while the widget was up
106
- }
107
- }, WIDGET_MS);
108
99
  }
109
100
 
110
101
  async function apply(ctx: ExtensionContext, label: string, result: HealResult): Promise<void> {
@@ -165,6 +156,14 @@ export default function registerModelHeal(pi: ExtensionAPI): void {
165
156
  runFlags(ctx);
166
157
  }, DEBOUNCE_MS);
167
158
  });
159
+ // A missing models.json throws ENOENT synchronously (caught below), but lock
160
+ // errors (EPERM while a write holds the file) arrive as an async "error" event
161
+ // that no try/catch can intercept: without this handler that event is an
162
+ // uncaughtException and pi exits. Losing the watcher is fine — a later
163
+ // session_start retries it.
164
+ watcher.on("error", () => {
165
+ stopWatcher();
166
+ });
168
167
  } catch {
169
168
  // models.json missing or not watchable
170
169
  }
@@ -218,8 +217,6 @@ export default function registerModelHeal(pi: ExtensionAPI): void {
218
217
  pi.on("session_shutdown", () => {
219
218
  cancelManualHeal();
220
219
  stopWatcher();
221
- if (widgetTimer) clearTimeout(widgetTimer);
222
- widgetTimer = undefined;
223
220
  });
224
221
 
225
222
  registerCommands(pi, (_args, ctx) => healNow(ctx));