@bismawy/pi-arnative 0.7.0 → 0.8.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.
- package/CHANGELOG.md +16 -0
- package/README.md +29 -4
- package/extensions/arnative.ts +173 -6
- package/extensions/autocompact.ts +294 -0
- package/extensions/footer.ts +3 -3
- package/extensions/model-heal.ts +248 -0
- package/extensions/timestamps.ts +30 -1
- package/extensions/tools.ts +3 -3
- package/extensions/ui-render-tweaks.ts +12 -1
- package/extensions/usage.ts +28 -28
- package/lib/compat.ts +415 -0
- package/lib/list-picker.ts +17 -1
- package/lib/model-heal.ts +640 -0
- package/lib/provider.ts +191 -32
- package/lib/usage-store.ts +1 -1
- package/package.json +3 -3
|
@@ -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
|
+
}
|
package/extensions/timestamps.ts
CHANGED
|
@@ -78,10 +78,31 @@ export function formatTimeBadge(timeStr: string, th: { fg(color: string, text: s
|
|
|
78
78
|
// \x1b[0m (full reset), so padding AFTER the reset loses the bubble bg and renders
|
|
79
79
|
// dark for the rest of the line. Re-apply the bubble bg after every reset and close
|
|
80
80
|
// it at end of line so it cannot leak. Same pattern as InputBgEditor below.
|
|
81
|
+
//
|
|
82
|
+
// The repair is pure per (line, bgOpen) pair, and pi's Markdown cache hands the render
|
|
83
|
+
// patch the SAME string references frame after frame — so a Map keyed by the source
|
|
84
|
+
// line turns every frame after the first into lookups instead of split/join rebuilds.
|
|
85
|
+
// Only the patched render closure calls this, so module-local state is correct even
|
|
86
|
+
// across /reload (the closure keeps this module instance alive). Reset when the bg
|
|
87
|
+
// code changes (theme switch); past the cap the whole map is dropped, because a
|
|
88
|
+
// session's user lines are far below it and correctness never depends on a hit.
|
|
89
|
+
const BUBBLE_BG_CACHE_MAX = 8192;
|
|
90
|
+
let bubbleBgOpen = "";
|
|
91
|
+
let bubbleBgCache = new Map<string, string>();
|
|
92
|
+
|
|
81
93
|
export function repairBubbleBg(line: string, bgOpen: string): string {
|
|
82
94
|
if (!bgOpen || (!line.includes("\x1b[0m") && !line.includes("\x1b[49m"))) return line;
|
|
95
|
+
if (bgOpen !== bubbleBgOpen) {
|
|
96
|
+
bubbleBgOpen = bgOpen;
|
|
97
|
+
bubbleBgCache = new Map();
|
|
98
|
+
}
|
|
99
|
+
const hit = bubbleBgCache.get(line);
|
|
100
|
+
if (hit !== undefined) return hit;
|
|
83
101
|
const patched = line.split("\x1b[0m").join(`\x1b[0m${bgOpen}`).split("\x1b[49m").join(`\x1b[49m${bgOpen}`);
|
|
84
|
-
|
|
102
|
+
const result = patched.endsWith(bgOpen) ? `${patched}\x1b[49m` : patched;
|
|
103
|
+
if (bubbleBgCache.size >= BUBBLE_BG_CACHE_MAX) bubbleBgCache.clear();
|
|
104
|
+
bubbleBgCache.set(line, result);
|
|
105
|
+
return result;
|
|
85
106
|
}
|
|
86
107
|
|
|
87
108
|
/**
|
|
@@ -249,6 +270,14 @@ if (isMain(import.meta.url)) {
|
|
|
249
270
|
assert(clean.includes(`\x1b[0m${bg}`), "bg re-applied after the reset");
|
|
250
271
|
assert(clean.endsWith("\x1b[49m"), "bubble bg closed at end of line");
|
|
251
272
|
assert(repairBubbleBg("plain", "") === "plain", "no bgOpen: unchanged");
|
|
273
|
+
|
|
274
|
+
// memoized repair: a different bg code resets the cache, so nothing repairs
|
|
275
|
+
// against a stale bubble background after a theme switch
|
|
276
|
+
const dirty2 = `${bg}Second\x1b[0m pad \x1b[49m`;
|
|
277
|
+
const otherBg = "\x1b[48;2;1;2;3m";
|
|
278
|
+
assert(repairBubbleBg(dirty2, otherBg).includes(`\x1b[0m${otherBg}`), "a new bg code repairs against that bg");
|
|
279
|
+
assert(repairBubbleBg(dirty2, bg).includes(`\x1b[0m${bg}`), "and back to the previous bg after another reset");
|
|
280
|
+
assert(repairBubbleBg(dirty2, bg) === repairBubbleBg(dirty2, bg), "repeat repair stays stable");
|
|
252
281
|
assert(ansiBgOpen(null, "userMessageBg") === "", "no theme: empty bgOpen");
|
|
253
282
|
assert(
|
|
254
283
|
ansiBgOpen({ bg: (_c, t) => `\x1b[48;2;52;53;61m${t}\x1b[49m` }, "userMessageBg") === "\x1b[48;2;52;53;61m",
|
package/extensions/tools.ts
CHANGED
|
@@ -1042,7 +1042,7 @@ if (isMain(import.meta.url)) {
|
|
|
1042
1042
|
);
|
|
1043
1043
|
|
|
1044
1044
|
// pi-fff override mode: find/grep re-registered with own renderers, no renderShell
|
|
1045
|
-
const fffCall = { render: () => ["\x1b[1mfind \x1b[22m\x1b[36m*.ts in
|
|
1045
|
+
const fffCall = { render: () => ["\x1b[1mfind \x1b[22m\x1b[36m*.ts in /tmp/work\x1b[39m"] };
|
|
1046
1046
|
const fffRes = { render: () => ["src/a.ts \x1b[2m... (6 more lines)\x1b[22m"] };
|
|
1047
1047
|
const fffFind = { toolName: "find", toolDefinition: { renderCall: () => fffCall, renderResult: () => fffRes } };
|
|
1048
1048
|
assert(
|
|
@@ -1053,10 +1053,10 @@ if (isMain(import.meta.url)) {
|
|
|
1053
1053
|
{ content: [{ type: "text", text: "src/a.ts\nsrc/b.ts" }] },
|
|
1054
1054
|
{ expanded: false, isPartial: false },
|
|
1055
1055
|
th,
|
|
1056
|
-
{ args: { pattern: "*.ts", path: "
|
|
1056
|
+
{ args: { pattern: "*.ts", path: "/tmp/work" }, state: {} },
|
|
1057
1057
|
).render(60);
|
|
1058
1058
|
assert(fffOut[0].startsWith("╭") && fffOut[fffOut.length - 1].startsWith("╰"), "pi-fff find: result wrapped in a box");
|
|
1059
|
-
assert(fffOut.some((l: string) => l.includes("*.ts in
|
|
1059
|
+
assert(fffOut.some((l: string) => l.includes("*.ts in /tmp/work")), "pi-fff find: renderCall title goes in the box");
|
|
1060
1060
|
assert(fffOut.some((l: string) => l.includes("6 more lines")), "pi-fff find: renderResult summary goes in the box");
|
|
1061
1061
|
|
|
1062
1062
|
// pi-fff default mode (`ffgrep`/`fffind`): same renderer shape, different names.
|
|
@@ -50,12 +50,19 @@ const activeTheme = () => getActiveTheme<Exclude<ActiveTheme, null>>();
|
|
|
50
50
|
// (hardcoded in handleReloadCommand, no auto-hide). Patches Container.render
|
|
51
51
|
// through the prototype chain (Container is not exported) and drops the whole box on match.
|
|
52
52
|
const RELOAD_TEXT = "Reloading keybindings, extensions, skills, prompts, themes, and context files...";
|
|
53
|
+
/** The reload box is a fixed 5-child container (2 borders, 2 spacers, one 78-char line), so it
|
|
54
|
+
* renders at most ~9 rows even wrapped. Anything larger cannot be the box, and this predicate
|
|
55
|
+
* runs per frame on every plain Container — including a transcript of tens of thousands of
|
|
56
|
+
* lines, where the substring scan is the single most expensive arnative render patch. */
|
|
57
|
+
const RELOAD_BOX_MAX_LINES = 64;
|
|
53
58
|
/**
|
|
54
59
|
* True only for the box itself: border rows, blank spacers and (possibly wrapped) copy of the
|
|
55
60
|
* message. The patch sits on every plain Container, so a bare substring test would blank a
|
|
56
|
-
* whole chat the moment a transcript line mentioned the phrase.
|
|
61
|
+
* whole chat the moment a transcript line mentioned the phrase. Containers larger than
|
|
62
|
+
* {@link RELOAD_BOX_MAX_LINES} are refused before any scanning starts.
|
|
57
63
|
*/
|
|
58
64
|
export function shouldHideReloadBox(lines: readonly string[]): boolean {
|
|
65
|
+
if (lines.length > RELOAD_BOX_MAX_LINES) return false;
|
|
59
66
|
if (!lines.some((l) => l.includes("Reloading keybindings"))) return false;
|
|
60
67
|
const rows = lines.map((l) => stripAnsi(l).trim());
|
|
61
68
|
return rows.every((r) => r === "" || /^[─-]+$/.test(r) || RELOAD_TEXT.includes(r));
|
|
@@ -373,6 +380,10 @@ if (isMain(import.meta.url)) {
|
|
|
373
380
|
assert(shouldHideReloadBox(["────", "", " Reloading keybindings, extensions,", " skills, prompts, themes, and context files...", "", "────"]) === true, "wrapped reload box detected");
|
|
374
381
|
assert(shouldHideReloadBox(["hello", "the log says Reloading keybindings", "world"]) === false, "chat lines that mention the phrase stay visible");
|
|
375
382
|
assert(shouldHideReloadBox(["hello", "world"]) === false, "normal lines pass through");
|
|
383
|
+
assert(
|
|
384
|
+
shouldHideReloadBox([...Array(RELOAD_BOX_MAX_LINES + 1).fill(""), " Reloading keybindings, extensions, skills, prompts, themes, and context files... "]) === false,
|
|
385
|
+
"a container larger than any reload box is refused before scanning",
|
|
386
|
+
);
|
|
376
387
|
|
|
377
388
|
// selection: reverse video replaced with explicit colors (bg selectedBg + fg text)
|
|
378
389
|
assert(
|
package/extensions/usage.ts
CHANGED
|
@@ -501,7 +501,7 @@ if (isMain(import.meta.url)) {
|
|
|
501
501
|
mkdirSync(join(fixture, "sessions", "ui"), { recursive: true });
|
|
502
502
|
const freeAsstOf = (provider: string, model: string, input: number) =>
|
|
503
503
|
JSON.stringify({ message: { role: "assistant", provider, model, usage: { input, output: 5, cacheRead: 1, cost: { total: 0 } } } });
|
|
504
|
-
const freeAsst = (model: string, input: number) => freeAsstOf("
|
|
504
|
+
const freeAsst = (model: string, input: number) => freeAsstOf("alpha", model, input);
|
|
505
505
|
writeFileSync(
|
|
506
506
|
join(fixture, "sessions", "ui", "rows.jsonl"),
|
|
507
507
|
[
|
|
@@ -509,50 +509,50 @@ if (isMain(import.meta.url)) {
|
|
|
509
509
|
freeAsst("other-model", 7),
|
|
510
510
|
// The shipped shape of the collision: a bare id and, on another provider, a path id
|
|
511
511
|
// that merely ENDS with it. Suffix matching folded the second into the first, so a first
|
|
512
|
-
// run under
|
|
512
|
+
// run under a shared alias showed two providers' usage as if it were one provider's own.
|
|
513
513
|
freeAsst("deepseek-v4.1-flash", 300),
|
|
514
|
-
freeAsstOf("
|
|
514
|
+
freeAsstOf("shared", "team/deepseek-ai/DeepSeek-V4.1-Flash", 200),
|
|
515
515
|
].join(String.fromCharCode(10)),
|
|
516
516
|
);
|
|
517
517
|
collectUsageSummary(true);
|
|
518
518
|
|
|
519
519
|
// Per-id totals: a model id reports its own tokens only, whatever it is a suffix of.
|
|
520
520
|
assert(getModelAllTimeUsage("deepseek-v4.1-flash").input === 300, "a bare id does not absorb a longer id that ends with it");
|
|
521
|
-
assert(getModelAllTimeUsage("
|
|
522
|
-
assert(getModelAllTimeUsage("
|
|
521
|
+
assert(getModelAllTimeUsage("team/deepseek-ai/DeepSeek-V4.1-Flash").input === 200, "a path id counts its own provider's tokens only");
|
|
522
|
+
assert(getModelAllTimeUsage("TEAM/DeepSeek-AI/deepseek-V4.1-Flash").input === 200, "case still does not split one model's history");
|
|
523
523
|
assert(getModelAllTimeUsage("deepseek-v4.1-flash:free").input === 300, "a route tag folds into the model it tags");
|
|
524
524
|
|
|
525
525
|
// Cost estimation: unpriced pairs use rates declared automatically in models.json.
|
|
526
526
|
assert(loadPriceTable() !== null && Object.keys(loadPriceTable()).length === 0, "no models.json rates means an empty table");
|
|
527
|
-
assert(!hasPrice("
|
|
528
|
-
assert(estimateCost(1000, 100, 0, "gemini-3.8-flash", "
|
|
527
|
+
assert(!hasPrice("alpha", "gemini-3.8-flash"), "a pair absent from models.json has no price");
|
|
528
|
+
assert(estimateCost(1000, 100, 0, "gemini-3.8-flash", "alpha") === null, "an unknown pair estimates nothing");
|
|
529
529
|
assert(collectUsageSummary(true).totals.estimatedCost === 0, "nothing is estimated without rates");
|
|
530
|
-
assert(estimateCost(1000, 100, 0, "other-model", "
|
|
530
|
+
assert(estimateCost(1000, 100, 0, "other-model", "alpha") === null, "a second unpriced pair estimates nothing either");
|
|
531
531
|
|
|
532
532
|
writeFileSync(
|
|
533
533
|
join(fixture, "models.json"),
|
|
534
534
|
JSON.stringify({
|
|
535
535
|
providers: {
|
|
536
|
-
|
|
537
|
-
|
|
536
|
+
alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 1, output: 2, cacheRead: 0.1 } }] },
|
|
537
|
+
beta: { models: [{ id: "gemini-3.8-flash", cost: { input: 10, output: 20 } }] },
|
|
538
538
|
},
|
|
539
539
|
}),
|
|
540
540
|
);
|
|
541
|
-
assert(hasPrice("
|
|
541
|
+
assert(hasPrice("alpha", "gemini-3.8-flash"), "a priced provider+model is found in the table");
|
|
542
542
|
assert(!hasPrice("enclave", "gemini-3.8-flash"), "another provider with no entry is not priced");
|
|
543
|
-
assert(estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "
|
|
543
|
+
assert(estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "alpha") === 1, "1M input tokens at alpha's $1/M costs $1");
|
|
544
544
|
assert(
|
|
545
|
-
estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "
|
|
546
|
-
"the SAME model at
|
|
545
|
+
estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "beta") === 10,
|
|
546
|
+
"the SAME model at beta costs 10x (rates are per provider, not per model)",
|
|
547
547
|
);
|
|
548
|
-
assert(estimateCost(0, 1_000_000, 0, "gemini-3.8-flash", "
|
|
549
|
-
assert(Math.abs(estimateCost(0, 0, 1_000_000, "gemini-3.8-flash", "
|
|
550
|
-
assert(estimateCost(1_000_000, 0, 0, "vendor/gemini-3.8-flash", "
|
|
548
|
+
assert(estimateCost(0, 1_000_000, 0, "gemini-3.8-flash", "alpha") === 2, "1M output tokens at $2/M costs $2");
|
|
549
|
+
assert(Math.abs(estimateCost(0, 0, 1_000_000, "gemini-3.8-flash", "alpha")! - 0.1) < 1e-9, "cache reads use their own rate");
|
|
550
|
+
assert(estimateCost(1_000_000, 0, 0, "vendor/gemini-3.8-flash", "alpha") === 1, "a vendor/my-model id matches the model rate");
|
|
551
551
|
const withPrices = collectUsageSummary(true);
|
|
552
552
|
assert(withPrices.totals.estimatedCost > 0, "models.json rates produce an estimate");
|
|
553
553
|
assert(withPrices.totals.reportedCost === 0, "the reported total stays at the provider's own number");
|
|
554
554
|
assert(withPrices.totals.cost === withPrices.totals.reportedCost, "the headline cost never absorbs the estimate");
|
|
555
|
-
assert(estimateCost(1_000_000, 0, 0, "other-model", "
|
|
555
|
+
assert(estimateCost(1_000_000, 0, 0, "other-model", "alpha") === null, "a pair with no rate stays unpriced even when others are priced");
|
|
556
556
|
|
|
557
557
|
const fakeTheme = {
|
|
558
558
|
fg: (_c: string, t: string) => `\x1b[38;2;100;100;100m${t}\x1b[39m`,
|
|
@@ -661,7 +661,7 @@ if (isMain(import.meta.url)) {
|
|
|
661
661
|
// The unpriced notice is gone: the `-` in Cost already says it.
|
|
662
662
|
assert(!body.includes("unpriced"), "the unpriced notice line is removed");
|
|
663
663
|
// Provider rows are capitalized so they read as names, not raw ids.
|
|
664
|
-
assert(plain(lines[firstRow]!).includes("
|
|
664
|
+
assert(plain(lines[firstRow]!).includes("Alpha") || plain(lines[firstRow]!).includes("Google"), "provider rows are capitalized");
|
|
665
665
|
|
|
666
666
|
// Thinking level -> theme slot is unit-tested in lib/ansi.ts (one definition); here we
|
|
667
667
|
// only prove the box border actually takes its color from that slot at render time.
|
|
@@ -776,20 +776,20 @@ if (isMain(import.meta.url)) {
|
|
|
776
776
|
join(fixture, "models.json"),
|
|
777
777
|
JSON.stringify({
|
|
778
778
|
providers: {
|
|
779
|
-
|
|
780
|
-
|
|
779
|
+
alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 0.28, output: 0.42, cacheRead: 0.028 } }] },
|
|
780
|
+
beta: { models: [{ id: "gemini-3.8-flash" }] },
|
|
781
781
|
},
|
|
782
782
|
}),
|
|
783
783
|
);
|
|
784
784
|
const fromModels = collectUsageSummary(true);
|
|
785
|
-
const
|
|
785
|
+
const alpha = fromModels.providers.find((p) => p.name === "alpha")!;
|
|
786
786
|
const expected = (100 / 1e6) * 0.28 + (5 / 1e6) * 0.42 + (1 / 1e6) * 0.028;
|
|
787
|
-
assert(Math.abs(
|
|
787
|
+
assert(Math.abs(alpha.estimatedCost - expected) < 1e-12, `models.json cost prices the provider, got ${alpha.estimatedCost}`);
|
|
788
788
|
assert(
|
|
789
|
-
Math.abs(
|
|
789
|
+
Math.abs(alpha.models.reduce((n, m) => n + m.estimatedCost, 0) - alpha.estimatedCost) < 1e-9,
|
|
790
790
|
"a provider's estimate is the sum of its models' estimates",
|
|
791
791
|
);
|
|
792
|
-
assert(
|
|
792
|
+
assert(alpha.models.find((m) => m.name === "other-model")!.estimatedCost === 0, "a model without a declared cost stays unpriced");
|
|
793
793
|
writeFileSync(join(fixture, "models.json"), "{}", "utf8");
|
|
794
794
|
collectUsageSummary(true);
|
|
795
795
|
|
|
@@ -800,7 +800,7 @@ if (isMain(import.meta.url)) {
|
|
|
800
800
|
(estModal as unknown as { summary: unknown }).summary = {
|
|
801
801
|
providers: [
|
|
802
802
|
{
|
|
803
|
-
name: "
|
|
803
|
+
name: "alpha", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000,
|
|
804
804
|
totalTokens: 1_500_000, cost: 0, estimatedCost: 0.546,
|
|
805
805
|
models: [{ name: "deepseek-v4.1-flash", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000, totalTokens: 1_500_000, cost: 0, estimatedCost: 0.546 }],
|
|
806
806
|
},
|
|
@@ -812,14 +812,14 @@ if (isMain(import.meta.url)) {
|
|
|
812
812
|
],
|
|
813
813
|
totals: { sessions: 2, msgs: 3, input: 3_200_000, output: 1_126_000, cacheRead: 2_000_000, totalTokens: 4_326_000, cost: 0.65, reportedCost: 0.65, estimatedCost: 0.546 },
|
|
814
814
|
};
|
|
815
|
-
(estModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["
|
|
815
|
+
(estModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["alpha"]);
|
|
816
816
|
const estLines = estModal.render(90);
|
|
817
817
|
const estBody = estLines.map(plain).join("\n");
|
|
818
818
|
assert(estBody.includes("~$0.55"), "a row with a rate but no reported cost shows the estimate with `~`");
|
|
819
819
|
assert(estBody.includes("$0.65") && !estBody.includes("~$0.65"), "a reported cost is shown as-is, never with `~`");
|
|
820
820
|
assert(estBody.includes("estimated (models.json)"), "the estimate line names models.json");
|
|
821
821
|
// Only the two table rows — the detail line also carries the estimate.
|
|
822
|
-
const estRows = estLines.map(plain).filter((l) => /^\u2502 [\u25be\u25b8 ] (
|
|
822
|
+
const estRows = estLines.map(plain).filter((l) => /^\u2502 [\u25be\u25b8 ] (Alpha|deepseek)/.test(l));
|
|
823
823
|
assert(estRows.length === 2 && estRows.every((l) => l.includes("~$0.55")), `the estimate shows on the provider row and its model row, got ${JSON.stringify(estRows)}`);
|
|
824
824
|
|
|
825
825
|
// Cost must survive every width: a clipped `$5` is worse than a dropped column.
|