@ponythewhite/base-context 1.0.1 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/base-context-runtime/pyproject.toml +1 -1
  3. package/dist/base-context-runtime/src/rlm/mcp.py +39 -17
  4. package/dist/base-context-runtime/test/test_mcp.py +87 -1
  5. package/dist/base-context-runtime/uv.lock +1 -1
  6. package/dist/build-info.json +1 -1
  7. package/dist/bundle/{bundled-modules-TXUMJ2XQ.js → bundled-modules-R5EAJ62K.js} +2 -2
  8. package/dist/bundle/{chunk-S3INFPZZ.js → chunk-BV25CVRM.js} +378 -199
  9. package/dist/bundle/{chunk-V3L54UD6.js → chunk-XDJ56NJA.js} +26 -11
  10. package/dist/bundle/{cli-main-BYMSRPH6.js → cli-main-OUKN743U.js} +2 -2
  11. package/dist/bundle/cli.js +1 -1
  12. package/dist/bundle/{main-ODOYCEQC.js → main-QPCXSW6X.js} +2 -2
  13. package/dist/cli/daemon-ps.d.ts.map +1 -1
  14. package/dist/cli/daemon-ps.js +1 -0
  15. package/dist/cli/daemon-ps.js.map +1 -1
  16. package/dist/core/auth-storage.d.ts +4 -0
  17. package/dist/core/auth-storage.d.ts.map +1 -1
  18. package/dist/core/auth-storage.js +77 -19
  19. package/dist/core/auth-storage.js.map +1 -1
  20. package/dist/core/kernel/bootstrap.d.ts.map +1 -1
  21. package/dist/core/kernel/bootstrap.js +5 -2
  22. package/dist/core/kernel/bootstrap.js.map +1 -1
  23. package/dist/core/mcp/mcp-manager.d.ts.map +1 -1
  24. package/dist/core/mcp/mcp-manager.js +2 -2
  25. package/dist/core/mcp/mcp-manager.js.map +1 -1
  26. package/dist/installer.mjs +5 -2
  27. package/dist/modes/daemon/daemon-supervisor-ownership.d.ts.map +1 -1
  28. package/dist/modes/daemon/daemon-supervisor-ownership.js +16 -16
  29. package/dist/modes/daemon/daemon-supervisor-ownership.js.map +1 -1
  30. package/dist/modes/interactive/auth-flows.d.ts.map +1 -1
  31. package/dist/modes/interactive/auth-flows.js +7 -6
  32. package/dist/modes/interactive/auth-flows.js.map +1 -1
  33. package/dist/modes/interactive/components/login-dialog.d.ts +3 -1
  34. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  35. package/dist/modes/interactive/components/login-dialog.js +3 -1
  36. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  37. package/dist/modes/interactive/components/menu-panel.d.ts +1 -0
  38. package/dist/modes/interactive/components/menu-panel.d.ts.map +1 -1
  39. package/dist/modes/interactive/components/menu-panel.js +3 -0
  40. package/dist/modes/interactive/components/menu-panel.js.map +1 -1
  41. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  42. package/dist/modes/interactive/interactive-mode.js +7 -5
  43. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  44. package/dist/modes/rpc/rpc-client.d.ts +2 -0
  45. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  46. package/dist/modes/rpc/rpc-client.js +58 -31
  47. package/dist/modes/rpc/rpc-client.js.map +1 -1
  48. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"auth-storage.d.ts","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAGN,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACpB,MAAM,+BAA+B,CAAC;AAUvC,MAAM,MAAM,gBAAgB,GAAG;IAC9B,IAAI,EAAE,SAAS,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACZ,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,OAAO,CAAC;CACd,GAAG,gBAAgB,CAAC;AAErB,MAAM,MAAM,cAAc,GAAG,gBAAgB,GAAG,eAAe,CAAC;AAEhE,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CA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AAG,cAAc,GAAG,SAAS,CAEhD;IAED;;OAEG;IACH,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,cAAc,GAAG,IAAI,CAKtD;IAED;;OAEG;IACH,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAK7B;IAED;;;;;OAKG;IACH,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAYrC;IAED;;OAEG;IACH,IAAI,IAAI,MAAM,EAAE,CAEf;IAED;;OAEG;IACH,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAE7B;IAED;;;OAGG;IACH,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAEjC;IAED;;OAEG;IACH,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,CAE1C;IAED;;OAEG;IACH,MAAM,IAAI,eAAe,CAExB;IAED,WAAW,IAAI,KAAK,EAAE,CAIrB;IAED;;OAEG;IACG,KAAK,CAAC,UAAU,EAAE,eAAe,EAAE,SAAS,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAatF;IAED;;OAEG;IACH,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAE7B;YAMa,yBAAyB;IAiDvC;;;;;;;OAOG;IACG,wBAAwB,CAC7B,UAAU,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAA;KAAE,GACrC,OAAO,CAAC,gBAAgB,CAAC,CAsI3B;IAEK,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAGxG;IAED;;OAEG;IACH,iBAAiB,qEAGhB;CACD","sourcesContent":["/**\n * Credential storage for API keys and OAuth tokens.\n * Handles loading, saving, and refreshing credentials from auth.json.\n *\n * Uses file locking to prevent race conditions when multiple pi instances\n * try to refresh tokens simultaneously.\n */\n\nimport { createHash } from \"node:crypto\";\nimport {\n\tfindEnvKeys,\n\tgetEnvApiKey,\n\ttype OAuthCredentials,\n\ttype OAuthLoginCallbacks,\n\ttype OAuthProviderId,\n} from \"@ponythewhite/base-context-ai\";\nimport { getOAuthApiKey, getOAuthProvider, getOAuthProviders } from \"@ponythewhite/base-context-ai/oauth\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.js\";\nimport { assertProductStatePath } from \"../runtime-paths.js\";\nimport { getProviderAuthContract, isProviderApiKeyAllowed } from \"./provider-contracts.js\";\nimport { resolveConfigValue, resolveConfigValueUncached } from \"./resolve-config-value.js\";\n\nexport type ApiKeyCredential = {\n\ttype: \"api_key\";\n\tkey: string;\n};\n\nexport type OAuthCredential = {\n\ttype: \"oauth\";\n} & OAuthCredentials;\n\nexport type AuthCredential = ApiKeyCredential | OAuthCredential;\n\nexport type AuthStorageData = Record<string, AuthCredential>;\n\nexport type AuthStatus = {\n\tconfigured: boolean;\n\tsource?: \"stored\" | \"runtime\" | \"environment\" | \"fallback\" | \"models_json_key\" | \"models_json_command\" | \"stale\";\n\tlabel?: string;\n};\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\ntype ActiveAuthStatusSource = Exclude<NonNullable<AuthStatus[\"source\"]>, \"stale\">;\n\nexport type AuthSourceToken = {\n\tprovider: string;\n\tsource: ActiveAuthStatusSource;\n\tidentityFingerprint: string;\n\tvalueFingerprint: string;\n};\n\ntype AuthSourceCandidate = {\n\tsource: ActiveAuthStatusSource;\n\tconfigured: boolean;\n\tlabel?: string;\n\tidentityFingerprint: string;\n\tvalueFingerprint?: string;\n\tresolveValueFingerprint?: () => string | undefined;\n};\n\ntype AuthApiKeyResult = {\n\tapiKey?: string;\n\tsourceToken?: AuthSourceToken;\n};\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tconstructor(private authPath: string = join(getAgentDir(), \"auth.json\")) {}\n\n\tprivate ensureParentDir(): void {\n\t\tassertProductStatePath(this.authPath);\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", \"utf-8\");\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\t\tlet compromisedError: Error | undefined;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\tconst release = lockfile.lockSync(path, {\n\t\t\t\t\trealpath: false,\n\t\t\t\t\tonCompromised: (error) => {\n\t\t\t\t\t\tcompromisedError ??= error;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (compromisedError) {\n\t\t\t\t\trelease();\n\t\t\t\t\tthrow compromisedError;\n\t\t\t\t}\n\t\t\t\treturn release;\n\t\t\t} catch (error) {\n\t\t\t\tif (compromisedError) throw compromisedError;\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, \"utf-8\");\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: 30000,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, \"utf-8\");\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\tif (lockCompromised) await release().catch(() => undefined);\n\t\t\t\telse await release();\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage {\n\tprivate data: AuthStorageData = {};\n\tprivate runtimeOverrides: Map<string, string> = new Map();\n\tprivate staleAuthSources: Map<string, AuthSourceToken[]> = new Map();\n\tprivate fallbackResolver?: (provider: string) => string | undefined;\n\tprivate loadError: Error | null = null;\n\tprivate errors: Error[] = [];\n\n\tprivate constructor(\n\t\tprivate storage: AuthStorageBackend,\n\t\tprivate readonly existingOpenAICodexSubscription = false,\n\t) {\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath?: string): AuthStorage {\n\t\treturn new AuthStorage(new FileAuthStorageBackend(authPath ?? join(getAgentDir(), \"auth.json\")));\n\t}\n\n\t/** Reuse an existing host login only through an explicitly read-only backend.\n\t * This SDK mode never logs in, writes credentials, or refreshes tokens.\n\t */\n\tstatic fromStorage(\n\t\tstorage: AuthStorageBackend,\n\t\toptions?: { existingOpenAICodexSubscription?: boolean },\n\t): AuthStorage {\n\t\tconst existing = options?.existingOpenAICodexSubscription === true;\n\t\tif (!existing) return new AuthStorage(storage);\n\t\tif (storage instanceof FileAuthStorageBackend)\n\t\t\tthrow new Error(\"Existing OpenAI subscription requires a read-only auth backend\");\n\t\tconst readOnly: AuthStorageBackend = {\n\t\t\twithLock: (read) =>\n\t\t\t\tstorage.withLock((current) => {\n\t\t\t\t\tconst { result, next } = read(current);\n\t\t\t\t\tif (next !== undefined) throw new Error(\"Existing OpenAI subscription storage is read-only\");\n\t\t\t\t\treturn { result };\n\t\t\t\t}),\n\t\t\t// Refresh happens inside this callback, so never invoke it in this mode.\n\t\t\twithLockAsync: async () => {\n\t\t\t\tthrow new Error(\"Existing OpenAI subscription refresh is disabled\");\n\t\t\t},\n\t\t};\n\t\treturn new AuthStorage(readOnly, true);\n\t}\n\n\tisExistingOpenAICodexSubscription(provider: string): boolean {\n\t\treturn this.existingOpenAICodexSubscription && provider === \"openai-codex\";\n\t}\n\n\tprivate assertWritableStorage(): void {\n\t\tif (this.existingOpenAICodexSubscription) throw new Error(\"Existing OpenAI subscription storage is read-only\");\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\t/**\n\t * Set a runtime API key override (not persisted to disk).\n\t * Used for CLI --api-key flag.\n\t */\n\tsetRuntimeApiKey(provider: string, apiKey: string): void {\n\t\tthis.clearStaleAuthSource(provider, \"runtime\");\n\t\tthis.runtimeOverrides.set(provider, apiKey);\n\t}\n\n\t/**\n\t * Remove a runtime API key override.\n\t */\n\tremoveRuntimeApiKey(provider: string): void {\n\t\tthis.clearStaleAuthSource(provider, \"runtime\");\n\t\tthis.runtimeOverrides.delete(provider);\n\t}\n\n\t/**\n\t * Set a fallback resolver for API keys not found in auth.json or env vars.\n\t * Used for custom provider keys from models.json.\n\t */\n\tsetFallbackResolver(resolver: (provider: string) => string | undefined): void {\n\t\tthis.fallbackResolver = resolver;\n\t}\n\n\tprivate recordError(error: unknown): void {\n\t\tconst normalizedError = error instanceof Error ? error : new Error(String(error));\n\t\tthis.errors.push(normalizedError);\n\t}\n\n\tprivate fingerprintAuthSource(source: ActiveAuthStatusSource, material: string): string {\n\t\tconst digest = createHash(\"sha256\").update(source).update(\"\\0\").update(material).digest(\"hex\");\n\t\treturn `${source}:${digest}`;\n\t}\n\n\tprivate createAuthSourceCandidate(options: {\n\t\tsource: ActiveAuthStatusSource;\n\t\tconfigured: boolean;\n\t\tidentityMaterial: string;\n\t\tvalueMaterial?: string;\n\t\tlabel?: string;\n\t\tresolveValueMaterial?: () => string | undefined;\n\t}): AuthSourceCandidate {\n\t\treturn {\n\t\t\tconfigured: options.configured,\n\t\t\tsource: options.source,\n\t\t\t...(options.label ? { label: options.label } : {}),\n\t\t\tidentityFingerprint: this.fingerprintAuthSource(options.source, `identity:${options.identityMaterial}`),\n\t\t\t...(options.valueMaterial !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\tvalueFingerprint: this.fingerprintAuthSource(\n\t\t\t\t\t\t\toptions.source,\n\t\t\t\t\t\t\t`value:${options.identityMaterial}\\0${options.valueMaterial}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(options.resolveValueMaterial\n\t\t\t\t? {\n\t\t\t\t\t\tresolveValueFingerprint: () => {\n\t\t\t\t\t\t\tconst valueMaterial = options.resolveValueMaterial?.();\n\t\t\t\t\t\t\treturn valueMaterial === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: this.fingerprintAuthSource(\n\t\t\t\t\t\t\t\t\t\toptions.source,\n\t\t\t\t\t\t\t\t\t\t`value:${options.identityMaterial}\\0${valueMaterial}`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\tprivate getStoredCredentialValueMaterial(providerId: string, credential: AuthCredential): string | undefined {\n\t\tif (credential.type === \"api_key\") {\n\t\t\tconst isCommand = credential.key.startsWith(\"!\");\n\t\t\tconst resolvedKey = isCommand\n\t\t\t\t? resolveConfigValueUncached(credential.key)\n\t\t\t\t: resolveConfigValue(credential.key);\n\t\t\tif (resolvedKey !== undefined && !isProviderApiKeyAllowed(providerId, resolvedKey)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (isCommand) {\n\t\t\t\treturn resolvedKey === undefined ? undefined : `api_key:command:${credential.key}\\0${resolvedKey}`;\n\t\t\t}\n\t\t\treturn `api_key:${credential.key}\\0${resolvedKey ?? \"\"}`;\n\t\t}\n\t\tif (this.isExistingOpenAICodexSubscription(providerId))\n\t\t\treturn `oauth:${credential.access}\\0${credential.expires}`;\n\t\tif (getProviderAuthContract(providerId).oauth !== \"supported\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst provider = getOAuthProvider(providerId);\n\t\tconst apiKey = provider?.getApiKey(credential) ?? credential.access;\n\t\treturn `oauth:${apiKey}\\0${credential.refresh}\\0${credential.expires}`;\n\t}\n\n\tprivate getRuntimeAuthCandidate(provider: string): AuthSourceCandidate | undefined {\n\t\tconst apiKey = this.runtimeOverrides.get(provider);\n\t\tif (!apiKey || !isProviderApiKeyAllowed(provider, apiKey)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\tlabel: \"--api-key\",\n\t\t\t...this.createAuthSourceCandidate({\n\t\t\t\tconfigured: false,\n\t\t\t\tsource: \"runtime\",\n\t\t\t\tidentityMaterial: provider,\n\t\t\t\tvalueMaterial: apiKey,\n\t\t\t}),\n\t\t};\n\t}\n\n\tprivate getStoredAuthCandidate(\n\t\tprovider: string,\n\t\toptions?: { resolveCommandValue?: boolean; resolvedCommandValue?: string },\n\t): AuthSourceCandidate | undefined {\n\t\tconst credential = this.data[provider];\n\t\tif (\n\t\t\t!credential ||\n\t\t\t(credential.type === \"oauth\" &&\n\t\t\t\tgetProviderAuthContract(provider).oauth !== \"supported\" &&\n\t\t\t\t!this.isExistingOpenAICodexSubscription(provider))\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst isCommandApiKey = credential.type === \"api_key\" && credential.key.startsWith(\"!\");\n\t\tif (credential.type === \"api_key\") {\n\t\t\tconst apiKey =\n\t\t\t\toptions?.resolvedCommandValue ?? (isCommandApiKey ? credential.key : resolveConfigValue(credential.key));\n\t\t\tif (apiKey !== undefined && !isProviderApiKeyAllowed(provider, apiKey)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t\tconst identityMaterial = isCommandApiKey ? `api_key:command:${credential.key}` : `${provider}:${credential.type}`;\n\t\tconst commandValueMaterial =\n\t\t\tisCommandApiKey && options?.resolvedCommandValue !== undefined\n\t\t\t\t? `api_key:command:${credential.key}\\0${options.resolvedCommandValue}`\n\t\t\t\t: undefined;\n\t\treturn this.createAuthSourceCandidate({\n\t\t\tconfigured: true,\n\t\t\tsource: \"stored\",\n\t\t\tidentityMaterial,\n\t\t\tvalueMaterial:\n\t\t\t\tcommandValueMaterial ??\n\t\t\t\t(isCommandApiKey && !options?.resolveCommandValue\n\t\t\t\t\t? undefined\n\t\t\t\t\t: this.getStoredCredentialValueMaterial(provider, credential)),\n\t\t\tresolveValueMaterial: isCommandApiKey\n\t\t\t\t? () => this.getStoredCredentialValueMaterial(provider, credential)\n\t\t\t\t: undefined,\n\t\t});\n\t}\n\n\tprivate getEnvironmentApiKey(provider: string): string | undefined {\n\t\tconst apiKey = getEnvApiKey(provider);\n\t\treturn apiKey && isProviderApiKeyAllowed(provider, apiKey) ? apiKey : undefined;\n\t}\n\n\tprivate getEnvironmentAuthCandidate(provider: string): AuthSourceCandidate | undefined {\n\t\tconst envKeys = findEnvKeys(provider);\n\t\tconst envKey = envKeys?.[0];\n\t\tconst apiKey = this.getEnvironmentApiKey(provider);\n\t\tif (!apiKey) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst label = envKey ?? \"ambient credentials\";\n\t\tconst identityMaterial = envKey ?? this.getAmbientEnvironmentIdentityMaterial(provider);\n\t\treturn this.createAuthSourceCandidate({\n\t\t\tconfigured: false,\n\t\t\tsource: \"environment\",\n\t\t\tlabel,\n\t\t\tidentityMaterial,\n\t\t\tvalueMaterial: `${identityMaterial}\\0${apiKey}`,\n\t\t});\n\t}\n\n\tprivate getAmbientEnvironmentIdentityMaterial(provider: string): string {\n\t\tif (provider === \"amazon-bedrock\") {\n\t\t\tif (process.env.AWS_PROFILE) return `amazon-bedrock:profile:${process.env.AWS_PROFILE}`;\n\t\t\tif (process.env.AWS_ACCESS_KEY_ID) {\n\t\t\t\treturn `amazon-bedrock:access-key:${process.env.AWS_ACCESS_KEY_ID}:${process.env.AWS_SECRET_ACCESS_KEY ?? \"\"}:${process.env.AWS_SESSION_TOKEN ?? \"\"}`;\n\t\t\t}\n\t\t\tif (process.env.AWS_BEARER_TOKEN_BEDROCK) {\n\t\t\t\treturn `amazon-bedrock:bearer:${process.env.AWS_BEARER_TOKEN_BEDROCK}`;\n\t\t\t}\n\t\t\tif (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) {\n\t\t\t\treturn `amazon-bedrock:ecs-relative:${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`;\n\t\t\t}\n\t\t\tif (process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI) {\n\t\t\t\treturn `amazon-bedrock:ecs-full:${process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI}`;\n\t\t\t}\n\t\t\tif (process.env.AWS_WEB_IDENTITY_TOKEN_FILE) {\n\t\t\t\treturn `amazon-bedrock:web-identity:${process.env.AWS_WEB_IDENTITY_TOKEN_FILE}`;\n\t\t\t}\n\t\t}\n\t\tif (provider === \"google-vertex\") {\n\t\t\tconst project = process.env.GOOGLE_CLOUD_PROJECT ?? process.env.GCLOUD_PROJECT ?? \"\";\n\t\t\tconst location = process.env.GOOGLE_CLOUD_LOCATION ?? \"\";\n\t\t\tconst credentialsPath = process.env.GOOGLE_APPLICATION_CREDENTIALS ?? \"application-default\";\n\t\t\treturn `google-vertex:${project}:${location}:${credentialsPath}`;\n\t\t}\n\t\treturn provider;\n\t}\n\n\tprivate getFallbackAuthCandidate(provider: string): AuthSourceCandidate | undefined {\n\t\tconst apiKey = this.fallbackResolver?.(provider);\n\t\tif (!apiKey || !isProviderApiKeyAllowed(provider, apiKey)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.createAuthSourceCandidate({\n\t\t\tconfigured: false,\n\t\t\tsource: \"fallback\",\n\t\t\tlabel: \"custom provider config\",\n\t\t\tidentityMaterial: provider,\n\t\t\tvalueMaterial: apiKey,\n\t\t});\n\t}\n\n\tprivate getAuthSourceCandidates(provider: string, options?: { includeFallback?: boolean }): AuthSourceCandidate[] {\n\t\tconst fallbackCandidate =\n\t\t\toptions?.includeFallback === false ? undefined : this.getFallbackAuthCandidate(provider);\n\t\tconst candidates = [\n\t\t\tthis.getRuntimeAuthCandidate(provider),\n\t\t\tthis.getStoredAuthCandidate(provider),\n\t\t\tthis.getEnvironmentAuthCandidate(provider),\n\t\t\tfallbackCandidate,\n\t\t];\n\t\treturn candidates.filter((candidate): candidate is AuthSourceCandidate => candidate !== undefined);\n\t}\n\n\tprivate isAuthSourceStale(provider: string, candidate: AuthSourceCandidate): boolean {\n\t\tconst matchingStale = this.getMatchingStaleAuthSources(provider, candidate);\n\t\tif (matchingStale.length === 0) {\n\t\t\treturn false;\n\t\t}\n\t\tconst valueFingerprint = candidate.valueFingerprint ?? candidate.resolveValueFingerprint?.();\n\t\treturn Boolean(valueFingerprint && matchingStale.some((token) => token.valueFingerprint === valueFingerprint));\n\t}\n\n\tprivate getMatchingStaleAuthSources(provider: string, candidate: AuthSourceCandidate): AuthSourceToken[] {\n\t\tconst stale = this.staleAuthSources.get(provider);\n\t\tif (!stale) {\n\t\t\treturn [];\n\t\t}\n\t\treturn stale.filter(\n\t\t\t(token) => token.source === candidate.source && token.identityFingerprint === candidate.identityFingerprint,\n\t\t);\n\t}\n\n\tprivate getAvailableAuthCandidate(\n\t\tprovider: string,\n\t\toptions?: { includeFallback?: boolean },\n\t): { candidate?: AuthSourceCandidate; hasStaleCandidate: boolean } {\n\t\tlet hasStaleCandidate = false;\n\t\tfor (const candidate of this.getAuthSourceCandidates(provider, options)) {\n\t\t\tif (this.isAuthSourceStale(provider, candidate)) {\n\t\t\t\thasStaleCandidate = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn { candidate, hasStaleCandidate };\n\t\t}\n\t\treturn { hasStaleCandidate };\n\t}\n\n\tprivate toAuthStatus(candidate: AuthSourceCandidate): AuthStatus {\n\t\treturn {\n\t\t\tconfigured: candidate.configured,\n\t\t\tsource: candidate.source,\n\t\t\t...(candidate.label ? { label: candidate.label } : {}),\n\t\t};\n\t}\n\n\tprivate getAuthStatusFromCandidates(provider: string): AuthStatus {\n\t\tconst { candidate, hasStaleCandidate } = this.getAvailableAuthCandidate(provider);\n\t\tif (candidate) {\n\t\t\treturn this.toAuthStatus(candidate);\n\t\t}\n\t\tif (hasStaleCandidate) {\n\t\t\treturn { configured: false, source: \"stale\", label: \"expired\" };\n\t\t}\n\t\treturn { configured: false };\n\t}\n\n\tmarkAuthStale(provider: string): boolean {\n\t\tconst token = this.getCurrentAuthSourceToken(provider);\n\t\treturn token ? this.markAuthSourceStale(token) : false;\n\t}\n\n\tprivate getAuthSourceTokenForCandidate(\n\t\tprovider: string,\n\t\tcandidate: AuthSourceCandidate,\n\t): AuthSourceToken | undefined {\n\t\tconst valueFingerprint = candidate.valueFingerprint ?? candidate.resolveValueFingerprint?.();\n\t\tif (!valueFingerprint) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\tprovider,\n\t\t\tsource: candidate.source,\n\t\t\tidentityFingerprint: candidate.identityFingerprint,\n\t\t\tvalueFingerprint,\n\t\t};\n\t}\n\n\tgetCurrentAuthSourceToken(provider: string): AuthSourceToken | undefined {\n\t\tconst { candidate } = this.getAvailableAuthCandidate(provider);\n\t\tif (!candidate) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.getAuthSourceTokenForCandidate(provider, candidate);\n\t}\n\n\tmarkAuthSourceStale(token: AuthSourceToken): boolean {\n\t\tif (token.provider.length === 0) {\n\t\t\treturn false;\n\t\t}\n\t\tconst stale = this.staleAuthSources.get(token.provider) ?? [];\n\t\tif (\n\t\t\t!stale.some(\n\t\t\t\t(existing) =>\n\t\t\t\t\texisting.source === token.source &&\n\t\t\t\t\texisting.identityFingerprint === token.identityFingerprint &&\n\t\t\t\t\texisting.valueFingerprint === token.valueFingerprint,\n\t\t\t)\n\t\t) {\n\t\t\tstale.push(token);\n\t\t}\n\t\tthis.staleAuthSources.set(token.provider, stale);\n\t\treturn true;\n\t}\n\n\tprivate clearStaleAuthSource(provider: string, source: ActiveAuthStatusSource): void {\n\t\tconst stale = this.staleAuthSources.get(provider);\n\t\tif (!stale) {\n\t\t\treturn;\n\t\t}\n\t\tconst next = stale.filter((token) => token.source !== source);\n\t\tif (next.length === 0) {\n\t\t\tthis.staleAuthSources.delete(provider);\n\t\t} else {\n\t\t\tthis.staleAuthSources.set(provider, next);\n\t\t}\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.data = this.parseStorageData(content);\n\t\t\tthis.loadError = null;\n\t\t} catch (error) {\n\t\t\tthis.loadError = error as Error;\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\tprivate persistProviderChange(provider: string, credential: AuthCredential | undefined): void {\n\t\tif (this.loadError) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\t\tconst merged: AuthStorageData = { ...currentData };\n\t\t\t\tif (credential) {\n\t\t\t\t\tmerged[provider] = credential;\n\t\t\t\t} else {\n\t\t\t\t\tdelete merged[provider];\n\t\t\t\t}\n\t\t\t\treturn { result: undefined, next: JSON.stringify(merged, null, 2) };\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\t/**\n\t * Get credential for a provider.\n\t */\n\tget(provider: string): AuthCredential | undefined {\n\t\treturn this.data[provider] ?? undefined;\n\t}\n\n\t/**\n\t * Set credential for a provider.\n\t */\n\tset(provider: string, credential: AuthCredential): void {\n\t\tthis.assertWritableStorage();\n\t\tthis.clearStaleAuthSource(provider, \"stored\");\n\t\tthis.data[provider] = credential;\n\t\tthis.persistProviderChange(provider, credential);\n\t}\n\n\t/**\n\t * Remove credential for a provider.\n\t */\n\tremove(provider: string): void {\n\t\tthis.assertWritableStorage();\n\t\tthis.clearStaleAuthSource(provider, \"stored\");\n\t\tdelete this.data[provider];\n\t\tthis.persistProviderChange(provider, undefined);\n\t}\n\n\t/**\n\t * Remove a provider's credential with the disk write verified: throws on any\n\t * load or write failure instead of recording it, so callers can refuse to\n\t * proceed while the credential may still exist on disk. Disk-authoritative\n\t * and idempotent — in-memory state is only updated after the write succeeds.\n\t */\n\tremoveVerified(provider: string): void {\n\t\tthis.assertWritableStorage();\n\t\tthis.storage.withLock((current) => {\n\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\tif (!(provider in currentData)) return { result: undefined };\n\t\t\tconst merged: AuthStorageData = { ...currentData };\n\t\t\tdelete merged[provider];\n\t\t\treturn { result: undefined, next: JSON.stringify(merged, null, 2) };\n\t\t});\n\t\tdelete this.data[provider];\n\t\t// Post-success only: a failed removal must not make a stale-marked credential selectable again.\n\t\tthis.clearStaleAuthSource(provider, \"stored\");\n\t}\n\n\t/**\n\t * List all providers with credentials.\n\t */\n\tlist(): string[] {\n\t\treturn Object.keys(this.data);\n\t}\n\n\t/**\n\t * Check if credentials exist for a provider in auth.json.\n\t */\n\thas(provider: string): boolean {\n\t\treturn provider in this.data;\n\t}\n\n\t/**\n\t * Check if any form of auth is configured for a provider.\n\t * Unlike getApiKey(), this doesn't refresh OAuth tokens.\n\t */\n\thasAuth(provider: string): boolean {\n\t\treturn this.getAvailableAuthCandidate(provider).candidate !== undefined;\n\t}\n\n\t/**\n\t * Return auth status without exposing credential values or refreshing tokens.\n\t */\n\tgetAuthStatus(provider: string): AuthStatus {\n\t\treturn this.getAuthStatusFromCandidates(provider);\n\t}\n\n\t/**\n\t * Get all credentials (for passing to getOAuthApiKey).\n\t */\n\tgetAll(): AuthStorageData {\n\t\treturn { ...this.data };\n\t}\n\n\tdrainErrors(): Error[] {\n\t\tconst drained = [...this.errors];\n\t\tthis.errors = [];\n\t\treturn drained;\n\t}\n\n\t/**\n\t * Login to an OAuth provider.\n\t */\n\tasync login(providerId: OAuthProviderId, callbacks: OAuthLoginCallbacks): Promise<void> {\n\t\tthis.assertWritableStorage();\n\t\tconst contract = getProviderAuthContract(providerId);\n\t\tif (contract.oauth !== \"supported\") {\n\t\t\tthrow new Error(contract.guidance);\n\t\t}\n\t\tconst provider = getOAuthProvider(providerId);\n\t\tif (!provider) {\n\t\t\tthrow new Error(`Unknown OAuth provider: ${providerId}`);\n\t\t}\n\n\t\tconst credentials = await provider.login(callbacks);\n\t\tthis.set(providerId, { type: \"oauth\", ...credentials });\n\t}\n\n\t/**\n\t * Logout from a provider.\n\t */\n\tlogout(provider: string): void {\n\t\tthis.remove(provider);\n\t}\n\n\t/**\n\t * Refresh OAuth token with backend locking to prevent race conditions.\n\t * Multiple pi instances may try to refresh simultaneously when tokens expire.\n\t */\n\tprivate async refreshOAuthTokenWithLock(\n\t\tproviderId: OAuthProviderId,\n\t): Promise<{ apiKey: string; newCredentials: OAuthCredentials } | null> {\n\t\tif (getProviderAuthContract(providerId).oauth !== \"supported\") {\n\t\t\treturn null;\n\t\t}\n\t\tconst provider = getOAuthProvider(providerId);\n\t\tif (!provider) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst result = await this.storage.withLockAsync(async (current) => {\n\t\t\tconst currentData = this.parseStorageData(current);\n\t\t\tthis.data = currentData;\n\t\t\tthis.loadError = null;\n\n\t\t\tconst cred = currentData[providerId];\n\t\t\tif (cred?.type !== \"oauth\" || getProviderAuthContract(providerId).oauth !== \"supported\") {\n\t\t\t\treturn { result: null };\n\t\t\t}\n\n\t\t\tif (Date.now() < cred.expires) {\n\t\t\t\treturn { result: { apiKey: provider.getApiKey(cred), newCredentials: cred } };\n\t\t\t}\n\n\t\t\tconst oauthCreds: Record<string, OAuthCredentials> = {};\n\t\t\tfor (const [key, value] of Object.entries(currentData)) {\n\t\t\t\tif (value.type === \"oauth\") {\n\t\t\t\t\toauthCreds[key] = value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst refreshed = await getOAuthApiKey(providerId, oauthCreds);\n\t\t\tif (!refreshed) {\n\t\t\t\treturn { result: null };\n\t\t\t}\n\n\t\t\tconst merged: AuthStorageData = {\n\t\t\t\t...currentData,\n\t\t\t\t[providerId]: { type: \"oauth\", ...refreshed.newCredentials },\n\t\t\t};\n\t\t\tthis.data = merged;\n\t\t\tthis.loadError = null;\n\t\t\treturn { result: refreshed, next: JSON.stringify(merged, null, 2) };\n\t\t});\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get API key for a provider.\n\t * Priority:\n\t * 1. Runtime override (CLI --api-key)\n\t * 2. auth.json\n\t * 3. Environment variable\n\t * 4. Fallback resolver (models.json custom providers)\n\t */\n\tasync getApiKeyWithSourceToken(\n\t\tproviderId: string,\n\t\toptions?: { includeFallback?: boolean },\n\t): Promise<AuthApiKeyResult> {\n\t\tif (this.isExistingOpenAICodexSubscription(providerId)) {\n\t\t\tif (this.runtimeOverrides.has(providerId))\n\t\t\t\tthrow new Error(\"Existing OpenAI subscription does not accept API-key overrides\");\n\t\t\tconst credential = this.data[providerId];\n\t\t\tif (\n\t\t\t\t!credential ||\n\t\t\t\tcredential.type !== \"oauth\" ||\n\t\t\t\ttypeof credential.access !== \"string\" ||\n\t\t\t\t!credential.access ||\n\t\t\t\t!Number.isFinite(credential.expires)\n\t\t\t)\n\t\t\t\tthrow new Error(\"Existing OpenAI subscription credential is unavailable\");\n\t\t\tif (Date.now() >= credential.expires) throw new Error(\"Existing OpenAI subscription credential has expired\");\n\t\t\tconst candidate = this.getStoredAuthCandidate(providerId);\n\t\t\tif (!candidate || this.isAuthSourceStale(providerId, candidate))\n\t\t\t\tthrow new Error(\"Existing OpenAI subscription credential is unavailable\");\n\t\t\treturn {\n\t\t\t\tapiKey: credential.access,\n\t\t\t\tsourceToken: this.getAuthSourceTokenForCandidate(providerId, candidate),\n\t\t\t};\n\t\t}\n\n\t\t// Runtime overrides take precedence over stored credentials and environment keys.\n\t\tconst runtimeCandidate = this.getRuntimeAuthCandidate(providerId);\n\t\tconst runtimeKey = this.runtimeOverrides.get(providerId);\n\t\tif (runtimeKey && runtimeCandidate && !this.isAuthSourceStale(providerId, runtimeCandidate)) {\n\t\t\treturn {\n\t\t\t\tapiKey: runtimeKey,\n\t\t\t\tsourceToken: this.getAuthSourceTokenForCandidate(providerId, runtimeCandidate),\n\t\t\t};\n\t\t}\n\n\t\tconst cred = this.data[providerId];\n\n\t\tif (cred?.type === \"api_key\") {\n\t\t\tconst storedCandidate = this.getStoredAuthCandidate(providerId);\n\t\t\tif (storedCandidate && !this.isAuthSourceStale(providerId, storedCandidate)) {\n\t\t\t\tconst hasStaleRecord = this.getMatchingStaleAuthSources(providerId, storedCandidate).length > 0;\n\t\t\t\tconst apiKey =\n\t\t\t\t\tcred.key.startsWith(\"!\") && hasStaleRecord\n\t\t\t\t\t\t? resolveConfigValueUncached(cred.key)\n\t\t\t\t\t\t: resolveConfigValue(cred.key);\n\t\t\t\tif (apiKey === undefined || isProviderApiKeyAllowed(providerId, apiKey)) {\n\t\t\t\t\tconst sourceToken =\n\t\t\t\t\t\tapiKey === undefined\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: this.getAuthSourceTokenForCandidate(\n\t\t\t\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\t\t\t\tcred.key.startsWith(\"!\")\n\t\t\t\t\t\t\t\t\t\t? (this.getStoredAuthCandidate(providerId, { resolvedCommandValue: apiKey }) ??\n\t\t\t\t\t\t\t\t\t\t\t\tstoredCandidate)\n\t\t\t\t\t\t\t\t\t\t: storedCandidate,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\treturn { apiKey, sourceToken };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (cred?.type === \"oauth\" && getProviderAuthContract(providerId).oauth === \"supported\") {\n\t\t\tconst storedCandidate = this.getStoredAuthCandidate(providerId);\n\t\t\tif (storedCandidate && !this.isAuthSourceStale(providerId, storedCandidate)) {\n\t\t\t\tconst provider = getOAuthProvider(providerId);\n\t\t\t\tif (!provider) {\n\t\t\t\t\treturn {};\n\t\t\t\t}\n\t\t\t\t// Lock refreshes so concurrent instances cannot race on the credential file.\n\t\t\t\tconst needsRefresh = Date.now() >= cred.expires;\n\n\t\t\t\tif (needsRefresh) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.refreshOAuthTokenWithLock(providerId);\n\t\t\t\t\t\tif (result) {\n\t\t\t\t\t\t\tconst refreshedCandidate = this.getStoredAuthCandidate(providerId);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tapiKey: result.apiKey,\n\t\t\t\t\t\t\t\tsourceToken: refreshedCandidate\n\t\t\t\t\t\t\t\t\t? this.getAuthSourceTokenForCandidate(providerId, refreshedCandidate)\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.recordError(error);\n\t\t\t\t\t\t// A peer may have refreshed successfully; reload before treating this refresh as failed.\n\t\t\t\t\t\tthis.reload();\n\t\t\t\t\t\tconst updatedCred = this.data[providerId];\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tupdatedCred?.type === \"oauth\" &&\n\t\t\t\t\t\t\tgetProviderAuthContract(providerId).oauth === \"supported\" &&\n\t\t\t\t\t\t\tDate.now() < updatedCred.expires\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst updatedCandidate = this.getStoredAuthCandidate(providerId);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tapiKey: provider.getApiKey(updatedCred),\n\t\t\t\t\t\t\t\tsourceToken: updatedCandidate\n\t\t\t\t\t\t\t\t\t? this.getAuthSourceTokenForCandidate(providerId, updatedCandidate)\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Preserve credentials for a later /login retry while discovery skips this provider.\n\t\t\t\t\t\treturn {};\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tapiKey: provider.getApiKey(cred),\n\t\t\t\t\t\tsourceToken: this.getAuthSourceTokenForCandidate(providerId, storedCandidate),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst envCandidate = this.getEnvironmentAuthCandidate(providerId);\n\t\tconst envKey = this.getEnvironmentApiKey(providerId);\n\t\tif (envKey && envCandidate && !this.isAuthSourceStale(providerId, envCandidate)) {\n\t\t\treturn {\n\t\t\t\tapiKey: envKey,\n\t\t\t\tsourceToken: this.getAuthSourceTokenForCandidate(providerId, envCandidate),\n\t\t\t};\n\t\t}\n\t\tif (options?.includeFallback !== false) {\n\t\t\tconst fallbackCandidate = this.getFallbackAuthCandidate(providerId);\n\t\t\tif (fallbackCandidate && !this.isAuthSourceStale(providerId, fallbackCandidate)) {\n\t\t\t\tconst apiKey = this.fallbackResolver?.(providerId) ?? undefined;\n\t\t\t\tif (apiKey === undefined || isProviderApiKeyAllowed(providerId, apiKey)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\tsourceToken: this.getAuthSourceTokenForCandidate(providerId, fallbackCandidate),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn {};\n\t}\n\n\tasync getApiKey(providerId: string, options?: { includeFallback?: boolean }): Promise<string | undefined> {\n\t\tconst result = await this.getApiKeyWithSourceToken(providerId, options);\n\t\treturn result.apiKey;\n\t}\n\n\t/**\n\t * Get supported registered OAuth providers. Read-only SDK storage cannot log in.\n\t */\n\tgetOAuthProviders() {\n\t\tif (this.existingOpenAICodexSubscription) return [];\n\t\treturn getOAuthProviders().filter((provider) => getProviderAuthContract(provider.id).oauth === \"supported\");\n\t}\n}\n"]}
