UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

352 lines (351 loc) • 14.6 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./utils-C8YECn2Q.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { a as resolveAgentDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as readConfigMachineState } from "./config-machine-state-DzLVE1Wy.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { r as updateConfigMachineState } from "./config-machine-state-write-DanSUxEP.mjs"; import { H as resolveNativeSharedAuthStorePath, b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs"; import { o as prepareSharedAuthStoreOwnership } from "./path-resolve-CpNl_n1M.mjs"; import { et as shouldUseMainOwnerForLocalOAuthCredential } from "./runtime-snapshots-1lyYKb7Y.mjs"; import { n as formatInlineCodeSpan } from "./markdown-code-C5it6V4Q.mjs"; import { a as buildAuthProfileUnusableHint, o as buildOAuthRefreshFailureLoginCommand, s as classifyOAuthRefreshFailure } from "./oauth-refresh-failure-DxrQiYzV.mjs"; import { i as findPersistedAuthProfileCredential } from "./store-Bh2lUvOT.mjs"; import { a as withAuthProfileReaderCleanup, i as hasLocalAuthProfileStoreSource, t as hasAnyAuthProfileStoreSource } from "./source-check-1bfdqQg5.mjs"; import { n as prepareAgentAuthProfileRowsRead } from "./sqlite-read-CREbuXqx.mjs"; import { d as loadAuthProfileStoreForRuntime, r as ensureAuthProfileStore } from "./store-runtime-dW0pXLJI.mjs"; import { r as resolveAuthStorePathForDisplay } from "./paths-BSElhsGi.mjs"; import { n as buildAuthHealthSummary, r as formatRemainingShort, t as DEFAULT_OAUTH_WARN_MS } from "./auth-health-sVoXFBMP.mjs"; import { n as resolveApiKeyForProfile, r as formatAuthDoctorHint } from "./oauth--EeX6RHc.mjs"; import { t as buildProviderAuthRecoveryHint } from "./provider-auth-recovery-hint-SMK7UCzs.mjs"; import "./auth-profiles-VRLhewIH.mjs"; import { t as listUnavailableAuthProfiles } from "./auth-unavailability-CTJJVKWL.mjs"; //#region 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 }; /** Explain the retired ambient-token activation once per state directory. */ 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") || readConfigMachineState(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 = loadAuthProfileStoreForRuntime(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 []; } /** Surface the one-time relocation while the legacy shared owner is still active. */ async function collectSharedAuthStoreFindings(e = process.env) { if ((await prepareSharedAuthStoreOwnership(e)).location !== "legacy-main") return []; const t = resolveNativeSharedAuthStorePath(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"); } function hasStoredCodexOAuthProfile() { const e = ensureAuthProfileStore(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("\n"); } function collectLegacyCodexProviderOverrideFindings(e) { const t = e.models?.providers?.[LEGACY_CODEX_PROVIDER_ID]; if (!t) return []; if (!hasLegacyCodexTransportOverride(t)) return []; if (!hasConfiguredCodexOAuthProfile(e) && !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" }]; } function listAuthProfileHealthTargets(e) { const t = /* @__PURE__ */ new Map(); if (hasAnyAuthProfileStoreSource() || Object.keys(e.auth?.profiles ?? {}).length > 0) t.set(resolveNativeSharedAuthStorePath(), { label: "Shared" }); for (const n of listAgentIds(e)) { const r = resolveAgentDir(e, n); const i = resolveAuthProfileDatabasePath(r); if (!t.has(i) && hasLocalAuthProfileStoreSource(r)) t.set(i, { label: `Agent ${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 "); } function collectAuthProfileCooldowns(e) { return listUnavailableAuthProfiles(e).map(({ 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 ?? findPersistedAuthProfileCredential({ 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"); } function loadAuthProfileHealth(e) { const t = loadAuthProfileStoreForRuntime(e.target.agentDir, { inheritedAuthDir: e.target.agentDir, allowKeychainPrompt: e.allowKeychainPrompt, readOnly: e.readOnly }); const n = e.target.agentDir ? Object.fromEntries(Object.entries(t.profiles).filter(([e, t]) => t.type !== "oauth" || !shouldUseMainOwnerForLocalOAuthCredential({ profileId: e, local: t, main: findPersistedAuthProfileCredential({ profileId: e }) }))) : t.profiles; 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); for (const i of 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; } /** Collects read-only structured findings for auth profile health. */ async function collectAuthProfileHealthFindings(e) { const t = listAuthProfileHealthTargets(e.cfg); const n = []; for (const r of t) { const i = 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, ...collectLegacyCodexProviderOverrideFindings(e.cfg)]; } /** Aggregate normal Doctor output; lint retains each store's location and finding. */ async function inspectAuthProfileHealth(e) { const t = 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 } = 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} = 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; } //#endregion export { collectAuthProfileHealthFindings, collectCopilotAmbientTokenFindings, collectLegacyCodexProviderOverrideFindings, collectSharedAuthStoreFindings, inspectAuthProfileHealth };