openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 22.7 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{A as resolveExpiresAtMsFromDurationMs,o as asDateTimestampMs}from"./number-coercion-B3CfI447.mjs";import{i as resolveOsHomeRelativePath,o as resolveRequiredOsHomeDir}from"./home-dir-DEN5DisQ.mjs";import{a as extractErrorCode}from"./error-coercion-DlKnt6w-.mjs";import{a as asOptionalRecord,l as isRecord,t as asNonArrayRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{F as EXTERNAL_CLI_SYNC_TTL_MS,R as authProfilesLog}from"./user-model-account-authority-B8H7rvCb.mjs";import{r as MINIMAX_CLI_PROFILE_ID}from"./profile-ids-CZ5PgZfr.mjs";import{a as isSafeToAdoptBootstrapOAuthIdentity}from"./oauth-shared-DTzAchzX.mjs";import{i as isOAuthRefreshFence}from"./oauth-refresh-marker-BhS7FuQa.mjs";import{r as hasUsableOAuthCredential}from"./credential-state-C3XZhGc-.mjs";import{t as loadJsonFileThroughSymlink}from"./json-file-BedClo2t.mjs";import fs from"node:fs";import path from"node:path";import{createHash,createHmac,randomBytes}from"node:crypto";import{userInfo}from"node:os";import{execSync}from"node:child_process";
//!src/plugin-sdk/provider-auth-claude-compat.ts
const CLAUDE_CLI_CREDENTIALS_FILE=`.credentials.json`;const CLAUDE_CLI_USER_SETTINGS_FILE=`settings.json`;const CLAUDE_MANAGED_SETTINGS_FILE=`managed-settings.json`;const CLAUDE_MANAGED_SETTINGS_DROP_IN_DIR=`managed-settings.d`;const CLAUDE_CLI_KEYCHAIN_SERVICE=`Claude Code-credentials`;const CLAUDE_CLI_KEYCHAIN_TIMEOUT_MS=2e3;const CLAUDE_CLI_KEYCHAIN_ACCOUNT_FALLBACK=`claude-code-user`;const MACOS_SECURITY_PATH=`/usr/bin/security`;const CLAUDE_NON_NATIVE_AUTH_ENV_KEYS=[`ANTHROPIC_API_KEY`,`ANTHROPIC_API_TOKEN`,`ANTHROPIC_AUTH_TOKEN`,`ANTHROPIC_OAUTH_TOKEN`,`CLAUDE_CODE_OAUTH_REFRESH_TOKEN`,`CLAUDE_CODE_OAUTH_TOKEN`,`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`,`CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR`,`CLAUDE_CODE_USE_BEDROCK`,`CLAUDE_CODE_USE_VERTEX`,`CLAUDE_CODE_USE_FOUNDRY`,`ANTHROPIC_UNIX_SOCKET`];const SAFE_KEYCHAIN_ACCOUNT_PATTERN=/^[a-zA-Z0-9._-]+$/u;let claudeCliCache=null;function resolveClaudeCliConfigDir(e,t=process.env){if(e!==void 0)return path.join(resolveOsHomeRelativePath(e,{env:t}),`.claude`);const n=t.CLAUDE_CONFIG_DIR;return n?path.resolve(n):path.join(resolveOsHomeRelativePath(`~`,{env:t}),`.claude`)}function resolveClaudeCliPath(e,t,n=process.env){return path.join(resolveClaudeCliConfigDir(e,n),t)}function resolveClaudeCliCredentialsPath(e,t=process.env){if(e!==void 0)return path.join(resolveClaudeCliConfigDir(e,t),CLAUDE_CLI_CREDENTIALS_FILE);const n=t.CLAUDE_SECURESTORAGE_CONFIG_DIR;if(n===void 0)return resolveClaudeCliPath(void 0,CLAUDE_CLI_CREDENTIALS_FILE,t);const r=n?path.resolve(n):path.join(resolveOsHomeRelativePath(`~`,{env:t}),`.claude`);return path.join(r,CLAUDE_CLI_CREDENTIALS_FILE)}function resolveClaudeCliAccountPath(e){if(e!==void 0)return path.join(resolveOsHomeRelativePath(e),`.claude.json`);const t=process.env.CLAUDE_CONFIG_DIR;return t?path.join(path.resolve(t),`.claude.json`):path.join(resolveOsHomeRelativePath(`~`),`.claude.json`)}function resolveClaudeCliKeychainService(e,t=process.env){if(e!==void 0)return CLAUDE_CLI_KEYCHAIN_SERVICE;const n=t.CLAUDE_SECURESTORAGE_CONFIG_DIR;const r=t.CLAUDE_CONFIG_DIR;const i=n!==void 0?n:r;if(!i)return CLAUDE_CLI_KEYCHAIN_SERVICE;const a=createHash(`sha256`).update(i.normalize(`NFC`)).digest(`hex`).slice(0,8);return`${CLAUDE_CLI_KEYCHAIN_SERVICE}-${a}`}function readFileMtimeMs$1(e){try{return fs.statSync(e).mtimeMs}catch{return null}}function parseClaudeCliOauthCredential(e){if(!e||typeof e!==`object`)return null;const t=asNonArrayRecord(e);const n=t.accessToken;const r=t.refreshToken;const i=t.expiresAt;if(typeof n!==`string`||!n||typeof i!==`number`||!Number.isFinite(i)||i<=0)return null;const a=normalizeOptionalString(t.subscriptionType);const o=normalizeOptionalString(t.rateLimitTier);const s={...a?{subscriptionType:a}:{},...o?{rateLimitTier:o}:{}};return typeof r===`string`&&r?{type:`oauth`,provider:`anthropic`,access:n,refresh:r,expires:i,...s}:{type:`token`,provider:`anthropic`,token:n,expires:i,...s}}function readClaudeAccountEmail(e){const t=loadJsonFileThroughSymlink(resolveClaudeCliAccountPath(e));const n=asNonArrayRecord(t).oauthAccount;const r=asNonArrayRecord(n).emailAddress;return normalizeOptionalString(r)}const CLAUDE_OAUTH_PROFILE_URL=`https://api.anthropic.com/api/oauth/profile`;const CLAUDE_OAUTH_PROFILE_TIMEOUT_MS=3e3;const CLAUDE_NATIVE_LOGIN_REFRESH_MARGIN_MS=6e5;const CLAUDE_NATIVE_LOGIN_ATTESTATION_LIMIT=64;const claudeNativeLoginAttestationKey=randomBytes(32);const claudeNativeLoginAttestations=/* @__PURE__ */ new Map;function fingerprintClaudeNativeLoginToken(e){return createHmac(`sha256`,claudeNativeLoginAttestationKey).update(e).digest(`hex`)}function readClaudeNativeLoginOwner(e={}){const t=readClaudeNativeLoginCredential(e);return t?claudeNativeLoginAttestations.get(fingerprintClaudeNativeLoginToken(t.value)):void 0}async function attestClaudeNativeLoginOwner(e={}){const t=readClaudeNativeLoginCredential(e);if(!t)return{};const n=t.expires-CLAUDE_NATIVE_LOGIN_REFRESH_MARGIN_MS;const r=fingerprintClaudeNativeLoginToken(t.value);const i=claudeNativeLoginAttestations.get(r);if(i||t.expires<=Date.now())return{...i?{owner:i}:{},refreshDueAt:n};let a;try{const n=await(e.fetchFn??globalThis.fetch)(CLAUDE_OAUTH_PROFILE_URL,{headers:{Authorization:`Bearer ${t.value}`,Accept:`application/json`,"User-Agent":`openclaw`},redirect:`error`,signal:AbortSignal.timeout(CLAUDE_OAUTH_PROFILE_TIMEOUT_MS)});if(n.ok){const e=asNonArrayRecord(asNonArrayRecord(await n.json()).account);const t=normalizeOptionalString(e.uuid);a=t?`uuid:${t}`:void 0}}catch{a=void 0}if(a){claudeNativeLoginAttestations.set(r,a);if(claudeNativeLoginAttestations.size>CLAUDE_NATIVE_LOGIN_ATTESTATION_LIMIT){const e=claudeNativeLoginAttestations.keys().next().value;if(e!==void 0)claudeNativeLoginAttestations.delete(e)}}return{...a?{owner:a}:{},refreshDueAt:n}}function readClaudeNativeLoginCredential(e){const{homeDir:t}=e;const n=e.env??process.env;if(CLAUDE_NON_NATIVE_AUTH_ENV_KEYS.some(e=>Boolean(n[e]?.trim()))||[n.CLAUDE_CONFIG_DIR,n.CLAUDE_SECURESTORAGE_CONFIG_DIR].some(e=>e&&!path.isAbsolute(e))||path.dirname(resolveClaudeCliCredentialsPath(t,n))!==resolveClaudeCliConfigDir(t,n)||readClaudeApiKeyHelper(t,n)||userSettingsSelectNonNativeAuth(t,n)||managedSettingsSelectNonNativeAuth(e.platform??process.platform))return;const r=e.execSync??execSync;const i=resolveClaudeCliKeychainService(t,n);let a=null;if((e.platform??process.platform)===`darwin`){const e=readClaudeKeychain(r,CLAUDE_CLI_KEYCHAIN_TIMEOUT_MS,i,n);if(e.state===`ok`){a=parseClaudeCliOauthCredential(e.value.claudeAiOauth);if(!a)return}else if((e.state===`absent`?`absent`:probeClaudeKeychainItem(r,i,n))!==`absent`)return}a??=parseClaudeCliOauthCredential(asNonArrayRecord(loadJsonFileThroughSymlink(resolveClaudeCliCredentialsPath(t,n))).claudeAiOauth);if(!a||a.type===`api_key_helper`)return;return{value:a.type===`oauth`?a.access:a.token,expires:a.expires}}function withClaudeAccountEmail(e,t){if(!e||e.type===`api_key_helper`)return e;if(path.dirname(resolveClaudeCliCredentialsPath(t))!==resolveClaudeCliConfigDir(t))return e;const n=readClaudeAccountEmail(t);return n?{...e,email:n}:e}function userSettingsSelectNonNativeAuth(e,t=process.env){return settingsEnvSelectsNonNativeAuth(loadJsonFileThroughSymlink(resolveClaudeCliPath(e,CLAUDE_CLI_USER_SETTINGS_FILE,t)))}function settingsEnvSelectsNonNativeAuth(e){const t=asNonArrayRecord(asNonArrayRecord(e).env);return CLAUDE_NON_NATIVE_AUTH_ENV_KEYS.some(e=>{const n=t[e];return typeof n===`string`&&n.trim()!==``})}function resolveClaudeManagedSettingsDir(e){return e===`darwin`?`/Library/Application Support/ClaudeCode`:e===`win32`?`C:\\Program Files\\ClaudeCode`:`/etc/claude-code`}function managedSettingsSelectNonNativeAuth(e){const t=resolveClaudeManagedSettingsDir(e);const n=path.join(t,CLAUDE_MANAGED_SETTINGS_DROP_IN_DIR);let r=[];try{r=fs.readdirSync(n).filter(e=>e.endsWith(`.json`)&&!e.startsWith(`.`))}catch{}return[path.join(t,CLAUDE_MANAGED_SETTINGS_FILE),...r.map(e=>path.join(n,e))].some(e=>{let t;try{t=asNonArrayRecord(loadJsonFileThroughSymlink(e))}catch{return false}const n=t.apiKeyHelper;return typeof n===`string`&&n.trim()!==``||settingsEnvSelectsNonNativeAuth(t)})}function readClaudeApiKeyHelper(e,t=process.env){const n=loadJsonFileThroughSymlink(resolveClaudeCliPath(e,CLAUDE_CLI_USER_SETTINGS_FILE,t));const r=asNonArrayRecord(n).apiKeyHelper;return typeof r===`string`&&r.trim()?{type:`api_key_helper`,provider:`anthropic`,helperHash:createHash(`sha256`).update(r.trim()).digest(`hex`)}:null}const SECURITY_ITEM_NOT_FOUND_STATUS=44;function isKeychainItemNotFound(e){return typeof e===`object`&&e!==null&&`status`in e&&e.status===SECURITY_ITEM_NOT_FOUND_STATUS}function readClaudeKeychain(e,t,n,r=process.env){let i;try{const a=resolveClaudeCliKeychainAccount(r);i=e(`${MACOS_SECURITY_PATH} find-generic-password -a "${a}" -w -s "${n}"`,{encoding:`utf8`,stdio:[`pipe`,`pipe`,`pipe`],...t===void 0?{}:{timeout:t}})}catch(e){return isKeychainItemNotFound(e)?{state:`absent`}:{state:`unknown`}}try{const e=JSON.parse(i.trim());return isRecord(e)?{state:`ok`,value:e}:{state:`unknown`}}catch{return{state:`unknown`}}}function probeClaudeKeychainItem(e,t,n=process.env){try{e(`${MACOS_SECURITY_PATH} find-generic-password -a "${resolveClaudeCliKeychainAccount(n)}" -s "${t}"`,{encoding:`utf8`,timeout:CLAUDE_CLI_KEYCHAIN_TIMEOUT_MS,stdio:[`pipe`,`pipe`,`pipe`]});return`present`}catch(e){return isKeychainItemNotFound(e)?`absent`:`unknown`}}function resolveClaudeCliKeychainAccount(e=process.env){let t;try{t=e.USER||userInfo().username}catch{t=void 0}return t&&SAFE_KEYCHAIN_ACCOUNT_PATTERN.test(t)?t:CLAUDE_CLI_KEYCHAIN_ACCOUNT_FALLBACK}function readClaudeCliCredentials(e){const t=readClaudeApiKeyHelper(e.homeDir);if(t)return t;const n=e.platform??process.platform;const r=e.execSync??execSync;const i=resolveClaudeCliKeychainService(e.homeDir);if(n===`darwin`&&e.allowKeychainPrompt!==false){const t=readClaudeKeychain(r,e.tryKeychainWithoutPrompt?CLAUDE_CLI_KEYCHAIN_TIMEOUT_MS:void 0,i);const n=parseClaudeCliOauthCredential(t.state===`ok`?t.value.claudeAiOauth:void 0);if(n)return withClaudeAccountEmail(n,e.homeDir)}const a=resolveClaudeCliCredentialsPath(e.homeDir);const o=loadJsonFileThroughSymlink(a);const s=withClaudeAccountEmail(parseClaudeCliOauthCredential(asNonArrayRecord(o).claudeAiOauth),e.homeDir);if(s)return s;if(e.onStoredCredentialUnreadable&&e.tryKeychainWithoutPrompt&&(fs.existsSync(a)||n===`darwin`&&probeClaudeKeychainItem(r,i)===`present`))e.onStoredCredentialUnreadable();return null}function readClaudeCliCredentialsCached(e={}){const t=e.platform??process.platform;const n=e.ttlMs??0;const r=resolveClaudeCliCredentialsPath(e.homeDir);const i=resolveClaudeCliPath(e.homeDir,CLAUDE_CLI_USER_SETTINGS_FILE);const a=resolveClaudeCliAccountPath(e.homeDir);const o=resolveClaudeCliKeychainService(e.homeDir);const s=`${r}:${i}:${a}:${t!==`darwin`?`file`:e.allowKeychainPrompt===false?e.tryKeychainWithoutPrompt?`keychain-presence`:`file`:e.tryKeychainWithoutPrompt?`keychain-bounded`:`keychain`}:${o}:${e.onStoredCredentialUnreadable&&e.tryKeychainWithoutPrompt?`notify`:`silent`}`;const c=`${readFileMtimeMs$1(r)??`missing`}:${readFileMtimeMs$1(i)??`missing`}:${readFileMtimeMs$1(a)??`missing`}`;const l=Date.now();if(n>0&&claudeCliCache?.cacheKey===s&&claudeCliCache.sourceFingerprint===c&&l-claudeCliCache.readAt<n)return claudeCliCache.value;const u=readClaudeCliCredentials({...e,platform:t});claudeCliCache=n>0?{value:u,readAt:l,cacheKey:s,sourceFingerprint:c}:null;return u}
//!src/agents/cli-credentials.ts
const CODEX_CLI_AUTH_FILENAME=`auth.json`;const MINIMAX_CLI_CREDENTIALS_RELATIVE_PATH=`.minimax/oauth_creds.json`;const GEMINI_CLI_CREDENTIALS_RELATIVE_PATH=`.gemini/oauth_creds.json`;const CODEX_CLI_FALLBACK_EXPIRY_MS=36e5;const readCachedCodexCredential=createCachedCliCredentialReader();function resolveCodexCliHomePath(e,t=process.env){const n=e??t.CODEX_HOME;const r=resolveOsHomeRelativePath(n||`~/.codex`,{env:t});try{return fs.realpathSync.native(r)}catch{return r}}function readCodexAuthMode(e){return(typeof e.auth_mode===`string`?e.auth_mode.toLowerCase():void 0)||(typeof e.OPENAI_API_KEY===`string`?`api_key`:`chatgpt`)}function hasCodexCliAuthFile(e){try{const t=fs.statSync(path.join(resolveCodexCliHomePath(e),CODEX_CLI_AUTH_FILENAME));return t.isFile()&&t.size>0}catch(e){const t=extractErrorCode(e);if(t===`ENOENT`||t===`ENOTDIR`)return false;throw e}}function readFileMtimeMs(e){try{return fs.statSync(e).mtimeMs}catch{return null}}function createCachedCliCredentialReader(){let e=null;return t=>{const{ttlMs:n,cacheKey:r,read:i,sourcePath:a}=t;if(n<=0)return i();const o=Date.now();const s=readFileMtimeMs(a);if(e&&e.cacheKey===r&&e.sourceFingerprint===s&&o-e.readAt<n)return e.value;const c=i();const l=readFileMtimeMs(a);if(l===s)e={value:c,readAt:o,cacheKey:r,sourceFingerprint:l};else e=null;return c}}function computeCodexKeychainAccount(e){return`cli|${createHash(`sha256`).update(e).digest(`hex`).slice(0,16)}`}function resolveCodexKeychainParams(e){return{platform:e?.platform??process.platform,execSyncImpl:e?.execSync??execSync,codexHome:resolveCodexCliHomePath(e?.codexHome)}}function decodeJwtPayload(e){const t=e.split(`.`).at(1);if(!t)return;try{const e=JSON.parse(Buffer.from(t,`base64url`).toString(`utf8`));return asOptionalRecord(e)}catch{return}}function decodeJwtExpiryMs(e){const t=decodeJwtPayload(e)?.exp;return typeof t===`number`&&Number.isFinite(t)&&t>0?asDateTimestampMs(t*1e3)??null:null}function readCodexKeychainAuthRecord(e){const{platform:t,execSyncImpl:n,codexHome:r}=resolveCodexKeychainParams(e);if(t!==`darwin`||e?.allowKeychainPrompt===false)return null;const i=computeCodexKeychainAccount(r);try{const e=n(`security find-generic-password -s "Codex Auth" -a "${i}" -w`,{encoding:`utf8`,timeout:5e3,stdio:[`pipe`,`pipe`,`pipe`]}).trim();return JSON.parse(e)}catch{return null}}function resolveCodexFallbackExpiryMs(e){return resolveExpiresAtMsFromDurationMs(CODEX_CLI_FALLBACK_EXPIRY_MS,{nowMs:e===void 0?void 0:Math.floor(e)})}function parseCodexOauthCredential(e,t){if(![`chatgpt`,`chatgptauthtokens`].includes(readCodexAuthMode(e)))return null;const n=e.tokens;const r=n?.access_token;const i=n?.refresh_token;if(typeof r!==`string`||!r)return null;if(typeof i!==`string`||!i)return null;const a=decodeJwtExpiryMs(r)??t;if(a===void 0)return null;return{type:`oauth`,provider:`openai`,access:r,refresh:i,expires:a,accountId:typeof n?.account_id===`string`?n.account_id:void 0,idToken:typeof n?.id_token===`string`?n.id_token:void 0}}function parseCodexApiKeyCredential(e){if(![`apikey`,`api_key`].includes(readCodexAuthMode(e)))return null;const t=typeof e.OPENAI_API_KEY===`string`?e.OPENAI_API_KEY.trim():``;return t?{type:`api_key`,provider:`openai`,key:t}:null}function readCliOauthTokenFields(e){const t=e.access_token;const n=e.refresh_token;const r=e.expiry_date;if(typeof t!==`string`||!t)return null;if(typeof n!==`string`||!n)return null;if(typeof r!==`number`||!Number.isFinite(r))return null;return{access:t,refresh:n,expires:r}}function readMiniMaxCliCredentials(e){const t=loadJsonFileThroughSymlink(e);if(!t||typeof t!==`object`)return null;const n=readCliOauthTokenFields(t);return n?{type:`oauth`,provider:`minimax-portal`,...n}:null}function readGeminiCliCredentials(e){const t=loadJsonFileThroughSymlink(e);if(!t||typeof t!==`object`)return null;const n=t;const r=readCliOauthTokenFields(n);if(!r)return null;const i=n.id_token;const a=typeof i===`string`&&i?decodeJwtPayload(i):void 0;return{type:`oauth`,provider:`google-gemini-cli`,...r,...typeof a?.email===`string`&&a.email?{email:a.email}:{},...typeof a?.sub===`string`&&a.sub?{accountId:a.sub}:{}}}function formatCodexApiKeyForLoginStatus(e){return e.length<=13?`***`:`${e.slice(0,8)}***${e.slice(-5)}`}function readCodexCliActiveApiKey(e){const{execSyncImpl:t,codexHome:n}=resolveCodexKeychainParams(e);let r;try{r=t(`codex login status 2>&1`,{encoding:`utf8`,timeout:5e3,stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env,CODEX_HOME:n}}).trim()}catch{return null}const i=/^Logged in using an API key - (.+)$/mu.exec(r)?.[1]?.trim();const a=r.trim()===`Logged in using an API key`;if(!i&&!a)return null;const o=[];const s=path.join(n,CODEX_CLI_AUTH_FILENAME);const c=loadJsonFileThroughSymlink(s);if(c&&typeof c===`object`){const e=parseCodexApiKeyCredential(c);if(e)o.push(e)}const l=readCodexKeychainAuthRecord({codexHome:n,allowKeychainPrompt:e?.allowKeychainPrompt,platform:e?.platform,execSync:e?.execSync});if(l){const e=parseCodexApiKeyCredential(l);if(e)o.push(e)}const u=new Set(o.filter(e=>a||formatCodexApiKeyForLoginStatus(e.key)===i).map(e=>e.key));if(u.size!==1)return null;const d=[...u][0];return d?{type:`api_key`,provider:`openai`,key:d}:null}function readCodexCliCredentials(e){const t=readCodexKeychainAuthRecord(e);if(t){const e=t.last_refresh;const n=parseCodexOauthCredential(t,resolveCodexFallbackExpiryMs(typeof e===`string`||typeof e===`number`?new Date(e).getTime():Date.now())??resolveCodexFallbackExpiryMs());if(n)return n}const n=path.join(resolveCodexCliHomePath(e?.codexHome),CODEX_CLI_AUTH_FILENAME);const r=loadJsonFileThroughSymlink(n);if(!r||typeof r!==`object`)return null;let i;try{i=resolveCodexFallbackExpiryMs(fs.statSync(n).mtimeMs)}catch{i=resolveCodexFallbackExpiryMs()}return parseCodexOauthCredential(r,i)}function readCodexCliCredentialsCached(e){const t=e?.platform??process.platform;const n=e?.ttlMs??0;const r=path.join(resolveCodexCliHomePath(e?.codexHome),CODEX_CLI_AUTH_FILENAME);const i=t===`darwin`&&e?.allowKeychainPrompt!==false?`keychain`:`file`;return readCachedCodexCredential({ttlMs:n,cacheKey:`${t}|${r}:${i}`,read:()=>readCodexCliCredentials({codexHome:e?.codexHome,allowKeychainPrompt:e?.allowKeychainPrompt,platform:e?.platform,execSync:e?.execSync}),sourcePath:r})}function createCachedCliFileReader(e,t){const n=createCachedCliCredentialReader();return r=>{const i=path.join(resolveOsHomeRelativePath(r?.homeDir??`~`),e);return n({ttlMs:r?.ttlMs??0,cacheKey:i,read:()=>t(i),sourcePath:i})}}const readCachedMiniMax=createCachedCliFileReader(MINIMAX_CLI_CREDENTIALS_RELATIVE_PATH,readMiniMaxCliCredentials);const readCachedGemini=createCachedCliFileReader(GEMINI_CLI_CREDENTIALS_RELATIVE_PATH,readGeminiCliCredentials);function readMiniMaxCliCredentialsCached(e){return readCachedMiniMax(e)}function readGeminiCliCredentialsCached(e){return readCachedGemini(e)}function isNativeCliLoginAttestationEnabled(e,t){const n=asOptionalRecord(t?.plugins?.entries?.anthropic?.config);return e===`claude-cli`&&asOptionalRecord(n?.historyRecovery)?.attestNativeLogin===true}async function resolveNativeCliLoginOwner(e,t){return e===`claude-cli`?await attestClaudeNativeLoginOwner({env:t}):{}}function readAttestedNativeCliLoginOwner(e,t){return e===`claude-cli`?readClaudeNativeLoginOwner({env:t}):void 0}
//!src/agents/auth-profiles/external-cli-sync.ts
const PERSISTED_EXTERNAL_CLI_AUTH_FLOW=`external-cli`;const MINIMAX_PROVIDER=`minimax-portal`;const MINIMAX_PROVIDER_IDS=[MINIMAX_PROVIDER,`minimax`,`minimax-cli`];function isMiniMaxCliProfile(e){return e.profileId===`minimax-portal:minimax-cli`&&(!e.credential||MINIMAX_PROVIDER_IDS.includes(e.credential.provider))}function readMiniMaxCredential(e,t){const n=readMiniMaxCliCredentialsCached({ttlMs:EXTERNAL_CLI_SYNC_TTL_MS,...e?{homeDir:resolveRequiredOsHomeDir(e)}:{}});return n&&t!==void 0?{...n,provider:t}:n}function isPersistedExternalCliAuthProfile(e){if(!isMiniMaxCliProfile(e))return false;return e.credential.authFlow===PERSISTED_EXTERNAL_CLI_AUTH_FLOW}function markPersistedExternalCliCredential(e){return{...e,authFlow:PERSISTED_EXTERNAL_CLI_AUTH_FLOW}}function listExternalCliSyncProviderIds(){return[...MINIMAX_PROVIDER_IDS]}function readExternalCliBootstrapCredential(e){if(!isMiniMaxCliProfile(e))return null;const t=readMiniMaxCredential(void 0,e.credential.provider);if(t&&isOAuthRefreshFence(e.credential))return null;return t}function normalizeProviderScope(e){return e===void 0?void 0:new Set(Array.from(e,normalizeProviderId).filter(Boolean))}function isMiniMaxCliInScope(e){const{options:t,store:n}=e;const r=normalizeProviderScope(t?.providerIds);if(r===void 0&&t?.profileIds===void 0){const e=n.profiles[MINIMAX_CLI_PROFILE_ID];return Object.hasOwn(n.profiles,`minimax-portal:minimax-cli`)&&e?.type===`oauth`&&MINIMAX_PROVIDER_IDS.includes(e.provider)}if(Array.from(t?.profileIds??[]).some(e=>`minimax-portal:minimax-cli`===e.trim()))return true;return MINIMAX_PROVIDER_IDS.some(e=>r?.has(e))}function isExternalCliAuthProfileInScope(e){return e.profileId===`minimax-portal:minimax-cli`&&isMiniMaxCliInScope({store:e.store})}function backfillExternalCliIdentity(e){const t=readMiniMaxCredential(e.env);if(!(t?.refresh===e.existingOAuth.refresh))return null;const n=markPersistedExternalCliCredential({...e.existingOAuth,...e.existingOAuth.email||!t.email?{}:{email:t.email}});return n.authFlow===e.existingOAuth.authFlow&&n.email===e.existingOAuth.email?null:n}function resolveExternalCliAuthProfiles(e,t){const n=Date.now();if(!isMiniMaxCliInScope({store:e,options:t}))return[];const r=MINIMAX_CLI_PROFILE_ID;const i=e.profiles[r];const a=i?.type===`oauth`&&MINIMAX_PROVIDER_IDS.includes(i.provider)?i:void 0;if(i&&!a)return[];if(a&&hasUsableOAuthCredential(a,{now:n})){const e=backfillExternalCliIdentity({existingOAuth:a,env:t?.env});return e?[{profileId:r,credential:e,persistence:`persisted`}]:[]}const o=readMiniMaxCredential(t?.env,a?.provider??MINIMAX_PROVIDER);if(!o)return[];if(a&&isOAuthRefreshFence(a)){authProfilesLog.warn(`refused unordered external cli oauth recovery for a fenced profile`,{profileId:r,provider:MINIMAX_PROVIDER});return[]}if(a&&!isSafeToAdoptBootstrapOAuthIdentity(a,o)){authProfilesLog.warn(`refused external cli oauth bootstrap: identity mismatch`,{profileId:r,provider:MINIMAX_PROVIDER});return[]}if(!hasUsableOAuthCredential(o,{now:n}))return[];return[{profileId:r,credential:markPersistedExternalCliCredential(o),persistence:`persisted`}]}export{resolveExternalCliAuthProfiles as a,readAttestedNativeCliLoginOwner as c,readGeminiCliCredentialsCached as d,resolveCodexCliHomePath as f,readExternalCliBootstrapCredential as i,readCodexCliActiveApiKey as l,readClaudeCliCredentialsCached as m,isPersistedExternalCliAuthProfile as n,hasCodexCliAuthFile as o,resolveNativeCliLoginOwner as p,listExternalCliSyncProviderIds as r,isNativeCliLoginAttestationEnabled as s,isExternalCliAuthProfileInScope as t,readCodexCliCredentialsCached as u};