/** * Keys Extension - /keys command for managing API keys + file watcher hot-reload. * * Per Q5 strategy C: explicit /keys command AND file watcher on * ~/.phi/agent/models.json + routing.json. * * Subcommands: * /keys : list configured providers with masked keys * /keys set : set or update a provider key * /keys remove : remove a provider key (preserves the rest of config) * /keys test : ping the provider API to validate the key * /keys reload : force reload from disk (triggers store_reloaded event) * * File watcher (started at session_start) reloads automatically when the * user edits ~/.phi/agent/models.json or routing.json with their text editor. * The smart-router and orchestrator listen for these events to invalidate * their internal caches. * * Security (Q6): keys are stored in plain text in ~/.phi/agent/models.json * with chmod 0600 on Unix. The user is warned in /setup and on `set`. */ import { ApiKeyStore, type ExtensionAPI, type ExtensionContext, getApiKeyStore, getConfigWatcher } from "phi-code"; import { pingAlibaba } from "./providers/alibaba.ts"; import { pingOpenCodeGo } from "./providers/opencode-go.ts"; import { bootstrapProviderConfig, isBootstrappableProvider } from "./providers/provider-bootstrap.ts"; type ProviderPingFn = (key: string, timeoutMs?: number) => Promise<{ ok: boolean; error?: string }>; const PROVIDER_PING_REGISTRY: Record = {}; /** * Public helper for other extensions to register a ping function for a provider. * Used by alibaba.ts / opencode-go.ts to expose validation. */ export function registerProviderPing(providerId: string, ping: ProviderPingFn): void { PROVIDER_PING_REGISTRY[providerId] = ping; } export default function keysExtension(pi: ExtensionAPI) { const store = getApiKeyStore(); const watcher = getConfigWatcher(); // Built-in pings so `/keys test ` works out of the box for the providers // phi ships builders for (previously nothing ever registered a ping). registerProviderPing("alibaba-codingplan", pingAlibaba); registerProviderPing("alibaba-codingplan-anthropic", pingAlibaba); registerProviderPing("opencode-go", pingOpenCodeGo); registerProviderPing("opencode-go-anthropic", pingOpenCodeGo); pi.registerCommand("keys", { description: "Manage API keys (list / set / remove / test / reload)", handler: async (args, ctx) => { const tokens = args.trim().split(/\s+/).filter(Boolean); const sub = tokens[0]?.toLowerCase() ?? ""; try { if (sub === "" || sub === "list") { const providers = store.listProviders(); if (providers.length === 0) { ctx.ui.notify( "No providers configured. Use `/keys set ` or `/setup` to add one.", "info", ); return; } let out = `**API Keys (${providers.length} providers)**\n\n`; out += `Storage: \`${store.configPath}\` (chmod 0600 on Unix)\n\n`; for (const id of providers) { const cfg = store.getProvider(id); const masked = ApiKeyStore.maskKey(cfg?.apiKey); const url = cfg?.baseUrl ?? "(no baseUrl)"; out += ` **${id}** : \`${masked}\` -> ${url}\n`; } out += `\nCommands: \`/keys set \`, \`/keys remove \`, \`/keys test \`, \`/keys reload\``; ctx.ui.notify(out, "info"); return; } if (sub === "set") { const id = tokens[1]; const key = tokens.slice(2).join(" "); if (!id || !key) { ctx.ui.notify("Usage: `/keys set `", "warning"); return; } // A bare `set` only updates the key; it cannot supply baseUrl/api/models. // For a never-configured id: bootstrap the full entry when phi ships a // builder for it (Alibaba Coding Plan, OpenCode Go); otherwise keep the // old behaviour and point at /setup. const existing = store.getProvider(id); if (!existing?.baseUrl) { if (!isBootstrappableProvider(id)) { ctx.ui.notify( `\`${id}\` is not a configured provider (no baseUrl on file). ` + `Run \`/setup\` to add it with an endpoint and models first; ` + `\`/keys set\` only updates the key of an already-configured provider.`, "warning", ); return; } const boot = bootstrapProviderConfig(id, key); if (!boot.ok) { ctx.ui.notify(`Cannot configure \`${id}\`: ${boot.error}`, "warning"); return; } watcher.muteForWrite("models_json_changed"); store.setKey(id, key, { baseUrl: boot.config.baseUrl, api: boot.config.api, models: boot.config.models, }); ctx.ui.notify( `Configured \`${id}\` (\`${ApiKeyStore.maskKey(key)}\`) — ${boot.note}\n` + `Stored in ${store.configPath}. Use \`/keys test ${id}\` to validate, then pick a model with \`/model\`.`, "info", ); return; } watcher.muteForWrite("models_json_changed"); store.setKey(id, key); ctx.ui.notify( `Key set for \`${id}\` (\`${ApiKeyStore.maskKey(key)}\`). Stored in ${store.configPath}.\n` + `Hot-reload will propagate to providers using this key.\n` + `Use \`/keys test ${id}\` to validate.`, "info", ); return; } if (sub === "remove" || sub === "rm" || sub === "delete") { const id = tokens[1]; if (!id) { ctx.ui.notify("Usage: `/keys remove `", "warning"); return; } const before = store.getKey(id); if (!before) { ctx.ui.notify(`No key configured for \`${id}\`. Nothing to remove.`, "info"); return; } watcher.muteForWrite("models_json_changed"); store.removeKey(id); ctx.ui.notify(`Key removed for \`${id}\` (provider config retained).`, "info"); return; } if (sub === "test") { const id = tokens[1]; if (!id) { ctx.ui.notify("Usage: `/keys test `", "warning"); return; } const key = store.getKey(id); if (!key) { ctx.ui.notify(`No key configured for \`${id}\`.`, "warning"); return; } const ping = PROVIDER_PING_REGISTRY[id]; if (!ping) { ctx.ui.notify( `No ping handler registered for \`${id}\`. Built-in pings exist for: ${Object.keys(PROVIDER_PING_REGISTRY).join(", ") || "(none)"}.`, "warning", ); return; } ctx.ui.notify(`Pinging \`${id}\`...`, "info"); const result = await ping(key); if (result.ok) { ctx.ui.notify(`\`${id}\`: API key valid (200 OK).`, "info"); } else { ctx.ui.notify(`\`${id}\`: ${result.error ?? "ping failed"}`, "error"); } return; } if (sub === "reload") { store.reloadFromDisk(); ctx.ui.notify("Reloaded keys from disk. Listeners notified.", "info"); return; } ctx.ui.notify("Unknown subcommand. Use: `/keys [list|set|remove|test|reload]`", "warning"); } catch (err) { ctx.ui.notify(`/keys error: ${err instanceof Error ? err.message : String(err)}`, "error"); } }, }); // The watcher is a process-wide singleton and session_start fires again on // /new, /resume and /fork: listeners are registered ONCE (re-registering // stacked duplicate reloads/notifications per session switch) and talk to // the CURRENT session's UI, never a ctx captured by an earlier session. let currentCtx: ExtensionContext | undefined; let watcherListeners: Array<[string, (data: unknown) => void]> | undefined; const notify = (message: string, type: "info" | "warning") => { try { currentCtx?.ui.notify(message, type); } catch { /* UI gone (session shutting down): nothing to show */ } }; pi.on("session_start", async (_event, ctx) => { currentCtx = ctx; try { store.load(); } catch { // Empty/missing models.json on first run is normal } watcher.start(); if (!watcherListeners) { watcherListeners = [ [ "models_json_changed", () => { try { store.reloadFromDisk(); notify("Detected change in `models.json`. Keys reloaded.", "info"); } catch (err) { notify(`Failed to reload models.json: ${err}`, "warning"); } }, ], [ "routing_json_changed", () => { notify("Detected change in `routing.json`. Smart-router will reload on next input.", "info"); pi.events.emit("routing_json_changed", { source: "watcher" }); }, ], [ "watcher_error", (data: unknown) => { const d = data as { path: string; error: unknown }; notify(`Config watcher error on ${d.path}: ${d.error}`, "warning"); }, ], ]; for (const [event, listener] of watcherListeners) watcher.on(event, listener); } const providers = store.listProviders(); if (providers.length > 0) { ctx.ui.notify( `Loaded ${providers.length} provider key(s) from \`~/.phi/agent/models.json\` (chmod 0600). ` + `Use \`/keys\` to list/manage. Editing this file in your editor will hot-reload.`, "info", ); } }); pi.on("session_shutdown", async () => { // Release the singleton watcher's listeners so a reloaded extension // instance does not stack a second set on top of these. for (const [event, listener] of watcherListeners ?? []) watcher.off(event, listener); watcherListeners = undefined; currentCtx = undefined; }); }