@bismawy/pi-arnative 0.15.0 → 0.16.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 +14 -0
- package/README.md +52 -67
- package/extensions/animations.ts +11 -26
- package/extensions/arnative.ts +253 -380
- package/extensions/autocompact.ts +5 -12
- package/extensions/budget.ts +87 -136
- package/extensions/footer.ts +27 -45
- package/extensions/render-cache.ts +5 -11
- package/extensions/section-headers.ts +4 -8
- package/extensions/todos.ts +83 -33
- package/extensions/tools.ts +13 -30
- package/extensions/usage-export.ts +3 -12
- package/lib/compat.ts +117 -17
- package/lib/list-picker.ts +5 -5
- package/lib/model-heal.ts +4 -8
- package/lib/preset-store.ts +63 -16
- package/lib/provider.ts +131 -17
- package/lib/spinner.ts +1 -1
- package/lib/usage-store.ts +11 -20
- package/package.json +1 -1
package/lib/provider.ts
CHANGED
|
@@ -9,13 +9,14 @@
|
|
|
9
9
|
import { matchesKey, visibleWidth } from "@earendil-works/pi-tui";
|
|
10
10
|
import type { ExtensionCommandContext, Theme, TUI } from "@earendil-works/pi-coding-agent";
|
|
11
11
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
12
|
-
import { mkdirSync, mkdtempSync, readdirSync, readFileSync,
|
|
12
|
+
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
|
13
13
|
import { tmpdir } from "node:os";
|
|
14
|
-
import {
|
|
15
|
-
import { assert, isMain } from "
|
|
16
|
-
import { buildEffortMap, isEffortProbeable, mergeMeta, parseModelMeta, probeEffort, suggestCompat, type Compat, type ModelMeta } from "./compat.ts";
|
|
17
|
-
import { screenTitle, type ScreenText } from "
|
|
18
|
-
import { stripAnsi } from "
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { assert, isMain } from "./check.ts";
|
|
16
|
+
import { buildCatalogIndex, buildEffortMap, findMetaForId, isEffortProbeable, mergeMeta, parseModelMeta, probeEffort, suggestCompat, type CatalogIndex, type Compat, type ModelMeta } from "./compat.ts";
|
|
17
|
+
import { screenTitle, type ScreenText } from "./box.ts";
|
|
18
|
+
import { stripAnsi } from "./ansi.ts";
|
|
19
|
+
import { writeAtomicSync } from "./preset-store.ts";
|
|
19
20
|
import { announce, statusRows } from "./status-widget.ts";
|
|
20
21
|
import { INPUT_LEGEND, InputPicker, LIST_LEGEND_MOVE, ListPicker, rowText, type ListRow } from "./list-picker.ts";
|
|
21
22
|
|
|
@@ -384,6 +385,80 @@ function wireModels(name: string, provider: { api?: unknown; baseUrl?: unknown }
|
|
|
384
385
|
/** A stored selection keeps its level; a new id gets the detected one. A probed limit is
|
|
385
386
|
* merged into the stored one, and a probed effort map travels with the level, so a reselect
|
|
386
387
|
* never loses what an earlier probe learned (an `auto` level serializes without a map). */
|
|
388
|
+
const PUBLIC_CATALOG_URL = "https://openrouter.ai/api/v1/models";
|
|
389
|
+
const PUBLIC_CATALOG_TTL_MS = 60 * 60 * 1000;
|
|
390
|
+
let publicCatalogCache: { index: CatalogIndex; at: number } | undefined;
|
|
391
|
+
|
|
392
|
+
type RegistryLike = { getAll?: () => readonly { id?: unknown; contextWindow?: unknown; maxTokens?: unknown }[] };
|
|
393
|
+
|
|
394
|
+
async function fetchPublicCatalog(fetchImpl: FetchLike, timeoutMs = 5_000): Promise<CatalogIndex | undefined> {
|
|
395
|
+
if (fetchImpl === fetch && publicCatalogCache && Date.now() - publicCatalogCache.at < PUBLIC_CATALOG_TTL_MS) {
|
|
396
|
+
return publicCatalogCache.index;
|
|
397
|
+
}
|
|
398
|
+
try {
|
|
399
|
+
const res = await fetchImpl(PUBLIC_CATALOG_URL, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
|
|
400
|
+
if (!res.ok) return undefined;
|
|
401
|
+
const parsed = parseModelMeta(await res.json());
|
|
402
|
+
const index = buildCatalogIndex(parsed);
|
|
403
|
+
if (fetchImpl === fetch) publicCatalogCache = { index, at: Date.now() };
|
|
404
|
+
return index;
|
|
405
|
+
} catch {
|
|
406
|
+
return undefined;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Fill missing `contextWindow` (and `maxTokens`) for picked models from pi's local
|
|
411
|
+
* model registry first, then from OpenRouter's public catalog if any still lack one. */
|
|
412
|
+
export async function resolveMissingMeta(
|
|
413
|
+
ids: readonly string[],
|
|
414
|
+
baseMeta: Map<string, ModelMeta> | undefined,
|
|
415
|
+
ctx: { modelRegistry?: RegistryLike } | undefined,
|
|
416
|
+
fetchImpl: FetchLike = fetch,
|
|
417
|
+
): Promise<Map<string, ModelMeta>> {
|
|
418
|
+
const out = new Map<string, ModelMeta>(baseMeta ?? []);
|
|
419
|
+
let missing = ids.filter((id) => out.get(id)?.contextWindow === undefined);
|
|
420
|
+
if (missing.length === 0) return out;
|
|
421
|
+
|
|
422
|
+
// Tier 1: pi's built-in catalog and already-configured providers (instant, offline).
|
|
423
|
+
try {
|
|
424
|
+
const all = ctx?.modelRegistry?.getAll?.() ?? [];
|
|
425
|
+
const entries: [string, ModelMeta][] = [];
|
|
426
|
+
for (const m of all) {
|
|
427
|
+
if (typeof m?.id !== "string" || typeof m.contextWindow !== "number" || m.contextWindow <= 0) continue;
|
|
428
|
+
entries.push([m.id, { contextWindow: m.contextWindow, ...(typeof m.maxTokens === "number" && m.maxTokens > 0 ? { maxTokens: m.maxTokens } : {}) }]);
|
|
429
|
+
}
|
|
430
|
+
if (entries.length > 0) {
|
|
431
|
+
const localIdx = buildCatalogIndex(entries);
|
|
432
|
+
for (const id of missing) {
|
|
433
|
+
const found = findMetaForId(id, localIdx);
|
|
434
|
+
if (found) out.set(id, mergeMeta(out.get(id), found));
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
} catch {
|
|
438
|
+
// Stale or partial registry must never block saving a provider.
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
missing = ids.filter((id) => out.get(id)?.contextWindow === undefined);
|
|
442
|
+
if (missing.length === 0) return out;
|
|
443
|
+
|
|
444
|
+
// Tier 2: public model catalog for open/commercial models not yet in local registry.
|
|
445
|
+
const publicIdx = await fetchPublicCatalog(fetchImpl);
|
|
446
|
+
if (publicIdx) {
|
|
447
|
+
for (const id of missing) {
|
|
448
|
+
const found = findMetaForId(id, publicIdx);
|
|
449
|
+
if (found) out.set(id, mergeMeta(out.get(id), found));
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return out;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const seedMeta = (entry: ProviderEntry, extra?: Map<string, ModelMeta>): Map<string, ModelMeta> => {
|
|
456
|
+
const out = new Map<string, ModelMeta>();
|
|
457
|
+
for (const m of entry.models) if (m.meta) out.set(m.id, m.meta);
|
|
458
|
+
if (extra) for (const [id, meta] of extra) out.set(id, mergeMeta(out.get(id), meta));
|
|
459
|
+
return out;
|
|
460
|
+
};
|
|
461
|
+
|
|
387
462
|
export function mergeLevels(entry: ProviderEntry, ids: string[], meta?: Map<string, ModelMeta>): ProviderModel[] {
|
|
388
463
|
return ids.map((id) => {
|
|
389
464
|
const existing = entry.models.find((m) => m.id === id);
|
|
@@ -420,14 +495,7 @@ function readJson(path: string): unknown {
|
|
|
420
495
|
}
|
|
421
496
|
|
|
422
497
|
function writeJson(path: string, value: unknown): void {
|
|
423
|
-
|
|
424
|
-
// Temp + rename, the package's own standard (preset-store.ts, usage-store.ts): a crash
|
|
425
|
-
// mid-write must never truncate models.json or auth.json — a corrupted auth.json breaks
|
|
426
|
-
// the stored credentials of every provider, and the wizard refuses to save until it is
|
|
427
|
-
// repaired by hand.
|
|
428
|
-
const tmp = `${path}.${process.pid}.tmp`;
|
|
429
|
-
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
430
|
-
renameSync(tmp, path);
|
|
498
|
+
writeAtomicSync(path, `${JSON.stringify(value, null, 2)}\n`);
|
|
431
499
|
}
|
|
432
500
|
|
|
433
501
|
export function loadModelsConfig(): unknown {
|
|
@@ -706,11 +774,19 @@ const addProviderFlow = async (ctx: ExtensionCommandContext): Promise<void> => {
|
|
|
706
774
|
return;
|
|
707
775
|
}
|
|
708
776
|
|
|
777
|
+
probingStatus(ctx, "resolving context limits…");
|
|
778
|
+
let resolvedMeta: Map<string, ModelMeta>;
|
|
779
|
+
try {
|
|
780
|
+
resolvedMeta = await resolveMissingMeta(picked, result?.meta, ctx as never);
|
|
781
|
+
} finally {
|
|
782
|
+
probingStatus(ctx, undefined);
|
|
783
|
+
}
|
|
784
|
+
|
|
709
785
|
const entry: ProviderEntry = {
|
|
710
786
|
name,
|
|
711
787
|
baseUrl: chatBaseUrl(flavor, endpoint),
|
|
712
788
|
api: flavor,
|
|
713
|
-
models: mergeLevels({ name, baseUrl: chatBaseUrl(flavor, endpoint), api: flavor, models: [] }, picked,
|
|
789
|
+
models: mergeLevels({ name, baseUrl: chatBaseUrl(flavor, endpoint), api: flavor, models: [] }, picked, resolvedMeta),
|
|
714
790
|
};
|
|
715
791
|
// A keyless endpoint still needs a resolvable credential for pi to list the models.
|
|
716
792
|
if (!key) entry.apiKey = result?.keyless ? "ollama" : "dummy";
|
|
@@ -814,7 +890,14 @@ const selectModelsFlow = async (ctx: ExtensionCommandContext, name: string, entr
|
|
|
814
890
|
if (answer === undefined || answer === "") return;
|
|
815
891
|
picked = answer.split(/[\s,]+/).filter(Boolean);
|
|
816
892
|
}
|
|
817
|
-
|
|
893
|
+
probingStatus(ctx, "resolving context limits…");
|
|
894
|
+
let resolvedMeta: Map<string, ModelMeta>;
|
|
895
|
+
try {
|
|
896
|
+
resolvedMeta = await resolveMissingMeta(picked, seedMeta(entry), ctx as never);
|
|
897
|
+
} finally {
|
|
898
|
+
probingStatus(ctx, undefined);
|
|
899
|
+
}
|
|
900
|
+
await saveModelsNamed(ctx, name, mergeLevels(entry, picked, resolvedMeta));
|
|
818
901
|
};
|
|
819
902
|
|
|
820
903
|
const probeModelsFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
|
|
@@ -844,7 +927,14 @@ const probeModelsFlow = async (ctx: ExtensionCommandContext, name: string, entry
|
|
|
844
927
|
if (answer === undefined || answer === "") return;
|
|
845
928
|
picked = answer.split(/[\s,]+/).filter(Boolean);
|
|
846
929
|
}
|
|
847
|
-
|
|
930
|
+
probingStatus(ctx, "resolving context limits…");
|
|
931
|
+
let resolvedMeta: Map<string, ModelMeta>;
|
|
932
|
+
try {
|
|
933
|
+
resolvedMeta = await resolveMissingMeta(picked, seedMeta(entry, result.meta), ctx as never);
|
|
934
|
+
} finally {
|
|
935
|
+
probingStatus(ctx, undefined);
|
|
936
|
+
}
|
|
937
|
+
await saveModelsNamed(ctx, name, mergeLevels(entry, picked, resolvedMeta));
|
|
848
938
|
};
|
|
849
939
|
|
|
850
940
|
const THINKING_LEGEND = "[/] Filter [Space] Off/auto [0-6] Set level [p] Probe [a/r] All auto/off [Enter] Save [Esc] Back";
|
|
@@ -876,6 +966,7 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
|
|
|
876
966
|
let warn: string | undefined;
|
|
877
967
|
let refresh: () => void = () => {};
|
|
878
968
|
let closed = false;
|
|
969
|
+
let probeAbort: AbortController | undefined;
|
|
879
970
|
const cycle = (label: string): void => {
|
|
880
971
|
levels.set(label, levels.get(label) === "off" ? "auto" : "off");
|
|
881
972
|
};
|
|
@@ -901,6 +992,9 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
|
|
|
901
992
|
}
|
|
902
993
|
busy = label;
|
|
903
994
|
progress = "starting…";
|
|
995
|
+
probeAbort?.abort();
|
|
996
|
+
const controller = new AbortController();
|
|
997
|
+
probeAbort = controller;
|
|
904
998
|
refresh();
|
|
905
999
|
try {
|
|
906
1000
|
const supported = await probeEffort(
|
|
@@ -908,12 +1002,14 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
|
|
|
908
1002
|
{
|
|
909
1003
|
baseUrl: entry.baseUrl,
|
|
910
1004
|
key: readAuthKey(name) ?? inlineKey(entry),
|
|
1005
|
+
signal: controller.signal,
|
|
911
1006
|
onLevel: (level, _accepted, index) => {
|
|
912
1007
|
progress = `${level} · ${index + 1}/7`;
|
|
913
1008
|
refresh();
|
|
914
1009
|
},
|
|
915
1010
|
},
|
|
916
1011
|
);
|
|
1012
|
+
if (controller.signal.aborted) return;
|
|
917
1013
|
if (supported.length === 0) {
|
|
918
1014
|
warn = `${label}: no effort level answered — the map is unchanged.`;
|
|
919
1015
|
return;
|
|
@@ -922,7 +1018,10 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
|
|
|
922
1018
|
probed.set(label, next);
|
|
923
1019
|
levels.set(label, "auto");
|
|
924
1020
|
warn = `${label}: accepts ${summary(next)}.`;
|
|
1021
|
+
} catch (err) {
|
|
1022
|
+
if (!controller.signal.aborted) throw err;
|
|
925
1023
|
} finally {
|
|
1024
|
+
if (probeAbort === controller) probeAbort = undefined;
|
|
926
1025
|
busy = undefined;
|
|
927
1026
|
progress = undefined;
|
|
928
1027
|
refresh();
|
|
@@ -936,6 +1035,7 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
|
|
|
936
1035
|
};
|
|
937
1036
|
const close = (value: boolean | null) => {
|
|
938
1037
|
closed = true;
|
|
1038
|
+
probeAbort?.abort();
|
|
939
1039
|
done(value);
|
|
940
1040
|
};
|
|
941
1041
|
const picker = new ListPicker(
|
|
@@ -1497,6 +1597,20 @@ if (isMain(import.meta.url)) {
|
|
|
1497
1597
|
assert(providerNames(loadModelsConfig()).join() === "t1", "the previous config survives the interrupted save");
|
|
1498
1598
|
assert(readAuthKey("t2") === undefined, "the interrupted save never reached auth.json");
|
|
1499
1599
|
rmSync(blockedTmp, { recursive: true, force: true });
|
|
1600
|
+
|
|
1601
|
+
// Automatic contextWindow fallback: probed > local modelRegistry > public catalog.
|
|
1602
|
+
const resolved = await resolveMissingMeta(
|
|
1603
|
+
["probed-m", "zai-org/GLM-5.3-Flash", "public/only-model", "unknown-model"],
|
|
1604
|
+
new Map([["probed-m", { contextWindow: 64_000 }]]),
|
|
1605
|
+
{ modelRegistry: { getAll: () => [{ id: "remote/river/zai-org/GLM-5.3-Flash", contextWindow: 1_000_000, maxTokens: 131_072 }] } },
|
|
1606
|
+
route({ "/api/v1/models": { data: [{ id: "public/only-model", context_length: 200_000, top_provider: { max_completion_tokens: 16_384 } }] } }),
|
|
1607
|
+
);
|
|
1608
|
+
assert(resolved.get("probed-m")?.contextWindow === 64_000, "a probed contextWindow stays untouched");
|
|
1609
|
+
assert(resolved.get("zai-org/GLM-5.3-Flash")?.contextWindow === 1_000_000, "missing window falls back to local modelRegistry");
|
|
1610
|
+
assert(resolved.get("public/only-model")?.contextWindow === 200_000 && resolved.get("public/only-model")?.maxTokens === 16_384, "still-missing window falls back to public catalog");
|
|
1611
|
+
assert(resolved.get("unknown-model") === undefined, "unknown models stay undefined without throwing");
|
|
1612
|
+
const offline = await resolveMissingMeta(["x"], undefined, undefined, (async () => { throw new Error("offline"); }) as unknown as typeof fetch);
|
|
1613
|
+
assert(offline.size === 0, "an offline public catalog failure degrades cleanly");
|
|
1500
1614
|
assert(readdirSync(tmp).every((f) => !f.endsWith(".tmp")), "a completed save leaves no temp files behind");
|
|
1501
1615
|
// Edit writes: the key moves to auth.json and leaves models.json, so the secret lives in
|
|
1502
1616
|
// one place; an env reference is configuration and stays put.
|
package/lib/spinner.ts
CHANGED
|
@@ -310,7 +310,7 @@ if (isMain(import.meta.url)) {
|
|
|
310
310
|
const def = SPINNER_PRESET_DEFS[p];
|
|
311
311
|
assert(def.note.length > 0, `${p} carries a picker note`);
|
|
312
312
|
for (const frame of def.frames) {
|
|
313
|
-
assert(
|
|
313
|
+
assert(!/[\ufffd\ue000-\uf8ff]/.test(frame), `${p}: frame ${frame} is not a blank private-use cell`);
|
|
314
314
|
}
|
|
315
315
|
if (def.frames.length > 0) {
|
|
316
316
|
assert(def.intervalMs > 0, `${p} with frames must set an interval`);
|
package/lib/usage-store.ts
CHANGED
|
@@ -20,6 +20,7 @@ import { tmpdir } from "node:os";
|
|
|
20
20
|
import { join, relative } from "node:path";
|
|
21
21
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
22
22
|
import { assert, isMain } from "./check.ts";
|
|
23
|
+
import { writeAtomicSync } from "./preset-store.ts";
|
|
23
24
|
|
|
24
25
|
interface UsageEntry {
|
|
25
26
|
provider: string;
|
|
@@ -533,10 +534,7 @@ function saveDiskCache(map: Map<string, FileCacheItem>): void {
|
|
|
533
534
|
const out: Record<string, DiskItem> = {};
|
|
534
535
|
for (const [k, v] of map.entries()) out[relative(sessionsDir, k)] = encodeDiskItem(v);
|
|
535
536
|
// Temp file + rename: a concurrent pi session never reads a half-written cache.
|
|
536
|
-
|
|
537
|
-
mkdirSync(cacheDir(), { recursive: true });
|
|
538
|
-
writeFileSync(tmp, JSON.stringify(out), "utf8");
|
|
539
|
-
renameSync(tmp, path);
|
|
537
|
+
writeAtomicSync(path, JSON.stringify(out));
|
|
540
538
|
} catch {
|
|
541
539
|
// ignore
|
|
542
540
|
}
|
|
@@ -773,16 +771,7 @@ function loadUsageBaseline(): Map<string, FileCacheItem> {
|
|
|
773
771
|
function writeUsageBaseline(raw: string | null): void {
|
|
774
772
|
const path = baselinePath();
|
|
775
773
|
if (raw === null) rmSync(path, { force: true });
|
|
776
|
-
else
|
|
777
|
-
mkdirSync(cacheDir(), { recursive: true });
|
|
778
|
-
const tmp = path + "." + process.pid + ".tmp";
|
|
779
|
-
try {
|
|
780
|
-
writeFileSync(tmp, raw, "utf8");
|
|
781
|
-
renameSync(tmp, path);
|
|
782
|
-
} finally {
|
|
783
|
-
rmSync(tmp, { force: true });
|
|
784
|
-
}
|
|
785
|
-
}
|
|
774
|
+
else writeAtomicSync(path, raw);
|
|
786
775
|
resetUsageCache();
|
|
787
776
|
}
|
|
788
777
|
|
|
@@ -1059,13 +1048,15 @@ export function collectUsageSummary(forceScan = false, range: UsageRange = "all"
|
|
|
1059
1048
|
// What this file contributes: range window and reset baseline already applied.
|
|
1060
1049
|
const effective: FileRollup = { providers: effectiveProviders(cached.rollup, baselineItem?.rollup, sinceDay, needDays), days: {} };
|
|
1061
1050
|
|
|
1062
|
-
// A file with no cwd in its cache item lands in "unknown" rather than being re-read.
|
|
1063
|
-
const projectName = cached.cwd ?? "unknown";
|
|
1064
|
-
let project = projectMap.get(projectName);
|
|
1065
|
-
if (!project) projectMap.set(projectName, (project = { sessions: new Set(), providers: new Map() }));
|
|
1066
|
-
project.sessions.add(file);
|
|
1067
1051
|
foldFileIntoProviderMap(providerMap, file, effective);
|
|
1068
|
-
|
|
1052
|
+
if (Object.keys(effective.providers).length > 0) {
|
|
1053
|
+
// A file with no cwd in its cache item lands in "unknown" rather than being re-read.
|
|
1054
|
+
const projectName = cached.cwd ?? "unknown";
|
|
1055
|
+
let project = projectMap.get(projectName);
|
|
1056
|
+
if (!project) projectMap.set(projectName, (project = { sessions: new Set(), providers: new Map() }));
|
|
1057
|
+
project.sessions.add(file);
|
|
1058
|
+
foldFileIntoProviderMap(project.providers, file, effective);
|
|
1059
|
+
}
|
|
1069
1060
|
const baseDays = baselineItem?.rollup.days;
|
|
1070
1061
|
for (const [dk, r] of Object.entries(cached.rollup.days)) {
|
|
1071
1062
|
// Day keys start with the fixed-width `YYYY-MM-DD`; the baseline's same-key row is
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bismawy/pi-arnative",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "Refined aesthetics. Cohesive tools. Built for Pi. Warm themes, rounded tool boxes, tabbed header, compact footer and a /usage dashboard.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|