@bismawy/pi-arnative 0.15.0 → 0.16.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 +19 -0
- package/README.md +52 -67
- package/extensions/animations.ts +11 -26
- package/extensions/arnative.ts +253 -380
- package/extensions/autocompact.ts +17 -22
- package/extensions/budget.ts +87 -136
- package/extensions/footer.ts +79 -60
- package/extensions/model-heal.ts +0 -0
- package/extensions/render-cache.ts +29 -15
- package/extensions/section-headers.ts +4 -8
- package/extensions/timestamps.ts +118 -41
- package/extensions/todos.ts +83 -33
- package/extensions/tools.ts +13 -30
- package/extensions/ui-render-tweaks.ts +0 -0
- package/extensions/usage-export.ts +3 -12
- package/extensions/usage.ts +0 -0
- package/lib/ansi.ts +0 -0
- package/lib/box.ts +0 -0
- package/lib/check.ts +0 -0
- package/lib/color.ts +0 -0
- package/lib/compat.ts +117 -17
- package/lib/format.ts +0 -0
- package/lib/list-picker.ts +5 -5
- package/lib/model-heal.ts +4 -8
- package/lib/patch.ts +0 -0
- package/lib/preset-store.ts +63 -16
- package/lib/provider.ts +131 -17
- package/lib/shortcuts.ts +0 -0
- package/lib/spinner.ts +1 -1
- package/lib/status-widget.ts +0 -0
- package/lib/todos.ts +0 -0
- package/lib/usage-store.ts +11 -20
- package/package.json +1 -1
- package/themes/arnative-blossom.json +0 -0
- package/themes/arnative-crimson.json +0 -0
- package/themes/arnative-cyberpunk.json +0 -0
- package/themes/arnative-dracula.json +0 -0
- package/themes/arnative-earthy.json +0 -0
- package/themes/arnative-garden.json +0 -0
- package/themes/arnative-gruvbox.json +0 -0
- package/themes/arnative-lemonade.json +0 -0
- package/themes/arnative-magical.json +0 -0
- package/themes/arnative-matrix.json +0 -0
- package/themes/arnative-neutral.json +0 -0
- package/themes/arnative-nord.json +0 -0
- package/themes/arnative-zinc.json +0 -0
- package/themes/arnative.json +0 -0
- package/themes/gen-themes.mjs +0 -0
package/extensions/todos.ts
CHANGED
|
@@ -6,12 +6,14 @@
|
|
|
6
6
|
* State lives in `<agent>/arnative/todos/<session id>.json`, so `/reload` and a resumed session
|
|
7
7
|
* keep the list; every mutation rewrites the file.
|
|
8
8
|
*/
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
9
|
+
import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
11
12
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
12
13
|
import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
13
14
|
import type { TuiMouseEvent } from "@earendil-works/pi-tui";
|
|
14
15
|
import { assert, isMain } from "../lib/check.ts";
|
|
16
|
+
import { writeAtomicSync } from "../lib/preset-store.ts";
|
|
15
17
|
import { inSpans, screenTitle, type TextSpan, textSpans } from "../lib/box.ts";
|
|
16
18
|
import { ListPicker, type ListPickerText } from "../lib/list-picker.ts";
|
|
17
19
|
import { LEGEND_READ_ONLY, SHORTCUT_SCROLL_TODOS_DOWN, SHORTCUT_SCROLL_TODOS_UP, SHORTCUT_TOGGLE_TODOS } from "../lib/shortcuts.ts";
|
|
@@ -76,10 +78,48 @@ function store(): WidgetStore {
|
|
|
76
78
|
return holder[STORE_KEY]!;
|
|
77
79
|
}
|
|
78
80
|
|
|
81
|
+
/** Completed/empty session todo files older than this are pruned on session start. */
|
|
82
|
+
const TODO_PRUNE_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
83
|
+
|
|
84
|
+
const todosDir = (): string => join(getAgentDir(), "arnative", "todos");
|
|
85
|
+
|
|
79
86
|
/** `<agent>/arnative/todos/<session id>.json` — one file per session, so two sessions in the
|
|
80
87
|
* same checkout never overwrite each other's list. */
|
|
81
88
|
const stateFile = (ctx: ExtensionContext): string =>
|
|
82
|
-
join(
|
|
89
|
+
join(todosDir(), `${ctx.sessionManager.getSessionId()}.json`);
|
|
90
|
+
|
|
91
|
+
/** Remove old todo files whose tasks are all completed (or empty) so `todos/` does not grow unbounded. */
|
|
92
|
+
export function pruneCompletedTodos(
|
|
93
|
+
dir: string = todosDir(),
|
|
94
|
+
opts: { maxAgeMs?: number; now?: number; skipFile?: string } = {},
|
|
95
|
+
): number {
|
|
96
|
+
const maxAgeMs = opts.maxAgeMs ?? TODO_PRUNE_AGE_MS;
|
|
97
|
+
const now = opts.now ?? Date.now();
|
|
98
|
+
let entries: string[];
|
|
99
|
+
try {
|
|
100
|
+
entries = readdirSync(dir);
|
|
101
|
+
} catch {
|
|
102
|
+
return 0;
|
|
103
|
+
}
|
|
104
|
+
let removed = 0;
|
|
105
|
+
for (const name of entries) {
|
|
106
|
+
if (!name.endsWith(".json")) continue;
|
|
107
|
+
const full = join(dir, name);
|
|
108
|
+
if (opts.skipFile && (full === opts.skipFile || name === opts.skipFile)) continue;
|
|
109
|
+
try {
|
|
110
|
+
if (now - statSync(full).mtimeMs < maxAgeMs) continue;
|
|
111
|
+
const parsed = normalizeState(JSON.parse(readFileSync(full, "utf8")) as unknown);
|
|
112
|
+
if (!parsed) continue;
|
|
113
|
+
if (parsed.tasks.length === 0 || allDone(parsed)) {
|
|
114
|
+
unlinkSync(full);
|
|
115
|
+
removed++;
|
|
116
|
+
}
|
|
117
|
+
} catch {
|
|
118
|
+
// leave unreadable or locked files alone
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return removed;
|
|
122
|
+
}
|
|
83
123
|
|
|
84
124
|
function loadState(ctx: ExtensionContext, reload = false): void {
|
|
85
125
|
const s = store();
|
|
@@ -98,22 +138,8 @@ function loadState(ctx: ExtensionContext, reload = false): void {
|
|
|
98
138
|
}
|
|
99
139
|
|
|
100
140
|
function saveState(ctx: ExtensionContext): void {
|
|
101
|
-
const path = stateFile(ctx);
|
|
102
141
|
try {
|
|
103
|
-
|
|
104
|
-
const payload = `${JSON.stringify(store().state, null, 2)}\n`;
|
|
105
|
-
const tmp = `${path}.${process.pid}.tmp`;
|
|
106
|
-
writeFileSync(tmp, payload, "utf8");
|
|
107
|
-
try {
|
|
108
|
-
renameSync(tmp, path);
|
|
109
|
-
} catch (error) {
|
|
110
|
-
// Windows refuses the replace while another process holds the file; an in-place
|
|
111
|
-
// write still lands, and a lost list is worse than the truncation window.
|
|
112
|
-
const code = (error as NodeJS.ErrnoException).code;
|
|
113
|
-
if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") throw error;
|
|
114
|
-
writeFileSync(path, payload, "utf8");
|
|
115
|
-
rmSync(tmp, { force: true });
|
|
116
|
-
}
|
|
142
|
+
writeAtomicSync(stateFile(ctx), `${JSON.stringify(store().state, null, 2)}\n`);
|
|
117
143
|
} catch {
|
|
118
144
|
// ignore: the list still renders from memory
|
|
119
145
|
}
|
|
@@ -302,6 +328,14 @@ function refresh(ctx: ExtensionContext, force = false): void {
|
|
|
302
328
|
holdRepeat = undefined;
|
|
303
329
|
}
|
|
304
330
|
};
|
|
331
|
+
const toggleExpanded = (): { handled: true; render: true } => {
|
|
332
|
+
s.expanded = !s.expanded;
|
|
333
|
+
s.top = null;
|
|
334
|
+
if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
|
|
335
|
+
else cancelHide(s);
|
|
336
|
+
s.tui?.requestRender(true);
|
|
337
|
+
return { handled: true, render: true };
|
|
338
|
+
};
|
|
305
339
|
/** Move the five-row window by `delta` rows and repaint. `top` stays absolute, so the
|
|
306
340
|
* window parks at the end of the list instead of drifting. */
|
|
307
341
|
const scroll = (delta: number): void => {
|
|
@@ -367,14 +401,7 @@ function refresh(ctx: ExtensionContext, force = false): void {
|
|
|
367
401
|
const onHint = inSpans(spans, event.y, event.x);
|
|
368
402
|
const onCounter = event.y === layout.up || event.y === layout.down;
|
|
369
403
|
if (!onHint && !onCounter) {
|
|
370
|
-
if (event.type === "click" && (event.clickCount ?? 1) === 1)
|
|
371
|
-
s.expanded = !s.expanded;
|
|
372
|
-
s.top = null;
|
|
373
|
-
if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
|
|
374
|
-
else cancelHide(s);
|
|
375
|
-
s.tui?.requestRender(true);
|
|
376
|
-
return { handled: true, render: true };
|
|
377
|
-
}
|
|
404
|
+
if (event.type === "click" && (event.clickCount ?? 1) === 1) return toggleExpanded();
|
|
378
405
|
return undefined;
|
|
379
406
|
}
|
|
380
407
|
// The press already did it, so the release and the click that may follow are
|
|
@@ -387,12 +414,7 @@ function refresh(ctx: ExtensionContext, force = false): void {
|
|
|
387
414
|
startHold(delta);
|
|
388
415
|
return { handled: true, render: true };
|
|
389
416
|
}
|
|
390
|
-
|
|
391
|
-
s.top = null;
|
|
392
|
-
if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
|
|
393
|
-
else cancelHide(s);
|
|
394
|
-
s.tui?.requestRender(true);
|
|
395
|
-
return { handled: true, render: true };
|
|
417
|
+
return toggleExpanded();
|
|
396
418
|
},
|
|
397
419
|
dispose: (): void => {
|
|
398
420
|
stopHold();
|
|
@@ -485,7 +507,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
485
507
|
});
|
|
486
508
|
|
|
487
509
|
pi.on("session_start", async (event, ctx) => {
|
|
488
|
-
|
|
510
|
+
const reload = (event as { reason?: string } | undefined)?.reason === "reload";
|
|
511
|
+
loadState(ctx, reload);
|
|
512
|
+
if (!reload) pruneCompletedTodos(todosDir(), { skipFile: stateFile(ctx) });
|
|
489
513
|
refresh(ctx, true);
|
|
490
514
|
});
|
|
491
515
|
|
|
@@ -583,5 +607,31 @@ if (isMain(import.meta.url)) {
|
|
|
583
607
|
// A new session with no file on disk starts empty instead of inheriting the previous session's list.
|
|
584
608
|
loadState({ sessionManager: { getSessionId: () => `empty-${process.pid}-${Date.now()}` } } as never);
|
|
585
609
|
assert(store().state.tasks.length === 0 && store().expanded === false, "session_start: a fresh session starts with an empty list");
|
|
610
|
+
// Auto-prune removes old completed/empty todo files while keeping open, recent, and active-session files.
|
|
611
|
+
const pruneTmp = mkdtempSync(join(tmpdir(), "arnative-todos-prune-"));
|
|
612
|
+
try {
|
|
613
|
+
const now = Date.now();
|
|
614
|
+
const oldSec = (now - TODO_PRUNE_AGE_MS - 60_000) / 1000;
|
|
615
|
+
const put = (name: string, data: unknown, old: boolean): string => {
|
|
616
|
+
const p = join(pruneTmp, name);
|
|
617
|
+
writeFileSync(p, JSON.stringify(data));
|
|
618
|
+
if (old) utimesSync(p, oldSec, oldSec);
|
|
619
|
+
return p;
|
|
620
|
+
};
|
|
621
|
+
put("old-done.json", { nextId: 2, tasks: [{ id: 1, subject: "a", status: "completed" }] }, true);
|
|
622
|
+
put("old-empty.json", { nextId: 1, tasks: [] }, true);
|
|
623
|
+
put("old-open.json", { nextId: 2, tasks: [{ id: 1, subject: "b", status: "pending" }] }, true);
|
|
624
|
+
put("recent-done.json", { nextId: 2, tasks: [{ id: 1, subject: "c", status: "completed" }] }, false);
|
|
625
|
+
const activePath = put("active-done.json", { nextId: 2, tasks: [{ id: 1, subject: "d", status: "completed" }] }, true);
|
|
626
|
+
const removed = pruneCompletedTodos(pruneTmp, { now, skipFile: activePath });
|
|
627
|
+
const left = readdirSync(pruneTmp).sort();
|
|
628
|
+
assert(removed === 2, `prune: expected 2 removed, got ${removed}`);
|
|
629
|
+
assert(
|
|
630
|
+
left.join(",") === "active-done.json,old-open.json,recent-done.json",
|
|
631
|
+
`prune: expected open/recent/active kept, got ${left.join(",")}`,
|
|
632
|
+
);
|
|
633
|
+
} finally {
|
|
634
|
+
rmSync(pruneTmp, { recursive: true, force: true });
|
|
635
|
+
}
|
|
586
636
|
console.log("todos extension self-check OK");
|
|
587
637
|
}
|
package/extensions/tools.ts
CHANGED
|
@@ -43,7 +43,7 @@ import { join } from "node:path";
|
|
|
43
43
|
import { inSpans, renderBoxLines as box, type TextSpan, textSpans } from "../lib/box.ts";
|
|
44
44
|
import { getActiveTheme, stripAnsi, softSecondaryOf } from "../lib/ansi.ts";
|
|
45
45
|
import { actionWord } from "../lib/todos.ts";
|
|
46
|
-
import { EDIT_DIFF_KEY,
|
|
46
|
+
import { EDIT_DIFF_KEY, choiceSetting, resetPresetCache } from "../lib/preset-store.ts";
|
|
47
47
|
import { clearRenderCache } from "./render-cache.ts";
|
|
48
48
|
import { assert, isMain } from "../lib/check.ts";
|
|
49
49
|
import { markPatched, originalOf } from "../lib/patch.ts";
|
|
@@ -982,6 +982,7 @@ function arnativeTools(pi: ExtensionAPI) {
|
|
|
982
982
|
});
|
|
983
983
|
pi.on("session_shutdown", async () => {
|
|
984
984
|
TIMINGS.clear();
|
|
985
|
+
ACTIVE = 0;
|
|
985
986
|
if (TICK) {
|
|
986
987
|
clearInterval(TICK);
|
|
987
988
|
TICK = null;
|
|
@@ -991,21 +992,18 @@ function arnativeTools(pi: ExtensionAPI) {
|
|
|
991
992
|
|
|
992
993
|
// Gap is only stripped for our own boxes (see OWN_BOX above).
|
|
993
994
|
|
|
995
|
+
const shellCall = (a: { command?: string }, _th: Theme, soft: (s: string) => string, expanded: boolean): string => {
|
|
996
|
+
const cmd = (a.command ?? "").replace(/\r?\n/g, " ").trim();
|
|
997
|
+
return paintLinks(expanded ? cmd : smartTitle(cmd), soft);
|
|
998
|
+
};
|
|
999
|
+
|
|
994
1000
|
// powershell: pi core registers it as a separate builtin (only on Windows); without
|
|
995
1001
|
// our own registration it keeps pi's "default" shell and renders as a bg block, not a
|
|
996
1002
|
// box (the same reason `bash` is re-registered below). Windows only: on any other
|
|
997
1003
|
// platform `getPowerShellConfig()` throws, and an unregistered tool would stay off
|
|
998
1004
|
// while our registration is active on load.
|
|
999
1005
|
if (process.platform === "win32")
|
|
1000
|
-
minimal(
|
|
1001
|
-
pi,
|
|
1002
|
-
createPowerShellTool(cwd),
|
|
1003
|
-
(th) => th.fg("accent", "PS>"),
|
|
1004
|
-
(a, _th, soft, expanded) => {
|
|
1005
|
-
const cmd = (a.command ?? "").replace(/\r?\n/g, " ").trim();
|
|
1006
|
-
return paintLinks(expanded ? cmd : smartTitle(cmd), soft);
|
|
1007
|
-
},
|
|
1008
|
-
);
|
|
1006
|
+
minimal(pi, createPowerShellTool(cwd), (th) => th.fg("accent", "PS>"), shellCall);
|
|
1009
1007
|
|
|
1010
1008
|
// ls: no renderShell of its own, so pi's default shell turns it into a bg block.
|
|
1011
1009
|
minimal(
|
|
@@ -1017,15 +1015,7 @@ function arnativeTools(pi: ExtensionAPI) {
|
|
|
1017
1015
|
);
|
|
1018
1016
|
|
|
1019
1017
|
// bash: ` $ <6 words>…` / `✓ $ <full title when expanded> 0.1s`
|
|
1020
|
-
minimal(
|
|
1021
|
-
pi,
|
|
1022
|
-
createBashTool(cwd),
|
|
1023
|
-
(th) => th.fg("accent", "$"),
|
|
1024
|
-
(a, _th, soft, expanded) => {
|
|
1025
|
-
const cmd = (a.command ?? "").replace(/\r?\n/g, " ").trim();
|
|
1026
|
-
return paintLinks(expanded ? cmd : smartTitle(cmd), soft);
|
|
1027
|
-
},
|
|
1028
|
-
);
|
|
1018
|
+
minimal(pi, createBashTool(cwd), (th) => th.fg("accent", "$"), shellCall);
|
|
1029
1019
|
|
|
1030
1020
|
// read: `read path[:range]` → ` N lines`
|
|
1031
1021
|
minimal(
|
|
@@ -1088,25 +1078,18 @@ function arnativeTools(pi: ExtensionAPI) {
|
|
|
1088
1078
|
);
|
|
1089
1079
|
}
|
|
1090
1080
|
|
|
1091
|
-
const EDIT_DIFF_CONFIG_KEY = Symbol.for("pi-arnative.editDiff");
|
|
1092
1081
|
const SPLIT_DIFF_MIN_WIDTH = 50;
|
|
1093
1082
|
const INTRA_LINE_MAX_TOKENS = 200;
|
|
1094
1083
|
|
|
1095
1084
|
export type EditDiffMode = "Split" | "Unified";
|
|
1096
1085
|
export const EDIT_DIFF_CHOICES: readonly EditDiffMode[] = ["Split", "Unified"];
|
|
1086
|
+
const editDiffSetting = choiceSetting(EDIT_DIFF_KEY, EDIT_DIFF_CHOICES, "Split");
|
|
1087
|
+
const EDIT_DIFF_CONFIG_KEY = editDiffSetting.slot;
|
|
1097
1088
|
|
|
1098
|
-
export
|
|
1099
|
-
const stored =
|
|
1100
|
-
(globalThis as Record<symbol, unknown>)[EDIT_DIFF_CONFIG_KEY] ??
|
|
1101
|
-
loadChoice(EDIT_DIFF_KEY, EDIT_DIFF_CHOICES);
|
|
1102
|
-
return EDIT_DIFF_CHOICES.includes(stored as EditDiffMode)
|
|
1103
|
-
? (stored as EditDiffMode)
|
|
1104
|
-
: "Split";
|
|
1105
|
-
}
|
|
1089
|
+
export const activeEditDiff = (): EditDiffMode => editDiffSetting.get();
|
|
1106
1090
|
|
|
1107
1091
|
export function setEditDiff(mode: EditDiffMode): void {
|
|
1108
|
-
(
|
|
1109
|
-
saveChoice(EDIT_DIFF_KEY, mode);
|
|
1092
|
+
editDiffSetting.set(mode);
|
|
1110
1093
|
clearRenderCache();
|
|
1111
1094
|
}
|
|
1112
1095
|
|
|
File without changes
|
|
@@ -16,8 +16,9 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
16
16
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
17
17
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
18
18
|
import { tmpdir } from "node:os";
|
|
19
|
-
import {
|
|
19
|
+
import { join } from "node:path";
|
|
20
20
|
import { assert, isMain } from "../lib/check.ts";
|
|
21
|
+
import { writeAtomicSync } from "../lib/preset-store.ts";
|
|
21
22
|
import { collectUsageSummary, resetUsageCache, type UsageSummary } from "../lib/usage-store.ts";
|
|
22
23
|
|
|
23
24
|
/** At most one write per minute, whatever the turn rate. */
|
|
@@ -77,17 +78,7 @@ export function renderProm(summary: UsageSummary, now: number): string {
|
|
|
77
78
|
* target open) falls back to an in-place write and removes its temp file — the
|
|
78
79
|
* `lib/preset-store.ts` pattern. */
|
|
79
80
|
export function writePromFile(text: string, path: string, rename: (from: string, to: string) => void = renameSync): void {
|
|
80
|
-
|
|
81
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
82
|
-
writeFileSync(tmp, text, "utf8");
|
|
83
|
-
try {
|
|
84
|
-
rename(tmp, path);
|
|
85
|
-
} catch (e) {
|
|
86
|
-
const code = (e as NodeJS.ErrnoException).code;
|
|
87
|
-
if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") throw e;
|
|
88
|
-
writeFileSync(path, text, "utf8");
|
|
89
|
-
rmSync(tmp, { force: true });
|
|
90
|
-
}
|
|
81
|
+
writeAtomicSync(path, text, rename);
|
|
91
82
|
}
|
|
92
83
|
|
|
93
84
|
let lastExportMs = 0;
|
package/extensions/usage.ts
CHANGED
|
File without changes
|
package/lib/ansi.ts
CHANGED
|
File without changes
|
package/lib/box.ts
CHANGED
|
File without changes
|
package/lib/check.ts
CHANGED
|
File without changes
|
package/lib/color.ts
CHANGED
|
File without changes
|
package/lib/compat.ts
CHANGED
|
@@ -119,32 +119,78 @@ export interface ModelMeta {
|
|
|
119
119
|
|
|
120
120
|
// Widest window first: max_model_len / max_input_tokens are upstream limits, not the
|
|
121
121
|
// served window, and some channels only publish the input side.
|
|
122
|
-
const CONTEXT_KEYS = [
|
|
123
|
-
|
|
122
|
+
const CONTEXT_KEYS = [
|
|
123
|
+
"context_length",
|
|
124
|
+
"context_window",
|
|
125
|
+
"max_context_length",
|
|
126
|
+
"max_model_len",
|
|
127
|
+
"max_context_window",
|
|
128
|
+
"max_context_window_tokens",
|
|
129
|
+
"max_input_tokens",
|
|
130
|
+
"max_input_length",
|
|
131
|
+
"context_size",
|
|
132
|
+
"inputTokenLimit",
|
|
133
|
+
"contextWindow",
|
|
134
|
+
"maxContextLength",
|
|
135
|
+
"maxModelLen",
|
|
136
|
+
"maxContextWindow",
|
|
137
|
+
"maxInputTokens",
|
|
138
|
+
"contextSize",
|
|
139
|
+
];
|
|
140
|
+
const OUTPUT_KEYS = [
|
|
141
|
+
"max_output_tokens",
|
|
142
|
+
"max_completion_tokens",
|
|
143
|
+
"max_output_length",
|
|
144
|
+
"max_tokens",
|
|
145
|
+
"outputTokenLimit",
|
|
146
|
+
"maxOutputTokens",
|
|
147
|
+
"maxCompletionTokens",
|
|
148
|
+
"maxTokens",
|
|
149
|
+
];
|
|
150
|
+
|
|
151
|
+
const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
124
152
|
|
|
125
153
|
const positiveInt = (value: unknown): number | undefined => {
|
|
126
154
|
const n = typeof value === "string" && value.trim() ? Number(value.trim()) : value;
|
|
127
155
|
return typeof n === "number" && Number.isFinite(n) && n > 0 ? Math.floor(n) : undefined;
|
|
128
156
|
};
|
|
129
157
|
|
|
130
|
-
/** Numeric limits from one catalog entry. */
|
|
158
|
+
/** Numeric limits from one catalog entry (top-level or nested `top_provider` / `limit` / `limits` / `capabilities.limits`). */
|
|
131
159
|
export function parseMeta(entry: unknown): ModelMeta {
|
|
132
|
-
const rec = (entry
|
|
160
|
+
const rec = isRecord(entry) ? entry : {};
|
|
161
|
+
const sources: Record<string, unknown>[] = [rec];
|
|
162
|
+
for (const nested of [rec.top_provider, rec.limit, rec.limits, isRecord(rec.capabilities) ? rec.capabilities.limits : undefined]) {
|
|
163
|
+
if (isRecord(nested)) sources.push(nested);
|
|
164
|
+
}
|
|
133
165
|
const out: ModelMeta = {};
|
|
134
|
-
for (const
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
166
|
+
for (const src of sources) {
|
|
167
|
+
for (const key of CONTEXT_KEYS) {
|
|
168
|
+
const value = positiveInt(src[key]);
|
|
169
|
+
if (value !== undefined) {
|
|
170
|
+
out.contextWindow = value;
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (out.contextWindow === undefined && (src === rec.limit || src === rec.limits)) {
|
|
175
|
+
const value = positiveInt(src.context);
|
|
176
|
+
if (value !== undefined) out.contextWindow = value;
|
|
139
177
|
}
|
|
178
|
+
if (out.contextWindow !== undefined) break;
|
|
140
179
|
}
|
|
141
|
-
for (const
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
180
|
+
for (const src of sources) {
|
|
181
|
+
for (const key of OUTPUT_KEYS) {
|
|
182
|
+
const value = positiveInt(src[key]);
|
|
183
|
+
if (value === undefined) continue;
|
|
184
|
+
// A "max_tokens" equal to the whole window is the context length, not a cap.
|
|
185
|
+
if (out.contextWindow !== undefined && value >= out.contextWindow) continue;
|
|
186
|
+
out.maxTokens = value;
|
|
187
|
+
break;
|
|
188
|
+
}
|
|
189
|
+
if (out.maxTokens === undefined && (src === rec.limit || src === rec.limits)) {
|
|
190
|
+
const value = positiveInt(src.output);
|
|
191
|
+
if (value !== undefined && (out.contextWindow === undefined || value < out.contextWindow)) out.maxTokens = value;
|
|
192
|
+
}
|
|
193
|
+
if (out.maxTokens !== undefined) break;
|
|
148
194
|
}
|
|
149
195
|
return out;
|
|
150
196
|
}
|
|
@@ -179,13 +225,55 @@ export function mergeMeta(prev: ModelMeta | undefined, next: ModelMeta): ModelMe
|
|
|
179
225
|
const out: ModelMeta = { ...prev };
|
|
180
226
|
const ctx = next.contextWindow;
|
|
181
227
|
if (ctx !== undefined && contextWindowAccepted(ctx, prev?.contextWindow)) out.contextWindow = ctx;
|
|
182
|
-
const effective =
|
|
228
|
+
const effective = out.contextWindow;
|
|
183
229
|
if (next.maxTokens !== undefined && (prev?.maxTokens === undefined || next.maxTokens > prev.maxTokens)) {
|
|
184
230
|
out.maxTokens = effective !== undefined && next.maxTokens > effective ? effective : next.maxTokens;
|
|
185
231
|
}
|
|
186
232
|
return out;
|
|
187
233
|
}
|
|
188
234
|
|
|
235
|
+
export interface CatalogIndex {
|
|
236
|
+
exact: Map<string, ModelMeta>;
|
|
237
|
+
bare: Map<string, ModelMeta>;
|
|
238
|
+
stripped: Map<string, ModelMeta>;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const bareModelName = (id: string): string => {
|
|
242
|
+
const lower = id.trim().toLowerCase();
|
|
243
|
+
const slash = lower.lastIndexOf("/");
|
|
244
|
+
return slash >= 0 ? lower.slice(slash + 1) : lower;
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
const stripVariantSuffix = (name: string): string => name.replace(/(?::(?:free|exacto|thinking)|-(?:fp8|fp16|bf16|int8|int4|awq|gptq))$/i, "");
|
|
248
|
+
|
|
249
|
+
const putPreferLarger = (map: Map<string, ModelMeta>, key: string, meta: ModelMeta): void => {
|
|
250
|
+
if (!key || meta.contextWindow === undefined) return;
|
|
251
|
+
const prev = map.get(key);
|
|
252
|
+
if (!prev || (prev.contextWindow ?? 0) < meta.contextWindow) map.set(key, meta);
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
/** Index model metadata by exact id, bare name (after `/`), and variant-stripped name for fallback lookup. */
|
|
256
|
+
export function buildCatalogIndex(entries: Iterable<[string, ModelMeta]>): CatalogIndex {
|
|
257
|
+
const index: CatalogIndex = { exact: new Map(), bare: new Map(), stripped: new Map() };
|
|
258
|
+
for (const [id, meta] of entries) {
|
|
259
|
+
if (meta.contextWindow === undefined) continue;
|
|
260
|
+
const exactKey = id.trim().toLowerCase();
|
|
261
|
+
const bare = bareModelName(id);
|
|
262
|
+
const stripped = stripVariantSuffix(bare);
|
|
263
|
+
putPreferLarger(index.exact, exactKey, meta);
|
|
264
|
+
putPreferLarger(index.bare, bare, meta);
|
|
265
|
+
putPreferLarger(index.stripped, stripped, meta);
|
|
266
|
+
}
|
|
267
|
+
return index;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Look up fallback `contextWindow` / `maxTokens` for a model id by exact, bare, or variant-stripped name. */
|
|
271
|
+
export function findMetaForId(id: string, index: CatalogIndex): ModelMeta | undefined {
|
|
272
|
+
const exactKey = id.trim().toLowerCase();
|
|
273
|
+
const bare = bareModelName(id);
|
|
274
|
+
return index.exact.get(exactKey) ?? index.bare.get(bare) ?? index.stripped.get(stripVariantSuffix(bare));
|
|
275
|
+
}
|
|
276
|
+
|
|
189
277
|
// ------------------------------------------------------- thinking effort
|
|
190
278
|
|
|
191
279
|
// pi's levels in clamp order; `off` has no wire name of its own.
|
|
@@ -362,6 +450,18 @@ if (isMain(import.meta.url)) {
|
|
|
362
450
|
assert(!contextWindowAccepted(8192, 1_000_000), "a per-request number is rejected");
|
|
363
451
|
assert(mergeMeta({ maxTokens: 4096 }, { maxTokens: 8192 }).maxTokens === 8192, "an output cap only grows");
|
|
364
452
|
assert(mergeMeta({ contextWindow: 1024 }, { maxTokens: 8192 }).maxTokens === 1024, "a cap above the window clamps to the window");
|
|
453
|
+
assert(mergeMeta({ contextWindow: 200_000 }, { contextWindow: 4096, maxTokens: 32_000 }).maxTokens === 32_000, "a rejected anomaly window does not clamp maxTokens");
|
|
454
|
+
|
|
455
|
+
// Nested shapes (Gemini inputTokenLimit, OpenRouter top_provider, models.dev limit) and fallback index.
|
|
456
|
+
assert(parseMeta({ inputTokenLimit: 1_048_576, outputTokenLimit: 65_536 }).contextWindow === 1_048_576, "gemini inputTokenLimit parses");
|
|
457
|
+
assert(parseMeta({ top_provider: { context_length: 200_000, max_completion_tokens: 16_384 } }).contextWindow === 200_000, "nested top_provider parses");
|
|
458
|
+
assert(parseMeta({ limit: { context: 262_144, output: 32_768 } }).maxTokens === 32_768, "nested limit.context/output parses");
|
|
459
|
+
const idx = buildCatalogIndex([
|
|
460
|
+
["z-ai/glm-5.3-flash", { contextWindow: 1_000_000, maxTokens: 131_072 }],
|
|
461
|
+
["qwen/qwen3.8-27b", { contextWindow: 262_144, maxTokens: 32_768 }],
|
|
462
|
+
]);
|
|
463
|
+
assert(findMetaForId("zai-org/GLM-5.3-Flash", idx)?.contextWindow === 1_000_000, "vendor prefix difference still matches bare name");
|
|
464
|
+
assert(findMetaForId("Qwen/Qwen3.8-27B-FP8", idx)?.contextWindow === 262_144, "quantization suffix strips for fallback lookup");
|
|
365
465
|
|
|
366
466
|
assert(buildEffortMap([]) === undefined, "nothing answered writes nothing");
|
|
367
467
|
const exact = buildEffortMap(["none", "low", "high", "max"])!;
|
package/lib/format.ts
CHANGED
|
File without changes
|
package/lib/list-picker.ts
CHANGED
|
@@ -5,11 +5,11 @@
|
|
|
5
5
|
* can import it without importing the settings menu back (no import cycle).
|
|
6
6
|
*/
|
|
7
7
|
import { Input, matchesKey, truncateToWidth, visibleWidth, type Component, type Focusable } from "@earendil-works/pi-tui";
|
|
8
|
-
import { softOf, thinkingColorOf } from "
|
|
9
|
-
import { renderScreen, screenTitle, type ScreenText } from "
|
|
10
|
-
import { assert, isMain } from "
|
|
11
|
-
import { ROW_DIVIDER } from "
|
|
12
|
-
import { LEGEND_LIVE, LEGEND_MOVE, LEGEND_ROOT, matchesBack } from "
|
|
8
|
+
import { softOf, thinkingColorOf } from "./ansi.ts";
|
|
9
|
+
import { renderScreen, screenTitle, type ScreenText } from "./box.ts";
|
|
10
|
+
import { assert, isMain } from "./check.ts";
|
|
11
|
+
import { ROW_DIVIDER } from "./format.ts";
|
|
12
|
+
import { LEGEND_LIVE, LEGEND_MOVE, LEGEND_ROOT, matchesBack } from "./shortcuts.ts";
|
|
13
13
|
|
|
14
14
|
// Legends come from the `KeySet`s the handlers match, so a key cannot be advertised on a
|
|
15
15
|
// screen that does not handle it; the root menu has nothing behind it and omits `←`.
|
package/lib/model-heal.ts
CHANGED
|
@@ -15,9 +15,9 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
17
17
|
import { execSync } from "node:child_process";
|
|
18
|
-
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync,
|
|
18
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
19
19
|
import { tmpdir } from "node:os";
|
|
20
|
-
import {
|
|
20
|
+
import { join } from "node:path";
|
|
21
21
|
import { assert, isMain } from "./check.ts";
|
|
22
22
|
import {
|
|
23
23
|
buildEffortMap,
|
|
@@ -32,7 +32,7 @@ import {
|
|
|
32
32
|
type CompatModel,
|
|
33
33
|
type ModelMeta,
|
|
34
34
|
} from "./compat.ts";
|
|
35
|
-
import { loadChoice, saveChoice } from "./preset-store.ts";
|
|
35
|
+
import { loadChoice, saveChoice, writeAtomicSync } from "./preset-store.ts";
|
|
36
36
|
import { levelToWire, loadModelsConfig, looseJsonParse, readAuthKey, saveModelsConfig, wireToLevel } from "./provider.ts";
|
|
37
37
|
|
|
38
38
|
// ------------------------------------------------------------- setting
|
|
@@ -283,11 +283,7 @@ function loadState(): HealState {
|
|
|
283
283
|
function saveState(part: Partial<Omit<HealState, "schema">>): void {
|
|
284
284
|
try {
|
|
285
285
|
const state = { ...loadState(), ...part };
|
|
286
|
-
|
|
287
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
288
|
-
const tmp = `${path}.${process.pid}.tmp`;
|
|
289
|
-
writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, "utf8");
|
|
290
|
-
renameSync(tmp, path);
|
|
286
|
+
writeAtomicSync(statePath(), `${JSON.stringify(state, null, 2)}\n`);
|
|
291
287
|
} catch {
|
|
292
288
|
// best effort: a lost stamp only costs one extra request next run
|
|
293
289
|
}
|
package/lib/patch.ts
CHANGED
|
File without changes
|
package/lib/preset-store.ts
CHANGED
|
@@ -114,6 +114,37 @@ function ordered(record: Record<string, unknown>): Record<string, unknown> {
|
|
|
114
114
|
return out;
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
+
/**
|
|
118
|
+
* Write UTF-8 text atomically via temp file + rename.
|
|
119
|
+
* Falls back to an in-place write on Windows EPERM/EBUSY/EXDEV lock errors and always
|
|
120
|
+
* cleans up its temp file when rename fails.
|
|
121
|
+
*/
|
|
122
|
+
export function writeAtomicSync(
|
|
123
|
+
path: string,
|
|
124
|
+
payload: string,
|
|
125
|
+
rename: (from: string, to: string) => void = renameSync,
|
|
126
|
+
): void {
|
|
127
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
128
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
129
|
+
writeFileSync(tmp, payload, "utf8");
|
|
130
|
+
try {
|
|
131
|
+
rename(tmp, path);
|
|
132
|
+
} catch (e) {
|
|
133
|
+
// Windows: a running pi session can hold the file open, and then the atomic
|
|
134
|
+
// replace fails with EPERM while an in-place write still lands.
|
|
135
|
+
const code = (e as NodeJS.ErrnoException).code;
|
|
136
|
+
if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") {
|
|
137
|
+
rmSync(tmp, { force: true });
|
|
138
|
+
throw e;
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
writeFileSync(path, payload, "utf8");
|
|
142
|
+
} finally {
|
|
143
|
+
rmSync(tmp, { force: true });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
117
148
|
/** Store a choice. Best effort: an unwritable agent dir must not break the TUI. */
|
|
118
149
|
export function saveChoice(key: string, value: string, rename: (from: string, to: string) => void = renameSync): void {
|
|
119
150
|
readConfig();
|
|
@@ -126,22 +157,7 @@ export function saveChoice(key: string, value: string, rename: (from: string, to
|
|
|
126
157
|
if (record[key] === value) return;
|
|
127
158
|
memo = { ...record, [key]: value };
|
|
128
159
|
try {
|
|
129
|
-
|
|
130
|
-
const tmp = `${path}.${process.pid}.tmp`;
|
|
131
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
132
|
-
const payload = `${JSON.stringify(ordered(memo), null, 2)}\n`;
|
|
133
|
-
writeFileSync(tmp, payload, "utf8");
|
|
134
|
-
try {
|
|
135
|
-
rename(tmp, path);
|
|
136
|
-
} catch (e) {
|
|
137
|
-
// Windows: a running pi session can hold config.json open, and then the atomic
|
|
138
|
-
// replace fails with EPERM while an in-place write still lands. A setting that
|
|
139
|
-
// silently never reaches disk is worse than the small truncation window here.
|
|
140
|
-
const code = (e as NodeJS.ErrnoException).code;
|
|
141
|
-
if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") throw e;
|
|
142
|
-
writeFileSync(path, payload, "utf8");
|
|
143
|
-
rmSync(tmp, { force: true });
|
|
144
|
-
}
|
|
160
|
+
writeAtomicSync(configPath(), `${JSON.stringify(ordered(memo), null, 2)}\n`, rename);
|
|
145
161
|
} catch {
|
|
146
162
|
process.emitWarning("Arnative settings were not saved; the choice applies only to this session.", { code: "ARNATIVE_PRESET_SAVE" });
|
|
147
163
|
}
|
|
@@ -158,6 +174,37 @@ export function ensureChoices(values: Record<string, string>): void {
|
|
|
158
174
|
for (const [key, value] of Object.entries(values)) saveChoice(key, value);
|
|
159
175
|
}
|
|
160
176
|
|
|
177
|
+
/** Reload-safe choice setting backed by globalThis[Symbol.for("pi-arnative.<key>")] + config.json. */
|
|
178
|
+
export function choiceSetting<T extends string>(
|
|
179
|
+
key: string,
|
|
180
|
+
allowed: readonly T[],
|
|
181
|
+
fallback: T,
|
|
182
|
+
): { readonly slot: symbol; get(): T; set(value: T): void } {
|
|
183
|
+
const slot = Symbol.for(`pi-arnative.${key}`);
|
|
184
|
+
const g = globalThis as Record<symbol, unknown>;
|
|
185
|
+
return {
|
|
186
|
+
slot,
|
|
187
|
+
get: () => {
|
|
188
|
+
const stored = g[slot] ?? loadChoice(key, allowed);
|
|
189
|
+
return allowed.includes(stored as T) ? (stored as T) : fallback;
|
|
190
|
+
},
|
|
191
|
+
set: (value: T) => {
|
|
192
|
+
g[slot] = value;
|
|
193
|
+
saveChoice(key, value);
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Reload-safe boolean ("on"/"off") setting backed by globalThis + config.json. */
|
|
199
|
+
export function flagSetting(key: string): { readonly slot: symbol; get(): boolean; set(on: boolean): void } {
|
|
200
|
+
const base = choiceSetting(key, ["on", "off"] as const, "off");
|
|
201
|
+
return {
|
|
202
|
+
slot: base.slot,
|
|
203
|
+
get: () => base.get() === "on",
|
|
204
|
+
set: (on: boolean) => base.set(on ? "on" : "off"),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
161
208
|
/** Drop the in-memory copy so the next read hits disk (a restart, in a test). */
|
|
162
209
|
export function resetPresetCache(): void {
|
|
163
210
|
memo = null;
|