@bismawy/pi-arnative 0.8.2 → 0.9.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 +86 -63
- package/README.md +61 -84
- package/extensions/animations.ts +0 -0
- package/extensions/arnative.ts +27 -4
- package/extensions/autocompact.ts +1 -1
- package/extensions/footer.ts +5 -2
- package/extensions/model-heal.ts +0 -0
- package/extensions/section-headers.ts +126 -44
- package/extensions/timestamps.ts +0 -0
- package/extensions/todos.ts +489 -0
- package/extensions/tools.ts +308 -100
- package/extensions/ui-render-tweaks.ts +0 -0
- package/extensions/usage.ts +0 -0
- package/lib/box.ts +77 -12
- package/lib/check.ts +0 -0
- package/lib/compat.ts +0 -0
- package/lib/format.ts +0 -0
- package/lib/list-picker.ts +0 -3
- package/lib/model-heal.ts +0 -0
- package/lib/patch.ts +0 -0
- package/lib/preset-store.ts +83 -4
- package/lib/provider.ts +256 -43
- package/lib/shortcuts.ts +8 -0
- package/lib/spinner.ts +0 -0
- package/lib/status-widget.ts +0 -0
- package/lib/todos.ts +473 -0
- package/lib/usage-store.ts +0 -0
- package/package.json +4 -3
package/lib/box.ts
CHANGED
|
@@ -4,9 +4,42 @@
|
|
|
4
4
|
* never loads it as an extension.
|
|
5
5
|
*/
|
|
6
6
|
import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
7
|
-
import { thinkingColorOf } from "./ansi.ts";
|
|
7
|
+
import { stripAnsi, thinkingColorOf } from "./ansi.ts";
|
|
8
8
|
import { assert, isMain } from "./check.ts";
|
|
9
9
|
|
|
10
|
+
/** A clickable span inside rendered lines: 0-based cell columns, inclusive. */
|
|
11
|
+
export interface TextSpan {
|
|
12
|
+
row: number;
|
|
13
|
+
start: number;
|
|
14
|
+
end: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Where `text` sits in each rendered line, in cell columns. A mouse handler needs this to
|
|
19
|
+
* make one piece of a box clickable and leave the rest to pi: a press the handler does not
|
|
20
|
+
* take stays with the text selection, so a box can be clicked and copied at once.
|
|
21
|
+
* A line that shows the text in part (narrow width) yields no span, so a clipped label is
|
|
22
|
+
* never half-clickable.
|
|
23
|
+
*/
|
|
24
|
+
export function textSpans(lines: readonly string[], text: string): TextSpan[] {
|
|
25
|
+
if (!text) return [];
|
|
26
|
+
const width = visibleWidth(text) - 1;
|
|
27
|
+
const spans: TextSpan[] = [];
|
|
28
|
+
lines.forEach((line, row) => {
|
|
29
|
+
const plain = stripAnsi(line);
|
|
30
|
+
const at = plain.indexOf(text);
|
|
31
|
+
if (at >= 0) {
|
|
32
|
+
const start = visibleWidth(plain.slice(0, at));
|
|
33
|
+
spans.push({ row, start, end: start + width });
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
return spans;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Whether the 0-based cell `x` on `row` lands inside one of `spans`. */
|
|
40
|
+
export const inSpans = (spans: readonly TextSpan[], row: number, x: number): boolean =>
|
|
41
|
+
spans.some((span) => span.row === row && x >= span.start && x <= span.end);
|
|
42
|
+
|
|
10
43
|
export type BoxTheme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; bold?(text: string): string };
|
|
11
44
|
type Dim = (s: string) => string;
|
|
12
45
|
|
|
@@ -72,26 +105,47 @@ export function renderScreen(
|
|
|
72
105
|
].map((l) => truncateToWidth(l, width, ""));
|
|
73
106
|
}
|
|
74
107
|
|
|
75
|
-
/**
|
|
76
|
-
*
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
108
|
+
/** Border paint: a theme token name, or a painter for a tier that has no token (the thinking
|
|
109
|
+
* slots, which `thinkingColorOf` resolves). */
|
|
110
|
+
export type BoxBorder = string | ((text: string) => string);
|
|
111
|
+
|
|
112
|
+
/** `renderBoxLines` plus where each input row landed: `starts[i]` is the first line index of
|
|
113
|
+
* `rows[i]`. A caller that hit-tests a row (the task list's scroll counters) needs this,
|
|
114
|
+
* because a row long enough to wrap occupies more than one line. */
|
|
115
|
+
export function renderBoxRows(
|
|
116
|
+
theme: BoxTheme | null,
|
|
117
|
+
width: number,
|
|
118
|
+
rows: string[],
|
|
119
|
+
bgType?: string,
|
|
120
|
+
border: BoxBorder = "dim",
|
|
121
|
+
): { lines: string[]; starts: number[] } {
|
|
122
|
+
const dim = typeof border === "string" ? (s: string) => (theme ? theme.fg(border, s) : s) : border;
|
|
81
123
|
const inner = Math.max(8, width - 4);
|
|
82
124
|
const lines = [boxEdge("╭", "╮", width, dim)];
|
|
125
|
+
const starts: number[] = [];
|
|
83
126
|
for (const row of rows) {
|
|
127
|
+
starts.push(lines.length);
|
|
84
128
|
for (const line of wrapTextWithAnsi(row, inner)) lines.push(boxRow(line, width, dim));
|
|
85
129
|
}
|
|
86
130
|
lines.push(boxEdge("╰", "╯", width, dim));
|
|
87
|
-
|
|
131
|
+
const paint = (input: string[]) => {
|
|
132
|
+
if (!bgType || !theme?.bg) return input;
|
|
88
133
|
try {
|
|
89
|
-
return
|
|
134
|
+
return input.map((l) => applyBg(l, width, (s) => theme!.bg!(bgType, s)));
|
|
90
135
|
} catch {
|
|
91
|
-
return
|
|
136
|
+
return input;
|
|
92
137
|
}
|
|
93
|
-
}
|
|
94
|
-
return lines;
|
|
138
|
+
};
|
|
139
|
+
return { lines: paint(lines), starts };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The box around `rows`. `bgType` = theme bg name (no-op when the theme has no `bg`);
|
|
143
|
+
* `borderColor` = border color.
|
|
144
|
+
* `theme` may be null: a box is patched in at module load, before `session_start`
|
|
145
|
+
* delivers the active theme. An uncolored box for that first frame beats a null
|
|
146
|
+
* deref that kills the process. */
|
|
147
|
+
export function renderBoxLines(theme: BoxTheme | null, width: number, rows: string[], bgType?: string, border: BoxBorder = "dim"): string[] {
|
|
148
|
+
return renderBoxRows(theme, width, rows, bgType, border).lines;
|
|
95
149
|
}
|
|
96
150
|
|
|
97
151
|
if (isMain(import.meta.url)) {
|
|
@@ -146,5 +200,16 @@ if (isMain(import.meta.url)) {
|
|
|
146
200
|
`a long description keeps the right wall at width ${w}`,
|
|
147
201
|
);
|
|
148
202
|
}
|
|
203
|
+
// Click target on a piece of text: cells, not characters, and nothing when clipped.
|
|
204
|
+
const line = renderBoxRows(th, 40, ["Todos (3/7) [click to expand]"], undefined, undefined).lines[1]!;
|
|
205
|
+
const spans = textSpans([line], "[click to expand]");
|
|
206
|
+
assert(spans.length === 1 && spans[0]!.row === 0, "textSpans finds the hint on its row");
|
|
207
|
+
assert(spans[0]!.start === visibleWidth("│ Todos (3/7) "), `span starts at the hint, got ${spans[0]!.start}`);
|
|
208
|
+
assert(inSpans(spans, 0, spans[0]!.start) && inSpans(spans, 0, spans[0]!.end), "span covers the first and last cell");
|
|
209
|
+
assert(!inSpans(spans, 0, spans[0]!.start - 1) && !inSpans(spans, 1, spans[0]!.start), "span excludes the cell before and other rows");
|
|
210
|
+
assert(textSpans([boxRow("Todos (3/7) [click to exp…", 24, (t) => t)], "[click to expand]").length === 0, "a clipped hint is not clickable");
|
|
211
|
+
// Wide characters before the hint shift cells, not characters.
|
|
212
|
+
const wide = textSpans([boxRow("日本 [x]", 24, (t) => t)], "[x]");
|
|
213
|
+
assert(wide[0]!.start === visibleWidth("│ 日本 "), `a wide glyph shifts by cells, got ${wide[0]!.start}`);
|
|
149
214
|
console.log("lib/box.ts OK");
|
|
150
215
|
}
|
package/lib/check.ts
CHANGED
|
File without changes
|
package/lib/compat.ts
CHANGED
|
File without changes
|
package/lib/format.ts
CHANGED
|
File without changes
|
package/lib/list-picker.ts
CHANGED
|
@@ -310,9 +310,6 @@ export class InputPicker implements Component, Focusable {
|
|
|
310
310
|
}
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
-
/** Title of a sub-screen, derived from `screenTitle` so the format lives in one place. */
|
|
314
|
-
export const pickerTitle = (setting: string): ScreenText["title"] => screenTitle(setting);
|
|
315
|
-
|
|
316
313
|
// Self-check: `node lib/list-picker.ts`
|
|
317
314
|
if (isMain(import.meta.url)) {
|
|
318
315
|
assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Open [Esc] Close", "root legend pinned, no ← behind the root menu");
|
package/lib/model-heal.ts
CHANGED
|
File without changes
|
package/lib/patch.ts
CHANGED
|
File without changes
|
package/lib/preset-store.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* Reads are memoised per process; every write re-reads the file and replaces it atomically
|
|
10
10
|
* (temp file + rename), so concurrent pi sessions that write different keys keep both.
|
|
11
11
|
*/
|
|
12
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
13
13
|
import { tmpdir } from "node:os";
|
|
14
14
|
import { dirname, join } from "node:path";
|
|
15
15
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
@@ -72,8 +72,21 @@ export function loadChoice<T extends string>(key: string, allowed: readonly T[])
|
|
|
72
72
|
return typeof value === "string" && (allowed as readonly string[]).includes(value) ? (value as T) : undefined;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
/** Reading order of `config.json`: the presets in the order the settings menu shows them,
|
|
76
|
+
* then `layoutVersion`, then anything else (a key from another module or a newer version).
|
|
77
|
+
* Times a user edits the file by hand or reads it back. */
|
|
78
|
+
const KEY_ORDER = ["headerPreset", "footerPreset", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "modelHeal"];
|
|
79
|
+
|
|
80
|
+
/** The record in {@link KEY_ORDER}; unknown keys keep the order they were written in. */
|
|
81
|
+
function ordered(record: Record<string, unknown>): Record<string, unknown> {
|
|
82
|
+
const out: Record<string, unknown> = {};
|
|
83
|
+
for (const key of KEY_ORDER) if (Object.hasOwn(record, key)) out[key] = record[key];
|
|
84
|
+
for (const [key, value] of Object.entries(record)) if (!Object.hasOwn(out, key)) out[key] = value;
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
|
|
75
88
|
/** Store a choice. Best effort: an unwritable agent dir must not break the TUI. */
|
|
76
|
-
export function saveChoice(key: string, value: string): void {
|
|
89
|
+
export function saveChoice(key: string, value: string, rename: (from: string, to: string) => void = renameSync): void {
|
|
77
90
|
if (readConfig()[key] === value) return;
|
|
78
91
|
// Re-read: another pi session may have written its own key since this one loaded.
|
|
79
92
|
memo = { ...readDisk().record, [key]: value };
|
|
@@ -81,13 +94,35 @@ export function saveChoice(key: string, value: string): void {
|
|
|
81
94
|
const path = configPath();
|
|
82
95
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
83
96
|
mkdirSync(dirname(path), { recursive: true });
|
|
84
|
-
|
|
85
|
-
|
|
97
|
+
const payload = `${JSON.stringify(ordered(memo), null, 2)}\n`;
|
|
98
|
+
writeFileSync(tmp, payload, "utf8");
|
|
99
|
+
try {
|
|
100
|
+
rename(tmp, path);
|
|
101
|
+
} catch (e) {
|
|
102
|
+
// Windows: a running pi session can hold config.json open, and then the atomic
|
|
103
|
+
// replace fails with EPERM while an in-place write still lands. A setting that
|
|
104
|
+
// silently never reaches disk is worse than the small truncation window here.
|
|
105
|
+
const code = (e as NodeJS.ErrnoException).code;
|
|
106
|
+
if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") throw e;
|
|
107
|
+
writeFileSync(path, payload, "utf8");
|
|
108
|
+
rmSync(tmp, { force: true });
|
|
109
|
+
}
|
|
86
110
|
} catch {
|
|
87
111
|
// ignore: the choice still applies for this session
|
|
88
112
|
}
|
|
89
113
|
}
|
|
90
114
|
|
|
115
|
+
/** Record the choices in use, so `config.json` names every preset instead of only the ones a
|
|
116
|
+
* user changed — a fresh install then reads a complete profile instead of an empty file.
|
|
117
|
+
* Runs at `session_start`; after the first run every key already matches and nothing is
|
|
118
|
+
* written. A present-but-unreadable config is never replaced by this partial record (the
|
|
119
|
+
* same rule the layout stamp follows), because that would drop the other keys. */
|
|
120
|
+
export function ensureChoices(values: Record<string, string>): void {
|
|
121
|
+
const { parsed } = readDisk();
|
|
122
|
+
if (!parsed && existsSync(configPath())) return;
|
|
123
|
+
for (const [key, value] of Object.entries(values)) saveChoice(key, value);
|
|
124
|
+
}
|
|
125
|
+
|
|
91
126
|
/** Drop the in-memory copy so the next read hits disk (a restart, in a test). */
|
|
92
127
|
export function resetPresetCache(): void {
|
|
93
128
|
memo = null;
|
|
@@ -148,6 +183,50 @@ if (isMain(import.meta.url)) {
|
|
|
148
183
|
const stamped = JSON.parse(readFileSync(join(stamp, "arnative", "config.json"), "utf8")) as Record<string, unknown>;
|
|
149
184
|
assert(stamped.headerPreset === "b" && stamped.layoutVersion === "1", "stamping merges, it does not replace");
|
|
150
185
|
rmSync(stamp, { recursive: true, force: true });
|
|
186
|
+
|
|
187
|
+
// The startup record names every choice, including the ones still at their default.
|
|
188
|
+
const profile = mkdtempSync(join(tmpdir(), "arnative-preset-profile-"));
|
|
189
|
+
process.env.PI_CODING_AGENT_DIR = profile;
|
|
190
|
+
resetPresetCache();
|
|
191
|
+
ensureChoices({ headerPreset: "Arnative (Full)", footerPreset: "Arnative (Full)" });
|
|
192
|
+
assert(loadChoice(HEADER_PRESET_KEY, ["Arnative (Full)"] as const) === "Arnative (Full)", "a default choice is written, not skipped");
|
|
193
|
+
assert(loadChoice(FOOTER_PRESET_KEY, ["Arnative (Full)"] as const) === "Arnative (Full)", "every key in the batch is written");
|
|
194
|
+
const profiled = readFileSync(join(profile, "arnative", "config.json"), "utf8");
|
|
195
|
+
ensureChoices({ headerPreset: "Arnative (Full)", footerPreset: "Arnative (Full)" });
|
|
196
|
+
assert(readFileSync(join(profile, "arnative", "config.json"), "utf8") === profiled, "a second record writes nothing");
|
|
197
|
+
|
|
198
|
+
// The file keeps one key order whatever order the writes arrived in.
|
|
199
|
+
const keyOrder = () => Object.keys(JSON.parse(readFileSync(join(profile, "arnative", "config.json"), "utf8")) as Record<string, unknown>);
|
|
200
|
+
assert(
|
|
201
|
+
keyOrder().join(",") === "headerPreset,footerPreset,layoutVersion",
|
|
202
|
+
"known keys follow KEY_ORDER, layoutVersion after the presets: " + keyOrder().join(","),
|
|
203
|
+
);
|
|
204
|
+
saveChoice("spinnerPreset", "Circle Wave");
|
|
205
|
+
saveChoice("zzz-other", "x");
|
|
206
|
+
assert(
|
|
207
|
+
keyOrder().join(",") === "headerPreset,footerPreset,spinnerPreset,layoutVersion,zzz-other",
|
|
208
|
+
"a newly written key slots into place, an unknown one goes last: " + keyOrder().join(","),
|
|
209
|
+
);
|
|
210
|
+
|
|
211
|
+
// Windows: a running pi session can hold the file open, so the atomic replace fails
|
|
212
|
+
// while the setting still has to land. The seam stands in for that rename.
|
|
213
|
+
const locked = () => {
|
|
214
|
+
throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" });
|
|
215
|
+
};
|
|
216
|
+
saveChoice(HEADER_PRESET_KEY, "b", locked);
|
|
217
|
+
resetPresetCache();
|
|
218
|
+
assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "a refused rename still writes the choice in place");
|
|
219
|
+
saveChoice(FOOTER_PRESET_KEY, "a", locked);
|
|
220
|
+
resetPresetCache();
|
|
221
|
+
assert(loadChoice(FOOTER_PRESET_KEY, ["a", "b"] as const) === "a" && loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "the in-place write keeps the other keys");
|
|
222
|
+
assert(!existsSync(join(profile, "arnative")) || readdirSync(join(profile, "arnative")).every((f) => !f.endsWith(".tmp")), "no temp file is left behind");
|
|
223
|
+
|
|
224
|
+
writeFileSync(join(profile, "arnative", "config.json"), "{not json", "utf8");
|
|
225
|
+
resetPresetCache();
|
|
226
|
+
ensureChoices({ headerPreset: "b" });
|
|
227
|
+
assert(readFileSync(join(profile, "arnative", "config.json"), "utf8") === "{not json", "the startup record leaves an unreadable config alone");
|
|
228
|
+
rmSync(profile, { recursive: true, force: true });
|
|
229
|
+
|
|
151
230
|
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
152
231
|
resetPresetCache();
|
|
153
232
|
|
package/lib/provider.ts
CHANGED
|
@@ -250,6 +250,43 @@ export function providerNames(config: unknown): string[] {
|
|
|
250
250
|
return isObj(config) && isObj(config.providers) ? Object.keys(config.providers) : [];
|
|
251
251
|
}
|
|
252
252
|
|
|
253
|
+
/** Pure patch of one provider's scalar fields (endpoint, id, display name, inline key).
|
|
254
|
+
* `undefined` drops the field; models, compat, headers and every sibling survive — the
|
|
255
|
+
* same contract as {@link withProviderModels}. */
|
|
256
|
+
export function withProviderFields(config: unknown, name: string, patch: Record<string, string | undefined>): Record<string, unknown> {
|
|
257
|
+
const root = isObj(config) ? { ...config } : {};
|
|
258
|
+
const providers = isObj(root.providers) ? { ...root.providers } : {};
|
|
259
|
+
const next: Record<string, unknown> = { ...(isObj(providers[name]) ? providers[name] : {}), ...patch };
|
|
260
|
+
for (const [key, value] of Object.entries(next)) if (value === undefined) delete next[key];
|
|
261
|
+
providers[name] = next;
|
|
262
|
+
root.providers = providers;
|
|
263
|
+
return root;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Pure rename: the provider keeps its position in the list, and a `name` that only
|
|
267
|
+
* repeated the old id follows it (a hand-written display name stays as written). */
|
|
268
|
+
export function renameProvider(config: unknown, from: string, to: string): Record<string, unknown> {
|
|
269
|
+
const root = isObj(config) ? { ...config } : {};
|
|
270
|
+
const providers = isObj(root.providers) ? { ...root.providers } : {};
|
|
271
|
+
if (!(from in providers)) return root;
|
|
272
|
+
root.providers = Object.fromEntries(
|
|
273
|
+
Object.entries(providers).map(([key, value]): [string, unknown] => {
|
|
274
|
+
if (key !== from) return [key, value];
|
|
275
|
+
const entry: Record<string, unknown> = isObj(value) ? { ...value } : {};
|
|
276
|
+
if (entry.name === from) entry.name = to;
|
|
277
|
+
return [to, entry];
|
|
278
|
+
}),
|
|
279
|
+
);
|
|
280
|
+
return root;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** The credential follows its provider in auth.json; a provider with no entry stays without one. */
|
|
284
|
+
export function renameAuth(auth: unknown, from: string, to: string): Record<string, unknown> {
|
|
285
|
+
const root = isObj(auth) ? { ...auth } : {};
|
|
286
|
+
if (!(from in root)) return root;
|
|
287
|
+
return Object.fromEntries(Object.entries(root).map(([key, value]): [string, unknown] => [key === from ? to : key, value]));
|
|
288
|
+
}
|
|
289
|
+
|
|
253
290
|
export interface ProviderSummary {
|
|
254
291
|
name: string;
|
|
255
292
|
api?: string;
|
|
@@ -395,6 +432,34 @@ export function saveProvider(name: string, entry: ProviderEntry, key: string | u
|
|
|
395
432
|
if (key) writeJson(authPath(), withAuth(readJson(authPath()), name, key));
|
|
396
433
|
}
|
|
397
434
|
|
|
435
|
+
/** Writes one provider's key: a real key lands in auth.json (the file /login writes, and the
|
|
436
|
+
* credential pi prefers over an inline models.json apiKey), `undefined` removes it. A
|
|
437
|
+
* literal inline key is dropped from models.json so the secret lives in one place; an
|
|
438
|
+
* env-var or shell reference is configuration, not a secret, and stays put. */
|
|
439
|
+
export function saveProviderKey(name: string, key: string | undefined): void {
|
|
440
|
+
const auth = readJson(authPath());
|
|
441
|
+
// Nothing stored and nothing to store: leave a missing auth.json missing.
|
|
442
|
+
if (key || (isObj(auth) && name in auth)) writeJson(authPath(), key ? withAuth(auth, name, key) : withoutAuth(auth, name));
|
|
443
|
+
const config = readJson(modelsPath());
|
|
444
|
+
const entry = isObj(config) && isObj(config.providers) && isObj(config.providers[name]) ? (config.providers[name] as Record<string, unknown>) : undefined;
|
|
445
|
+
if (!entry || typeof entry.apiKey !== "string" || /^[$!]/.test(entry.apiKey)) return;
|
|
446
|
+
writeJson(modelsPath(), withProviderFields(config, name, { apiKey: undefined }));
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** `dummy`/`ollama` are placeholders a keyless entry carries so pi can list its models;
|
|
450
|
+
* `$VAR`, `${VAR}` and `!command` are references, not secrets. Neither is a stored key. */
|
|
451
|
+
const PLACEHOLDER_KEYS = new Set(["dummy", "ollama"]);
|
|
452
|
+
export function inlineKey(entry: ProviderEntry): string | undefined {
|
|
453
|
+
const value = entry.apiKey;
|
|
454
|
+
if (!value || PLACEHOLDER_KEYS.has(value) || /^[$!]/.test(value)) return undefined;
|
|
455
|
+
return value;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** One secret as it may be shown on screen: its last four characters, never the whole key. */
|
|
459
|
+
export function keyHint(key: string): string {
|
|
460
|
+
return key.length > 8 ? `••••${key.slice(-4)}` : "••••";
|
|
461
|
+
}
|
|
462
|
+
|
|
398
463
|
export function deleteProviderNamed(name: string): boolean {
|
|
399
464
|
const config = readJson(modelsPath());
|
|
400
465
|
if (!providerNames(config).includes(name)) return false;
|
|
@@ -685,10 +750,8 @@ const selectModelsFlow = async (ctx: ExtensionCommandContext, name: string, entr
|
|
|
685
750
|
};
|
|
686
751
|
|
|
687
752
|
const probeModelsFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
|
|
688
|
-
// The real key lives in auth.json;
|
|
689
|
-
const
|
|
690
|
-
const inline = entry.apiKey && entry.apiKey !== "dummy" && entry.apiKey !== "ollama" ? entry.apiKey : "";
|
|
691
|
-
const key = stored ?? inline;
|
|
753
|
+
// The real key lives in auth.json; a placeholder never authenticates a probe.
|
|
754
|
+
const key = readAuthKey(name) ?? inlineKey(entry) ?? "";
|
|
692
755
|
probingStatus(ctx, "probing endpoint…");
|
|
693
756
|
let result: ProbeResult | undefined;
|
|
694
757
|
try {
|
|
@@ -755,13 +818,12 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
|
|
|
755
818
|
busy = label;
|
|
756
819
|
progress = "starting…";
|
|
757
820
|
refresh();
|
|
758
|
-
const inline = entry.apiKey && entry.apiKey !== "dummy" && entry.apiKey !== "ollama" ? entry.apiKey : undefined;
|
|
759
821
|
try {
|
|
760
822
|
const supported = await probeEffort(
|
|
761
823
|
{ provider: name, id: label, api: entry.api, baseUrl: entry.baseUrl, reasoning: true, compat },
|
|
762
824
|
{
|
|
763
825
|
baseUrl: entry.baseUrl,
|
|
764
|
-
key: readAuthKey(name) ??
|
|
826
|
+
key: readAuthKey(name) ?? inlineKey(entry),
|
|
765
827
|
onLevel: (level, _accepted, index) => {
|
|
766
828
|
progress = `${level} · ${index + 1}/7`;
|
|
767
829
|
refresh();
|
|
@@ -872,66 +934,172 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
|
|
|
872
934
|
if (warn) ctx.ui.notify(`[arnative] ${warn}`, "info");
|
|
873
935
|
};
|
|
874
936
|
|
|
937
|
+
const ACTION_EDIT = "Edit";
|
|
875
938
|
const ACTION_SELECT = "Select models";
|
|
876
939
|
const ACTION_PROBE = "Probe models";
|
|
877
940
|
const ACTION_THINKING = "Thinking";
|
|
878
941
|
const ACTION_DELETE = "Delete";
|
|
879
942
|
|
|
880
|
-
const
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
943
|
+
const EDIT_BASE = "Base URL";
|
|
944
|
+
const EDIT_NAME = "Provider name";
|
|
945
|
+
const EDIT_KEY = "API key";
|
|
946
|
+
|
|
947
|
+
const ACTIONS_DESCRIPTION = "Edit the endpoint, key or models, re-probe, or delete.";
|
|
948
|
+
|
|
949
|
+
/** One menu row picker shared by the action and edit menus: Enter returns the row's label,
|
|
950
|
+
* `←` and Esc return undefined (the caller decides what that leaves for). */
|
|
951
|
+
const chooseRow = async (ctx: ExtensionCommandContext, title: string, description: string, rows: ListRow[]): Promise<string | undefined> => {
|
|
952
|
+
if (ctx.mode !== "tui") {
|
|
953
|
+
const picked = await ctx.ui.select(title, rows.map(rowText));
|
|
954
|
+
if (picked === undefined) return undefined;
|
|
955
|
+
// Labels are distinct prefixes of their own flat row, so `startsWith` is unambiguous.
|
|
956
|
+
return rows.find((r) => picked.startsWith(r.label))?.label;
|
|
957
|
+
}
|
|
958
|
+
const chosen = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
|
|
959
|
+
const picker = new ListPicker(
|
|
960
|
+
theme,
|
|
961
|
+
rows,
|
|
962
|
+
undefined,
|
|
963
|
+
{
|
|
964
|
+
preview: () => {},
|
|
965
|
+
revert: () => {},
|
|
966
|
+
done: () => done(rows[picker.index]?.label),
|
|
967
|
+
cancel: () => done(null),
|
|
968
|
+
// `←` leaves this menu for its parent; Esc closes the screen it is on.
|
|
969
|
+
back: () => done(null),
|
|
970
|
+
requestRender: () => tui.requestRender(),
|
|
971
|
+
},
|
|
972
|
+
{ title: screenTitle(title), description, legend: LIST_LEGEND_MOVE },
|
|
973
|
+
false,
|
|
974
|
+
ctx.thinkingLevel,
|
|
975
|
+
);
|
|
976
|
+
return picker;
|
|
977
|
+
});
|
|
978
|
+
return chosen ?? undefined;
|
|
979
|
+
};
|
|
980
|
+
|
|
981
|
+
/** One field written through to models.json, with the notify that says what landed. */
|
|
982
|
+
const saveField = (ctx: ExtensionCommandContext, name: string, patch: Record<string, string | undefined>, note: string): void => {
|
|
983
|
+
try {
|
|
984
|
+
writeJson(modelsPath(), withProviderFields(readJson(modelsPath()), name, patch));
|
|
985
|
+
} catch (error) {
|
|
986
|
+
ctx.ui.notify(`[arnative] Not saved: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
ctx.ui.notify(`[arnative] ${note}`, "info");
|
|
990
|
+
};
|
|
991
|
+
|
|
992
|
+
/** Base URL: stored exactly as typed (normalized only for a bare host). The flavor's own
|
|
993
|
+
* `/v1` rewriting stays in the add flow — an edit must land what the user wrote. */
|
|
994
|
+
const editBaseUrlFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
|
|
995
|
+
const value = await readInput(ctx, "Edit", "Base URL — the endpoint pi calls (include /v1 for OpenAI-style)", "https://api.example.com/v1", entry.baseUrl);
|
|
996
|
+
// Esc cancels; an emptied field keeps what is stored rather than blanking the endpoint.
|
|
997
|
+
if (!value) return;
|
|
998
|
+
const baseUrl = normalizeBase(value);
|
|
999
|
+
if (baseUrl === entry.baseUrl) return;
|
|
1000
|
+
saveField(ctx, name, { baseUrl }, `${name}: base URL is now ${baseUrl}. Run Probe models to re-read its list.`);
|
|
1001
|
+
};
|
|
1002
|
+
|
|
1003
|
+
/** Provider id: the models.json key and the auth.json credential move together, so the key
|
|
1004
|
+
* never ends up under an id no provider answers to. Returns the id to keep using. */
|
|
1005
|
+
const editNameFlow = async (ctx: ExtensionCommandContext, name: string): Promise<string> => {
|
|
1006
|
+
const value = await readInput(ctx, "Edit", "provider id (letters, digits, - and _)", name, name);
|
|
1007
|
+
if (!value || value === name) return name;
|
|
1008
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value)) {
|
|
1009
|
+
ctx.ui.notify(`[arnative] "${value}" is not a usable provider id (letters, digits, - and _ only).`, "warning");
|
|
1010
|
+
return name;
|
|
1011
|
+
}
|
|
1012
|
+
if (providerNames(loadModelsConfig()).includes(value)) {
|
|
1013
|
+
ctx.ui.notify(`[arnative] "${value}" is already a provider — pick another id.`, "warning");
|
|
1014
|
+
return name;
|
|
1015
|
+
}
|
|
1016
|
+
const auth = readJson(authPath());
|
|
1017
|
+
const holdsKey = isObj(auth) && isObj(auth[name]);
|
|
1018
|
+
try {
|
|
1019
|
+
if (holdsKey) writeJson(authPath(), renameAuth(auth, name, value));
|
|
1020
|
+
try {
|
|
1021
|
+
writeJson(modelsPath(), renameProvider(readJson(modelsPath()), name, value));
|
|
1022
|
+
} catch (error) {
|
|
1023
|
+
// Put the credential back where the old id still looks for it.
|
|
1024
|
+
if (holdsKey) writeJson(authPath(), auth);
|
|
1025
|
+
throw error;
|
|
1026
|
+
}
|
|
1027
|
+
} catch (error) {
|
|
1028
|
+
ctx.ui.notify(`[arnative] Not renamed: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
|
|
1029
|
+
return name;
|
|
1030
|
+
}
|
|
1031
|
+
ctx.ui.notify(`[arnative] Renamed ${name} → ${value}. Open /model to refresh.`, "info");
|
|
1032
|
+
return value;
|
|
1033
|
+
};
|
|
1034
|
+
|
|
1035
|
+
/** API key: written to auth.json (the store pi prefers over an inline models.json key), so
|
|
1036
|
+
* a literal key leaves models.json instead of being stored twice. */
|
|
1037
|
+
const editKeyFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
|
|
1038
|
+
const stored = readAuthKey(name) ?? inlineKey(entry);
|
|
1039
|
+
const field = stored ? `API key — stored ${keyHint(stored)}, empty keeps it` : "API key — empty for a keyless endpoint";
|
|
1040
|
+
const value = await readInput(ctx, "Edit", field, "sk-…");
|
|
1041
|
+
if (!value) return;
|
|
1042
|
+
try {
|
|
1043
|
+
saveProviderKey(name, value);
|
|
1044
|
+
} catch (error) {
|
|
1045
|
+
ctx.ui.notify(`[arnative] Not saved: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
ctx.ui.notify(`[arnative] ${name}: API key replaced (${keyHint(value)}). Open /model to refresh.`, "info");
|
|
1049
|
+
};
|
|
1050
|
+
|
|
1051
|
+
/** The Edit menu: one field per row, each write immediate. Returns the provider id to keep
|
|
1052
|
+
* using — a rename changes it, and every later action follows the new one. */
|
|
1053
|
+
const editFlow = async (ctx: ExtensionCommandContext, name: string): Promise<string> => {
|
|
1054
|
+
let id = name;
|
|
1055
|
+
for (;;) {
|
|
1056
|
+
const entry = loadProviderEntry(loadModelsConfig(), id);
|
|
1057
|
+
if (!entry) {
|
|
1058
|
+
ctx.ui.notify(`[arnative] ${id} is gone — the list will refresh.`, "warning");
|
|
1059
|
+
return id;
|
|
1060
|
+
}
|
|
1061
|
+
const key = readAuthKey(id) ?? inlineKey(entry);
|
|
1062
|
+
const rows: ListRow[] = [
|
|
1063
|
+
{ label: EDIT_BASE, note: entry.baseUrl || "not set" },
|
|
1064
|
+
{ label: EDIT_NAME, note: id },
|
|
1065
|
+
{ label: EDIT_KEY, note: key ? keyHint(key) : "not set" },
|
|
1066
|
+
];
|
|
1067
|
+
const action = await chooseRow(ctx, `Edit · ${id}`, "one field per row — each saves on Enter", rows);
|
|
1068
|
+
if (!action) return id;
|
|
1069
|
+
if (action === EDIT_BASE) await editBaseUrlFlow(ctx, id, entry);
|
|
1070
|
+
else if (action === EDIT_NAME) id = await editNameFlow(ctx, id);
|
|
1071
|
+
else await editKeyFlow(ctx, id, entry);
|
|
1072
|
+
}
|
|
884
1073
|
};
|
|
885
1074
|
|
|
886
1075
|
/** Enter on an existing provider: an action menu instead of a straight delete. Every
|
|
887
|
-
* action writes through to models.json (and auth.json for delete) before
|
|
1076
|
+
* action writes through to models.json (and auth.json for edit, rename and delete) before
|
|
1077
|
+
* returning. */
|
|
888
1078
|
const providerActionFlow = async (ctx: ExtensionCommandContext, name: string): Promise<void> => {
|
|
1079
|
+
let id = name;
|
|
889
1080
|
for (;;) {
|
|
890
|
-
const entry = loadProviderEntry(loadModelsConfig(),
|
|
1081
|
+
const entry = loadProviderEntry(loadModelsConfig(), id);
|
|
891
1082
|
if (!entry) {
|
|
892
|
-
ctx.ui.notify(`[arnative] ${
|
|
1083
|
+
ctx.ui.notify(`[arnative] ${id} is gone — the list will refresh.`, "warning");
|
|
893
1084
|
return;
|
|
894
1085
|
}
|
|
895
1086
|
const rows: ListRow[] = [
|
|
1087
|
+
{ label: ACTION_EDIT, note: "base URL, provider name, API key" },
|
|
896
1088
|
{ label: ACTION_SELECT, note: "tick the models this provider exposes" },
|
|
897
1089
|
{ label: ACTION_PROBE, note: "re-read the model list from the endpoint" },
|
|
898
1090
|
{ label: ACTION_THINKING, note: "toggle reasoning per model (auto-detected)" },
|
|
899
1091
|
{ label: ACTION_DELETE, note: "remove the provider and its stored key" },
|
|
900
1092
|
];
|
|
901
|
-
|
|
902
|
-
if (ctx.mode === "tui") {
|
|
903
|
-
action = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
|
|
904
|
-
const picker = new ListPicker(
|
|
905
|
-
theme,
|
|
906
|
-
rows,
|
|
907
|
-
undefined,
|
|
908
|
-
{
|
|
909
|
-
preview: () => {},
|
|
910
|
-
revert: () => {},
|
|
911
|
-
done: () => done(rows[picker.index]?.label),
|
|
912
|
-
cancel: () => done(null),
|
|
913
|
-
// `←` leaves the actions for the provider list; Esc closes the whole menu.
|
|
914
|
-
back: () => done(null),
|
|
915
|
-
requestRender: () => tui.requestRender(),
|
|
916
|
-
},
|
|
917
|
-
{ ...ACTIONS_TEXT, title: screenTitle(`Provider · ${name}`) },
|
|
918
|
-
false,
|
|
919
|
-
ctx.thinkingLevel,
|
|
920
|
-
);
|
|
921
|
-
return picker;
|
|
922
|
-
});
|
|
923
|
-
} else {
|
|
924
|
-
const picked = await ctx.ui.select(`${name} — edit or delete`, rows.map(rowText));
|
|
925
|
-
action = picked === undefined ? undefined : rows.find((r) => picked.startsWith(r.label))?.label;
|
|
926
|
-
}
|
|
1093
|
+
const action = await chooseRow(ctx, `Provider · ${id}`, ACTIONS_DESCRIPTION, rows);
|
|
927
1094
|
if (!action) return;
|
|
928
1095
|
if (action === ACTION_DELETE) {
|
|
929
|
-
await deleteProviderFlow(ctx,
|
|
1096
|
+
await deleteProviderFlow(ctx, id);
|
|
930
1097
|
return;
|
|
931
1098
|
}
|
|
932
|
-
if (action ===
|
|
933
|
-
else if (action ===
|
|
934
|
-
else if (action ===
|
|
1099
|
+
if (action === ACTION_EDIT) id = await editFlow(ctx, id);
|
|
1100
|
+
else if (action === ACTION_SELECT) await selectModelsFlow(ctx, id, entry);
|
|
1101
|
+
else if (action === ACTION_PROBE) await probeModelsFlow(ctx, id, entry);
|
|
1102
|
+
else if (action === ACTION_THINKING) await thinkingFlow(ctx, id, entry);
|
|
935
1103
|
}
|
|
936
1104
|
};
|
|
937
1105
|
|
|
@@ -1067,6 +1235,34 @@ if (isMain(import.meta.url)) {
|
|
|
1067
1235
|
assert((auth.b as { key: string }).key === "2" && auth.a !== undefined, "withAuth adds one credential");
|
|
1068
1236
|
assert(withoutAuth(auth, "a").a === undefined, "withoutAuth removes one");
|
|
1069
1237
|
|
|
1238
|
+
// Secrets: the hint never shows more than the tail, and only a literal inline key counts.
|
|
1239
|
+
assert(keyHint("sk-abcdefgh1234") === "••••1234", "the hint keeps the last four characters");
|
|
1240
|
+
assert(keyHint("short") === "••••", "a short secret shows nothing at all");
|
|
1241
|
+
assert(!keyHint("sk-abcdefgh1234").includes("abcdefgh"), "the body of the key never reaches the screen");
|
|
1242
|
+
assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "dummy", models: [] }) === undefined, "a placeholder is not a key");
|
|
1243
|
+
assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "ollama", models: [] }) === undefined, "the keyless placeholder is not a key");
|
|
1244
|
+
assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "$OPENAI_KEY", models: [] }) === undefined, "an env reference is not a key");
|
|
1245
|
+
assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "sk-1", models: [] }) === "sk-1", "a literal key is read back");
|
|
1246
|
+
|
|
1247
|
+
// The Edit screen's patches: one field lands, the models and every sibling survive, and
|
|
1248
|
+
// a rename keeps the provider's place in the list with its credential following it.
|
|
1249
|
+
const fieldEntry = { providers: { r: { name: "r", baseUrl: "old", api: "openai-completions", apiKey: "sk-1", compat: { x: 1 }, models: [{ id: "m1" }] } } };
|
|
1250
|
+
const patched = withProviderFields(fieldEntry, "r", { baseUrl: "https://new.example/v1" });
|
|
1251
|
+
const patchedEntry = (patched.providers as Record<string, Record<string, unknown>>).r!;
|
|
1252
|
+
assert(patchedEntry.baseUrl === "https://new.example/v1" && patchedEntry.apiKey === "sk-1", "withProviderFields rewrites the named field only");
|
|
1253
|
+
assert((patchedEntry.models as unknown[]).length === 1 && patchedEntry.compat !== undefined, "an endpoint edit keeps models and compat");
|
|
1254
|
+
assert(((fieldEntry.providers as Record<string, Record<string, unknown>>).r!).baseUrl === "old", "withProviderFields does not mutate its input");
|
|
1255
|
+
assert((withProviderFields(fieldEntry, "r", { apiKey: undefined }).providers as Record<string, Record<string, unknown>>).r!.apiKey === undefined, "an undefined patch drops the field");
|
|
1256
|
+
const renamed = renameProvider({ providers: { a: { name: "a", models: [{ id: "m" }] }, b: { name: "" } } }, "a", "c");
|
|
1257
|
+
assert(providerNames(renamed).join() === "c,b", "renameProvider keeps the position and changes the id");
|
|
1258
|
+
assert((renamed.providers as Record<string, { name?: string; models?: unknown[] }>).c!.name === "c", "a name that repeated the old id follows it");
|
|
1259
|
+
assert(((renamed.providers as Record<string, { models?: unknown[] }>).c!.models ?? []).length === 1, "a rename keeps the models");
|
|
1260
|
+
assert((renameProvider({ providers: { a: { name: "Keep" } } }, "a", "c").providers as Record<string, { name?: string }>).c!.name === "Keep", "a hand-written display name is untouched");
|
|
1261
|
+
assert((renameProvider({ providers: { a: {} } }, "missing", "c").providers as Record<string, unknown>).a !== undefined, "renaming a missing provider writes nothing");
|
|
1262
|
+
const movedAuth = renameAuth({ a: { type: "api_key", key: "1" }, b: { type: "api_key", key: "2" } }, "a", "c");
|
|
1263
|
+
assert((movedAuth.c as { key: string }).key === "1" && movedAuth.a === undefined && (movedAuth.b as { key: string }).key === "2", "renameAuth moves one credential");
|
|
1264
|
+
assert(renameAuth({}, "a", "c").a === undefined, "an absent credential is not invented");
|
|
1265
|
+
|
|
1070
1266
|
// The model picker screen: checks toggle, `a` cycles, Esc leaves, Enter returns the ids.
|
|
1071
1267
|
const fakeTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
|
|
1072
1268
|
const renderModels = (checked: Set<string>, rows: ListRow[]) =>
|
|
@@ -1184,6 +1380,23 @@ if (isMain(import.meta.url)) {
|
|
|
1184
1380
|
assert(readAuthKey("t2") === undefined, "the interrupted save never reached auth.json");
|
|
1185
1381
|
rmSync(blockedTmp, { recursive: true, force: true });
|
|
1186
1382
|
assert(readdirSync(tmp).every((f) => !f.endsWith(".tmp")), "a completed save leaves no temp files behind");
|
|
1383
|
+
// Edit writes: the key moves to auth.json and leaves models.json, so the secret lives in
|
|
1384
|
+
// one place; an env reference is configuration and stays put.
|
|
1385
|
+
saveProvider("t3", { name: "t3", baseUrl: "https://z.com/v1", api: "openai-completions", apiKey: "sk-inline", models: [{ id: "m" }] }, undefined);
|
|
1386
|
+
saveProviderKey("t3", "sk-edited");
|
|
1387
|
+
assert(readAuthKey("t3") === "sk-edited", "an edited key lands in auth.json");
|
|
1388
|
+
const t3 = (loadModelsConfig().providers as Record<string, Record<string, unknown>>).t3!;
|
|
1389
|
+
assert(t3.apiKey === undefined, "the inline copy is dropped, so the secret lives in one place");
|
|
1390
|
+
assert(t3.baseUrl === "https://z.com/v1" && (t3.models as unknown[]).length === 1, "the key edit leaves the rest of the entry alone");
|
|
1391
|
+
saveProviderKey("t3", undefined);
|
|
1392
|
+
assert(readAuthKey("t3") === undefined, "an empty key removes the credential");
|
|
1393
|
+
saveProvider("t4", { name: "t4", baseUrl: "https://w.com/v1", api: "openai-completions", apiKey: "$W_KEY", models: [] }, undefined);
|
|
1394
|
+
saveProviderKey("t4", "sk-y");
|
|
1395
|
+
assert((loadModelsConfig().providers as Record<string, Record<string, unknown>>).t4!.apiKey === "$W_KEY", "an env reference survives an edit");
|
|
1396
|
+
saveProvider("t5", { name: "t5", baseUrl: "https://v.com/v1", api: "openai-completions", models: [{ id: "m" }] }, "sk-t5");
|
|
1397
|
+
saveModelsConfig(renameProvider(loadModelsConfig(), "t5", "t6"));
|
|
1398
|
+
assert(providerNames(loadModelsConfig()).includes("t6") && !providerNames(loadModelsConfig()).includes("t5"), "a rename reaches models.json");
|
|
1399
|
+
assert(loadProviderEntry(loadModelsConfig(), "t6")?.models[0]!.id === "m", "the renamed provider keeps its models");
|
|
1187
1400
|
delete process.env.PI_CODING_AGENT_DIR;
|
|
1188
1401
|
rmSync(tmp, { recursive: true, force: true });
|
|
1189
1402
|
|