import { writeFileSync, readFileSync, existsSync, mkdirSync, chmodSync } from "fs"; import { homedir } from "os"; import { join } from "path"; const AUTH_JSON = join(homedir(), ".pi", "agent", "auth.json"); /** * Save SumoPod API key to Pi's auth.json. * * Pi reads auth.json for provider credentials via AuthStorage.getApiKey(). * Format: { "sumopod": { "type": "api_key", "key": "sk-xxx" } } */ export function setSumopodApiKey(apiKey: string): void { const dir = join(homedir(), ".pi", "agent"); if (!existsSync(dir)) { mkdirSync(dir, { recursive: true, mode: 0o700 }); } // Read existing auth.json (preserve other providers) let data: Record = {}; if (existsSync(AUTH_JSON)) { try { data = JSON.parse(readFileSync(AUTH_JSON, "utf-8")); } catch { // Malformed — don't overwrite, bail out throw new Error(`auth.json is malformed. Fix it manually at: ${AUTH_JSON}`); } } data["sumopod"] = { type: "api_key", key: apiKey }; writeFileSync(AUTH_JSON, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 0o600 }); try { chmodSync(AUTH_JSON, 0o600); } catch { /* best-effort on Windows */ } }