openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
4 lines • 13.4 kB
JavaScript
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import"./utils-Dlk0IYAa.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{a as resolveAgentDir}from"./agent-scope-config-CG9CFpGX.mjs";import{t as readConfigMachineStateAsync}from"./config-machine-state-async-v5VPG1tC.mjs";import{r as updateConfigMachineState}from"./config-machine-state-write-y_DUumZ_.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{t as quoteCliArg}from"./quote-cli-arg-BUHoGELl.mjs";import{b as resolveAuthProfileDatabasePath}from"./sqlite-y_WDH-Xr.mjs";import{d as resolveSharedAuthStorePath,o as prepareSharedAuthStoreOwnership}from"./path-resolve-TSS6dv07.mjs";import{et as shouldUseMainOwnerForLocalOAuthCredential}from"./runtime-snapshots-DYK7vyJv.mjs";import{n as formatInlineCodeSpan}from"./markdown-code-rYi19S0p.mjs";import{a as buildAuthProfileUnusableHint,o as buildOAuthRefreshFailureLoginCommand,s as classifyOAuthRefreshFailure}from"./oauth-refresh-failure-BdZMhNvV.mjs";import{a as hasLocalAuthProfileStoreSourceAsync,n as hasAnyAuthProfileStoreSourceAsync,o as withAuthProfileReaderCleanup}from"./source-check-rCWqGxdp.mjs";import{n as prepareAgentAuthProfileRowsRead}from"./sqlite-read-CE01Jx_X.mjs";import{f as loadAuthProfileStoreForRuntimeAsync,i as ensureAuthProfileStoreAsync,l as findPersistedAuthProfileCredentialAsync}from"./store-runtime-GNz-2GjY.mjs";import{r as resolveAuthStorePathForDisplay}from"./paths-BDkFWGjX.mjs";import{n as buildAuthHealthSummary,r as formatRemainingShort,t as DEFAULT_OAUTH_WARN_MS}from"./auth-health-DIboE8Qn.mjs";import{n as resolveApiKeyForProfile,r as formatAuthDoctorHint}from"./oauth-DMxm8Ns0.mjs";import{t as buildProviderAuthRecoveryHint}from"./provider-auth-recovery-hint-DoaLcFof.mjs";import"./auth-profiles-nMUErGRQ.mjs";import{t as listUnavailableAuthProfiles}from"./auth-unavailability-7pFoIfQW.mjs";
//!src/commands/doctor-auth.ts
const OPENAI_PROVIDER_ID=`openai`;const LEGACY_CODEX_PROVIDER_ID=`openai-codex`;const OPENAI_BASE_URL=`https://api.openai.com/v1`;const LEGACY_CODEX_APIS=/* @__PURE__ */ new Set([`openai-responses`,`openai-completions`]);const AUTH_PROFILES_CHECK_ID=`core/doctor/auth-profiles`;const COPILOT_NOTICE_KEY=`doctor.githubCopilotAmbientTokenNotice`;const DOCTOR_REAUTH_PROVIDER_ALIASES={[LEGACY_CODEX_PROVIDER_ID]:OPENAI_PROVIDER_ID};async function collectCopilotAmbientTokenFindings(e,t=process.env){if(!(t.GH_TOKEN?.trim()||t.GITHUB_TOKEN?.trim())||t.COPILOT_GITHUB_TOKEN?.trim()||e.models?.providers?.[`github-copilot`]||Object.values(e.auth?.profiles??{}).some(e=>e.provider===`github-copilot`)||await readConfigMachineStateAsync(COPILOT_NOTICE_KEY,{env:t}))return[];const n=[void 0,...listAgentIds(e).map(n=>resolveAgentDir(e,n,t))];for(const e of n){const n=await loadAuthProfileStoreForRuntimeAsync(e,{readOnly:true,allowKeychainPrompt:false},t);if(Object.values(n.profiles).some(e=>e.provider===`github-copilot`))return[]}let r=false;updateConfigMachineState(COPILOT_NOTICE_KEY,e=>{r=e!==true;return true},{env:t});if(r)return[{checkId:`core/doctor/copilot-ambient-token`,severity:`info`,category:`recommended`,message:`GitHub Copilot is no longer enabled by GH_TOKEN/GITHUB_TOKEN.`,fixHint:`To use Copilot, run openclaw models auth login --provider github-copilot or set COPILOT_GITHUB_TOKEN. No action needed if you do not use Copilot.`,docsUrl:`https://docs.openclaw.ai/providers/github-copilot`}];return[]}async function collectSharedAuthStoreFindings(e=process.env){if((await prepareSharedAuthStoreOwnership(e)).location!==`legacy-main`)return[];const t=resolveSharedAuthStorePath(e);const n=await prepareAgentAuthProfileRowsRead({databasePath:t,env:e});if(!await withAuthProfileReaderCleanup(async()=>{const e=await n.read();n.assertCurrent();return e.store.status===`readable`},[n],{read:`Shared auth source read failed`,cleanup:`Shared auth source cleanup failed`}))return[];return[{checkId:`core/doctor/shared-auth-store`,severity:`warning`,category:`recommended`,message:`Shared auth profiles still live in the main agent database.`,fixHint:`Run openclaw doctor --fix to move them into shared SQLite state and make the main agent deletable.`,docsUrl:`https://docs.openclaw.ai/concepts/oauth`}]}function hasConfiguredCodexOAuthProfile(e){return Object.values(e.auth?.profiles??{}).some(e=>(e.provider===OPENAI_PROVIDER_ID||e.provider===LEGACY_CODEX_PROVIDER_ID)&&e.mode===`oauth`)}async function hasStoredCodexOAuthProfile(){const e=await ensureAuthProfileStoreAsync(void 0,{allowKeychainPrompt:false,readOnly:true});return Object.values(e.profiles).some(e=>(e.provider===OPENAI_PROVIDER_ID||e.provider===LEGACY_CODEX_PROVIDER_ID)&&e.type===`oauth`)}function normalizeCodexOverrideBaseUrl(e){if(typeof e!==`string`)return;return e.trim().replace(/\/+$/,``)}function isLegacyCodexTransportShape(e,t){if(!isRecord(e))return false;const n=typeof e.api===`string`?e.api:void 0;if(!n||!LEGACY_CODEX_APIS.has(n))return false;const r=normalizeCodexOverrideBaseUrl(e.baseUrl??t);return!r||r===OPENAI_BASE_URL}function hasLegacyCodexTransportOverride(e){if(!isRecord(e))return false;if(isLegacyCodexTransportShape(e))return true;const t=e.models;if(!Array.isArray(t))return false;return t.some(t=>isLegacyCodexTransportShape(t,e.baseUrl))}function buildCodexProviderOverrideWarning(e){const t=[`- models.providers.${LEGACY_CODEX_PROVIDER_ID} contains a legacy transport override while Codex OAuth is configured.`,`- Older OpenAI transport settings can shadow the built-in Codex OAuth provider path.`];if(isRecord(e)){const n=e;if(typeof n.api===`string`)t.push(`- models.providers.${LEGACY_CODEX_PROVIDER_ID}.api=${n.api}`);if(typeof n.baseUrl===`string`)t.push(`- models.providers.${LEGACY_CODEX_PROVIDER_ID}.baseUrl=${n.baseUrl}`)}t.push(`- Remove or rewrite the legacy transport override to restore the built-in Codex OAuth provider path after recent fixes.`);t.push(`- Custom proxies and header-only overrides can stay; this warning only targets old OpenAI transport settings.`);return t.join(`
`)}async function collectLegacyCodexProviderOverrideFindings(e){const t=e.models?.providers?.[LEGACY_CODEX_PROVIDER_ID];if(!t)return[];if(!hasLegacyCodexTransportOverride(t))return[];if(!hasConfiguredCodexOAuthProfile(e)&&!await hasStoredCodexOAuthProfile())return[];return[{checkId:AUTH_PROFILES_CHECK_ID,severity:`warning`,category:`fix-now`,message:`Legacy openai-codex transport override can shadow configured Codex OAuth credentials.`,path:`models.providers.${LEGACY_CODEX_PROVIDER_ID}`,target:LEGACY_CODEX_PROVIDER_ID,fixHint:buildCodexProviderOverrideWarning(t),docsUrl:`https://docs.openclaw.ai/providers/openai`}]}async function listAuthProfileHealthTargets(e){await prepareSharedAuthStoreOwnership();const t=/* @__PURE__ */ new Map;if(await hasAnyAuthProfileStoreSourceAsync()||Object.keys(e.auth?.profiles??{}).length>0)t.set(resolveSharedAuthStorePath(),{label:`Shared`});for(const n of listAgentIds(e)){const r=resolveAgentDir(e,n);const i=resolveAuthProfileDatabasePath(r);if(!t.has(i)&&await hasLocalAuthProfileStoreSourceAsync(r))t.set(i,{label:`Agent ${n}`,agentId:n,agentDir:r})}return[...t.values()]}function formatOAuthRefreshFailureReason(e){switch(e){case`refresh_token_reused`:case`expired`:case`invalid_grant`:case`revoked`:return e;case`sign_in_again`:return`sign in again`;case`invalid_refresh_token`:return`invalid refresh token`;default:return`refresh failed`}}async function resolveAuthIssueHint(e,t,n){if(e.reasonCode===`invalid_expires`)return`Invalid token expires metadata. Set a future Unix ms timestamp or remove expires.`;if(e.reasonCode===`malformed_api_key`)return`Paste the API key value, not an OpenClaw onboarding command.`;const r=await formatAuthDoctorHint({cfg:t,store:n,provider:e.provider,profileId:e.profileId});if(r.trim())return r;return buildProviderAuthRecoveryHint({provider:e.provider}).replace(/^Run /,`Re-auth via `)}async function collectAuthProfileCooldowns(e){return Promise.all(listUnavailableAuthProfiles(e).map(async({profileId:e,provider:t,kind:n,reason:r,classification:i,remainingMs:a})=>{const o=i??r;return{profileId:e,kind:`${n}${o?`:${o}`:``}`,remaining:formatRemainingShort(a),hint:buildAuthProfileUnusableHint({kind:n,reason:r,provider:t??(await findPersistedAuthProfileCredentialAsync({profileId:e}))?.provider??e,profileId:e})}}))}function isAuthProfileHealthIssue(e){if(e.type===`api_key`)return e.status===`missing`;return(e.type===`oauth`||e.type===`token`)&&(e.status===`expired`||e.status===`expiring`||e.status===`missing`)}async function loadAuthProfileHealth(e){const t=await loadAuthProfileStoreForRuntimeAsync(e.target.agentDir,{inheritedAuthDir:e.target.agentDir,allowKeychainPrompt:e.allowKeychainPrompt,readOnly:e.readOnly});const n={};for(const[r,i]of Object.entries(t.profiles)){if(e.target.agentDir&&i.type===`oauth`&&shouldUseMainOwnerForLocalOAuthCredential({profileId:r,local:i,main:await findPersistedAuthProfileCredentialAsync({profileId:r})}))continue;n[r]=i}return{store:t,summary:buildAuthHealthSummary({store:{...t,profiles:n},cfg:e.cfg,warnAfterMs:DEFAULT_OAUTH_WARN_MS})}}async function collectAuthProfileTargetFindings(e){const t=[];const n=e.labelStores?`${e.target.label} auth profile`:`Auth profile`;const r=resolveAuthStorePathForDisplay(e.target.agentDir);const i=new Map(Object.entries(e.store.order??{}).flatMap(([e,t])=>t.map(t=>[t,e])));for(const[a,o]of i){if(e.store.profiles[a]||await findPersistedAuthProfileCredentialAsync({agentDir:e.target.agentDir,profileId:a}))continue;t.push({checkId:AUTH_PROFILES_CHECK_ID,severity:`warning`,category:`fix-now`,message:`${n} ${a} is referenced by saved ${o} account order but has no effective credential.`,path:r,target:a,requirement:`missing_ordered_profile`,fixHint:`Inspect available accounts with openclaw models auth list${e.target.agentId?` --agent ${quoteCliArg(e.target.agentId)}`:``} --provider ${quoteCliArg(o)}. Restore the missing credential or explicitly change the saved account order.`,docsUrl:`https://docs.openclaw.ai/concepts/oauth`})}for(const i of await collectAuthProfileCooldowns(e.store))t.push({checkId:AUTH_PROFILES_CHECK_ID,severity:`warning`,category:`fix-now`,message:`${n} ${i.profileId} is ${i.kind} (${i.remaining}).`,path:r,target:i.profileId,fixHint:i.hint,docsUrl:`https://docs.openclaw.ai/concepts/oauth`});for(const i of e.summary.profiles.filter(isAuthProfileHealthIssue)){const a=i.remainingMs!==void 0?` (${formatRemainingShort(i.remainingMs)})`:``;const o=i.reasonCode?` [${i.reasonCode}]`:``;t.push({checkId:AUTH_PROFILES_CHECK_ID,severity:`warning`,category:i.status===`expiring`?`recommended`:`fix-now`,message:`${n} ${i.profileId} is ${i.status}${o}${a}.`,path:r,target:i.profileId,...i.reasonCode?{requirement:i.reasonCode}:{},fixHint:await resolveAuthIssueHint(i,e.cfg,e.store),docsUrl:`https://docs.openclaw.ai/concepts/oauth`})}return t}async function collectAuthProfileHealthFindings(e){const t=await listAuthProfileHealthTargets(e.cfg);const n=[];for(const r of t){const i=await loadAuthProfileHealth({cfg:e.cfg,target:r,allowKeychainPrompt:e.allowKeychainPrompt??false,readOnly:true});n.push(...await collectAuthProfileTargetFindings({...e,...i,target:r,labelStores:t.length>1}))}return[...n,...await collectLegacyCodexProviderOverrideFindings(e.cfg)]}async function inspectAuthProfileHealth(e){const t=await listAuthProfileHealthTargets(e.cfg);const n=/* @__PURE__ */ new Map;for(const r of t){const{cfg:t,prompter:i,allowKeychainPrompt:a}=e;let{store:o,summary:s}=await loadAuthProfileHealth({cfg:t,target:r,allowKeychainPrompt:a});const c=s.profiles.filter(isAuthProfileHealthIssue).filter(e=>e.type===`oauth`);const l=/* @__PURE__ */ new Map;if(c.length>0&&await i.confirmAutoFix({message:`Refresh expiring OAuth tokens now? (static tokens need re-auth)`,initialValue:true})){for(const e of c)try{await resolveApiKeyForProfile({cfg:t,store:o,profileId:e.profileId,agentDir:r.agentDir,forceRefresh:true})}catch(t){const n=formatErrorMessage(t);const r=e.profileId;const i=e.provider;const a=classifyOAuthRefreshFailure(n);if(!a){l.set(r,`OAuth refresh failed: ${n}`);continue}const o=a.provider??i;const s=o?DOCTOR_REAUTH_PROVIDER_ALIASES[o]??o:null;const c=buildOAuthRefreshFailureLoginCommand(s,{profileId:s===o?r:void 0});const u=formatInlineCodeSpan(c);l.set(r,a.reason?`- ${r}: re-auth required [${formatOAuthRefreshFailureReason(a.reason)}] — Run ${u}.`:`- ${r}: OAuth refresh failed — Try again; if this persists, run ${u}.`)}({store:o,summary:s}=await loadAuthProfileHealth({cfg:t,target:r,allowKeychainPrompt:false}))}const u=await collectAuthProfileTargetFindings({cfg:t,target:r,labelStores:false,store:o,summary:s});for(const[e,t]of u.entries()){const n=t.target&&l.get(t.target);if(n)u[e]={...t,message:`${t.message} ${n}`}}for(const e of u){const{path:t,...i}=e;const a=JSON.stringify(i);const o=n.get(a);if(o)o.stores.add(r.label);else n.set(a,{finding:e,stores:/* @__PURE__ */ new Set([r.label])})}}const r=[];for(const{finding:e,stores:i}of[...n.values()].toSorted((e,t)=>e.finding.message.localeCompare(t.finding.message))){const{path:n,...a}=e;r.push({...a,...i.size===1?{path:n}:{},message:i.size===t.length?e.message:`${e.message} (stores: ${[...i].toSorted().join(`, `)})`})}return r}export{collectAuthProfileHealthFindings,collectCopilotAmbientTokenFindings,collectLegacyCodexProviderOverrideFindings,collectSharedAuthStoreFindings,inspectAuthProfileHealth};