UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

6 lines • 7.34 kB
import{A as resolveExpiresAtMsFromDurationMs}from"../../number-coercion-B3CfI447.mjs";import{t as formatCliCommand}from"../../command-format-D7KhNLP0.mjs";import{t as parseDurationMs}from"../../parse-duration-BueP0M46.mjs";import{f as listProfilesForProvider}from"../../order-B8e_5ABM.mjs";import{n as suggestOAuthProfileIdForLegacyDefault}from"../../repair-C0j0sRhV.mjs";import"../../number-runtime-G0nhUVZu.mjs";import{t as applyAuthProfileConfig}from"../../provider-auth-helpers-5o5rkp5c.mjs";import{t as applyProviderDefaultModel}from"../../provider-setup-BwWnv6lb.mjs";import"../../cli-runtime-BLVbyFtb.mjs";import{t as applyProviderAuthConfigPatch}from"../../provider-auth-Czspvb3-.mjs";import{i as upsertAuthProfileWithLockOrThrowCompat}from"../../provider-auth-write-compat-iCHCUMSb.mjs";import{n as validateAnthropicSetupToken,t as buildTokenProfileId}from"../../provider-auth-token-kKebY-yg.mjs";import"../../provider-auth-api-key-Zmh0L12P.mjs";import{t as probeClaudeCliAuthStatus}from"../../cli-auth-seam-DPpCHsYU.mjs";import{t as buildAnthropicCliMigrationResult}from"../../cli-migration-D5_i0Jmu.mjs"; //!extensions/anthropic/auth.runtime.ts const PROVIDER_ID=`anthropic`;async function runAnthropicApiKeyAuth(e,t){const n=await t(e);const r=e.config.models?.providers?.[PROVIDER_ID];if([r?.headers,r?.request?.headers].some(e=>Object.entries(e??{}).some(([e,t])=>e.toLowerCase()===`anthropic-workspace-id`&&(typeof t!==`string`||t.trim().length>0))))return n;await e.prompter.note(`API keys that are not scoped to a workspace require an Anthropic workspace ID from the Claude Console. This provider setting applies to all Anthropic API requests, not an agent's local workspace. Leave it blank for a workspace-scoped key.`,`Anthropic API workspace`);const i=(await e.prompter.text({message:`Anthropic workspace ID (optional for workspace-scoped keys)`,placeholder:`wrkspc_...`})).trim();return i?{...n,configPatch:{models:{providers:{anthropic:{headers:{"anthropic-workspace-id":i}}}}}}:n}const ANTHROPIC_SETUP_TOKEN_NOTE_LINES=[`Anthropic setup-token auth is supported in OpenClaw.`,`OpenClaw prefers the native Claude CLI runtime when it is available on the host.`,`Anthropic staff told us this OpenClaw path is allowed again.`,`If you want a direct API billing path instead, use ${formatCliCommand(`openclaw models auth login --provider anthropic --method api-key --set-default`)} or ${formatCliCommand(`openclaw models auth login --provider anthropic --method cli --set-default`)}.`];function normalizeAnthropicSetupTokenInput(e){return e.replaceAll(/\s+/g,``)}function resolveAnthropicSetupTokenProfileId(e={},t){if(typeof t===`string`){const e=t.trim();if(e.length>0){if(e.startsWith(`${PROVIDER_ID}:`))return e;return buildTokenProfileId({provider:PROVIDER_ID,name:e})}}let n=`${PROVIDER_ID}:default`;for(let t=1;;t+=1){const r=e.auth?.profiles?.[n];if(!r||r.provider===PROVIDER_ID&&(r.mode===`token`||r.mode===`oauth`))return n;n=buildTokenProfileId({provider:PROVIDER_ID,name:t===1?`setup-token`:`setup-token-${t}`})}}function resolveAnthropicSetupTokenExpiry(e){if(typeof e!==`string`||e.trim().length===0)return;return resolveExpiresAtMsFromDurationMs(parseDurationMs(e.trim(),{defaultUnit:`d`}))}async function runAnthropicSetupTokenAuth(e,t){const n=(typeof e.opts?.token===`string`&&e.opts.token.trim().length>0?normalizeAnthropicSetupTokenInput(e.opts.token):void 0)??normalizeAnthropicSetupTokenInput(await e.prompter.text({message:`Paste Anthropic setup-token`,validate:e=>validateAnthropicSetupToken(normalizeAnthropicSetupTokenInput(e))}));const r=validateAnthropicSetupToken(n);if(r)throw new Error(r);const i=resolveAnthropicSetupTokenProfileId(e.config,e.opts?.tokenProfileId);const a=resolveAnthropicSetupTokenExpiry(e.opts?.tokenExpiresIn);return{profiles:[{profileId:i,credential:{type:`token`,provider:PROVIDER_ID,token:n,...a?{expires:a}:{}}}],defaultModel:t,notes:[...ANTHROPIC_SETUP_TOKEN_NOTE_LINES]}}function validateAnthropicSetupTokenNonInteractive(e){if(e.opts.secretInputMode===`ref`)throw new Error(`Anthropic setup-token input cannot be stored with --secret-input-mode ref. Use --secret-input-mode plaintext.`);const t=typeof e.opts.token===`string`?normalizeAnthropicSetupTokenInput(e.opts.token):``;const n=validateAnthropicSetupToken(t);if(n)throw new Error([`Anthropic setup-token auth requires --token with a valid setup-token.`,n].join(` `));try{resolveAnthropicSetupTokenExpiry(e.opts.tokenExpiresIn)}catch(e){throw new Error(`Invalid --token-expires-in: ${e instanceof Error?e.message:String(e)}`,{cause:e})}return t}async function runAnthropicSetupTokenNonInteractive(e,t){const n=validateAnthropicSetupTokenNonInteractive(e);const r=resolveAnthropicSetupTokenProfileId(e.config,e.opts.tokenProfileId);const i=resolveAnthropicSetupTokenExpiry(e.opts.tokenExpiresIn);await upsertAuthProfileWithLockOrThrowCompat({profileId:r,credential:{type:`token`,provider:PROVIDER_ID,token:n,...i?{expires:i}:{}},agentDir:e.agentDir});e.runtime.log(ANTHROPIC_SETUP_TOKEN_NOTE_LINES[0]);e.runtime.log(ANTHROPIC_SETUP_TOKEN_NOTE_LINES[1]);const a=applyAuthProfileConfig(e.config,{profileId:r,provider:PROVIDER_ID,mode:e.config.auth?.profiles?.[r]?.mode===`oauth`?`oauth`:`token`});const o=a.agents?.defaults?.model&&typeof a.agents.defaults.model===`object`?a.agents.defaults.model:{};return{...a,agents:{...a.agents,defaults:{...a.agents?.defaults,model:{...o,primary:t}}}}}function buildAnthropicAuthDoctorHint(e){const t=e.profileId??`anthropic:default`;const n=suggestOAuthProfileIdForLegacyDefault({cfg:e.config,store:e.store,provider:PROVIDER_ID,legacyProfileId:t});if(!n||n===t)return``;const r=listProfilesForProvider(e.store,PROVIDER_ID).filter(t=>e.store.profiles[t]?.type===`oauth`).join(`, `);const i=e.config?.auth?.profiles?.[t]?.mode;const a=e.config?.auth?.profiles?.[t]?.provider;return[`Doctor hint (for GitHub issue):`,`- provider: ${PROVIDER_ID}`,`- config: ${t}${a||i?` (provider=${a??`?`}, mode=${i??`?`})`:``}`,`- auth store oauth profiles: ${r||`(none)`}`,`- suggested profile: ${n}`,`Fix: run "${formatCliCommand(`openclaw doctor --yes`)}"`].join(` `)}async function runAnthropicCliMigration(e){const t=await probeClaudeCliAuthStatus({env:e.env??process.env});if(t.status!==`available`){const e=t.status===`missing`?[`Claude CLI is not authenticated on this host.`,`Run ${formatCliCommand(`claude auth login`)} first, then re-run this setup.`]:t.status===`not-installed`?["Claude CLI (`claude`) was not found on PATH.",`Install Claude Code or add it to PATH, run ${formatCliCommand(`claude auth login`)}, then re-run this setup.`]:[t.status===`timeout`?`Could not verify the installed Claude CLI login within ${t.timeoutMs/1e3} s.`:`Could not verify the installed Claude CLI login.`,`Run ${formatCliCommand(`claude auth status --json`)}, then retry this setup.`];throw new Error(e.join(` `))}return buildAnthropicCliMigrationResult(e.config)}async function runAnthropicCliMigrationNonInteractive(e){const t=await runAnthropicCliMigration(e);return applyProviderDefaultModel(applyProviderAuthConfigPatch(e.config,t.configPatch,t),t.defaultModel)}export{buildAnthropicAuthDoctorHint,runAnthropicApiKeyAuth,runAnthropicCliMigration,runAnthropicCliMigrationNonInteractive,runAnthropicSetupTokenAuth,runAnthropicSetupTokenNonInteractive,validateAnthropicSetupTokenNonInteractive};