UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 11.9 kB
import{i as normalizeBoundedOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{o as resolveGlobalSingleton}from"./global-singleton-DolL9xGt.mjs";import{p as toErrorObject}from"./error-coercion-DlKnt6w-.mjs";import{a as asOptionalRecord,i as asOptionalObjectRecord,p as readStringField}from"./record-coerce-BTbqdJ3-.mjs";import{n as materializeErrorStack}from"./error-graph-internal-Bt2pFJBM.mjs";import{n as sanitizeForLog}from"./ansi-54CEWBZf.mjs";import{c as redactSensitiveText}from"./redact-BT59pdZ_.mjs";import"./errors-D37BJTfI.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{n as formatInlineCodeSpan}from"./markdown-code-rYi19S0p.mjs";import{r as isRecoverableOAuthRefreshFailure}from"./oauth-refresh-outcome-CW1zSJnY.mjs"; //!src/shared/provider-login-command.ts function formatProviderLoginCommand(e){return!e||/^(?:refresh|access|cancel|choice)$/iu.test(e)?`/login`:`/login ${e}`} //!src/agents/auth-profiles/oauth-refresh-failure.ts function formatRawErrorMessage(e){if(e instanceof Error){let t=e.message||e.name||`Error`;let n=e.cause;const r=/* @__PURE__ */ new Set([e]);while(n&&!r.has(n)){r.add(n);if(n instanceof Error){if(n.message)t+=` | ${n.message}`;n=n.cause}else if(typeof n===`string`){t+=` | ${n}`;break}else break}return t}if(typeof e===`string`||typeof e===`number`||typeof e===`boolean`||typeof e===`bigint`)return String(e);try{return JSON.stringify(e)??String(e)}catch{return Object.prototype.toString.call(e)}}function formatRedactedOAuthRefreshError(e,t){let n=formatRawErrorMessage(e);for(const e of t)n=n.split(e).join(`[redacted]`);return redactSensitiveText(n)}const oauthRefreshCleanupAggregates=/* @__PURE__ */ new WeakSet;const settledRefreshFailures=resolveGlobalSingleton(Symbol.for(`openclaw.settledOAuthRefreshFailures`),()=>/* @__PURE__ */ new WeakMap);function appendOAuthRefreshCleanupErrors(e,t){const n=toErrorObject(e,`OAuth refresh failed`);if(t.length===0)return n;const r=t.map(e=>toErrorObject(e,`OAuth refresh cleanup failed`));const i=n instanceof AggregateError&&oauthRefreshCleanupAggregates.has(n)?[...n.errors,...r]:[n,...r];const a=new AggregateError(i,`OAuth refresh failed and cleanup could not be completed.`,{cause:i[0]});oauthRefreshCleanupAggregates.add(a);return a}function readSettledOAuthRefreshCause(e){return e instanceof Error?settledRefreshFailures.get(e)??e:e}function readOAuthRefreshInitiatingError(e){const t=readSettledOAuthRefreshCause(e);return t instanceof AggregateError&&oauthRefreshCleanupAggregates.has(t)&&t.errors.length>0?readSettledOAuthRefreshCause(t.errors[0]):t}const OAUTH_REFRESH_FAILURE_ERROR_TYPE_MAX_CHARS=100;const OAUTH_REFRESH_FAILURE_SUMMARY_MAX_CHARS=500;function markOAuthRefreshFailureSettled(e,t=e){materializeErrorStack(e);if(t!==e)materializeErrorStack(t);settledRefreshFailures.set(e,t)}function isSettledOAuthRefreshFailure(e){return e instanceof Error&&settledRefreshFailures.has(e)}function readProviderOAuthRefreshFailure(e){const t=asOptionalRecord(asOptionalRecord(e)?.oauthRefreshFailure);if(!t)return null;const n=normalizeBoundedOptionalString(t.summary,OAUTH_REFRESH_FAILURE_SUMMARY_MAX_CHARS);const r=normalizeBoundedOptionalString(t.errorType,OAUTH_REFRESH_FAILURE_ERROR_TYPE_MAX_CHARS);const i=typeof t.reason===`string`?classifyOAuthRefreshFailureReason(t.reason):null;const a=typeof t.status===`number`&&Number.isInteger(t.status)&&t.status>=100&&t.status<=599?t.status:void 0;if(!n&&!r&&!i&&!a)return null;return{...r?{errorType:r}:{},...i?{reason:i}:{},...a?{status:a}:{},...n?{summary:n}:{}}}const isTransientOAuthRefreshFailure=isRecoverableOAuthRefreshFailure;var OAuthRefreshFailureError=class OAuthRefreshFailureError extends Error{constructor(e){super(e.message,{cause:e.cause});const t=e.cause instanceof OAuthRefreshFailureError?e.cause:readProviderOAuthRefreshFailure(e.cause);this.name=`OAuthRefreshFailureError`;this.retryable=e.retryable??(e.cause instanceof OAuthRefreshFailureError?e.cause.retryable:void 0);this.errorType=normalizeBoundedOptionalString(e.errorType??t?.errorType,OAUTH_REFRESH_FAILURE_ERROR_TYPE_MAX_CHARS);this.provider=e.provider;this.profileId=e.profileId;this.reason=e.reason!==void 0?e.reason:t?.reason??classifyOAuthRefreshFailureReason(e.message);this.status=e.status??t?.status;this.summary=normalizeBoundedOptionalString(e.summary??t?.summary,OAUTH_REFRESH_FAILURE_SUMMARY_MAX_CHARS)}};var OAuthRefreshOwnerError=class extends OAuthRefreshFailureError{};function createOAuthRefreshUserFacingCause(e){if(e instanceof Error&&`code`in e&&e.code===`refresh_contention`)return new Error(e.message);return e}var OAuthManagerRefreshError=class extends OAuthRefreshFailureError{#e;constructor(e){const t=readOAuthRefreshInitiatingError(e.cause);const n=asOptionalObjectRecord(t);const r=createOAuthRefreshUserFacingCause(t);const i=e.refreshedStore.profiles[e.profileId];const a=collectOAuthCredentialSecrets(e.credential,...e.attemptedCredentials??[],i?.type===`oauth`?i:void 0);const o=t instanceof OAuthRefreshFailureError?t:readProviderOAuthRefreshFailure(t);const s=formatRedactedOAuthRefreshError(r,a);super({provider:e.credential.provider,profileId:e.profileId,message:`OAuth token refresh failed for ${e.credential.provider}: ${s}`,cause:createRedactedOAuthRefreshCause(e.cause,a),retryable:e.retryable??(t instanceof OAuthRefreshFailureError?t.retryable:void 0),errorType:o?.errorType,reason:o?.reason,status:o?.status,summary:o?.summary?formatRedactedOAuthRefreshError(o.summary,a):void 0});this.name=`OAuthManagerRefreshError`;this.profileId=e.profileId;this.#e=e.refreshedStore;if(isSettledOAuthRefreshFailure(e.cause))markOAuthRefreshFailureSettled(this);if(n){this.code=readStringField(n,`code`);this.lockPath=readStringField(n,`lockPath`)??readStringField(asOptionalObjectRecord(n.cause),`lockPath`)}}getRefreshedStore(){return this.#e}toJSON(){return{name:this.name,message:this.message,profileId:this.profileId,provider:this.provider}}};function collectOAuthCredentialSecrets(...e){const t=/* @__PURE__ */ new Set;for(const n of e)for(const e of[n?.access,n?.refresh,n?.idToken])if(e)t.add(e);return Array.from(t).toSorted((e,t)=>t.length-e.length)}function createRedactedOAuthRefreshCause(e,t){const n=readSettledOAuthRefreshCause(e);if(n instanceof AggregateError){const e=n.errors.map(e=>createRedactedOAuthRefreshCause(e,t));const r=new AggregateError(e,formatRedactedOAuthRefreshError(n.message,t),e.length>0?{cause:e[0]}:void 0);r.name=n.name;return r}const r=createOAuthRefreshUserFacingCause(n);const i=formatRedactedOAuthRefreshError(r,t);const a=new Error(i);if(r instanceof Error&&r.name)a.name=r.name;return a}const OAUTH_REFRESH_FAILURE_PROVIDER_RE=/OAuth token refresh failed for ([^:]+):/i;const SAFE_PROVIDER_ID_RE=/^[a-z0-9][a-z0-9._-]*$/;const CLAUDE_CLI_AUTH_FAILURE_RE=/\bclaude-cli\b.+?\b(failed to authenticate|401\s+invalid authentication credentials)\b/is;function isClaudeCliExpiredOAuthMessage(e){return CLAUDE_CLI_AUTH_FAILURE_RE.test(e)}function classifyStructuredClaudeCliOAuthFailureReason(e){const t=asOptionalObjectRecord(e);if(t?.name!==`FailoverError`||t.provider!==`claude-cli`||t.reason!==`auth`||t.status!==401)return null;const n=typeof t.rawError===`string`?t.rawError:``;const r=`${e instanceof Error?e.message:``}\n${n}`;const i=r.toLowerCase();if(/\bnot logged in\b\s*·\s*please run \/login\b/i.test(r))return`sign_in_again`;return i.includes(`failed to authenticate`)||i.includes(`invalid authentication credentials`)?`revoked`:null}function isOAuthRefreshFailureMessage(e){const t=e.toLowerCase();return t.includes(`oauth token refresh failed`)||t.includes(`access token could not be refreshed`)||t.includes(`authentication session could not be refreshed automatically`)||isClaudeCliExpiredOAuthMessage(e)}function extractOAuthRefreshFailureProvider(e){if(isClaudeCliExpiredOAuthMessage(e))return`claude-cli`;const t=e.match(OAUTH_REFRESH_FAILURE_PROVIDER_RE)?.[1]?.trim();return t&&t.length>0?t:null}function sanitizeOAuthRefreshFailureProvider(e){const t=e?sanitizeForLog(e).replaceAll("`",``).trim():``;const n=normalizeProviderId(t);return n&&SAFE_PROVIDER_ID_RE.test(n)?n:null}function sanitizeOAuthRefreshFailureProfileId(e){return(e?sanitizeForLog(e).trim():``)||null}function quoteShellArg(e){return`'${process.platform===`win32`?e.replaceAll(`'`,`''`):e.replaceAll(`'`,`'\\''`)}'`}function classifyOAuthRefreshFailureReason(e){const t=e.toLowerCase();return OAUTH_REFRESH_REASON_SIGNALS.find(([,e])=>e.some(e=>t.includes(e)))?.[0]??(isClaudeCliExpiredOAuthMessage(e)?`revoked`:null)}const OAUTH_REFRESH_REASON_SIGNALS=[[`refresh_token_reused`,[`refresh_token_reused`]],[`expired`,[`refresh_token_expired`]],[`invalid_grant`,[`invalid_grant`]],[`token_invalidated`,[`token_invalidated`]],[`sign_in_again`,[`sign_in_again`,`signing in again`,`sign in again`,`log in again`]],[`invalid_refresh_token`,[`invalid_refresh_token`,`invalid refresh token`]],[`revoked`,[`revoked`]]];function classifyOAuthRefreshFailure(e){if(!isOAuthRefreshFailureMessage(e))return null;return{provider:sanitizeOAuthRefreshFailureProvider(extractOAuthRefreshFailureProvider(e)),reason:classifyOAuthRefreshFailureReason(e)}}function classifyOAuthRefreshFailureError(e){const t=/* @__PURE__ */ new Set;let n=null;let r=e;while(r&&typeof r===`object`){const e=classifyStructuredClaudeCliOAuthFailureReason(r);if(e)return{provider:`claude-cli`,reason:e};if(r instanceof OAuthRefreshFailureError){const e=sanitizeOAuthRefreshFailureProfileId(r.profileId);return{...r.errorType?{errorType:r.errorType}:{},provider:sanitizeOAuthRefreshFailureProvider(r.provider),...e?{profileId:e}:{},reason:r.reason,...r.status?{status:r.status}:{},...r.summary?{summary:r.summary}:{}}}const i=asOptionalRecord(r);const a=i?.rawError;if(typeof a===`string`){const e=classifyOAuthRefreshFailure(a);if(e){const t=i?.profileId;const r=sanitizeOAuthRefreshFailureProfileId(typeof t===`string`?t:void 0);n??={...e,...r?{profileId:r}:{}}}}if(t.has(r))return n;t.add(r);r=r.cause}return n}function buildOAuthRefreshFailureLoginCommand(e,t){const n=sanitizeOAuthRefreshFailureProvider(e);if(t?.surface===`chat`)return formatProviderLoginCommand(n===`claude-cli`?null:n);const r=sanitizeOAuthRefreshFailureProfileId(t?.profileId);const i=t?.agentId?sanitizeForLog(t.agentId).trim():void 0;const a=i?` --agent ${quoteShellArg(i)}`:``;const o=r?` --profile-id ${quoteShellArg(r)}`:``;const s=n===`claude-cli`?` --provider anthropic --method cli`:n?` --provider ${n}`:``;const c=formatCliCommand(`openclaw models auth login${s}${n?o:``}${a}`);return n===`claude-cli`?`${formatCliCommand(`claude auth login`)} && ${c}`:c}function buildAuthProfileUnusableHint(e){if(e.reason===`auth`||e.reason===`auth_permanent`||e.reason===`session_expired`){if(e.provider===`google-gemini-cli`){const e=formatCliCommand(`openclaw models auth login --provider google`);return`Gemini CLI OAuth cannot be repaired by OpenClaw. Connect Google with an AI Studio API key using ${formatInlineCodeSpan(e)}, then select that Google profile for the Gemini CLI runtime.`}const t=buildOAuthRefreshFailureLoginCommand(e.provider,{profileId:e.profileId});return`Re-authenticate with ${formatInlineCodeSpan(t)}.`}if(e.kind===`disabled`&&e.reason===`billing`)return`Top up credits (provider billing) or switch provider.`;return`Wait for cooldown or switch provider.`}export{buildAuthProfileUnusableHint as a,classifyOAuthRefreshFailureError as c,isTransientOAuthRefreshFailure as d,markOAuthRefreshFailureSettled as f,appendOAuthRefreshCleanupErrors as i,classifyOAuthRefreshFailureReason as l,OAuthRefreshFailureError as n,buildOAuthRefreshFailureLoginCommand as o,formatProviderLoginCommand as p,OAuthRefreshOwnerError as r,classifyOAuthRefreshFailure as s,OAuthManagerRefreshError as t,isSettledOAuthRefreshFailure as u};