@bismawy/pi-arnative 0.9.0 → 0.10.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/lib/provider.ts CHANGED
@@ -187,7 +187,6 @@ export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhi
187
187
  * level travels to the endpoint unchanged — for models that take an effort parameter. */
188
188
  export type ThinkingSetting = ThinkingLevel | "auto";
189
189
  export const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
190
- export const THINKING_SETTINGS: ThinkingSetting[] = ["off", "auto", ...THINKING_LEVELS.slice(1)];
191
190
 
192
191
  export interface ProviderModel {
193
192
  id: string;
@@ -250,6 +249,43 @@ export function providerNames(config: unknown): string[] {
250
249
  return isObj(config) && isObj(config.providers) ? Object.keys(config.providers) : [];
251
250
  }
252
251
 
252
+ /** Pure patch of one provider's scalar fields (endpoint, id, display name, inline key).
253
+ * `undefined` drops the field; models, compat, headers and every sibling survive — the
254
+ * same contract as {@link withProviderModels}. */
255
+ export function withProviderFields(config: unknown, name: string, patch: Record<string, string | undefined>): Record<string, unknown> {
256
+ const root = isObj(config) ? { ...config } : {};
257
+ const providers = isObj(root.providers) ? { ...root.providers } : {};
258
+ const next: Record<string, unknown> = { ...(isObj(providers[name]) ? providers[name] : {}), ...patch };
259
+ for (const [key, value] of Object.entries(next)) if (value === undefined) delete next[key];
260
+ providers[name] = next;
261
+ root.providers = providers;
262
+ return root;
263
+ }
264
+
265
+ /** Pure rename: the provider keeps its position in the list, and a `name` that only
266
+ * repeated the old id follows it (a hand-written display name stays as written). */
267
+ export function renameProvider(config: unknown, from: string, to: string): Record<string, unknown> {
268
+ const root = isObj(config) ? { ...config } : {};
269
+ const providers = isObj(root.providers) ? { ...root.providers } : {};
270
+ if (!(from in providers)) return root;
271
+ root.providers = Object.fromEntries(
272
+ Object.entries(providers).map(([key, value]): [string, unknown] => {
273
+ if (key !== from) return [key, value];
274
+ const entry: Record<string, unknown> = isObj(value) ? { ...value } : {};
275
+ if (entry.name === from) entry.name = to;
276
+ return [to, entry];
277
+ }),
278
+ );
279
+ return root;
280
+ }
281
+
282
+ /** The credential follows its provider in auth.json; a provider with no entry stays without one. */
283
+ export function renameAuth(auth: unknown, from: string, to: string): Record<string, unknown> {
284
+ const root = isObj(auth) ? { ...auth } : {};
285
+ if (!(from in root)) return root;
286
+ return Object.fromEntries(Object.entries(root).map(([key, value]): [string, unknown] => [key === from ? to : key, value]));
287
+ }
288
+
253
289
  export interface ProviderSummary {
254
290
  name: string;
255
291
  api?: string;
@@ -280,22 +316,34 @@ export function withoutAuth(auth: unknown, name: string): Record<string, unknown
280
316
 
281
317
  /** Rewrites one provider's model list and nothing else — compat, headers, name, every
282
318
  * sibling field survives an edit exactly as it was stored. Levels serialize to pi's
283
- * wire shape: `reasoning` for anything thinking, plus a `thinkingLevelMap` that pins
284
- * exactly one supported level for a detected variant. */
319
+ * wire shape: `reasoning` for anything thinking, plus a `thinkingLevelMap` whose pinned
320
+ * level is a ceiling: every effort up to it maps to itself, every level above it is null,
321
+ * and `off` stays unmapped. pi reads null as unsupported, so the old map that nulled every
322
+ * level but one left the user stuck on that level, unable to lower it or turn thinking off. */
285
323
  export function levelToWire(level: ThinkingSetting | undefined): { reasoning?: true; thinkingLevelMap?: Record<string, string | null> } {
286
324
  if (level === undefined || level === "off") return {};
287
325
  if (level === "auto") return { reasoning: true };
326
+ const ceiling = THINKING_LEVELS.indexOf(level);
288
327
  const thinkingLevelMap: Record<string, string | null> = {};
289
- for (const l of THINKING_LEVELS) thinkingLevelMap[l] = l === level ? level : null;
328
+ THINKING_LEVELS.forEach((l, i) => {
329
+ if (l !== "off") thinkingLevelMap[l] = i <= ceiling ? l : null;
330
+ });
290
331
  return { reasoning: true, thinkingLevelMap };
291
332
  }
292
333
 
293
- /** Reads pi's wire shape back into a level: a single non-off mapped level is that level;
294
- * `reasoning: true` without a pin is `auto`. */
334
+ /** Reads pi's wire shape back into a level: the highest level mapped to itself is that level
335
+ * when every level above it is null (a ceiling, or the old single-pin shape). Any other map
336
+ * (heal's default, a probed remap) and `reasoning: true` alone are `auto`. */
295
337
  export function wireToLevel(reasoning: unknown, map: unknown): ThinkingSetting {
296
- if (map !== null && typeof map === "object") {
297
- const pinned = THINKING_LEVELS.filter((l) => l !== "off" && typeof (map as Record<string, unknown>)[l] === "string");
298
- if (pinned.length === 1) return pinned[0]!;
338
+ if (isObj(map)) {
339
+ const levels = THINKING_LEVELS.filter((l) => l !== "off");
340
+ const top = levels.findLastIndex((l) => map[l] === l);
341
+ if (top !== -1 && levels.slice(top + 1).every((l) => map[l] === null)) {
342
+ // A ceiling maps every level below it to itself; the old single pin nulls them all.
343
+ // Anything else (an exact probed map with gaps) is a map, not a pin.
344
+ const below = levels.slice(0, top);
345
+ if (below.every((l) => map[l] === l) || below.every((l) => map[l] === null)) return levels[top]!;
346
+ }
299
347
  }
300
348
  return reasoning === true ? "auto" : "off";
301
349
  }
@@ -395,6 +443,34 @@ export function saveProvider(name: string, entry: ProviderEntry, key: string | u
395
443
  if (key) writeJson(authPath(), withAuth(readJson(authPath()), name, key));
396
444
  }
397
445
 
446
+ /** Writes one provider's key: a real key lands in auth.json (the file /login writes, and the
447
+ * credential pi prefers over an inline models.json apiKey), `undefined` removes it. A
448
+ * literal inline key is dropped from models.json so the secret lives in one place; an
449
+ * env-var or shell reference is configuration, not a secret, and stays put. */
450
+ export function saveProviderKey(name: string, key: string | undefined): void {
451
+ const auth = readJson(authPath());
452
+ // Nothing stored and nothing to store: leave a missing auth.json missing.
453
+ if (key || (isObj(auth) && name in auth)) writeJson(authPath(), key ? withAuth(auth, name, key) : withoutAuth(auth, name));
454
+ const config = readJson(modelsPath());
455
+ const entry = isObj(config) && isObj(config.providers) && isObj(config.providers[name]) ? (config.providers[name] as Record<string, unknown>) : undefined;
456
+ if (!entry || typeof entry.apiKey !== "string" || /^[$!]/.test(entry.apiKey)) return;
457
+ writeJson(modelsPath(), withProviderFields(config, name, { apiKey: undefined }));
458
+ }
459
+
460
+ /** `dummy`/`ollama` are placeholders a keyless entry carries so pi can list its models;
461
+ * `$VAR`, `${VAR}` and `!command` are references, not secrets. Neither is a stored key. */
462
+ const PLACEHOLDER_KEYS = new Set(["dummy", "ollama"]);
463
+ export function inlineKey(entry: ProviderEntry): string | undefined {
464
+ const value = entry.apiKey;
465
+ if (!value || PLACEHOLDER_KEYS.has(value) || /^[$!]/.test(value)) return undefined;
466
+ return value;
467
+ }
468
+
469
+ /** One secret as it may be shown on screen: its last four characters, never the whole key. */
470
+ export function keyHint(key: string): string {
471
+ return key.length > 8 ? `••••${key.slice(-4)}` : "••••";
472
+ }
473
+
398
474
  export function deleteProviderNamed(name: string): boolean {
399
475
  const config = readJson(modelsPath());
400
476
  if (!providerNames(config).includes(name)) return false;
@@ -425,7 +501,9 @@ export function loadProviderEntry(config: unknown, name: string): ProviderEntry
425
501
  const contextWindow = typeof m.contextWindow === "number" ? m.contextWindow : undefined;
426
502
  const maxTokens = typeof m.maxTokens === "number" ? m.maxTokens : undefined;
427
503
  const meta = contextWindow === undefined && maxTokens === undefined ? undefined : { contextWindow, maxTokens };
428
- return [{ id: m.id, ...(level === "off" ? {} : { level }), ...(meta ? { meta } : {}), ...(isObj(m.compat) ? { compat: m.compat } : {}) }];
504
+ // An `auto` model keeps its stored map, so a later save never wipes what a probe learned.
505
+ const map = level === "auto" && isObj(m.thinkingLevelMap) ? (m.thinkingLevelMap as Record<string, string | null>) : undefined;
506
+ return [{ id: m.id, ...(level === "off" ? {} : { level }), ...(map ? { map } : {}), ...(meta ? { meta } : {}), ...(isObj(m.compat) ? { compat: m.compat } : {}) }];
429
507
  })
430
508
  : [];
431
509
  return {
@@ -447,13 +525,13 @@ const PROVIDERS_TEXT: ScreenText = {
447
525
 
448
526
  const ADD_ROW = "+ Add provider";
449
527
 
450
- const MODEL_LEGEND = "[↑↓] Move [Space] Toggle [a] API [Enter] Save [Esc] Cancel";
451
- const MODEL_LEGEND_LOCKED = "[↑↓] Move [Space] Toggle [Enter] Save [Esc] Cancel";
528
+ const MODEL_LEGEND = "[/] Filter [Space] Toggle [a] API [Enter] Save [Esc] Back";
529
+ const MODEL_LEGEND_LOCKED = "[/] Filter [Space] Toggle [Enter] Save [Esc] Back";
452
530
  /** Rows visible before the model list scrolls (a relay catalog can exceed the screen). */
453
531
  const MODEL_VIEWPORT = 10;
454
532
 
455
533
  /** One model-selection screen: Space checks rows, `a` cycles the API flavor (unless the
456
- * stored api is final), Enter saves. Esc leaves without writing anything. */
534
+ * stored api is final), `/` filters by name, Enter saves. Esc leaves without writing anything. */
457
535
  const pickModels = async (
458
536
  ctx: ExtensionCommandContext,
459
537
  models: string[],
@@ -487,6 +565,9 @@ const pickModels = async (
487
565
  flavor = API_FLAVORS[(API_FLAVORS.indexOf(flavor) + 1) % API_FLAVORS.length]!;
488
566
  },
489
567
  description: () => `${FLAVOR_LABELS[flavor]}${opts.via ? ` · ${opts.via}` : ""}`,
568
+ // A relay catalog is long (one had 75 ids), so the same filter line / keeps on the
569
+ // Thinking screen narrows it here too: the count stays whole, the rows do not.
570
+ search: "models",
490
571
  // The picked count lives in the legend, accented, next to the keys it refers to.
491
572
  legend: () =>
492
573
  `${theme.fg("accent", `${checked.size}/${models.length} picked`)}${theme.fg("dim", ` · ${opts.lockFlavor ? MODEL_LEGEND_LOCKED : MODEL_LEGEND}`)}`,
@@ -578,7 +659,7 @@ const addProviderFlow = async (ctx: ExtensionCommandContext): Promise<void> => {
578
659
 
579
660
  const key = await readInput(ctx, "Provider", "API key — empty for local or keyless endpoints", "sk-…");
580
661
  // Esc cancels the flow, Enter on an empty field means keyless: readInput keeps the two
581
- // apart (undefined vs ""), and the field's own legend promises [Esc] Cancel.
662
+ // apart (undefined vs ""), and the field's own legend promises [Esc] Back.
582
663
  if (key === undefined) return;
583
664
 
584
665
  const suggested = guessProviderName(endpoint);
@@ -659,14 +740,39 @@ const levelsSummary = (models: ProviderModel[]): string => {
659
740
 
660
741
  /** Writes one provider's model list through to models.json (auth.json is untouched — the
661
742
  * key only changes through add or delete). */
662
- const saveModelsNamed = (ctx: ExtensionCommandContext, name: string, models: ProviderModel[]): void => {
743
+ type ModelRef = { provider: string; id: string };
744
+ type SetModel = (model: ModelRef) => Promise<unknown>;
745
+ type RegistryRef = { refresh(options?: { allowNetwork?: boolean }): Promise<unknown>; find(provider: string, id: string): ModelRef | undefined };
746
+
747
+ let setSessionModel: SetModel | undefined;
748
+ /** pi.setModel lives on the extension API, not on a command ctx; the extension binds it once. */
749
+ export const bindSetModel = (fn: SetModel): void => {
750
+ setSessionModel = fn;
751
+ };
752
+
753
+ /** Load models.json into the running session. A registry refresh alone is not enough: pi keeps
754
+ * the session model object (and its thinkingLevelMap) until the model is picked again, so
755
+ * /thinking kept offering the old levels even after /reload. */
756
+ export async function reloadCurrentModel(ctx: { modelRegistry?: RegistryRef; model?: ModelRef }, setModel: SetModel | undefined = setSessionModel): Promise<boolean> {
757
+ const registry = ctx.modelRegistry;
758
+ if (!registry) return false;
759
+ await registry.refresh({ allowNetwork: false });
760
+ const current = ctx.model;
761
+ if (!current) return true;
762
+ const fresh = registry.find(current.provider, current.id);
763
+ if (!fresh || fresh === current) return true;
764
+ if (!setModel) return false;
765
+ await setModel(fresh);
766
+ return true;
767
+ }
768
+ const saveModelsNamed = async (ctx: ExtensionCommandContext, name: string, models: ProviderModel[]): Promise<void> => {
663
769
  try {
664
770
  writeJson(modelsPath(), withProviderModels(readJson(modelsPath()), name, models));
665
771
  } catch (error) {
666
772
  ctx.ui.notify(`[arnative] Not saved: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
667
773
  return;
668
774
  }
669
- ctx.ui.notify(`[arnative] ${name}: ${models.length} models, ${levelsSummary(models)} — models.json updated. Open /model to refresh.`, "info");
775
+ ctx.ui.notify(`[arnative] ${name}: ${models.length} models, ${levelsSummary(models)} — ${(await reloadCurrentModel(ctx as never).catch(() => false)) ? "models.json updated and loaded." : "models.json updated. Pick the model again in /model to load it."}`, "info");
670
776
  };
671
777
 
672
778
  const selectModelsFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
@@ -681,14 +787,12 @@ const selectModelsFlow = async (ctx: ExtensionCommandContext, name: string, entr
681
787
  if (answer === undefined || answer === "") return;
682
788
  picked = answer.split(/[\s,]+/).filter(Boolean);
683
789
  }
684
- saveModelsNamed(ctx, name, mergeLevels(entry, picked));
790
+ await saveModelsNamed(ctx, name, mergeLevels(entry, picked));
685
791
  };
686
792
 
687
793
  const probeModelsFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
688
- // The real key lives in auth.json; an inline dummy never authenticates a probe.
689
- const stored = readAuthKey(name);
690
- const inline = entry.apiKey && entry.apiKey !== "dummy" && entry.apiKey !== "ollama" ? entry.apiKey : "";
691
- const key = stored ?? inline;
794
+ // The real key lives in auth.json; a placeholder never authenticates a probe.
795
+ const key = readAuthKey(name) ?? inlineKey(entry) ?? "";
692
796
  probingStatus(ctx, "probing endpoint…");
693
797
  let result: ProbeResult | undefined;
694
798
  try {
@@ -713,38 +817,54 @@ const probeModelsFlow = async (ctx: ExtensionCommandContext, name: string, entry
713
817
  if (answer === undefined || answer === "") return;
714
818
  picked = answer.split(/[\s,]+/).filter(Boolean);
715
819
  }
716
- saveModelsNamed(ctx, name, mergeLevels(entry, picked, result.meta));
820
+ await saveModelsNamed(ctx, name, mergeLevels(entry, picked, result.meta));
717
821
  };
718
822
 
719
- const THINKING_LEGEND = "[↑↓] Move [Space] Cycle [A] All auto [R] All off [p] Probe [Enter] Save [Esc] Cancel";
823
+ const THINKING_LEGEND = "[/] Filter [Space] Off/auto [0-6] Levels [p] Probe [a/r] All auto/off [Enter] Save [Esc] Back";
824
+ // minimal … max: the efforts a map can offer; off is pi's own switch, not an effort.
825
+ const EFFORT_LEVELS = THINKING_LEVELS.slice(1);
826
+
827
+ /** The levels pi offers for a map, read the way pi reads it: a null drops a level, and
828
+ * xhigh and max need an entry of their own. No map is pi's default scale. */
829
+ export function offeredLevels(map: Record<string, string | null> | undefined): ThinkingLevel[] {
830
+ return EFFORT_LEVELS.filter((l) => (map?.[l] === undefined ? l !== "xhigh" && l !== "max" : map[l] !== null));
831
+ }
720
832
 
721
- /** Space cycles one model through off → auto → minimal → … → max. `auto` means
722
- * `reasoning: true` with no map (every `/think` level passes through unchanged); an
723
- * explicit level pins `thinkingLevelMap` to that single value. `p` asks the channel which
724
- * effort names it really accepts and stores the answer as the model's map. */
833
+ /** Thinking says what each model can do; the level to use is picked per session in /thinking.
834
+ * Space switches a model between off (chat) and auto (reasoning). The levels auto offers come
835
+ * from a probe (p), from model heal, or from 1-6, which toggle minimal … max by hand for a
836
+ * relay that answers a probe and then ignores the effort. A pin an older version stored, or
837
+ * an id suffix such as -high, opens as the level list it allowed. */
725
838
  const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
726
- const levels = new Map(entry.models.map((m) => [m.id, m.level ?? detectLevel(m.id)] as const));
839
+ const levels = new Map<string, ThinkingSetting>();
727
840
  const probed = new Map<string, Record<string, string | null>>();
728
- const cycle = (label: string): void => {
729
- const current = levels.get(label) ?? "off";
730
- const next = THINKING_SETTINGS[(THINKING_SETTINGS.indexOf(current) + 1) % THINKING_SETTINGS.length]!;
731
- levels.set(label, next);
732
- // A probed map belongs to `auto` only: a pinned level states its own answer.
733
- if (next !== "auto") probed.delete(label);
734
- };
735
- const rows: ListRow[] = entry.models.map((m) => ({ label: m.id }));
736
- /** "medium→high, max off" — what a probed map actually changed. */
737
- const summary = (map: Record<string, string | null>): string => {
738
- const parts = Object.entries(map)
739
- .filter(([level, value]) => value !== level && !(value === null && level === "off"))
740
- .map(([level, value]) => (value === null ? `${level} off` : `${level}→${value}`));
741
- return parts.length === 0 ? "all levels accepted" : parts.join(", ");
742
- };
841
+ for (const m of entry.models) {
842
+ const level = m.level ?? detectLevel(m.id);
843
+ const map = m.map ?? (level === "off" || level === "auto" ? undefined : levelToWire(level).thinkingLevelMap);
844
+ levels.set(m.id, level === "off" ? "off" : "auto");
845
+ if (map) probed.set(m.id, map);
846
+ }
743
847
  let busy: string | undefined;
744
848
  let progress: string | undefined;
745
849
  let warn: string | undefined;
746
850
  let refresh: () => void = () => {};
747
851
  let closed = false;
852
+ const cycle = (label: string): void => {
853
+ levels.set(label, levels.get(label) === "off" ? "auto" : "off");
854
+ };
855
+ const toggleLevel = (label: string, level: ThinkingLevel): void => {
856
+ const current = offeredLevels(probed.get(label));
857
+ const next = current.includes(level) ? current.filter((l) => l !== level) : [...current, level];
858
+ if (next.length === 0) {
859
+ warn = `${label}: keep at least one level, or press Space to turn thinking off.`;
860
+ return;
861
+ }
862
+ probed.set(label, buildEffortMap(next)!);
863
+ levels.set(label, "auto");
864
+ };
865
+ const rows: ListRow[] = entry.models.map((m) => ({ label: m.id }));
866
+ /** "low high max": the levels /thinking will list for the model. */
867
+ const summary = (map: Record<string, string | null> | undefined): string => offeredLevels(map).join(" ");
748
868
  const probe = async (label: string): Promise<void> => {
749
869
  const model = entry.models.find((m) => m.id === label);
750
870
  const compat = model?.compat ?? {};
@@ -755,13 +875,12 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
755
875
  busy = label;
756
876
  progress = "starting…";
757
877
  refresh();
758
- const inline = entry.apiKey && entry.apiKey !== "dummy" && entry.apiKey !== "ollama" ? entry.apiKey : undefined;
759
878
  try {
760
879
  const supported = await probeEffort(
761
880
  { provider: name, id: label, api: entry.api, baseUrl: entry.baseUrl, reasoning: true, compat },
762
881
  {
763
882
  baseUrl: entry.baseUrl,
764
- key: readAuthKey(name) ?? inline,
883
+ key: readAuthKey(name) ?? inlineKey(entry),
765
884
  onLevel: (level, _accepted, index) => {
766
885
  progress = `${level} · ${index + 1}/7`;
767
886
  refresh();
@@ -772,11 +891,10 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
772
891
  warn = `${label}: no effort level answered — the map is unchanged.`;
773
892
  return;
774
893
  }
775
- const current = probed.get(label) ?? levelToWire(levels.get(label))?.thinkingLevelMap;
776
- const next = buildEffortMap(current, supported);
777
- if (next) probed.set(label, next);
894
+ const next = buildEffortMap(supported)!;
895
+ probed.set(label, next);
778
896
  levels.set(label, "auto");
779
- warn = `${label}: ${next ? summary(next) : "every level is accepted as-is"}.`;
897
+ warn = `${label}: accepts ${summary(next)}.`;
780
898
  } finally {
781
899
  busy = undefined;
782
900
  progress = undefined;
@@ -813,35 +931,40 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
813
931
  },
814
932
  press: (keyData) => {
815
933
  if (busy) return;
816
- // Plain letters only: Ctrl/Alt/F-keys are swallowed or remapped by some
817
- // terminals, so the two bulk keys stay on the same key everywhere. Shift keeps
818
- // them deliberate — pi-tui lowercases a key id, so "A" would mean plain `a`.
819
- if (matchesKey(keyData, "shift+a")) {
820
- for (const id of levels.keys()) levels.set(id, "auto");
821
- probed.clear();
934
+ // Letters reach here only outside the filter (/ toggles typing), so the commands are
935
+ // plain keys. Neither bulk key clears a map: it is what the model accepts.
936
+ if (matchesKey(keyData, "a") || matchesKey(keyData, "r")) {
937
+ const to = matchesKey(keyData, "a") ? "auto" : "off";
938
+ for (const id of levels.keys()) levels.set(id, to);
822
939
  refresh();
823
940
  return;
824
941
  }
825
- if (matchesKey(keyData, "shift+r")) {
826
- for (const id of levels.keys()) levels.set(id, "off");
827
- probed.clear();
942
+ const label = rows[picker.index]?.label;
943
+ if (!label) return;
944
+ if (keyData === "0") {
945
+ probed.set(label, buildEffortMap([...EFFORT_LEVELS])!);
946
+ levels.set(label, "auto");
828
947
  refresh();
829
948
  return;
830
949
  }
831
- const label = rows[picker.index]?.label;
832
- if (!label || !matchesKey(keyData, "p")) return;
833
- void probe(label);
950
+ const digit = EFFORT_LEVELS.findIndex((_l, i) => keyData === String(i + 1));
951
+ if (digit !== -1) {
952
+ toggleLevel(label, EFFORT_LEVELS[digit]!);
953
+ refresh();
954
+ return;
955
+ }
956
+ if (matchesKey(keyData, "p")) void probe(label);
834
957
  },
835
958
  note: (label) => {
836
959
  if (busy === label) return `probing ${progress ?? ""}`.trim();
837
- const map = probed.get(label);
838
- return `${levels.get(label) ?? "off"}${map ? ` · ${summary(map)}` : ""}`;
960
+ return levels.get(label) === "auto" ? `auto · ${summary(probed.get(label))}` : "off";
839
961
  },
840
- description: () => `cycle: ${THINKING_SETTINGS.join(" → ")}`,
962
+ description: () => "0 all · 1-6 minimal low medium high xhigh max · / filter, / or Enter done",
963
+ search: "models",
841
964
  legend: () =>
842
965
  `${theme.fg("accent", `${[...levels.values()].filter((l) => l !== "off").length}/${rows.length} thinking`)}${theme.fg("dim", ` · ${THINKING_LEGEND}`)}`,
843
966
  },
844
- { title: screenTitle("Thinking"), description: "level per model — auto-detected from the id", legend: THINKING_LEGEND },
967
+ { title: screenTitle("Thinking"), description: "levels each model accepts — p probes, 1-6 toggle by hand", legend: THINKING_LEGEND },
845
968
  false,
846
969
  ctx.thinkingLevel,
847
970
  MODEL_VIEWPORT,
@@ -850,17 +973,26 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
850
973
  });
851
974
  saved = outcome === true;
852
975
  } else {
853
- // No custom screens (RPC/headless): `id:level` pairs, e.g. `o1-mini:low`.
854
- const answer = await readInput(ctx, "Thinking", "levels as id:level pairs — empty = cancel", "", [...levels].map(([id, l]) => `${id}:${l}`).join(", "));
976
+ // No custom screens (RPC/headless): `id:off`, `id:auto` or `id:low+high+max`.
977
+ const current = [...levels].map(([id, l]) => `${id}:${l === "off" ? "off" : probed.has(id) ? offeredLevels(probed.get(id)).join("+") : "auto"}`);
978
+ const answer = await readInput(ctx, "Thinking", "id:off, id:auto or id:low+high+max — empty = cancel", "", current.join(", "));
855
979
  if (answer === undefined || answer === "") return;
856
980
  for (const pair of answer.split(/[\s,]+/).filter(Boolean)) {
857
- const [id, level] = pair.split(":");
858
- if (id && level && THINKING_SETTINGS.includes(level as ThinkingSetting)) levels.set(id, level as ThinkingSetting);
981
+ const [id, value] = pair.split(":");
982
+ if (!id || !value || !levels.has(id)) continue;
983
+ if (value === "off" || value === "auto") {
984
+ levels.set(id, value);
985
+ continue;
986
+ }
987
+ const list = value.split("+").filter((l) => (EFFORT_LEVELS as string[]).includes(l));
988
+ if (list.length === 0) continue;
989
+ probed.set(id, buildEffortMap(list)!);
990
+ levels.set(id, "auto");
859
991
  }
860
992
  saved = true;
861
993
  }
862
994
  if (!saved) return;
863
- saveModelsNamed(
995
+ await saveModelsNamed(
864
996
  ctx,
865
997
  name,
866
998
  entry.models.map((m) => {
@@ -872,66 +1004,172 @@ const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: P
872
1004
  if (warn) ctx.ui.notify(`[arnative] ${warn}`, "info");
873
1005
  };
874
1006
 
1007
+ const ACTION_EDIT = "Edit";
875
1008
  const ACTION_SELECT = "Select models";
876
1009
  const ACTION_PROBE = "Probe models";
877
1010
  const ACTION_THINKING = "Thinking";
878
1011
  const ACTION_DELETE = "Delete";
879
1012
 
880
- const ACTIONS_TEXT: ScreenText = {
881
- title: screenTitle("Provider"),
882
- description: "Edit the models, re-probe, toggle thinking, or delete.",
883
- legend: LIST_LEGEND_MOVE,
1013
+ const EDIT_BASE = "Base URL";
1014
+ const EDIT_NAME = "Provider name";
1015
+ const EDIT_KEY = "API key";
1016
+
1017
+ const ACTIONS_DESCRIPTION = "Edit the endpoint, key or models, re-probe, or delete.";
1018
+
1019
+ /** One menu row picker shared by the action and edit menus: Enter returns the row's label,
1020
+ * `←` and Esc return undefined (the caller decides what that leaves for). */
1021
+ const chooseRow = async (ctx: ExtensionCommandContext, title: string, description: string, rows: ListRow[]): Promise<string | undefined> => {
1022
+ if (ctx.mode !== "tui") {
1023
+ const picked = await ctx.ui.select(title, rows.map(rowText));
1024
+ if (picked === undefined) return undefined;
1025
+ // Labels are distinct prefixes of their own flat row, so `startsWith` is unambiguous.
1026
+ return rows.find((r) => picked.startsWith(r.label))?.label;
1027
+ }
1028
+ const chosen = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
1029
+ const picker = new ListPicker(
1030
+ theme,
1031
+ rows,
1032
+ undefined,
1033
+ {
1034
+ preview: () => {},
1035
+ revert: () => {},
1036
+ done: () => done(rows[picker.index]?.label),
1037
+ cancel: () => done(null),
1038
+ // `←` leaves this menu for its parent; Esc closes the screen it is on.
1039
+ back: () => done(null),
1040
+ requestRender: () => tui.requestRender(),
1041
+ },
1042
+ { title: screenTitle(title), description, legend: LIST_LEGEND_MOVE },
1043
+ false,
1044
+ ctx.thinkingLevel,
1045
+ );
1046
+ return picker;
1047
+ });
1048
+ return chosen ?? undefined;
1049
+ };
1050
+
1051
+ /** One field written through to models.json, with the notify that says what landed. */
1052
+ const saveField = (ctx: ExtensionCommandContext, name: string, patch: Record<string, string | undefined>, note: string): void => {
1053
+ try {
1054
+ writeJson(modelsPath(), withProviderFields(readJson(modelsPath()), name, patch));
1055
+ } catch (error) {
1056
+ ctx.ui.notify(`[arnative] Not saved: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
1057
+ return;
1058
+ }
1059
+ ctx.ui.notify(`[arnative] ${note}`, "info");
1060
+ };
1061
+
1062
+ /** Base URL: stored exactly as typed (normalized only for a bare host). The flavor's own
1063
+ * `/v1` rewriting stays in the add flow — an edit must land what the user wrote. */
1064
+ const editBaseUrlFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
1065
+ const value = await readInput(ctx, "Edit", "Base URL — the endpoint pi calls (include /v1 for OpenAI-style)", "https://api.example.com/v1", entry.baseUrl);
1066
+ // Esc cancels; an emptied field keeps what is stored rather than blanking the endpoint.
1067
+ if (!value) return;
1068
+ const baseUrl = normalizeBase(value);
1069
+ if (baseUrl === entry.baseUrl) return;
1070
+ saveField(ctx, name, { baseUrl }, `${name}: base URL is now ${baseUrl}. Run Probe models to re-read its list.`);
1071
+ };
1072
+
1073
+ /** Provider id: the models.json key and the auth.json credential move together, so the key
1074
+ * never ends up under an id no provider answers to. Returns the id to keep using. */
1075
+ const editNameFlow = async (ctx: ExtensionCommandContext, name: string): Promise<string> => {
1076
+ const value = await readInput(ctx, "Edit", "provider id (letters, digits, - and _)", name, name);
1077
+ if (!value || value === name) return name;
1078
+ if (!/^[A-Za-z0-9_-]+$/.test(value)) {
1079
+ ctx.ui.notify(`[arnative] "${value}" is not a usable provider id (letters, digits, - and _ only).`, "warning");
1080
+ return name;
1081
+ }
1082
+ if (providerNames(loadModelsConfig()).includes(value)) {
1083
+ ctx.ui.notify(`[arnative] "${value}" is already a provider — pick another id.`, "warning");
1084
+ return name;
1085
+ }
1086
+ const auth = readJson(authPath());
1087
+ const holdsKey = isObj(auth) && isObj(auth[name]);
1088
+ try {
1089
+ if (holdsKey) writeJson(authPath(), renameAuth(auth, name, value));
1090
+ try {
1091
+ writeJson(modelsPath(), renameProvider(readJson(modelsPath()), name, value));
1092
+ } catch (error) {
1093
+ // Put the credential back where the old id still looks for it.
1094
+ if (holdsKey) writeJson(authPath(), auth);
1095
+ throw error;
1096
+ }
1097
+ } catch (error) {
1098
+ ctx.ui.notify(`[arnative] Not renamed: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
1099
+ return name;
1100
+ }
1101
+ ctx.ui.notify(`[arnative] Renamed ${name} → ${value}. Open /model to refresh.`, "info");
1102
+ return value;
1103
+ };
1104
+
1105
+ /** API key: written to auth.json (the store pi prefers over an inline models.json key), so
1106
+ * a literal key leaves models.json instead of being stored twice. */
1107
+ const editKeyFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
1108
+ const stored = readAuthKey(name) ?? inlineKey(entry);
1109
+ const field = stored ? `API key — stored ${keyHint(stored)}, empty keeps it` : "API key — empty for a keyless endpoint";
1110
+ const value = await readInput(ctx, "Edit", field, "sk-…");
1111
+ if (!value) return;
1112
+ try {
1113
+ saveProviderKey(name, value);
1114
+ } catch (error) {
1115
+ ctx.ui.notify(`[arnative] Not saved: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
1116
+ return;
1117
+ }
1118
+ ctx.ui.notify(`[arnative] ${name}: API key replaced (${keyHint(value)}). Open /model to refresh.`, "info");
1119
+ };
1120
+
1121
+ /** The Edit menu: one field per row, each write immediate. Returns the provider id to keep
1122
+ * using — a rename changes it, and every later action follows the new one. */
1123
+ const editFlow = async (ctx: ExtensionCommandContext, name: string): Promise<string> => {
1124
+ let id = name;
1125
+ for (;;) {
1126
+ const entry = loadProviderEntry(loadModelsConfig(), id);
1127
+ if (!entry) {
1128
+ ctx.ui.notify(`[arnative] ${id} is gone — the list will refresh.`, "warning");
1129
+ return id;
1130
+ }
1131
+ const key = readAuthKey(id) ?? inlineKey(entry);
1132
+ const rows: ListRow[] = [
1133
+ { label: EDIT_BASE, note: entry.baseUrl || "not set" },
1134
+ { label: EDIT_NAME, note: id },
1135
+ { label: EDIT_KEY, note: key ? keyHint(key) : "not set" },
1136
+ ];
1137
+ const action = await chooseRow(ctx, `Edit · ${id}`, "one field per row — each saves on Enter", rows);
1138
+ if (!action) return id;
1139
+ if (action === EDIT_BASE) await editBaseUrlFlow(ctx, id, entry);
1140
+ else if (action === EDIT_NAME) id = await editNameFlow(ctx, id);
1141
+ else await editKeyFlow(ctx, id, entry);
1142
+ }
884
1143
  };
885
1144
 
886
1145
  /** 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 returning. */
1146
+ * action writes through to models.json (and auth.json for edit, rename and delete) before
1147
+ * returning. */
888
1148
  const providerActionFlow = async (ctx: ExtensionCommandContext, name: string): Promise<void> => {
1149
+ let id = name;
889
1150
  for (;;) {
890
- const entry = loadProviderEntry(loadModelsConfig(), name);
1151
+ const entry = loadProviderEntry(loadModelsConfig(), id);
891
1152
  if (!entry) {
892
- ctx.ui.notify(`[arnative] ${name} is gone — the list will refresh.`, "warning");
1153
+ ctx.ui.notify(`[arnative] ${id} is gone — the list will refresh.`, "warning");
893
1154
  return;
894
1155
  }
895
1156
  const rows: ListRow[] = [
1157
+ { label: ACTION_EDIT, note: "base URL, provider name, API key" },
896
1158
  { label: ACTION_SELECT, note: "tick the models this provider exposes" },
897
1159
  { label: ACTION_PROBE, note: "re-read the model list from the endpoint" },
898
1160
  { label: ACTION_THINKING, note: "toggle reasoning per model (auto-detected)" },
899
1161
  { label: ACTION_DELETE, note: "remove the provider and its stored key" },
900
1162
  ];
901
- let action: string | null | undefined;
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
- }
1163
+ const action = await chooseRow(ctx, `Provider · ${id}`, ACTIONS_DESCRIPTION, rows);
927
1164
  if (!action) return;
928
1165
  if (action === ACTION_DELETE) {
929
- await deleteProviderFlow(ctx, name);
1166
+ await deleteProviderFlow(ctx, id);
930
1167
  return;
931
1168
  }
932
- if (action === ACTION_SELECT) await selectModelsFlow(ctx, name, entry);
933
- else if (action === ACTION_PROBE) await probeModelsFlow(ctx, name, entry);
934
- else if (action === ACTION_THINKING) await thinkingFlow(ctx, name, entry);
1169
+ if (action === ACTION_EDIT) id = await editFlow(ctx, id);
1170
+ else if (action === ACTION_SELECT) await selectModelsFlow(ctx, id, entry);
1171
+ else if (action === ACTION_PROBE) await probeModelsFlow(ctx, id, entry);
1172
+ else if (action === ACTION_THINKING) await thinkingFlow(ctx, id, entry);
935
1173
  }
936
1174
  };
937
1175
 
@@ -1067,6 +1305,34 @@ if (isMain(import.meta.url)) {
1067
1305
  assert((auth.b as { key: string }).key === "2" && auth.a !== undefined, "withAuth adds one credential");
1068
1306
  assert(withoutAuth(auth, "a").a === undefined, "withoutAuth removes one");
1069
1307
 
1308
+ // Secrets: the hint never shows more than the tail, and only a literal inline key counts.
1309
+ assert(keyHint("sk-abcdefgh1234") === "••••1234", "the hint keeps the last four characters");
1310
+ assert(keyHint("short") === "••••", "a short secret shows nothing at all");
1311
+ assert(!keyHint("sk-abcdefgh1234").includes("abcdefgh"), "the body of the key never reaches the screen");
1312
+ assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "dummy", models: [] }) === undefined, "a placeholder is not a key");
1313
+ assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "ollama", models: [] }) === undefined, "the keyless placeholder is not a key");
1314
+ assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "$OPENAI_KEY", models: [] }) === undefined, "an env reference is not a key");
1315
+ assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "sk-1", models: [] }) === "sk-1", "a literal key is read back");
1316
+
1317
+ // The Edit screen's patches: one field lands, the models and every sibling survive, and
1318
+ // a rename keeps the provider's place in the list with its credential following it.
1319
+ const fieldEntry = { providers: { r: { name: "r", baseUrl: "old", api: "openai-completions", apiKey: "sk-1", compat: { x: 1 }, models: [{ id: "m1" }] } } };
1320
+ const patched = withProviderFields(fieldEntry, "r", { baseUrl: "https://new.example/v1" });
1321
+ const patchedEntry = (patched.providers as Record<string, Record<string, unknown>>).r!;
1322
+ assert(patchedEntry.baseUrl === "https://new.example/v1" && patchedEntry.apiKey === "sk-1", "withProviderFields rewrites the named field only");
1323
+ assert((patchedEntry.models as unknown[]).length === 1 && patchedEntry.compat !== undefined, "an endpoint edit keeps models and compat");
1324
+ assert(((fieldEntry.providers as Record<string, Record<string, unknown>>).r!).baseUrl === "old", "withProviderFields does not mutate its input");
1325
+ assert((withProviderFields(fieldEntry, "r", { apiKey: undefined }).providers as Record<string, Record<string, unknown>>).r!.apiKey === undefined, "an undefined patch drops the field");
1326
+ const renamed = renameProvider({ providers: { a: { name: "a", models: [{ id: "m" }] }, b: { name: "" } } }, "a", "c");
1327
+ assert(providerNames(renamed).join() === "c,b", "renameProvider keeps the position and changes the id");
1328
+ assert((renamed.providers as Record<string, { name?: string; models?: unknown[] }>).c!.name === "c", "a name that repeated the old id follows it");
1329
+ assert(((renamed.providers as Record<string, { models?: unknown[] }>).c!.models ?? []).length === 1, "a rename keeps the models");
1330
+ assert((renameProvider({ providers: { a: { name: "Keep" } } }, "a", "c").providers as Record<string, { name?: string }>).c!.name === "Keep", "a hand-written display name is untouched");
1331
+ assert((renameProvider({ providers: { a: {} } }, "missing", "c").providers as Record<string, unknown>).a !== undefined, "renaming a missing provider writes nothing");
1332
+ const movedAuth = renameAuth({ a: { type: "api_key", key: "1" }, b: { type: "api_key", key: "2" } }, "a", "c");
1333
+ assert((movedAuth.c as { key: string }).key === "1" && movedAuth.a === undefined && (movedAuth.b as { key: string }).key === "2", "renameAuth moves one credential");
1334
+ assert(renameAuth({}, "a", "c").a === undefined, "an absent credential is not invented");
1335
+
1070
1336
  // The model picker screen: checks toggle, `a` cycles, Esc leaves, Enter returns the ids.
