diff --git a/src/agents/pi-model-discovery.ts b/src/agents/pi-model-discovery.ts index 67f4aa8959b..dc8463b6dab 100644 --- a/src/agents/pi-model-discovery.ts +++ b/src/agents/pi-model-discovery.ts @@ -1,3 +1,4 @@ +import fs from "node:fs"; import path from "node:path"; import { AuthStorage, @@ -8,6 +9,51 @@ import { ensureAuthProfileStore } from "./auth-profiles.js"; import { resolvePiCredentialMapFromStore, type PiCredentialMap } from "./pi-auth-credentials.js"; export { AuthStorage, ModelRegistry } from "@mariozechner/pi-coding-agent"; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function scrubLegacyStaticAuthJsonEntries(pathname: string): void { + if (!fs.existsSync(pathname)) { + return; + } + + let parsed: unknown; + try { + parsed = JSON.parse(fs.readFileSync(pathname, "utf8")) as unknown; + } catch { + return; + } + if (!isRecord(parsed)) { + return; + } + + let changed = false; + for (const [provider, value] of Object.entries(parsed)) { + if (!isRecord(value)) { + continue; + } + if (value.type !== "api_key") { + continue; + } + delete parsed[provider]; + changed = true; + } + + if (!changed) { + return; + } + + if (Object.keys(parsed).length === 0) { + fs.rmSync(pathname, { force: true }); + return; + } + + fs.writeFileSync(pathname, `${JSON.stringify(parsed, null, 2)}\n`, "utf8"); + fs.chmodSync(pathname, 0o600); +} + function createAuthStorage(AuthStorageLike: unknown, path: string, creds: PiCredentialMap) { const withInMemory = AuthStorageLike as { inMemory?: (data?: unknown) => unknown }; if (typeof withInMemory.inMemory === "function") { @@ -54,7 +100,9 @@ function resolvePiCredentials(agentDir: string): PiCredentialMap { // Compatibility helpers for pi-coding-agent 0.50+ (discover* helpers removed). export function discoverAuthStorage(agentDir: string): AuthStorage { const credentials = resolvePiCredentials(agentDir); - return createAuthStorage(AuthStorage, path.join(agentDir, "auth.json"), credentials); + const authPath = path.join(agentDir, "auth.json"); + scrubLegacyStaticAuthJsonEntries(authPath); + return createAuthStorage(AuthStorage, authPath, credentials); } export function discoverModels(authStorage: AuthStorage, agentDir: string): ModelRegistry {