1
+ {"version":3,"file":"auth-storage.d.ts","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAGN,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACpB,MAAM,+BAA+B,CAAC;AAUvC,MAAM,MAAM,gBAAgB,GAAG;IAC9B,IAAI,EAAE,SAAS,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACZ,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,OAAO,CAAC;CACd,GAAG,gBAAgB,CAAC;AAErB,MAAM,MAAM,cAAc,GAAG,gBAAgB,GAAG,eAAe,CAAC;AAEhE,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;AAE7D,MAAM,MAAM,UAAU,GAAG;IACxB,UAAU,EAAE,OAAO,CAAC;IACpB,MAAM,CAAC,EAAE,QAAQ,GAAG,SAAS,GAAG,aAAa,GAAG,UAAU,GAA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ent":["/**\n * Credential storage for API keys and OAuth tokens.\n * Handles loading, saving, and refreshing credentials from auth.json.\n *\n * Uses file locking to prevent race conditions when multiple pi instances\n * try to refresh tokens simultaneously.\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n\tfindEnvKeys,\n\tgetEnvApiKey,\n\ttype OAuthCredentials,\n\ttype OAuthLoginCallbacks,\n\ttype OAuthProviderId,\n} from \"@ponythewhite/base-context-ai\";\nimport { getOAuthApiKey, getOAuthProvider, getOAuthProviders } from \"@ponythewhite/base-context-ai/oauth\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.js\";\nimport { assertProductStatePath } from \"../runtime-paths.js\";\nimport { getProviderAuthContract, isProviderApiKeyAllowed } from \"./provider-contracts.js\";\nimport { resolveConfigValue, resolveConfigValueUncached } from \"./resolve-config-value.js\";\n\nexport type ApiKeyCredential = {\n\ttype: \"api_key\";\n\tkey: string;\n};\n\nexport type OAuthCredential = {\n\ttype: \"oauth\";\n} & OAuthCredentials;\n\nexport type AuthCredential = ApiKeyCredential | OAuthCredential;\n\nexport type AuthStorageData = Record<string, AuthCredential>;\n\nexport type AuthStatus = {\n\tconfigured: boolean;\n\tsource?: \"stored\" | \"runtime\" | \"environment\" | \"fallback\" | \"models_json_key\" | \"models_json_command\" | \"stale\";\n\tlabel?: string;\n};\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\n// Only active login ownership is persisted; it is not a credential or a history.\ntype AuthStorageState = {\n\tcredentials: AuthStorageData;\n\tloginAttempts: Record<string, string>;\n};\n\ntype ActiveAuthStatusSource = Exclude<NonNullable<AuthStatus[\"source\"]>, \"stale\">;\n\nexport type AuthSourceToken = {\n\tprovider: string;\n\tsource: ActiveAuthStatusSource;\n\tidentityFingerprint: string;\n\tvalueFingerprint: string;\n};\n\ntype AuthSourceCandidate = {\n\tsource: ActiveAuthStatusSource;\n\tconfigured: boolean;\n\tlabel?: string;\n\tidentityFingerprint: string;\n\tvalueFingerprint?: string;\n\tresolveValueFingerprint?: () => string | undefined;\n};\n\ntype AuthApiKeyResult = {\n\tapiKey?: string;\n\tsourceToken?: AuthSourceToken;\n};\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tconstructor(private authPath: string = join(getAgentDir(), \"auth.json\")) {}\n\n\tprivate ensureParentDir(): void {\n\t\tassertProductStatePath(this.authPath);\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", \"utf-8\");\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\t\tlet compromisedError: Error | undefined;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\tconst release = lockfile.lockSync(path, {\n\t\t\t\t\trealpath: false,\n\t\t\t\t\tonCompromised: (error) => {\n\t\t\t\t\t\tcompromisedError ??= error;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (compromisedError) {\n\t\t\t\t\trelease();\n\t\t\t\t\tthrow compromisedError;\n\t\t\t\t}\n\t\t\t\treturn release;\n\t\t\t} catch (error) {\n\t\t\t\tif (compromisedError) throw compromisedError;\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, \"utf-8\");\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: 30000,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, \"utf-8\");\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\tif (lockCompromised) await release().catch(() => undefined);\n\t\t\t\telse await release();\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage {\n\tprivate data: AuthStorageData = {};\n\tprivate runtimeOverrides: Map<string, string> = new Map();\n\tprivate staleAuthSources: Map<string, AuthSourceToken[]> = new Map();\n\tprivate fallbackResolver?: (provider: string) => string | undefined;\n\tprivate loadError: Error | null = null;\n\tprivate errors: Error[] = [];\n\n\tprivate constructor(\n\t\tprivate storage: AuthStorageBackend,\n\t\tprivate readonly existingOpenAICodexSubscription = false,\n\t) {\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath?: string): AuthStorage {\n\t\treturn new AuthStorage(new FileAuthStorageBackend(authPath ?? join(getAgentDir(), \"auth.json\")));\n\t}\n\n\t/** Reuse an existing host login only through an explicitly read-only backend.\n\t * This SDK mode never logs in, writes credentials, or refreshes tokens.\n\t */\n\tstatic fromStorage(\n\t\tstorage: AuthStorageBackend,\n\t\toptions?: { existingOpenAICodexSubscription?: boolean },\n\t): AuthStorage {\n\t\tconst existing = options?.existingOpenAICodexSubscription === true;\n\t\tif (!existing) return new AuthStorage(storage);\n\t\tif (storage instanceof FileAuthStorageBackend)\n\t\t\tthrow new Error(\"Existing OpenAI subscription requires a read-only auth backend\");\n\t\tconst readOnly: AuthStorageBackend = {\n\t\t\twithLock: (read) =>\n\t\t\t\tstorage.withLock((current) => {\n\t\t\t\t\tconst { result, next } = read(current);\n\t\t\t\t\tif (next !== undefined) throw new Error(\"Existing OpenAI subscription storage is read-only\");\n\t\t\t\t\treturn { result };\n\t\t\t\t}),\n\t\t\t// Refresh happens inside this callback, so never invoke it in this mode.\n\t\t\twithLockAsync: async () => {\n\t\t\t\tthrow new Error(\"Existing OpenAI subscription refresh is disabled\");\n\t\t\t},\n\t\t};\n\t\treturn new AuthStorage(readOnly, true);\n\t}\n\n\tisExistingOpenAICodexSubscription(provider: string): boolean {\n\t\treturn this.existingOpenAICodexSubscription && provider === \"openai-codex\";\n\t}\n\n\tprivate assertWritableStorage(): void {\n\t\tif (this.existingOpenAICodexSubscription) throw new Error(\"Existing OpenAI subscription storage is read-only\");\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\t/**\n\t * Set a runtime API key override (not persisted to disk).\n\t * Used for CLI --api-key flag.\n\t */\n\tsetRuntimeApiKey(provider: string, apiKey: string): void {\n\t\tthis.clearStaleAuthSource(provider, \"runtime\");\n\t\tthis.runtimeOverrides.set(provider, apiKey);\n\t}\n\n\t/**\n\t * Remove a runtime API key override.\n\t */\n\tremoveRuntimeApiKey(provider: string): void {\n\t\tthis.clearStaleAuthSource(provider, \"runtime\");\n\t\tthis.runtimeOverrides.delete(provider);\n\t}\n\n\t/**\n\t * Set a fallback resolver for API keys not found in auth.json or env vars.\n\t * Used for custom provider keys from models.json.\n\t */\n\tsetFallbackResolver(resolver: (provider: string) => string | undefined): void {\n\t\tthis.fallbackResolver = resolver;\n\t}\n\n\tprivate recordError(error: unknown): void {\n\t\tconst normalizedError = error instanceof Error ? error : new Error(String(error));\n\t\tthis.errors.push(normalizedError);\n\t}\n\n\tprivate fingerprintAuthSource(source: ActiveAuthStatusSource, material: string): string {\n\t\tconst digest = createHash(\"sha256\").update(source).update(\"\\0\").update(material).digest(\"hex\");\n\t\treturn `${source}:${digest}`;\n\t}\n\n\tprivate createAuthSourceCandidate(options: {\n\t\tsource: ActiveAuthStatusSource;\n\t\tconfigured: boolean;\n\t\tidentityMaterial: string;\n\t\tvalueMaterial?: string;\n\t\tlabel?: string;\n\t\tresolveValueMaterial?: () => string | undefined;\n\t}): AuthSourceCandidate {\n\t\treturn {\n\t\t\tconfigured: options.configured,\n\t\t\tsource: options.source,\n\t\t\t...(options.label ? { label: options.label } : {}),\n\t\t\tidentityFingerprint: this.fingerprintAuthSource(options.source, `identity:${options.identityMaterial}`),\n\t\t\t...(options.valueMaterial !== undefined\n\t\t\t\t? {\n\t\t\t\t\t\tvalueFingerprint: this.fingerprintAuthSource(\n\t\t\t\t\t\t\toptions.source,\n\t\t\t\t\t\t\t`value:${options.identityMaterial}\\0${options.valueMaterial}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(options.resolveValueMaterial\n\t\t\t\t? {\n\t\t\t\t\t\tresolveValueFingerprint: () => {\n\t\t\t\t\t\t\tconst valueMaterial = options.resolveValueMaterial?.();\n\t\t\t\t\t\t\treturn valueMaterial === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: this.fingerprintAuthSource(\n\t\t\t\t\t\t\t\t\t\toptions.source,\n\t\t\t\t\t\t\t\t\t\t`value:${options.identityMaterial}\\0${valueMaterial}`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\tprivate getStoredCredentialValueMaterial(providerId: string, credential: AuthCredential): string | undefined {\n\t\tif (credential.type === \"api_key\") {\n\t\t\tconst isCommand = credential.key.startsWith(\"!\");\n\t\t\tconst resolvedKey = isCommand\n\t\t\t\t? resolveConfigValueUncached(credential.key)\n\t\t\t\t: resolveConfigValue(credential.key);\n\t\t\tif (resolvedKey !== undefined && !isProviderApiKeyAllowed(providerId, resolvedKey)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (isCommand) {\n\t\t\t\treturn resolvedKey === undefined ? undefined : `api_key:command:${credential.key}\\0${resolvedKey}`;\n\t\t\t}\n\t\t\treturn `api_key:${credential.key}\\0${resolvedKey ?? \"\"}`;\n\t\t}\n\t\tif (this.isExistingOpenAICodexSubscription(providerId))\n\t\t\treturn `oauth:${credential.access}\\0${credential.expires}`;\n\t\tif (getProviderAuthContract(providerId).oauth !== \"supported\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst provider = getOAuthProvider(providerId);\n\t\tconst apiKey = provider?.getApiKey(credential) ?? credential.access;\n\t\treturn `oauth:${apiKey}\\0${credential.refresh}\\0${credential.expires}`;\n\t}\n\n\tprivate getRuntimeAuthCandidate(provider: string): AuthSourceCandidate | undefined {\n\t\tconst apiKey = this.runtimeOverrides.get(provider);\n\t\tif (!apiKey || !isProviderApiKeyAllowed(provider, apiKey)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\tlabel: \"--api-key\",\n\t\t\t...this.createAuthSourceCandidate({\n\t\t\t\tconfigured: false,\n\t\t\t\tsource: \"runtime\",\n\t\t\t\tidentityMaterial: provider,\n\t\t\t\tvalueMaterial: apiKey,\n\t\t\t}),\n\t\t};\n\t}\n\n\tprivate getStoredAuthCandidate(\n\t\tprovider: string,\n\t\toptions?: { resolveCommandValue?: boolean; resolvedCommandValue?: string },\n\t): AuthSourceCandidate | undefined {\n\t\tconst credential = this.data[provider];\n\t\tif (\n\t\t\t!credential ||\n\t\t\t(credential.type === \"oauth\" &&\n\t\t\t\tgetProviderAuthContract(provider).oauth !== \"supported\" &&\n\t\t\t\t!this.isExistingOpenAICodexSubscription(provider))\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst isCommandApiKey = credential.type === \"api_key\" && credential.key.startsWith(\"!\");\n\t\tif (credential.type === \"api_key\") {\n\t\t\tconst apiKey =\n\t\t\t\toptions?.resolvedCommandValue ?? (isCommandApiKey ? credential.key : resolveConfigValue(credential.key));\n\t\t\tif (apiKey !== undefined && !isProviderApiKeyAllowed(provider, apiKey)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t\tconst identityMaterial = isCommandApiKey ? `api_key:command:${credential.key}` : `${provider}:${credential.type}`;\n\t\tconst commandValueMaterial =\n\t\t\tisCommandApiKey && options?.resolvedCommandValue !== undefined\n\t\t\t\t? `api_key:command:${credential.key}\\0${options.resolvedCommandValue}`\n\t\t\t\t: undefined;\n\t\treturn this.createAuthSourceCandidate({\n\t\t\tconfigured: true,\n\t\t\tsource: \"stored\",\n\t\t\tidentityMaterial,\n\t\t\tvalueMaterial:\n\t\t\t\tcommandValueMaterial ??\n\t\t\t\t(isCommandApiKey && !options?.resolveCommandValue\n\t\t\t\t\t? undefined\n\t\t\t\t\t: this.getStoredCredentialValueMaterial(provider, credential)),\n\t\t\tresolveValueMaterial: isCommandApiKey\n\t\t\t\t? () => this.getStoredCredentialValueMaterial(provider, credential)\n\t\t\t\t: undefined,\n\t\t});\n\t}\n\n\tprivate getEnvironmentApiKey(provider: string): string | undefined {\n\t\tconst apiKey = getEnvApiKey(provider);\n\t\treturn apiKey && isProviderApiKeyAllowed(provider, apiKey) ? apiKey : undefined;\n\t}\n\n\tprivate getEnvironmentAuthCandidate(provider: string): AuthSourceCandidate | undefined {\n\t\tconst envKeys = findEnvKeys(provider);\n\t\tconst envKey = envKeys?.[0];\n\t\tconst apiKey = this.getEnvironmentApiKey(provider);\n\t\tif (!apiKey) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst label = envKey ?? \"ambient credentials\";\n\t\tconst identityMaterial = envKey ?? this.getAmbientEnvironmentIdentityMaterial(provider);\n\t\treturn this.createAuthSourceCandidate({\n\t\t\tconfigured: false,\n\t\t\tsource: \"environment\",\n\t\t\tlabel,\n\t\t\tidentityMaterial,\n\t\t\tvalueMaterial: `${identityMaterial}\\0${apiKey}`,\n\t\t});\n\t}\n\n\tprivate getAmbientEnvironmentIdentityMaterial(provider: string): string {\n\t\tif (provider === \"amazon-bedrock\") {\n\t\t\tif (process.env.AWS_PROFILE) return `amazon-bedrock:profile:${process.env.AWS_PROFILE}`;\n\t\t\tif (process.env.AWS_ACCESS_KEY_ID) {\n\t\t\t\treturn `amazon-bedrock:access-key:${process.env.AWS_ACCESS_KEY_ID}:${process.env.AWS_SECRET_ACCESS_KEY ?? \"\"}:${process.env.AWS_SESSION_TOKEN ?? \"\"}`;\n\t\t\t}\n\t\t\tif (process.env.AWS_BEARER_TOKEN_BEDROCK) {\n\t\t\t\treturn `amazon-bedrock:bearer:${process.env.AWS_BEARER_TOKEN_BEDROCK}`;\n\t\t\t}\n\t\t\tif (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) {\n\t\t\t\treturn `amazon-bedrock:ecs-relative:${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`;\n\t\t\t}\n\t\t\tif (process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI) {\n\t\t\t\treturn `amazon-bedrock:ecs-full:${process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI}`;\n\t\t\t}\n\t\t\tif (process.env.AWS_WEB_IDENTITY_TOKEN_FILE) {\n\t\t\t\treturn `amazon-bedrock:web-identity:${process.env.AWS_WEB_IDENTITY_TOKEN_FILE}`;\n\t\t\t}\n\t\t}\n\t\tif (provider === \"google-vertex\") {\n\t\t\tconst project = process.env.GOOGLE_CLOUD_PROJECT ?? process.env.GCLOUD_PROJECT ?? \"\";\n\t\t\tconst location = process.env.GOOGLE_CLOUD_LOCATION ?? \"\";\n\t\t\tconst credentialsPath = process.env.GOOGLE_APPLICATION_CREDENTIALS ?? \"application-default\";\n\t\t\treturn `google-vertex:${project}:${location}:${credentialsPath}`;\n\t\t}\n\t\treturn provider;\n\t}\n\n\tprivate getFallbackAuthCandidate(provider: string): AuthSourceCandidate | undefined {\n\t\tconst apiKey = this.fallbackResolver?.(provider);\n\t\tif (!apiKey || !isProviderApiKeyAllowed(provider, apiKey)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.createAuthSourceCandidate({\n\t\t\tconfigured: false,\n\t\t\tsource: \"fallback\",\n\t\t\tlabel: \"custom provider config\",\n\t\t\tidentityMaterial: provider,\n\t\t\tvalueMaterial: apiKey,\n\t\t});\n\t}\n\n\tprivate getAuthSourceCandidates(provider: string, options?: { includeFallback?: boolean }): AuthSourceCandidate[] {\n\t\tconst fallbackCandidate =\n\t\t\toptions?.includeFallback === false ? undefined : this.getFallbackAuthCandidate(provider);\n\t\tconst candidates = [\n\t\t\tthis.getRuntimeAuthCandidate(provider),\n\t\t\tthis.getStoredAuthCandidate(provider),\n\t\t\tthis.getEnvironmentAuthCandidate(provider),\n\t\t\tfallbackCandidate,\n\t\t];\n\t\treturn candidates.filter((candidate): candidate is AuthSourceCandidate => candidate !== undefined);\n\t}\n\n\tprivate isAuthSourceStale(provider: string, candidate: AuthSourceCandidate): boolean {\n\t\tconst matchingStale = this.getMatchingStaleAuthSources(provider, candidate);\n\t\tif (matchingStale.length === 0) {\n\t\t\treturn false;\n\t\t}\n\t\tconst valueFingerprint = candidate.valueFingerprint ?? candidate.resolveValueFingerprint?.();\n\t\treturn Boolean(valueFingerprint && matchingStale.some((token) => token.valueFingerprint === valueFingerprint));\n\t}\n\n\tprivate getMatchingStaleAuthSources(provider: string, candidate: AuthSourceCandidate): AuthSourceToken[] {\n\t\tconst stale = this.staleAuthSources.get(provider);\n\t\tif (!stale) {\n\t\t\treturn [];\n\t\t}\n\t\treturn stale.filter(\n\t\t\t(token) => token.source === candidate.source && token.identityFingerprint === candidate.identityFingerprint,\n\t\t);\n\t}\n\n\tprivate getAvailableAuthCandidate(\n\t\tprovider: string,\n\t\toptions?: { includeFallback?: boolean },\n\t): { candidate?: AuthSourceCandidate; hasStaleCandidate: boolean } {\n\t\tlet hasStaleCandidate = false;\n\t\tfor (const candidate of this.getAuthSourceCandidates(provider, options)) {\n\t\t\tif (this.isAuthSourceStale(provider, candidate)) {\n\t\t\t\thasStaleCandidate = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn { candidate, hasStaleCandidate };\n\t\t}\n\t\treturn { hasStaleCandidate };\n\t}\n\n\tprivate toAuthStatus(candidate: AuthSourceCandidate): AuthStatus {\n\t\treturn {\n\t\t\tconfigured: candidate.configured,\n\t\t\tsource: candidate.source,\n\t\t\t...(candidate.label ? { label: candidate.label } : {}),\n\t\t};\n\t}\n\n\tprivate getAuthStatusFromCandidates(provider: string): AuthStatus {\n\t\tconst { candidate, hasStaleCandidate } = this.getAvailableAuthCandidate(provider);\n\t\tif (candidate) {\n\t\t\treturn this.toAuthStatus(candidate);\n\t\t}\n\t\tif (hasStaleCandidate) {\n\t\t\treturn { configured: false, source: \"stale\", label: \"expired\" };\n\t\t}\n\t\treturn { configured: false };\n\t}\n\n\tmarkAuthStale(provider: string): boolean {\n\t\tconst token = this.getCurrentAuthSourceToken(provider);\n\t\treturn token ? this.markAuthSourceStale(token) : false;\n\t}\n\n\tprivate getAuthSourceTokenForCandidate(\n\t\tprovider: string,\n\t\tcandidate: AuthSourceCandidate,\n\t): AuthSourceToken | undefined {\n\t\tconst valueFingerprint = candidate.valueFingerprint ?? candidate.resolveValueFingerprint?.();\n\t\tif (!valueFingerprint) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\tprovider,\n\t\t\tsource: candidate.source,\n\t\t\tidentityFingerprint: candidate.identityFingerprint,\n\t\t\tvalueFingerprint,\n\t\t};\n\t}\n\n\tgetCurrentAuthSourceToken(provider: string): AuthSourceToken | undefined {\n\t\tconst { candidate } = this.getAvailableAuthCandidate(provider);\n\t\tif (!candidate) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.getAuthSourceTokenForCandidate(provider, candidate);\n\t}\n\n\tmarkAuthSourceStale(token: AuthSourceToken): boolean {\n\t\tif (token.provider.length === 0) {\n\t\t\treturn false;\n\t\t}\n\t\tconst stale = this.staleAuthSources.get(token.provider) ?? [];\n\t\tif (\n\t\t\t!stale.some(\n\t\t\t\t(existing) =>\n\t\t\t\t\texisting.source === token.source &&\n\t\t\t\t\texisting.identityFingerprint === token.identityFingerprint &&\n\t\t\t\t\texisting.valueFingerprint === token.valueFingerprint,\n\t\t\t)\n\t\t) {\n\t\t\tstale.push(token);\n\t\t}\n\t\tthis.staleAuthSources.set(token.provider, stale);\n\t\treturn true;\n\t}\n\n\tprivate clearStaleAuthSource(provider: string, source: ActiveAuthStatusSource): void {\n\t\tconst stale = this.staleAuthSources.get(provider);\n\t\tif (!stale) {\n\t\t\treturn;\n\t\t}\n\t\tconst next = stale.filter((token) => token.source !== source);\n\t\tif (next.length === 0) {\n\t\t\tthis.staleAuthSources.delete(provider);\n\t\t} else {\n\t\t\tthis.staleAuthSources.set(provider, next);\n\t\t}\n\t}\n\n\tprivate parseStorageState(content: string | undefined): AuthStorageState {\n\t\tconst { __base_context_login_attempts: loginAttempts = {}, ...credentials } = JSON.parse(\n\t\t\tcontent || \"{}\",\n\t\t) as AuthStorageData & { __base_context_login_attempts?: Record<string, string> };\n\t\treturn { credentials, loginAttempts };\n\t}\n\n\tprivate serializeStorageState({ credentials, loginAttempts }: AuthStorageState): string {\n\t\treturn JSON.stringify(\n\t\t\t{\n\t\t\t\t...credentials,\n\t\t\t\t...(Object.keys(loginAttempts).length > 0 ? { __base_context_login_attempts: loginAttempts } : {}),\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\treturn this.parseStorageState(content).credentials;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.data = this.parseStorageData(content);\n\t\t\tthis.loadError = null;\n\t\t} catch (error) {\n\t\t\tthis.loadError = error as Error;\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\tprivate persistProviderChange(provider: string, credential: AuthCredential | undefined): void {\n\t\tif (this.loadError) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tconst state = this.parseStorageState(current);\n\t\t\t\tdelete state.loginAttempts[provider];\n\t\t\t\tif (credential) {\n\t\t\t\t\tstate.credentials[provider] = credential;\n\t\t\t\t} else {\n\t\t\t\t\tdelete state.credentials[provider];\n\t\t\t\t}\n\t\t\t\treturn { result: undefined, next: this.serializeStorageState(state) };\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.recordError(error);\n\t\t}\n\t}\n\n\t/**\n\t * Get credential for a provider.\n\t */\n\tget(provider: string): AuthCredential | undefined {\n\t\treturn this.data[provider] ?? undefined;\n\t}\n\n\t/**\n\t * Set credential for a provider.\n\t */\n\tset(provider: string, credential: AuthCredential): void {\n\t\tthis.assertWritableStorage();\n\t\tthis.clearStaleAuthSource(provider, \"stored\");\n\t\tthis.data[provider] = credential;\n\t\tthis.persistProviderChange(provider, credential);\n\t}\n\n\t/**\n\t * Remove credential for a provider.\n\t */\n\tremove(provider: string): void {\n\t\tthis.assertWritableStorage();\n\t\tthis.clearStaleAuthSource(provider, \"stored\");\n\t\tdelete this.data[provider];\n\t\tthis.persistProviderChange(provider, undefined);\n\t}\n\n\t/**\n\t * Remove a provider's credential with the disk write verified: throws on any\n\t * load or write failure instead of recording it, so callers can refuse to\n\t * proceed while the credential may still exist on disk. Disk-authoritative\n\t * and idempotent — in-memory state is only updated after the write succeeds.\n\t */\n\tremoveVerified(provider: string): void {\n\t\tthis.assertWritableStorage();\n\t\tthis.storage.withLock((current) => {\n\t\t\tconst state = this.parseStorageState(current);\n\t\t\tif (!(provider in state.credentials) && !(provider in state.loginAttempts)) return { result: undefined };\n\t\t\tdelete state.credentials[provider];\n\t\t\tdelete state.loginAttempts[provider];\n\t\t\treturn { result: undefined, next: this.serializeStorageState(state) };\n\t\t});\n\t\tdelete this.data[provider];\n\t\t// Post-success only: a failed removal must not make a stale-marked credential selectable again.\n\t\tthis.clearStaleAuthSource(provider, \"stored\");\n\t}\n\n\t/**\n\t * List all providers with credentials.\n\t */\n\tlist(): string[] {\n\t\treturn Object.keys(this.data);\n\t}\n\n\t/**\n\t * Check if credentials exist for a provider in auth.json.\n\t */\n\thas(provider: string): boolean {\n\t\treturn provider in this.data;\n\t}\n\n\t/**\n\t * Check if any form of auth is configured for a provider.\n\t * Unlike getApiKey(), this doesn't refresh OAuth tokens.\n\t */\n\thasAuth(provider: string): boolean {\n\t\treturn this.getAvailableAuthCandidate(provider).candidate !== undefined;\n\t}\n\n\t/**\n\t * Return auth status without exposing credential values or refreshing tokens.\n\t */\n\tgetAuthStatus(provider: string): AuthStatus {\n\t\treturn this.getAuthStatusFromCandidates(provider);\n\t}\n\n\t/**\n\t * Get all credentials (for passing to getOAuthApiKey).\n\t */\n\tgetAll(): AuthStorageData {\n\t\treturn { ...this.data };\n\t}\n\n\tdrainErrors(): Error[] {\n\t\tconst drained = [...this.errors];\n\t\tthis.errors = [];\n\t\treturn drained;\n\t}\n\n\t/**\n\t * Login to an OAuth provider.\n\t */\n\tasync login(providerId: OAuthProviderId, callbacks: OAuthLoginCallbacks): Promise<void> {\n\t\tthis.assertWritableStorage();\n\t\tconst contract = getProviderAuthContract(providerId);\n\t\tif (contract.oauth !== \"supported\") {\n\t\t\tthrow new Error(contract.guidance);\n\t\t}\n\t\tconst provider = getOAuthProvider(providerId);\n\t\tif (!provider) {\n\t\t\tthrow new Error(`Unknown OAuth provider: ${providerId}`);\n\t\t}\n\n\t\tawait this.setFromLogin(\n\t\t\tproviderId,\n\t\t\tasync () => ({ type: \"oauth\", ...(await provider.login(callbacks)) }),\n\t\t\tcallbacks.signal,\n\t\t);\n\t}\n\n\t/** Collect credentials without holding the lock, then commit only for the current login. */\n\tasync setFromLogin(\n\t\tproviderId: string,\n\t\tcollectCredential: () => Promise<AuthCredential>,\n\t\tsignal?: AbortSignal,\n\t): Promise<void> {\n\t\tthis.assertWritableStorage();\n\t\tif (signal?.aborted) throw new Error(\"Login cancelled\");\n\t\tconst attemptId = randomUUID();\n\t\tthis.storage.withLock((current) => {\n\t\t\tconst state = this.parseStorageState(current);\n\t\t\tstate.loginAttempts[providerId] = attemptId;\n\t\t\treturn { result: undefined, next: this.serializeStorageState(state) };\n\t\t});\n\n\t\tconst releaseAttempt = () => {\n\t\t\ttry {\n\t\t\t\tthis.storage.withLock((current) => {\n\t\t\t\t\tconst state = this.parseStorageState(current);\n\t\t\t\t\tif (state.loginAttempts[providerId] !== attemptId) return { result: undefined };\n\t\t\t\t\tdelete state.loginAttempts[providerId];\n\t\t\t\t\treturn { result: undefined, next: this.serializeStorageState(state) };\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthis.recordError(error);\n\t\t\t}\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", releaseAttempt, { once: true });\n\t\ttry {\n\t\t\tconst credential = await collectCredential();\n\t\t\tif (signal?.aborted) throw new Error(\"Login cancelled\");\n\t\t\tconst data = this.storage.withLock((current) => {\n\t\t\t\tconst state = this.parseStorageState(current);\n\t\t\t\tif (state.loginAttempts[providerId] !== attemptId) {\n\t\t\t\t\tthrow new Error(\"Login cancelled: credentials changed or login was superseded\");\n\t\t\t\t}\n\t\t\t\tdelete state.loginAttempts[providerId];\n\t\t\t\tstate.credentials[providerId] = credential;\n\t\t\t\treturn { result: state.credentials, next: this.serializeStorageState(state) };\n\t\t\t});\n\t\t\tthis.data = data;\n\t\t\tthis.loadError = null;\n\t\t\tthis.clearStaleAuthSource(providerId, \"stored\");\n\t\t} catch (error) {\n\t\t\treleaseAttempt();\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tsignal?.removeEventListener(\"abort\", releaseAttempt);\n\t\t}\n\t}\n\n\t/**\n\t * Logout from a provider.\n\t */\n\tlogout(provider: string): void {\n\t\tthis.remove(provider);\n\t}\n\n\t/**\n\t * Refresh OAuth token with backend locking to prevent race conditions.\n\t * Multiple pi instances may try to refresh simultaneously when tokens expire.\n\t */\n\tprivate async refreshOAuthTokenWithLock(\n\t\tproviderId: OAuthProviderId,\n\t): Promise<{ apiKey: string; newCredentials: OAuthCredentials } | null> {\n\t\tif (getProviderAuthContract(providerId).oauth !== \"supported\") {\n\t\t\treturn null;\n\t\t}\n\t\tconst provider = getOAuthProvider(providerId);\n\t\tif (!provider) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst result = await this.storage.withLockAsync(async (current) => {\n\t\t\tconst state = this.parseStorageState(current);\n\t\t\tconst currentData = state.credentials;\n\t\t\tthis.data = currentData;\n\t\t\tthis.loadError = null;\n\n\t\t\tconst cred = currentData[providerId];\n\t\t\tif (cred?.type !== \"oauth\" || getProviderAuthContract(providerId).oauth !== \"supported\") {\n\t\t\t\treturn { result: null };\n\t\t\t}\n\n\t\t\tif (Date.now() < cred.expires) {\n\t\t\t\treturn { result: { apiKey: provider.getApiKey(cred), newCredentials: cred } };\n\t\t\t}\n\n\t\t\tconst oauthCreds: Record<string, OAuthCredentials> = {};\n\t\t\tfor (const [key, value] of Object.entries(currentData)) {\n\t\t\t\tif (value.type === \"oauth\") {\n\t\t\t\t\toauthCreds[key] = value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst refreshed = await getOAuthApiKey(providerId, oauthCreds);\n\t\t\tif (!refreshed) {\n\t\t\t\treturn { result: null };\n\t\t\t}\n\n\t\t\tconst merged: AuthStorageData = {\n\t\t\t\t...currentData,\n\t\t\t\t[providerId]: { type: \"oauth\", ...refreshed.newCredentials },\n\t\t\t};\n\t\t\tthis.data = merged;\n\t\t\tthis.loadError = null;\n\t\t\treturn { result: refreshed, next: this.serializeStorageState({ ...state, credentials: merged }) };\n\t\t});\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get API key for a provider.\n\t * Priority:\n\t * 1. Runtime override (CLI --api-key)\n\t * 2. auth.json\n\t * 3. Environment variable\n\t * 4. Fallback resolver (models.json custom providers)\n\t */\n\tasync getApiKeyWithSourceToken(\n\t\tproviderId: string,\n\t\toptions?: { includeFallback?: boolean },\n\t): Promise<AuthApiKeyResult> {\n\t\tif (this.isExistingOpenAICodexSubscription(providerId)) {\n\t\t\tif (this.runtimeOverrides.has(providerId))\n\t\t\t\tthrow new Error(\"Existing OpenAI subscription does not accept API-key overrides\");\n\t\t\tconst credential = this.data[providerId];\n\t\t\tif (\n\t\t\t\t!credential ||\n\t\t\t\tcredential.type !== \"oauth\" ||\n\t\t\t\ttypeof credential.access !== \"string\" ||\n\t\t\t\t!credential.access ||\n\t\t\t\t!Number.isFinite(credential.expires)\n\t\t\t)\n\t\t\t\tthrow new Error(\"Existing OpenAI subscription credential is unavailable\");\n\t\t\tif (Date.now() >= credential.expires) throw new Error(\"Existing OpenAI subscription credential has expired\");\n\t\t\tconst candidate = this.getStoredAuthCandidate(providerId);\n\t\t\tif (!candidate || this.isAuthSourceStale(providerId, candidate))\n\t\t\t\tthrow new Error(\"Existing OpenAI subscription credential is unavailable\");\n\t\t\treturn {\n\t\t\t\tapiKey: credential.access,\n\t\t\t\tsourceToken: this.getAuthSourceTokenForCandidate(providerId, candidate),\n\t\t\t};\n\t\t}\n\n\t\t// Runtime overrides take precedence over stored credentials and environment keys.\n\t\tconst runtimeCandidate = this.getRuntimeAuthCandidate(providerId);\n\t\tconst runtimeKey = this.runtimeOverrides.get(providerId);\n\t\tif (runtimeKey && runtimeCandidate && !this.isAuthSourceStale(providerId, runtimeCandidate)) {\n\t\t\treturn {\n\t\t\t\tapiKey: runtimeKey,\n\t\t\t\tsourceToken: this.getAuthSourceTokenForCandidate(providerId, runtimeCandidate),\n\t\t\t};\n\t\t}\n\n\t\tconst cred = this.data[providerId];\n\n\t\tif (cred?.type === \"api_key\") {\n\t\t\tconst storedCandidate = this.getStoredAuthCandidate(providerId);\n\t\t\tif (storedCandidate && !this.isAuthSourceStale(providerId, storedCandidate)) {\n\t\t\t\tconst hasStaleRecord = this.getMatchingStaleAuthSources(providerId, storedCandidate).length > 0;\n\t\t\t\tconst apiKey =\n\t\t\t\t\tcred.key.startsWith(\"!\") && hasStaleRecord\n\t\t\t\t\t\t? resolveConfigValueUncached(cred.key)\n\t\t\t\t\t\t: resolveConfigValue(cred.key);\n\t\t\t\tif (apiKey === undefined || isProviderApiKeyAllowed(providerId, apiKey)) {\n\t\t\t\t\tconst sourceToken =\n\t\t\t\t\t\tapiKey === undefined\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: this.getAuthSourceTokenForCandidate(\n\t\t\t\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\t\t\t\tcred.key.startsWith(\"!\")\n\t\t\t\t\t\t\t\t\t\t? (this.getStoredAuthCandidate(providerId, { resolvedCommandValue: apiKey }) ??\n\t\t\t\t\t\t\t\t\t\t\t\tstoredCandidate)\n\t\t\t\t\t\t\t\t\t\t: storedCandidate,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\treturn { apiKey, sourceToken };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (cred?.type === \"oauth\" && getProviderAuthContract(providerId).oauth === \"supported\") {\n\t\t\tconst storedCandidate = this.getStoredAuthCandidate(providerId);\n\t\t\tif (storedCandidate && !this.isAuthSourceStale(providerId, storedCandidate)) {\n\t\t\t\tconst provider = getOAuthProvider(providerId);\n\t\t\t\tif (!provider) {\n\t\t\t\t\treturn {};\n\t\t\t\t}\n\t\t\t\t// Lock refreshes so concurrent instances cannot race on the credential file.\n\t\t\t\tconst needsRefresh = Date.now() >= cred.expires;\n\n\t\t\t\tif (needsRefresh) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.refreshOAuthTokenWithLock(providerId);\n\t\t\t\t\t\tif (result) {\n\t\t\t\t\t\t\tconst refreshedCandidate = this.getStoredAuthCandidate(providerId);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tapiKey: result.apiKey,\n\t\t\t\t\t\t\t\tsourceToken: refreshedCandidate\n\t\t\t\t\t\t\t\t\t? this.getAuthSourceTokenForCandidate(providerId, refreshedCandidate)\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.recordError(error);\n\t\t\t\t\t\t// A peer may have refreshed successfully; reload before treating this refresh as failed.\n\t\t\t\t\t\tthis.reload();\n\t\t\t\t\t\tconst updatedCred = this.data[providerId];\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tupdatedCred?.type === \"oauth\" &&\n\t\t\t\t\t\t\tgetProviderAuthContract(providerId).oauth === \"supported\" &&\n\t\t\t\t\t\t\tDate.now() < updatedCred.expires\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst updatedCandidate = this.getStoredAuthCandidate(providerId);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tapiKey: provider.getApiKey(updatedCred),\n\t\t\t\t\t\t\t\tsourceToken: updatedCandidate\n\t\t\t\t\t\t\t\t\t? this.getAuthSourceTokenForCandidate(providerId, updatedCandidate)\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Preserve credentials for a later /login retry while discovery skips this provider.\n\t\t\t\t\t\treturn {};\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tapiKey: provider.getApiKey(cred),\n\t\t\t\t\t\tsourceToken: this.getAuthSourceTokenForCandidate(providerId, storedCandidate),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst envCandidate = this.getEnvironmentAuthCandidate(providerId);\n\t\tconst envKey = this.getEnvironmentApiKey(providerId);\n\t\tif (envKey && envCandidate && !this.isAuthSourceStale(providerId, envCandidate)) {\n\t\t\treturn {\n\t\t\t\tapiKey: envKey,\n\t\t\t\tsourceToken: this.getAuthSourceTokenForCandidate(providerId, envCandidate),\n\t\t\t};\n\t\t}\n\t\tif (options?.includeFallback !== false) {\n\t\t\tconst fallbackCandidate = this.getFallbackAuthCandidate(providerId);\n\t\t\tif (fallbackCandidate && !this.isAuthSourceStale(providerId, fallbackCandidate)) {\n\t\t\t\tconst apiKey = this.fallbackResolver?.(providerId) ?? undefined;\n\t\t\t\tif (apiKey === undefined || isProviderApiKeyAllowed(providerId, apiKey)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tapiKey,\n\t\t\t\t\t\tsourceToken: this.getAuthSourceTokenForCandidate(providerId, fallbackCandidate),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn {};\n\t}\n\n\tasync getApiKey(providerId: string, options?: { includeFallback?: boolean }): Promise<string | undefined> {\n\t\tconst result = await this.getApiKeyWithSourceToken(providerId, options);\n\t\treturn result.apiKey;\n\t}\n\n\t/**\n\t * Get supported registered OAuth providers. Read-only SDK storage cannot log in.\n\t */\n\tgetOAuthProviders() {\n\t\tif (this.existingOpenAICodexSubscription) return [];\n\t\treturn getOAuthProviders().filter((provider) => getProviderAuthContract(provider.id).oauth === \"supported\");\n\t}\n}\n"]}
@@ -5,7 +5,7 @@
5
5
  * Uses file locking to prevent race conditions when multiple pi instances
6
6
  * try to refresh tokens simultaneously.
7
7
  */
8
- import { createHash } from "node:crypto";
8
+ import { createHash, randomUUID } from "node:crypto";
9
9
  import { findEnvKeys, getEnvApiKey, } from "@ponythewhite/base-context-ai";
10
10
  import { getOAuthApiKey, getOAuthProvider, getOAuthProviders } from "@ponythewhite/base-context-ai/oauth";
11
11
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
@@ -496,11 +496,18 @@ export class AuthStorage {
496
496
  this.staleAuthSources.set(provider, next);
497
497
  }
498
498
  }
