import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent"; import { readFileSync, existsSync } from "node:fs"; import { join } from "node:path"; import { homedir } from "node:os"; import { loadSettings } from "./settings.js"; function readAuthJson(): Record | null { const authPath = join(process.env.HOME || homedir(), ".pi", "agent", "auth.json"); if (!existsSync(authPath)) return null; try { const raw = readFileSync(authPath, "utf-8"); const parsed = JSON.parse(raw); if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null; return parsed as Record; } catch { return null; } } export async function agentrouterConfigCommand( _args: string, ctx: ExtensionCommandContext ): Promise { const settings = loadSettings(ctx.cwd); const lines: string[] = []; lines.push(`Agent Router Configuration`); lines.push(`========================`); lines.push(``); lines.push(`API Base: ${settings.api_base}`); lines.push(`Debug: ${settings.debug}`); lines.push(``); // ── auth.json entries (primary) ───────────────────────────────────────── const authData = readAuthJson(); const prefix = settings.provider_prefix ?? "agentrouter"; if (authData) { const authEntries = Object.entries(authData) .filter(([name]) => name === prefix || name.startsWith(`${prefix}_`)) .filter(([, entry]) => entry.type === "api_key" && entry.key) .map(([name, entry]) => ({ name, key: entry.key })); if (authEntries.length > 0) { lines.push(`Credentials (from auth.json):`); for (const { name, key } of authEntries) { lines.push(` ${name}: ${key.slice(0, 8)}...`); } lines.push(``); if (settings.api_keys && settings.api_keys.length > 0) { lines.push(`(settings.json api_keys ignored — auth.json is active)`); lines.push(``); } ctx.ui.notify(lines.join("\n"), "info"); return; } } // ── Fallback: settings.json api_keys ──────────────────────────────────── lines.push(`API Keys: ${settings.api_keys?.length ?? 0} configured (settings.json — deprecated)`); lines.push(``); if (settings.api_keys) { lines.push(`Keys:`); settings.api_keys.forEach((key, i) => { if (typeof key === "string") { const display = key === "$AGENT_ROUTER_API_KEY" ? "$AGENT_ROUTER_API_KEY" : key.slice(0, 8) + "..."; lines.push(` [${i}] ${display}`); } else { lines.push(` [${i}] id=${key.id ?? i}, key=${key.key.slice(0, 8)}...`); } }); } ctx.ui.notify(lines.join("\n"), "info"); }