UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

174 lines (173 loc) • 8.36 kB
import { A as resolveExpiresAtMsFromDurationMs } from "../../number-coercion-D6u-4YD8.mjs"; import { t as formatCliCommand } from "../../command-format-CqdwUgPk.mjs"; import { t as parseDurationMs } from "../../parse-duration-D6UJm52I.mjs"; import { f as listProfilesForProvider } from "../../order-jOvee2J6.mjs"; import { n as suggestOAuthProfileIdForLegacyDefault } from "../../repair-O0s3O0SG.mjs"; import "../../number-runtime-W4chuk8B.mjs"; import { t as applyAuthProfileConfig } from "../../provider-auth-helpers-ByDXB7Po.mjs"; import { t as applyProviderDefaultModel } from "../../provider-setup-C508VQAW.mjs"; import "../../cli-runtime-DeVPX2l7.mjs"; import { t as applyProviderAuthConfigPatch } from "../../provider-auth-D_oAZ3fr.mjs"; import { i as upsertAuthProfileWithLockOrThrowCompat } from "../../provider-auth-write-compat-a9sIepqY.mjs"; import { n as validateAnthropicSetupToken, t as buildTokenProfileId } from "../../provider-auth-token-CEoV5Js5.mjs"; import "../../provider-auth-api-key-D-0BDe0y.mjs"; import { t as probeClaudeCliAuthStatus } from "../../cli-auth-seam-Dxnd0-CS.mjs"; import { t as buildAnthropicCliMigrationResult } from "../../cli-migration-DR4oUq4N.mjs"; //#region extensions/anthropic/auth.runtime.ts /** Auth execution stays deferred until a setup or doctor hook is invoked. */ const PROVIDER_ID = "anthropic"; /** Collect provider account scope separately from the agent's filesystem workspace. */ 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("\n")); 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("\n"); } 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("\n")); } return buildAnthropicCliMigrationResult(e.config); } async function runAnthropicCliMigrationNonInteractive(e) { const t = await runAnthropicCliMigration(e); return applyProviderDefaultModel(applyProviderAuthConfigPatch(e.config, t.configPatch, t), t.defaultModel); } //#endregion export { buildAnthropicAuthDoctorHint, runAnthropicApiKeyAuth, runAnthropicCliMigration, runAnthropicCliMigrationNonInteractive, runAnthropicSetupTokenAuth, runAnthropicSetupTokenNonInteractive, validateAnthropicSetupTokenNonInteractive };