499
+ parseStorageState(content) {
500
+ const { __base_context_login_attempts: loginAttempts = {}, ...credentials } = JSON.parse(content || "{}");
501
+ return { credentials, loginAttempts };
502
+ }
503
+ serializeStorageState({ credentials, loginAttempts }) {
504
+ return JSON.stringify({
505
+ ...credentials,
506
+ ...(Object.keys(loginAttempts).length > 0 ? { __base_context_login_attempts: loginAttempts } : {}),
507
+ }, null, 2);
508
+ }
499
509
  parseStorageData(content) {
500
- if (!content) {
501
- return {};
502
- }
503
- return JSON.parse(content);
510
+ return this.parseStorageState(content).credentials;
504
511
  }
505
512
  /**
506
513
  * Reload credentials from storage.
@@ -526,15 +533,15 @@ export class AuthStorage {
526
533
  }
527
534
  try {
528
535
  this.storage.withLock((current) => {
529
- const currentData = this.parseStorageData(current);
530
- const merged = { ...currentData };
536
+ const state = this.parseStorageState(current);
537
+ delete state.loginAttempts[provider];
531
538
  if (credential) {
532
- merged[provider] = credential;
539
+ state.credentials[provider] = credential;
533
540
  }
534
541
  else {
535
- delete merged[provider];
542
+ delete state.credentials[provider];
536
543
  }
537
- return { result: undefined, next: JSON.stringify(merged, null, 2) };
544
+ return { result: undefined, next: this.serializeStorageState(state) };
538
545
  });
539
546
  }
540
547
  catch (error) {
@@ -574,12 +581,12 @@ export class AuthStorage {
574
581
  removeVerified(provider) {
575
582
  this.assertWritableStorage();
576
583
  this.storage.withLock((current) => {
577
- const currentData = this.parseStorageData(current);
578
- if (!(provider in currentData))
584
+ const state = this.parseStorageState(current);
585
+ if (!(provider in state.credentials) && !(provider in state.loginAttempts))
579
586
  return { result: undefined };
580
- const merged = { ...currentData };
581
- delete merged[provider];
582
- return { result: undefined, next: JSON.stringify(merged, null, 2) };
587
+ delete state.credentials[provider];
588
+ delete state.loginAttempts[provider];
589
+ return { result: undefined, next: this.serializeStorageState(state) };
583
590
  });
584
591
  delete this.data[provider];
585
592
  // Post-success only: a failed removal must not make a stale-marked credential selectable again.
@@ -634,8 +641,58 @@ export class AuthStorage {
634
641
  if (!provider) {
635
642
  throw new Error(`Unknown OAuth provider: ${providerId}`);
636
643
  }
637
- const credentials = await provider.login(callbacks);
638
- this.set(providerId, { type: "oauth", ...credentials });
644
+ await this.setFromLogin(providerId, async () => ({ type: "oauth", ...(await provider.login(callbacks)) }), callbacks.signal);
645
+ }
646
+ /** Collect credentials without holding the lock, then commit only for the current login. */
647
+ async setFromLogin(providerId, collectCredential, signal) {
648
+ this.assertWritableStorage();
649
+ if (signal?.aborted)
650
+ throw new Error("Login cancelled");
651
+ const attemptId = randomUUID();
652
+ this.storage.withLock((current) => {
653
+ const state = this.parseStorageState(current);
654
+ state.loginAttempts[providerId] = attemptId;
655
+ return { result: undefined, next: this.serializeStorageState(state) };
656
+ });
657
+ const releaseAttempt = () => {
658
+ try {
659
+ this.storage.withLock((current) => {
660
+ const state = this.parseStorageState(current);
661
+ if (state.loginAttempts[providerId] !== attemptId)
662
+ return { result: undefined };
663
+ delete state.loginAttempts[providerId];
664
+ return { result: undefined, next: this.serializeStorageState(state) };
665
+ });
666
+ }
667
+ catch (error) {
668
+ this.recordError(error);
669
+ }
670
+ };
671
+ signal?.addEventListener("abort", releaseAttempt, { once: true });
672
+ try {
673
+ const credential = await collectCredential();
674
+ if (signal?.aborted)
675
+ throw new Error("Login cancelled");
676
+ const data = this.storage.withLock((current) => {
677
+ const state = this.parseStorageState(current);
678
+ if (state.loginAttempts[providerId] !== attemptId) {
679
+ throw new Error("Login cancelled: credentials changed or login was superseded");
680
+ }
681
+ delete state.loginAttempts[providerId];
682
+ state.credentials[providerId] = credential;
683
+ return { result: state.credentials, next: this.serializeStorageState(state) };
684
+ });
685
+ this.data = data;
686
+ this.loadError = null;
687
+ this.clearStaleAuthSource(providerId, "stored");
688
+ }
689
+ catch (error) {
690
+ releaseAttempt();
691
+ throw error;
692
+ }
693
+ finally {
694
+ signal?.removeEventListener("abort", releaseAttempt);
695
+ }
639
696
  }
640
697
  /**
641
698
  * Logout from a provider.
@@ -656,7 +713,8 @@ export class AuthStorage {
656
713
  return null;
657
714
  }
658
715
  const result = await this.storage.withLockAsync(async (current) => {
659
- const currentData = this.parseStorageData(current);
716
+ const state = this.parseStorageState(current);
717
+ const currentData = state.credentials;
660
718
  this.data = currentData;
661
719
  this.loadError = null;
662
720
  const cred = currentData[providerId];
@@ -682,7 +740,7 @@ export class AuthStorage {
682
740
  };
683
741
  this.data = merged;
684
742
  this.loadError = null;
685
- return { result: refreshed, next: JSON.stringify(merged, null, 2) };
743
+ return { result: refreshed, next: this.serializeStorageState({ ...state, credentials: merged }) };
686
744
  });
687
745
  return result;
688
746
  }