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;IAED;;;;OAIG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,OAAO,CAAC,uBAAuB,CAAC,GAAG,IAAI,CAa/F;IAED;;;OAGG;IACH,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAQlC;IAED;;OAEG;IACH,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAM9C;IAED;;;;;;OAMG;IACH,OAAO,CAAC,OAAO;CAmBf;AAID,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,kBAAkB,GAAG,WAAW,CAKxE;AAED,wBAAgB,iBAAiB,IAAI,IAAI,CAExC","sourcesContent":["/**\n * API Key Store - Centralized storage and hot-reload for provider API keys.\n *\n * Per Q5 strategy C: explicit /keys command + file watcher both supported.\n * Per Q6 strategy A: keys stored in plain text in ~/.phi/agent/models.json\n * with chmod 0600 on Unix and clear warnings to users.\n *\n * Storage format: models.json providers.<id>.apiKey. Resolution follows the\n * same convention as model-registry/resolve-config-value (\"env var name or\n * literal value\", plus \"!cmd\" shell commands):\n *   1. Value in models.json — \"!cmd\" runs the command (cached per process),\n *      an env-var NAME resolves to its value, \"$NAME\" (legacy notation)\n *      resolves NAME and is never returned literally, anything else is the\n *      literal key\n *   2. process.env[envVar] (legacy fallback)\n *\n * The file may contain // comments and trailing commas (same tolerance as\n * model-registry). Note that setKey()/removeKey() rewrite the file as plain\n * JSON, so comments do not survive a programmatic write.\n *\n * Events emitted via the EventEmitter:\n *   - \"key_changed\" { provider }       : when setKey() or external edit detected\n *   - \"key_removed\" { provider }       : when removeKey() called\n *   - \"store_reloaded\"                 : when reloadFromDisk() succeeds\n */\n\nimport { EventEmitter } from \"node:events\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { getModelsPath } from \"../config.ts\";\nimport { stripBom } from \"../utils/text.ts\";\nimport { stripJsonComments } from \"./json-utils.ts\";\nimport { resolveConfigValue } from \"./resolve-config-value.ts\";\n\nexport interface ProviderConfigPersisted {\n\tbaseUrl?: string;\n\tapi?: string;\n\tapiKey?: string;\n\theaders?: Record<string, string>;\n\tauthHeader?: boolean;\n\tmodels?: unknown[];\n\tmodelOverrides?: Record<string, unknown>;\n}\n\nexport interface ModelsConfigPersisted {\n\t$comment?: string;\n\tproviders: Record<string, ProviderConfigPersisted>;\n}\n\nexport interface ApiKeyStoreOptions {\n\tconfigPath?: string;\n}\n\nexport class ApiKeyStore extends EventEmitter {\n\treadonly configPath: string;\n\tprivate config: ModelsConfigPersisted = { providers: {} };\n\tprivate loaded = false;\n\n\tconstructor(options: ApiKeyStoreOptions = {}) {\n\t\tsuper();\n\t\tthis.configPath = options.configPath ?? getModelsPath();\n\t}\n\n\t/**\n\t * Load config from disk. Creates an empty file if missing.\n\t */\n\tload(): ModelsConfigPersisted {\n\t\ttry {\n\t\t\tif (!existsSync(this.configPath)) {\n\t\t\t\treturn this.config;\n\t\t\t}\n\t\t\tconst raw = readFileSync(this.configPath, \"utf-8\");\n\t\t\t// Same comment/trailing-comma tolerance as model-registry: a commented\n\t\t\t// models.json must not break /keys hot-reload while the agent still runs.\n\t\t\tconst parsed = JSON.parse(stripJsonComments(stripBom(raw))) as ModelsConfigPersisted;\n\t\t\tif (!parsed.providers || typeof parsed.providers !== \"object\") {\n\t\t\t\tparsed.providers = {};\n\t\t\t}\n\t\t\tthis.config = parsed;\n\t\t\tthis.loaded = true;\n\t\t\treturn this.config;\n\t\t} catch (err) {\n\t\t\tthrow new Error(`Failed to load ${this.configPath}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t}\n\t}\n\n\t/**\n\t * Reload from disk and emit \"store_reloaded\".\n\t */\n\treloadFromDisk(): void {\n\t\tthis.load();\n\t\tthis.emit(\"store_reloaded\");\n\t}\n\n\t/**\n\t * Get the API key for a provider, with env-var fallback.\n\t *\n\t * The stored value is resolved through `resolveConfigValue`, the single\n\t * convention shared with the model runtime, so a config that works at\n\t * request time also works here: `$NAME` / `${NAME}` read the environment,\n\t * `!cmd` runs a shell command, anything else is a literal credential.\n\t *\n\t * (Before pi 0.84 a bare `NAME` also read the environment. That was\n\t * ambiguous — a literal key matching an env-var name was silently shadowed —\n\t * and the convention is now explicit. Configs written the old way must add\n\t * the `$`.)\n\t *\n\t * Returns undefined if no source yields a value.\n\t */\n\tgetKey(providerId: string, envVar?: string): string | undefined {\n\t\tif (!this.loaded) this.load();\n\t\tconst stored = this.config.providers[providerId]?.apiKey?.trim();\n\t\tif (stored && stored.length > 0) {\n\t\t\tconst resolved = resolveConfigValue(stored)?.trim();\n\t\t\tif (resolved) return resolved;\n\t\t}\n\t\tif (envVar) return process.env[envVar]?.trim() || undefined;\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Get the full provider config block for a provider.\n\t */\n\tgetProvider(providerId: string): ProviderConfigPersisted | undefined {\n\t\tif (!this.loaded) this.load();\n\t\treturn this.config.providers[providerId];\n\t}\n\n\t/**\n\t * List all configured provider IDs.\n\t */\n\tlistProviders(): string[] {\n\t\tif (!this.loaded) this.load();\n\t\treturn Object.keys(this.config.providers);\n\t}\n\n\t/**\n\t * Set the API key for a provider. Creates the provider entry if missing.\n\t * Performs atomic write (tmp + rename) and chmod 0600 on Unix.\n\t * Emits \"key_changed\" event.\n\t */\n\tsetKey(providerId: string, key: string, providerConfig?: Partial<ProviderConfigPersisted>): void {\n\t\tif (!this.loaded) this.load();\n\t\tconst existing = this.config.providers[providerId] ?? {};\n\t\tthis.config.providers[providerId] = {\n\t\t\t...existing,\n\t\t\t...providerConfig,\n\t\t\tapiKey: key,\n\t\t};\n\t\tthis.persist();\n\t\t// Do not include the raw key in the event payload to avoid leaking the\n\t\t// secret to listeners/logs. Listeners that need the value read it back\n\t\t// via getKey(providerId).\n\t\tthis.emit(\"key_changed\", { provider: providerId });\n\t}\n\n\t/**\n\t * Remove the API key for a provider (but keep the rest of the provider config).\n\t * Emits \"key_removed\" event.\n\t */\n\tremoveKey(providerId: string): void {\n\t\tif (!this.loaded) this.load();\n\t\tconst existing = this.config.providers[providerId];\n\t\tif (!existing) return;\n\t\tconst { apiKey: _removed, ...rest } = existing;\n\t\tthis.config.providers[providerId] = rest;\n\t\tthis.persist();\n\t\tthis.emit(\"key_removed\", { provider: providerId });\n\t}\n\n\t/**\n\t * Mask an API key for display (preserves length info without exposing the secret).\n\t */\n\tstatic maskKey(key: string | undefined): string {\n\t\tif (!key) return \"(not set)\";\n\t\tconst trimmed = key.trim();\n\t\tif (trimmed.length === 0) return \"(empty)\";\n\t\tif (trimmed.length <= 8) return \"********\";\n\t\treturn `${trimmed.slice(0, 6)}...${trimmed.slice(-4)}`;\n\t}\n\n\t/**\n\t * Atomic write of the config to disk:\n\t *   1. Ensure parent dir exists\n\t *   2. Write to <path>.tmp\n\t *   3. Rename to <path> (atomic on POSIX)\n\t *   4. Apply chmod 0600 on Unix (silently skip on Windows)\n\t */\n\tprivate persist(): void {\n\t\tconst isPosix = process.platform !== \"win32\";\n\t\tconst parent = dirname(this.configPath);\n\t\tmkdirSync(parent, isPosix ? { recursive: true, mode: 0o700 } : { recursive: true });\n\t\tconst tmpPath = `${this.configPath}.tmp`;\n\t\tconst payload = `${JSON.stringify(this.config, null, 2)}\\n`;\n\t\t// Write the tmp file with restrictive perms from the start so the plaintext\n\t\t// key is never world-readable on disk (mode is still subject to umask, hence\n\t\t// the belt-and-suspenders chmod below after the rename).\n\t\twriteFileSync(tmpPath, payload, isPosix ? { encoding: \"utf-8\", mode: 0o600 } : \"utf-8\");\n\t\trenameSync(tmpPath, this.configPath);\n\t\tif (isPosix) {\n\t\t\ttry {\n\t\t\t\tchmodSync(this.configPath, 0o600);\n\t\t\t} catch {\n\t\t\t\t// chmod may fail on some filesystems (eg WSL); non-critical\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Module-level singleton for convenience. */\nlet _singleton: ApiKeyStore | null = null;\nexport function getApiKeyStore(options?: ApiKeyStoreOptions): ApiKeyStore {\n\tif (!_singleton || (options?.configPath && _singleton.configPath !== options.configPath)) {\n\t\t_singleton = new ApiKeyStore(options);\n\t}\n\treturn _singleton;\n}\n\nexport function _resetApiKeyStore(): void {\n\t_singleton = null;\n}\n"]}