@bismawy/pi-arnative 0.8.0-rc.1 → 0.8.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.
- package/CHANGELOG.md +11 -1
- package/README.md +14 -1
- package/extensions/arnative.ts +110 -6
- package/extensions/model-heal.ts +248 -0
- package/extensions/section-headers.ts +9 -7
- package/extensions/ui-render-tweaks.ts +31 -0
- package/lib/compat.ts +1 -1
- package/lib/model-heal.ts +640 -0
- package/lib/provider.ts +8 -2
- package/lib/status-widget.ts +71 -0
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
## [0.8.
|
|
3
|
+
## [0.8.1] - 2026-10-26
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
- **`/providers` is its own command.** The provider screen was reachable only as `/arnative providers`; it now also answers to `/providers`, through the same handler, so the two cannot drift. Both are registered in `registerCommands` and the self-check pins the set (`extensions/arnative.ts`).
|
|
7
|
+
- **Status rows above the chat column now use the arnative mark and the theme's `dim` token.** pi renders a `setWidget` string array as unstyled `Text`, so every status line (model heal, the provider probe, other extensions' `setWidget` calls) landed in the default foreground. A render patch turns those arrays into a component factory that receives the live theme: the `\ueb1b` mark leads the block with one space, rows align under it, and a row another extension already painted keeps its own colour (an error row stays red). `lib/status-widget.ts`.
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
- **The Extensions tab lists packages, not every module inside them.** The header used to print one row per loaded entry point (`@bismawy/pi-arnative@0.8.0:footer.ts`, `:model-heal.ts`, …), so a twelve-module package filled the box on its own. The `:subpath` is dropped and each package appears once with its version — the count matches what `pi list` shows. Local single-file extensions (`hark.ts`) are unchanged (`extensions/section-headers.ts`, `extractItemsFromBody`).
|
|
11
|
+
|
|
12
|
+
## [0.8.0] - 2026-10-26
|
|
4
13
|
|
|
5
14
|
### Added
|
|
15
|
+
- **Model heal keeps `models.json` correct with no command (adopted from pi-auto-compat).** On `session_start`, `model_select`, a change to `models.json` (debounced watcher) and an assistant error that names a rejected parameter, three passes run on the rules the provider wizard already uses: flags (missing compat flags and a default `thinkingLevelMap`, offline), meta (`contextWindow`/`maxTokens` from each channel's `GET /models`, 6 h TTL, unit anomalies rejected, caps clamped to the window) and effort (the `reasoning_effort` levels a relay accepts, remapped to the nearest accepted one, 24 h TTL). Each pass is one read-modify-write that writes only real differences: an explicit value (even `false`) is never overwritten, a hand-edited network value stays manual, a user-shaped map is never probed, a corrupt file is reported and never rewritten, and the first write keeps a backup. Channel-wide flags land at provider level; extension-owned providers are fixed through `modelOverrides`. `/arnative` → **Model heal** picks `Full` (default), `Flags` (offline only) or `Off`; `/model-heal` forces every pass now, and `/auto-compat` stays as an alias once pi-auto-compat is uninstalled. While pi-auto-compat is still installed, pi-arnative defers to it and says so once, so two healers never write the same file. State lives in `<agent>/arnative/model-heal.json` (`lib/model-heal.ts`, `extensions/model-heal.ts`).
|
|
6
16
|
- **Auto-compact keeps long sessions light.** `/arnative` → **Auto-compact** picks **Smart** — a tier table by context window (≥768k→20%, ≥384k→40%, ≥192k→80%, below 192k→pi core; every tier lands the trigger near the same ~200k-token transcript ceiling) — or a **manual token budget** (`100k`–`400k`, one absolute number for any window). When a run settles with the context at or above the threshold, pi's own compaction fires through `ctx.compact()` — the same machinery and summary as `/compact`, never mid-run. Small windows defer entirely: a 128k model keeps pi's near-full `reserveTokens` compaction untouched. The saved choice is marked with a green ✓ at the end of its picker row. Guards: no re-trigger while a compaction runs, a growth-margin wait (5% of the threshold) after an attempt that freed too little or failed (usage oscillating at the threshold cannot re-summarize every turn), and a full reset on session start (`extensions/autocompact.ts`).
|
|
7
17
|
- **The push gate hook now ships with the repo.** `.githooks/pre-push` is the pre-push gate the README describes (it used to live only in a machine-local setup): it rejects a branch push whose tip tree does not match the `.git/arnative-preview` stamp that `npm run preview` writes, so a fix cannot reach GitHub without a live preview. Tags and branch deletions pass; activate per clone with `git config core.hooksPath .githooks`.
|
|
8
18
|
- **Providers now write the limits and compat flags the endpoint implies.** The wizard already read the `/models` answer to list ids and threw the rest away; the same answer now also supplies each model's `contextWindow`/`maxTokens` (kept through later edits that never mention them) and a `compat` block the rules imply — developer-role off for reasoning models on a third-party OpenAI-compatible channel, session-affinity headers, Anthropic cache control on Claude-style relays, deepseek thinking format, adaptive thinking on Opus/Sonnet ≥ 4.6 and Fable ≥ 5 — while any value already in `models.json` still wins (`lib/compat.ts`, `suggestCompat`; `lib/provider.ts`, `wireModels`).
|
package/README.md
CHANGED
|
@@ -19,6 +19,7 @@ pi-arnative replaces pi’s default terminal chrome with a unified, cohesive vis
|
|
|
19
19
|
- Transcript Clock: Timestamps for conversation messages with clean bubble backgrounds.
|
|
20
20
|
- Usage Dashboard: Real-time token counts and cost tracking across all local sessions via `/usage`.
|
|
21
21
|
- Custom Providers: any OpenAI-, Anthropic-, Gemini- or Ollama-compatible endpoint from three inputs — URL, key, name; models are probed and picked, saved to pi's own `models.json`/`auth.json`, together with the context window and output cap the probe answered and the compat flags the endpoint needs. Enter on a stored provider edits: reselect models, re-probe the endpoint, cycle per-model thinking levels (off → auto → minimal → low → medium → high → xhigh → max, auto-detected from ids), set all of them at once (`[A]` auto, `[R]` off), probe which effort levels the channel really accepts (`p`), or delete.
|
|
22
|
+
- Model Heal: keeps `models.json` correct with no command (adopted from pi-auto-compat) — missing compat flags, the context window and output cap each channel's `/models` publishes, and the effort levels a relay really accepts. Explicit values always win.
|
|
22
23
|
|
|
23
24
|
<details>
|
|
24
25
|
<summary><b>Configuration & Presets</b></summary>
|
|
@@ -41,6 +42,14 @@ When the context crosses the chosen threshold after a run settles, pi's own comp
|
|
|
41
42
|
|
|
42
43
|
Off by default. Guards: no re-trigger while a compaction runs, a growth-margin wait (5% of the threshold) after an attempt that freed too little or failed, and a full reset on session start. Pi's own `compaction.reserveTokens` threshold, including per-model overrides, is unaffected; whichever fires first wins.
|
|
43
44
|
|
|
45
|
+
### Model heal
|
|
46
|
+
Configurable via `/arnative` → **Model heal** (saved to `~/.pi/agent/arnative/config.json`). Runs on its own on session start, model select, a change to `models.json`, and an error that names a rejected parameter:
|
|
47
|
+
- **Full** (default): compat flags offline, plus `contextWindow`/`maxTokens` from each channel's `GET /models` (6 h TTL) and the accepted `reasoning_effort` levels written as a `thinkingLevelMap` (24 h TTL).
|
|
48
|
+
- **Flags**: the offline compat pass only, no network.
|
|
49
|
+
- **Off**: nothing.
|
|
50
|
+
|
|
51
|
+
`/model-heal` forces every pass now, ignoring the TTLs (`/auto-compat` is an alias once pi-auto-compat is uninstalled). A value you set by hand — even `false` — is never overwritten, a corrupt `models.json` is reported and never rewritten, and the first write keeps a backup. While pi-auto-compat is still installed, pi-arnative defers to it and says so once.
|
|
52
|
+
|
|
44
53
|
</details>
|
|
45
54
|
|
|
46
55
|
## Install
|
|
@@ -67,7 +76,9 @@ npm run dev
|
|
|
67
76
|
| `ctrl+alt+n` · `alt+n` | New session (`/new`) |
|
|
68
77
|
| `ctrl+alt+m` · `alt+m` | Toggle Minimal footer |
|
|
69
78
|
| `/usage` | Token & cost dashboard (or `/arnative` → **Usage**) |
|
|
70
|
-
| `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Auto-compact, Providers, Usage) |
|
|
79
|
+
| `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Auto-compact, Model heal, Providers, Usage) |
|
|
80
|
+
| `/providers` | Provider screen (or `/arnative` → **Providers**) |
|
|
81
|
+
| `/model-heal` | Heal `models.json` now (or `/arnative` → **Model heal**) |
|
|
71
82
|
| Click tool / `ctrl+o` | Toggle tool output box |
|
|
72
83
|
| `←` | Back — step back from submenus/dashboard to menu |
|
|
73
84
|
|
|
@@ -100,6 +111,8 @@ To bind `app.session.new` in `~/.pi/agent/keybindings.json`:
|
|
|
100
111
|
| `extensions/footer.ts` | 3-row status grid footer and boxed editor (preset: `/arnative footers`) |
|
|
101
112
|
| `extensions/animations.ts` | Working spinner presets and `/arnative` → Animations picker |
|
|
102
113
|
| `extensions/autocompact.ts` | Auto-compact: Smart tiers by window or a fixed token budget (`/arnative` → Auto-compact) |
|
|
114
|
+
| `extensions/model-heal.ts` | Model heal triggers: session start, model select, `models.json` watcher, rejected-parameter errors, `/model-heal` |
|
|
115
|
+
| `lib/model-heal.ts` | Model heal passes: compat flags, `/models` limits sync, effort probe |
|
|
103
116
|
| `lib/spinner.ts` | Spinner preset catalog: frames, cadence, and painters |
|
|
104
117
|
| `extensions/arnative.ts` | Settings menu with live preview and navigation |
|
|
105
118
|
| `lib/provider.ts` | Custom provider wizard: probe, model pick, edit actions, `models.json`/`auth.json` save |
|
package/extensions/arnative.ts
CHANGED
|
@@ -25,6 +25,8 @@ import {
|
|
|
25
25
|
import { FOOTER_PRESETS, activeFooterPreset, setFooterPreset, type FooterPreset } from "./footer.ts";
|
|
26
26
|
import { HEADER_PRESETS, activeHeaderPreset, setHeaderPreset, type HeaderPreset } from "./section-headers.ts";
|
|
27
27
|
import { AUTO_COMPACT_CHOICES, activeAutoCompact, setAutoCompact, type AutoCompactChoice } from "./autocompact.ts";
|
|
28
|
+
import { healNow } from "./model-heal.ts";
|
|
29
|
+
import { MODEL_HEAL_CHOICES, activeModelHeal, setModelHeal, type ModelHealChoice } from "../lib/model-heal.ts";
|
|
28
30
|
import { LIST_LEGEND_LIVE, LIST_LEGEND_MOVE, LIST_LEGEND_ROOT, ListPicker, nameRows, rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
|
|
29
31
|
import { openProviders } from "../lib/provider.ts";
|
|
30
32
|
import { openUsage } from "./usage.ts";
|
|
@@ -307,6 +309,75 @@ const openAutoCompact = async (ctx: ExtensionCommandContext): Promise<boolean |
|
|
|
307
309
|
return goBack === true;
|
|
308
310
|
};
|
|
309
311
|
|
|
312
|
+
const MODEL_HEAL_PICKER_TEXT: ListPickerText = {
|
|
313
|
+
title: screenTitle("Model heal"),
|
|
314
|
+
description: "Keeps models.json correct on its own: session start, model switch, file change, rejected parameter.",
|
|
315
|
+
legend: LIST_LEGEND_MOVE,
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
const MODEL_HEAL_RUN_NOW = "Run now";
|
|
319
|
+
|
|
320
|
+
const MODEL_HEAL_NOTES: Record<ModelHealChoice, string> = {
|
|
321
|
+
Full: "flags + limits from /models + probed thinking levels",
|
|
322
|
+
Flags: "offline compat flags only, no network",
|
|
323
|
+
Off: "never touch models.json",
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
/** Rows for the Model heal picker: the saved mode ends its row with a green check; the
|
|
327
|
+
* last row is an action, never a saved choice. */
|
|
328
|
+
export function modelHealRows(opened: ModelHealChoice): ListRow[] {
|
|
329
|
+
return [
|
|
330
|
+
...MODEL_HEAL_CHOICES.map((c) => ({ label: c, note: MODEL_HEAL_NOTES[c], chosen: c === opened })),
|
|
331
|
+
{ label: MODEL_HEAL_RUN_NOW, note: "heal every channel now, ignoring the 6h/24h TTLs" },
|
|
332
|
+
];
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const openModelHeal = async (ctx: ExtensionCommandContext): Promise<boolean | void> => {
|
|
336
|
+
const opened = activeModelHeal();
|
|
337
|
+
|
|
338
|
+
if (ctx.mode !== "tui") {
|
|
339
|
+
const labels = [...MODEL_HEAL_CHOICES, MODEL_HEAL_RUN_NOW].map((c) => (c === opened ? c + " ✓" : c));
|
|
340
|
+
const pick = await ctx.ui.select(MODEL_HEAL_PICKER_TEXT.title, labels);
|
|
341
|
+
if (pick === undefined) return;
|
|
342
|
+
const index = labels.indexOf(pick);
|
|
343
|
+
if (index === MODEL_HEAL_CHOICES.length) {
|
|
344
|
+
await healNow(ctx);
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
setModelHeal(MODEL_HEAL_CHOICES[index]!);
|
|
348
|
+
ctx.ui.notify("[arnative] Model heal: " + MODEL_HEAL_CHOICES[index]!, "info");
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
let runNow = false;
|
|
353
|
+
const goBack = await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
|
|
354
|
+
const picker = new ListPicker(
|
|
355
|
+
theme,
|
|
356
|
+
modelHealRows(opened),
|
|
357
|
+
opened,
|
|
358
|
+
{
|
|
359
|
+
preview: () => {},
|
|
360
|
+
revert: () => {},
|
|
361
|
+
done: () => {
|
|
362
|
+
if (picker.index === MODEL_HEAL_CHOICES.length) runNow = true;
|
|
363
|
+
else setModelHeal(MODEL_HEAL_CHOICES[picker.index]!);
|
|
364
|
+
done(false);
|
|
365
|
+
},
|
|
366
|
+
cancel: () => done(false),
|
|
367
|
+
back: () => done(true),
|
|
368
|
+
requestRender: () => tui.requestRender(),
|
|
369
|
+
},
|
|
370
|
+
MODEL_HEAL_PICKER_TEXT,
|
|
371
|
+
false,
|
|
372
|
+
ctx.thinkingLevel,
|
|
373
|
+
);
|
|
374
|
+
return picker;
|
|
375
|
+
});
|
|
376
|
+
// After the picker closed: the run notifies, and a notice under an open overlay is lost.
|
|
377
|
+
if (runNow) await healNow(ctx);
|
|
378
|
+
return goBack === true;
|
|
379
|
+
};
|
|
380
|
+
|
|
310
381
|
export const MENUS: ArnativeMenu[] = [
|
|
311
382
|
{
|
|
312
383
|
value: "themes",
|
|
@@ -338,6 +409,12 @@ export const MENUS: ArnativeMenu[] = [
|
|
|
338
409
|
description: "smart by window or a fixed token budget (off by default)",
|
|
339
410
|
open: openAutoCompact,
|
|
340
411
|
},
|
|
412
|
+
{
|
|
413
|
+
value: "heal",
|
|
414
|
+
label: "Model heal",
|
|
415
|
+
description: "auto-fix models.json: compat flags, limits, thinking levels (on by default)",
|
|
416
|
+
open: openModelHeal,
|
|
417
|
+
},
|
|
341
418
|
{
|
|
342
419
|
value: "providers",
|
|
343
420
|
label: "Providers",
|
|
@@ -437,6 +514,22 @@ export function shouldApplyDefaultTheme(
|
|
|
437
514
|
return themeSetting === undefined && themes.some((t) => t.name === DEFAULT_THEME);
|
|
438
515
|
}
|
|
439
516
|
|
|
517
|
+
/** Register every slash command this package owns. Exported so the self-check can assert the
|
|
518
|
+
* set without starting a session. */
|
|
519
|
+
export function registerCommands(pi: Pick<ExtensionAPI, "registerCommand">): void {
|
|
520
|
+
pi.registerCommand("arnative", {
|
|
521
|
+
description: "Arnative settings menu: themes, headers, footers, providers, usage",
|
|
522
|
+
getArgumentCompletions: arnativeCompletions,
|
|
523
|
+
handler: arnativeHandler,
|
|
524
|
+
});
|
|
525
|
+
// Shortcut for the screen people reach for by name: it goes through the same handler, so
|
|
526
|
+
// `/providers` and `/arnative providers` cannot drift apart.
|
|
527
|
+
pi.registerCommand("providers", {
|
|
528
|
+
description: "Custom endpoints: add, edit or remove a provider (same as /arnative providers)",
|
|
529
|
+
handler: (_args: string, ctx: ExtensionCommandContext) => arnativeHandler("providers", ctx),
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
|
|
440
533
|
export default function (pi: ExtensionAPI) {
|
|
441
534
|
pi.on("session_start", async (_event, ctx) => {
|
|
442
535
|
// `setTheme` writes the choice into pi's settings, so this runs once per install and the
|
|
@@ -444,11 +537,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
444
537
|
if (!shouldApplyDefaultTheme(pi.getSettings()?.theme, ctx.ui.getAllThemes())) return;
|
|
445
538
|
ctx.ui.setTheme(DEFAULT_THEME);
|
|
446
539
|
});
|
|
447
|
-
pi
|
|
448
|
-
description: "Arnative settings menu: themes, headers, footers, providers, usage",
|
|
449
|
-
getArgumentCompletions: arnativeCompletions,
|
|
450
|
-
handler: arnativeHandler,
|
|
451
|
-
});
|
|
540
|
+
registerCommands(pi);
|
|
452
541
|
}
|
|
453
542
|
|
|
454
543
|
// Self-check: `node extensions/arnative.ts`
|
|
@@ -464,7 +553,14 @@ if (isMain(import.meta.url)) {
|
|
|
464
553
|
assert(MENU_DESC === "Themes, headers, footers, animations, auto-compact, providers, usage", `the menu description is the pinned string, got ${MENU_DESC}`);
|
|
465
554
|
// Every menu row is reachable and the description names them all, so a new screen cannot
|
|
466
555
|
// be added to MENUS and forgotten in the copy a user reads first.
|
|
467
|
-
assert(MENUS.length ===
|
|
556
|
+
assert(MENUS.length === 8, "eight settings screens");
|
|
557
|
+
{
|
|
558
|
+
const values = MENUS.map((m) => m.value);
|
|
559
|
+
assert(values.indexOf("heal") === values.indexOf("compact") + 1, "Model heal row sits right after Auto-compact");
|
|
560
|
+
const heal = modelHealRows("Flags");
|
|
561
|
+
assert(heal.map((r) => r.label).join(",") === "Full,Flags,Off,Run now", "Model heal rows: three modes then Run now");
|
|
562
|
+
assert(heal.filter((r) => r.chosen).map((r) => r.label).join(",") === "Flags", "Model heal marks only the saved mode");
|
|
563
|
+
}
|
|
468
564
|
for (const label of ["Themes", "Headers", "Footers", "Animations", "Auto-compact", "Providers", "Usage"]) {
|
|
469
565
|
assert(MENUS.some((m) => m.label === label), `MENUS carries the ${label} screen`);
|
|
470
566
|
}
|
|
@@ -489,6 +585,14 @@ if (isMain(import.meta.url)) {
|
|
|
489
585
|
assert(autoCompactRows("Off")[0]!.chosen === true, "the marker moves when the saved choice changes");
|
|
490
586
|
assert(arnativeCompletions("pr")![0]!.value === "providers", "providers menu has completions");
|
|
491
587
|
assert(MENUS.some((m) => m.value === "providers"), "providers menu registered");
|
|
588
|
+
// Every slash command, and the one alias: `/providers` must land on the providers screen.
|
|
589
|
+
{
|
|
590
|
+
const registered = new Map<string, { description: string; handler: unknown }>();
|
|
591
|
+
registerCommands({ registerCommand: (name, options) => { registered.set(name, options as never); } } as never);
|
|
592
|
+
assert([...registered.keys()].join(",") === "arnative,providers", "two commands: /arnative and /providers");
|
|
593
|
+
assert(typeof registered.get("providers")!.handler === "function", "/providers has a handler");
|
|
594
|
+
assert(MENUS.some((m) => m.value === "providers"), "/providers routes to a menu row that exists");
|
|
595
|
+
}
|
|
492
596
|
// Usage is reachable from /arnative even though it is a dashboard, not a setting.
|
|
493
597
|
assert(MENUS.some((m) => m.value === "usage"), "usage menu registered");
|
|
494
598
|
assert(arnativeCompletions("us")![0]!.value === "usage", "usage menu has completions");
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model heal trigger: runs the passes in lib/model-heal.ts with no command.
|
|
3
|
+
|
|
4
|
+
* Triggers: session_start, model_select, a change to models.json (debounced watcher), and an
|
|
5
|
+
* assistant error that names a rejected parameter (pi's auto-retry would otherwise burn its
|
|
6
|
+
* attempts on the same bad effort level). /model-heal forces every pass now, ignoring TTLs.
|
|
7
|
+
|
|
8
|
+
* Mode (/arnative -> Model heal): Full = flags + network passes, Flags = offline flags
|
|
9
|
+
* only, Off = nothing. While pi-auto-compat is installed this module defers to it and says so
|
|
10
|
+
* once, so two healers never write models.json at the same time.
|
|
11
|
+
*/
|
|
12
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
13
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import { type FSWatcher, watch } from "node:fs";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { assert, isMain } from "../lib/check.ts";
|
|
17
|
+
import { REJECTION_RE } from "../lib/compat.ts";
|
|
18
|
+
import { activeModelHeal, autoCompatInstalled, healEffort, healFlags, healMeta, type HealDeps, type HealResult, type ModelHealChoice, type RtModel } from "../lib/model-heal.ts";
|
|
19
|
+
|
|
20
|
+
interface RegistryLike {
|
|
21
|
+
getAll?: () => unknown[];
|
|
22
|
+
refresh?: (options?: { allowNetwork?: boolean }) => Promise<unknown>;
|
|
23
|
+
getRegisteredProviderConfig?: (provider: string) => unknown;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface AssistantMessage {
|
|
27
|
+
role?: string;
|
|
28
|
+
provider?: string;
|
|
29
|
+
model?: string;
|
|
30
|
+
errorMessage?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const DEBOUNCE_MS = 800;
|
|
34
|
+
const WIDGET_MS = 10_000;
|
|
35
|
+
|
|
36
|
+
const registryOf = (ctx: unknown): RegistryLike | undefined => (ctx as { modelRegistry?: RegistryLike } | undefined)?.modelRegistry;
|
|
37
|
+
|
|
38
|
+
/** The session's view of the registry, in the shape the passes take. An extension that
|
|
39
|
+
* supplies its own model list owns it: only modelOverrides reaches the merged model. */
|
|
40
|
+
export function depsFor(ctx: unknown): HealDeps {
|
|
41
|
+
const registry = registryOf(ctx);
|
|
42
|
+
return {
|
|
43
|
+
models: () => (registry?.getAll?.() ?? []).filter((m): m is RtModel => !!m && typeof m === "object"),
|
|
44
|
+
ownsModels: (provider) => {
|
|
45
|
+
try {
|
|
46
|
+
const cfg = registry?.getRegisteredProviderConfig?.(provider) as { models?: unknown; refreshModels?: unknown } | undefined;
|
|
47
|
+
return !!cfg && typeof cfg === "object" && (Array.isArray(cfg.models) || typeof cfg.refreshModels === "function");
|
|
48
|
+
} catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Only a parameter rejection says the level on the wire is wrong; auth, quota and
|
|
56
|
+
* transport errors cost no probe. */
|
|
57
|
+
export function isRejectedParam(message: AssistantMessage | undefined): boolean {
|
|
58
|
+
if (!message || message.role !== "assistant" || !message.provider || !message.model) return false;
|
|
59
|
+
return REJECTION_RE.test(message.errorMessage ?? "");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Whether a pass may run: Off runs nothing, Flags runs only the offline flags pass, Full runs
|
|
63
|
+
* everything, and an installed pi-auto-compat owns models.json in every mode. */
|
|
64
|
+
export function healAllowed(need: "Flags" | "Full", mode: ModelHealChoice, autoCompat: boolean): boolean {
|
|
65
|
+
if (autoCompat || mode === "Off") return false;
|
|
66
|
+
return need === "Flags" || mode === "Full";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The one-time hand-over notice: only when heal is wanted and pi-auto-compat holds the file. */
|
|
70
|
+
export const deferNotice = (mode: ModelHealChoice, autoCompat: boolean): boolean => mode !== "Off" && autoCompat;
|
|
71
|
+
|
|
72
|
+
export default function registerModelHeal(pi: ExtensionAPI): void {
|
|
73
|
+
let watcher: FSWatcher | undefined;
|
|
74
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
75
|
+
let widgetTimer: ReturnType<typeof setTimeout> | undefined;
|
|
76
|
+
let deferNoticeShown = false;
|
|
77
|
+
|
|
78
|
+
// ctx getters throw once the session was replaced or reloaded, and deferred callbacks
|
|
79
|
+
// (timer, watcher, network passes) can outlive it: capture ui while live, guard dismissal.
|
|
80
|
+
function notify(ctx: ExtensionContext, lines: string[]): void {
|
|
81
|
+
let ui: ExtensionContext["ui"] | undefined;
|
|
82
|
+
try {
|
|
83
|
+
ui = ctx.ui;
|
|
84
|
+
ui?.setWidget?.("model-heal", lines.map((line) => "model-heal: " + line));
|
|
85
|
+
} catch {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (widgetTimer) clearTimeout(widgetTimer);
|
|
89
|
+
widgetTimer = setTimeout(() => {
|
|
90
|
+
widgetTimer = undefined;
|
|
91
|
+
try {
|
|
92
|
+
ui?.setWidget?.("model-heal", undefined);
|
|
93
|
+
} catch {
|
|
94
|
+
// session replaced while the widget was up
|
|
95
|
+
}
|
|
96
|
+
}, WIDGET_MS);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function apply(ctx: ExtensionContext, label: string, result: HealResult): Promise<void> {
|
|
100
|
+
if (!result.changed) return;
|
|
101
|
+
let refreshed = true;
|
|
102
|
+
try {
|
|
103
|
+
await registryOf(ctx)?.refresh?.({ allowNetwork: false });
|
|
104
|
+
} catch {
|
|
105
|
+
refreshed = false;
|
|
106
|
+
}
|
|
107
|
+
notify(ctx, [label + " (" + result.detail.length + " change(s))" + (refreshed ? "" : " - run /reload to load it")]);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const enabled = (need: "Flags" | "Full"): boolean => healAllowed(need, activeModelHeal(), autoCompatInstalled());
|
|
111
|
+
|
|
112
|
+
function runFlags(ctx: ExtensionContext, only?: RtModel[]): void {
|
|
113
|
+
if (!enabled("Flags")) return;
|
|
114
|
+
try {
|
|
115
|
+
const result = healFlags(depsFor(ctx), only, ctx.model as RtModel | undefined);
|
|
116
|
+
void apply(ctx, "flags healed", result).catch(() => undefined);
|
|
117
|
+
} catch {
|
|
118
|
+
// stale ctx: the next session_start runs the pass again
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function runNetwork(ctx: ExtensionContext, force: boolean): void {
|
|
123
|
+
if (!enabled("Full")) return;
|
|
124
|
+
let deps: HealDeps;
|
|
125
|
+
try {
|
|
126
|
+
deps = depsFor(ctx);
|
|
127
|
+
} catch {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
void healMeta(deps, force).then((r) => apply(ctx, "limits synced", r)).catch(() => undefined);
|
|
131
|
+
void healEffort(deps, force).then((r) => apply(ctx, "thinking levels probed", r)).catch(() => undefined);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function stopWatcher(): void {
|
|
135
|
+
if (timer) clearTimeout(timer);
|
|
136
|
+
timer = undefined;
|
|
137
|
+
try {
|
|
138
|
+
watcher?.close();
|
|
139
|
+
} catch {
|
|
140
|
+
// already closed
|
|
141
|
+
}
|
|
142
|
+
watcher = undefined;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function startWatcher(ctx: ExtensionContext): void {
|
|
146
|
+
stopWatcher();
|
|
147
|
+
try {
|
|
148
|
+
// A pass's own write fires this too; the re-run finds nothing to change.
|
|
149
|
+
watcher = watch(join(getAgentDir(), "models.json"), { persistent: false }, () => {
|
|
150
|
+
if (timer) clearTimeout(timer);
|
|
151
|
+
timer = setTimeout(() => {
|
|
152
|
+
timer = undefined;
|
|
153
|
+
runFlags(ctx);
|
|
154
|
+
}, DEBOUNCE_MS);
|
|
155
|
+
});
|
|
156
|
+
} catch {
|
|
157
|
+
// models.json missing or not watchable
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
pi.on("session_start", (_event, ctx) => {
|
|
162
|
+
stopWatcher();
|
|
163
|
+
if (deferNotice(activeModelHeal(), autoCompatInstalled())) {
|
|
164
|
+
if (!deferNoticeShown) notify(ctx, ["pi-auto-compat is installed, so it heals models.json. Uninstall it to hand over to pi-arnative."]);
|
|
165
|
+
deferNoticeShown = true;
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
runFlags(ctx);
|
|
169
|
+
if (enabled("Flags")) startWatcher(ctx);
|
|
170
|
+
runNetwork(ctx, false);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
pi.on("model_select", (event, ctx) => {
|
|
174
|
+
const model = (event as { model?: RtModel } | undefined)?.model;
|
|
175
|
+
runFlags(ctx, model ? [model] : undefined);
|
|
176
|
+
runNetwork(ctx, false); // TTL-gated: network only when a channel is stale
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
pi.on("message_end", (event, ctx) => {
|
|
180
|
+
const message = (event as { message?: AssistantMessage } | undefined)?.message;
|
|
181
|
+
if (!isRejectedParam(message) || !enabled("Full")) return;
|
|
182
|
+
try {
|
|
183
|
+
const deps = depsFor(ctx);
|
|
184
|
+
const target = deps.models().find((m) => m.provider.toLowerCase() === message!.provider!.toLowerCase() && m.id === message!.model);
|
|
185
|
+
if (!target) return;
|
|
186
|
+
void healEffort(deps, true, [target]).then((r) => apply(ctx, "thinking levels re-probed", r)).catch(() => undefined);
|
|
187
|
+
} catch {
|
|
188
|
+
// stale ctx
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
pi.on("session_shutdown", () => {
|
|
193
|
+
stopWatcher();
|
|
194
|
+
if (widgetTimer) clearTimeout(widgetTimer);
|
|
195
|
+
widgetTimer = undefined;
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
registerCommands(pi, (_args, ctx) => healNow(ctx));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Every pass now, ignoring TTLs: the /model-heal command and the /arnative Run now row. */
|
|
202
|
+
export async function healNow(ctx: ExtensionContext): Promise<void> {
|
|
203
|
+
if (autoCompatInstalled()) {
|
|
204
|
+
ctx.ui.notify("[arnative] pi-auto-compat is installed and heals models.json. Run /auto-compat, or uninstall it to use model heal.", "warning");
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const deps = depsFor(ctx);
|
|
208
|
+
const flags = healFlags(deps, undefined, ctx.model as RtModel | undefined);
|
|
209
|
+
const meta = await healMeta(deps, true);
|
|
210
|
+
const effort = await healEffort(deps, true);
|
|
211
|
+
const detail = [...flags.detail, ...meta.detail, ...effort.detail];
|
|
212
|
+
const errors = [...flags.errors, ...meta.errors, ...effort.errors];
|
|
213
|
+
if (detail.length > 0) {
|
|
214
|
+
await registryOf(ctx)?.refresh?.({ allowNetwork: false }).catch(() => undefined);
|
|
215
|
+
ctx.ui.notify("[arnative] Model heal fixed:\n - " + detail.join("\n - "), "info");
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
ctx.ui.notify(
|
|
219
|
+
errors.length ? "[arnative] Model heal: nothing to fix; " + errors.length + " endpoint(s) unreachable: " + errors.join("; ") : "[arnative] Model heal: nothing to fix.",
|
|
220
|
+
errors.length ? "warning" : "info",
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function registerCommands(pi: ExtensionAPI, runNow: (args: string, ctx: ExtensionContext) => Promise<void>): void {
|
|
225
|
+
const description = "Heal models.json now: compat flags, contextWindow/maxTokens from each /models, accepted thinking efforts";
|
|
226
|
+
pi.registerCommand("model-heal", { description, handler: runNow });
|
|
227
|
+
// Migration alias: keeps the old habit working once pi-auto-compat is uninstalled.
|
|
228
|
+
if (!autoCompatInstalled()) pi.registerCommand("auto-compat", { description: description + " (alias of /model-heal)", handler: runNow });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (isMain(import.meta.url)) {
|
|
232
|
+
assert(isRejectedParam({ role: "assistant", provider: "r", model: "m", errorMessage: "400 invalid reasoning_effort" }), "a rejected effort triggers a re-probe");
|
|
233
|
+
assert(!isRejectedParam({ role: "assistant", provider: "r", model: "m", errorMessage: "401 unauthorized" }), "an auth failure costs no probe");
|
|
234
|
+
assert(!isRejectedParam({ role: "user", provider: "r", model: "m", errorMessage: "bad request" }), "only assistant messages count");
|
|
235
|
+
assert(!isRejectedParam(undefined), "no message, no probe");
|
|
236
|
+
assert(healAllowed("Flags", "Full", false) && healAllowed("Full", "Full", false), "Full runs every pass");
|
|
237
|
+
assert(healAllowed("Flags", "Flags", false) && !healAllowed("Full", "Flags", false), "Flags runs only the offline pass");
|
|
238
|
+
assert(!healAllowed("Flags", "Off", false) && !healAllowed("Full", "Off", false), "Off runs nothing");
|
|
239
|
+
assert(!healAllowed("Flags", "Full", true) && !healAllowed("Flags", "Flags", true), "an installed pi-auto-compat owns the file");
|
|
240
|
+
assert(deferNotice("Full", true) && deferNotice("Flags", true), "the hand-over notice shows while heal is wanted");
|
|
241
|
+
assert(!deferNotice("Off", true) && !deferNotice("Full", false), "and stays quiet when Off or nothing to defer to");
|
|
242
|
+
const owned = depsFor({ modelRegistry: { getAll: () => [{ provider: "x", id: "a" }, null], getRegisteredProviderConfig: (p: string) => (p === "ext" ? { refreshModels: () => [] } : undefined) } });
|
|
243
|
+
assert(owned.models().length === 1, "non-object registry entries are dropped");
|
|
244
|
+
assert(owned.ownsModels("ext") && !owned.ownsModels("x"), "an extension list with refreshModels owns its models");
|
|
245
|
+
const throwing = depsFor({ modelRegistry: { getRegisteredProviderConfig: () => { throw new Error("stale"); } } });
|
|
246
|
+
assert(!throwing.ownsModels("x") && throwing.models().length === 0, "a stale registry reads as empty");
|
|
247
|
+
console.log("model-heal extension self-check OK");
|
|
248
|
+
}
|
|
@@ -214,14 +214,16 @@ export function extractItemsFromBody(body: string, isExtensions = false): string
|
|
|
214
214
|
}
|
|
215
215
|
}
|
|
216
216
|
if (!isExtensions) return items;
|
|
217
|
-
|
|
217
|
+
// One row per package (like `pi list`): drop the `:subpath` of every module inside a
|
|
218
|
+
// package and repeat nothing. Local single-file extensions (`hark.ts`) stay as they are.
|
|
219
|
+
const labels = new Set<string>();
|
|
220
|
+
for (const item of items) {
|
|
218
221
|
const colon = item.indexOf(":");
|
|
219
|
-
const
|
|
220
|
-
const ver = installedVersion(
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
});
|
|
222
|
+
const base = (colon === -1 ? item : item.slice(0, colon)).trim();
|
|
223
|
+
const ver = installedVersion(base);
|
|
224
|
+
labels.add(ver ? `${base}@${ver}` : base);
|
|
225
|
+
}
|
|
226
|
+
return [...labels];
|
|
225
227
|
}
|
|
226
228
|
|
|
227
229
|
// Cheatsheet for the Shortcut tab. Mirrors README "Shortcuts" plus the bindings the
|
|
@@ -38,6 +38,7 @@ import {
|
|
|
38
38
|
} from "@earendil-works/pi-tui";
|
|
39
39
|
import { readdirSync, readFileSync } from "node:fs";
|
|
40
40
|
import { renderBoxLines } from "../lib/box.ts";
|
|
41
|
+
import { statusRows } from "../lib/status-widget.ts";
|
|
41
42
|
import { ansiBgOpen, getActiveTheme, setActiveTheme, stripAnsi, themeOf, softSecondaryOf } from "../lib/ansi.ts";
|
|
42
43
|
import { assert, isMain } from "../lib/check.ts";
|
|
43
44
|
import { contrast, oklchToRgb, parseOklch, toHex } from "../lib/color.ts";
|
|
@@ -273,6 +274,36 @@ if (InteractiveMode?.prototype && !(globalThis as Record<symbol, boolean>)[PACKA
|
|
|
273
274
|
|
|
274
275
|
// arnative box border helper -> lib/box.ts (one definition for every box)
|
|
275
276
|
|
|
277
|
+
// 7. Status rows above the chat column (pi's `aboveEditor` widget slot). pi turns a string
|
|
278
|
+
// array into unstyled `Text`, so an extension's status line ignores the theme and lands in
|
|
279
|
+
// the default foreground. Every such array is handed to a component factory instead, which
|
|
280
|
+
// receives the live theme: the arnative mark leads the block and every row is `dim`.
|
|
281
|
+
const STATUS_WIDGET_KEY = Symbol.for("pi-arnative.statusWidgetRows");
|
|
282
|
+
if (InteractiveMode?.prototype && !(globalThis as Record<symbol, boolean>)[STATUS_WIDGET_KEY]) {
|
|
283
|
+
(globalThis as Record<symbol, boolean>)[STATUS_WIDGET_KEY] = true;
|
|
284
|
+
const proto = InteractiveMode.prototype as unknown as {
|
|
285
|
+
setExtensionWidget(key: string, content: unknown, options?: { placement?: string }): void;
|
|
286
|
+
};
|
|
287
|
+
const origSetWidget = proto.setExtensionWidget;
|
|
288
|
+
proto.setExtensionWidget = function (key: string, content: unknown, options?: { placement?: string }) {
|
|
289
|
+
if (Array.isArray(content) && content.every((line) => typeof line === "string")) {
|
|
290
|
+
const rows = content as string[];
|
|
291
|
+
content = (_tui: unknown, th: Parameters<typeof statusRows>[0]) => ({
|
|
292
|
+
dispose() {
|
|
293
|
+
/* no listeners, no timers */
|
|
294
|
+
},
|
|
295
|
+
invalidate() {
|
|
296
|
+
/* the rows are fixed at set time */
|
|
297
|
+
},
|
|
298
|
+
render(width: number): string[] {
|
|
299
|
+
return statusRows(th ?? activeTheme(), rows, width);
|
|
300
|
+
},
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
return origSetWidget.call(this, key, content, options);
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
276
307
|
export class JevReviewBoxComponent implements Component {
|
|
277
308
|
private text: string;
|
|
278
309
|
private th: { fg(c: string, t: string): string; bg?(c: string, t: string): string };
|
package/lib/compat.ts
CHANGED
|
@@ -197,7 +197,7 @@ const PROBE_TOKENS = 16;
|
|
|
197
197
|
const RETRY_PAUSE_MS = 1000;
|
|
198
198
|
// Only a parameter rejection indicts the level. Auth, quota and transport errors say
|
|
199
199
|
// nothing, and marking a level accepted without an answer would be a lie.
|
|
200
|
-
const REJECTION_RE = /provider.?error|invalid.?request|http 400|400[.:]|reasoning.?effort|thinking|unsupported|not supported|invalid (?:value|option|parameter|enum)|bad request/i;
|
|
200
|
+
export const REJECTION_RE = /provider.?error|invalid.?request|http 400|400[.:]|reasoning.?effort|thinking|unsupported|not supported|invalid (?:value|option|parameter|enum)|bad request/i;
|
|
201
201
|
|
|
202
202
|
/** A reasoning model on a relay that expects `reasoning_effort` and does not publish its
|
|
203
203
|
* own level support — the only case a probe can fix. */
|