@bismawy/pi-arnative 0.14.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 +19 -0
- package/README.md +52 -67
- package/extensions/animations.ts +11 -26
- package/extensions/arnative.ts +290 -346
- 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 +229 -33
- 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 +66 -17
- 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/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/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/preset-store.ts
CHANGED
|
@@ -30,6 +30,8 @@ export const BUDGET_ENFORCE_KEY = "budgetEnforce";
|
|
|
30
30
|
export const RENDER_CACHE_KEY = "renderCache";
|
|
31
31
|
/** Remote proxy payload limit: `"Off"` or `"<N> MB"`, absent reads as `"1 MB"`. */
|
|
32
32
|
export const PAYLOAD_LIMIT_KEY = "payloadLimit";
|
|
33
|
+
/** Expanded `edit` diff layout: `"Split"` (default) or `"Unified"`. */
|
|
34
|
+
export const EDIT_DIFF_KEY = "editDiff";
|
|
33
35
|
|
|
34
36
|
// Resolved per call, not at import: the self-check points getAgentDir() at a fixture dir.
|
|
35
37
|
// Everything pi-arnative writes lives in one folder (agent dir/arnative); the config moved
|
|
@@ -102,7 +104,7 @@ export function loadNumber(key: string, range: { min: number; max: number }): nu
|
|
|
102
104
|
/** Reading order of `config.json`: the presets in the order the settings menu shows them,
|
|
103
105
|
* then `layoutVersion`, then anything else (a key from another module or a newer version).
|
|
104
106
|
* Times a user edits the file by hand or reads it back. */
|
|
105
|
-
const KEY_ORDER = ["headerPreset", "footerPreset", "footerCost", "chatboxPreset", "chatboxPrompt", "chatboxDialog", "budgetDay", "budgetMonth", "budgetEnforce", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "payloadLimit", "modelHeal", "renderCache"];
|
|
107
|
+
const KEY_ORDER = ["headerPreset", "footerPreset", "footerCost", "chatboxPreset", "chatboxPrompt", "chatboxDialog", "budgetDay", "budgetMonth", "budgetEnforce", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "payloadLimit", "modelHeal", "renderCache", "editDiff"];
|
|
106
108
|
|
|
107
109
|
/** The record in {@link KEY_ORDER}; unknown keys keep the order they were written in. */
|
|
108
110
|
function ordered(record: Record<string, unknown>): Record<string, unknown> {
|
|
@@ -112,6 +114,37 @@ function ordered(record: Record<string, unknown>): Record<string, unknown> {
|
|
|
112
114
|
return out;
|
|
113
115
|
}
|
|
114
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
|
+
|
|
115
148
|
/** Store a choice. Best effort: an unwritable agent dir must not break the TUI. */
|
|
116
149
|
export function saveChoice(key: string, value: string, rename: (from: string, to: string) => void = renameSync): void {
|
|
117
150
|
readConfig();
|
|
@@ -124,22 +157,7 @@ export function saveChoice(key: string, value: string, rename: (from: string, to
|
|
|
124
157
|
if (record[key] === value) return;
|
|
125
158
|
memo = { ...record, [key]: value };
|
|
126
159
|
try {
|
|
127
|
-
|
|
128
|
-
const tmp = `${path}.${process.pid}.tmp`;
|
|
129
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
130
|
-
const payload = `${JSON.stringify(ordered(memo), null, 2)}\n`;
|
|
131
|
-
writeFileSync(tmp, payload, "utf8");
|
|
132
|
-
try {
|
|
133
|
-
rename(tmp, path);
|
|
134
|
-
} catch (e) {
|
|
135
|
-
// Windows: a running pi session can hold config.json open, and then the atomic
|
|
136
|
-
// replace fails with EPERM while an in-place write still lands. A setting that
|
|
137
|
-
// silently never reaches disk is worse than the small truncation window here.
|
|
138
|
-
const code = (e as NodeJS.ErrnoException).code;
|
|
139
|
-
if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") throw e;
|
|
140
|
-
writeFileSync(path, payload, "utf8");
|
|
141
|
-
rmSync(tmp, { force: true });
|
|
142
|
-
}
|
|
160
|
+
writeAtomicSync(configPath(), `${JSON.stringify(ordered(memo), null, 2)}\n`, rename);
|
|
143
161
|
} catch {
|
|
144
162
|
process.emitWarning("Arnative settings were not saved; the choice applies only to this session.", { code: "ARNATIVE_PRESET_SAVE" });
|
|
145
163
|
}
|
|
@@ -156,6 +174,37 @@ export function ensureChoices(values: Record<string, string>): void {
|
|
|
156
174
|
for (const [key, value] of Object.entries(values)) saveChoice(key, value);
|
|
157
175
|
}
|
|
158
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
|
+
|
|
159
208
|
/** Drop the in-memory copy so the next read hits disk (a restart, in a test). */
|
|
160
209
|
export function resetPresetCache(): void {
|
|
161
210
|
memo = null;
|
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",
|