1071
1337
  const fakeTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
1072
1338
  const renderModels = (checked: Set<string>, rows: ListRow[]) =>
@@ -1080,6 +1346,14 @@ if (isMain(import.meta.url)) {
1080
1346
  const picked0 = renderModels(new Set(["m1"]), [{ label: "m1" }, { label: "m2" }]);
1081
1347
  assert(picked0.some((l) => l.includes("[x] m1")) && picked0.some((l) => l.includes("[ ] m2")), "checked and unchecked rows render");
1082
1348
  assert(picked0.some((l) => l.includes("[a] API")), "the model legend advertises the flavor switch");
1349
+ // Models and Probe models share this screen, so the filter is checked once here.
1350
+ const searchable = new ListPicker(fakeTheme, [{ label: "river/flash" }, { label: "river/glm" }, { label: "other/kimi" }], undefined, { preview: () => {}, revert: () => {}, done: () => {}, requestRender: () => {}, search: "models" }, { title: screenTitle("Models"), description: "d", legend: MODEL_LEGEND }, false);
1351
+ assert(searchable.render(70).map(stripAnsi).some((l) => l.includes("> Type to filter models...")), "the idle model filter names the key-less placeholder");
1352
+ searchable.handleInput("/");
1353
+ for (const ch of "river glm") searchable.handleInput(ch);
1354
+ const narrowed = searchable.render(70).map(stripAnsi);
1355
+ assert(narrowed.filter((l) => /river\/(flash|glm)|other\/kimi/.test(l)).length === 1 && narrowed.some((l) => l.includes("river/glm")), "typing narrows the model list to the fuzzy match");
1356
+ assert(searchable.index === 1, "the selection follows the filtered row back to its model");
1083
1357
 
1084
1358
  // The store reads with pi's own tolerance: a hand-edited models.json (comments, trailing
1085
1359
  // commas) is exactly what pi itself accepts, and strings containing `//` or `,]` survive.
@@ -1114,7 +1388,15 @@ if (isMain(import.meta.url)) {
1114
1388
  const wireHigh = levelToWire("high") as { reasoning?: boolean; thinkingLevelMap?: Record<string, string | null> };
1115
1389
  assert(wireHigh.reasoning === true, "a pinned level sets reasoning");
1116
1390
  assert(wireHigh.thinkingLevelMap?.high === "high", "the pinned level maps to itself");
1117
- assert(THINKING_LEVELS.filter((l) => wireHigh.thinkingLevelMap![l] === null).length === 6, "every other level is null");
1391
+ assert(wireHigh.thinkingLevelMap?.medium === "medium" && wireHigh.thinkingLevelMap?.minimal === "minimal", "levels below the ceiling stay available");
1392
+ assert(wireHigh.thinkingLevelMap?.xhigh === null && wireHigh.thinkingLevelMap?.max === null, "levels above the ceiling are null");
1393
+ assert(!("off" in wireHigh.thinkingLevelMap!), "off stays unmapped, so thinking can still be turned off");
1394
+ assert(wireToLevel(true, { off: null, minimal: null, low: null, medium: null, high: null, xhigh: "xhigh", max: null }) === "xhigh", "the old single-pin shape still reads as its level");
1395
+ assert(wireToLevel(true, { low: "low", medium: "medium", high: "high", xhigh: "xhigh" }) === "auto", "heal's default map is auto, not an xhigh pin");
1396
+ assert(wireToLevel(true, { medium: "high" }) === "auto", "a probed remap is auto");
1397
+ assert(wireToLevel(true, { minimal: null, low: "low", medium: null, high: "high", xhigh: null, max: "max" }) === "auto", "an exact probed map with gaps is auto, not a max ceiling");
1398
+ assert(loadProviderEntry({ providers: { p: { models: [{ id: "m", reasoning: true, thinkingLevelMap: { medium: null } }] } } }, "p")?.models[0]?.map?.medium === null, "a probed map survives a reload");
1399
+ for (const l of ["minimal", "low", "medium", "high", "xhigh", "max"] as const) assert(wireToLevel(true, levelToWire(l).thinkingLevelMap) === l, `wire round-trips ${l}`);
1118
1400
  assert(levelToWire("xhigh")!.thinkingLevelMap!.xhigh === "xhigh", "xhigh needs its explicit map entry");
1119
1401
  const wireAuto = levelToWire("auto") as { reasoning?: boolean; thinkingLevelMap?: Record<string, string | null> };
1120
1402
  assert(wireAuto.reasoning === true && wireAuto.thinkingLevelMap === undefined, "auto is reasoning without a map");
@@ -1159,7 +1441,6 @@ if (isMain(import.meta.url)) {
1159
1441
  assert(levelsSummary([{ id: "a" }]) === "0 thinking", "an all-chat save says so plainly");
1160
1442
  // The Thinking screen's bulk keys are Shift+letter: pi-tui lowercases a key id, so this
1161
1443
  // pins that they stay distinct from the plain letters navigation already uses.
1162
- assert(matchesKey("A", "shift+a") && !matchesKey("a", "shift+a"), "Shift+A is its own key, not plain a");
1163
1444
  assert(matchesKey("R", "shift+r") && !matchesKey("r", "shift+r"), "Shift+R is its own key, not plain r");
1164
1445
 
1165
1446
  // The stored key is read back from auth.json in an isolated agent dir (never the user's).
@@ -1184,6 +1465,23 @@ if (isMain(import.meta.url)) {
1184
1465
  assert(readAuthKey("t2") === undefined, "the interrupted save never reached auth.json");
1185
1466
  rmSync(blockedTmp, { recursive: true, force: true });
1186
1467
  assert(readdirSync(tmp).every((f) => !f.endsWith(".tmp")), "a completed save leaves no temp files behind");
1468
+ // Edit writes: the key moves to auth.json and leaves models.json, so the secret lives in
1469
+ // one place; an env reference is configuration and stays put.
1470
+ saveProvider("t3", { name: "t3", baseUrl: "https://z.com/v1", api: "openai-completions", apiKey: "sk-inline", models: [{ id: "m" }] }, undefined);
1471
+ saveProviderKey("t3", "sk-edited");
1472
+ assert(readAuthKey("t3") === "sk-edited", "an edited key lands in auth.json");
1473
+ const t3 = (loadModelsConfig().providers as Record<string, Record<string, unknown>>).t3!;
1474
+ assert(t3.apiKey === undefined, "the inline copy is dropped, so the secret lives in one place");
1475
+ assert(t3.baseUrl === "https://z.com/v1" && (t3.models as unknown[]).length === 1, "the key edit leaves the rest of the entry alone");
1476
+ saveProviderKey("t3", undefined);
1477
+ assert(readAuthKey("t3") === undefined, "an empty key removes the credential");
1478
+ saveProvider("t4", { name: "t4", baseUrl: "https://w.com/v1", api: "openai-completions", apiKey: "$W_KEY", models: [] }, undefined);
1479
+ saveProviderKey("t4", "sk-y");
1480
+ assert((loadModelsConfig().providers as Record<string, Record<string, unknown>>).t4!.apiKey === "$W_KEY", "an env reference survives an edit");
1481
+ saveProvider("t5", { name: "t5", baseUrl: "https://v.com/v1", api: "openai-completions", models: [{ id: "m" }] }, "sk-t5");
1482
+ saveModelsConfig(renameProvider(loadModelsConfig(), "t5", "t6"));
1483
+ assert(providerNames(loadModelsConfig()).includes("t6") && !providerNames(loadModelsConfig()).includes("t5"), "a rename reaches models.json");
1484
+ assert(loadProviderEntry(loadModelsConfig(), "t6")?.models[0]!.id === "m", "the renamed provider keeps its models");
1187
1485
  delete process.env.PI_CODING_AGENT_DIR;
1188
1486
  rmSync(tmp, { recursive: true, force: true });
1189
1487