UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

645 lines (644 loc) • 21.9 kB
import { g as normalizeUniqueStringEntries } from "./string-normalization-DLmfYZXI.mjs"; import { t as appendConfigPathSegment } from "./dot-path-BJ4tyWKJ.mjs"; import { _ as resolveSecretInputRef, o as hasConfiguredSecretInput, p as normalizeSecretInputString } from "./types.secrets-BmNLLnHp.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { a as captureAsyncWorkTracker, o as getAsyncWorkSignal, t as AsyncWorkScope } from "./async-work-scope-BXagjUap.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { _ as resolveDefaultAgentId, a as resolveAgentDir, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import { a as copyConfigResolutionFactsExcept, i as copyConfigResolutionFacts, p as resolveConfigSecretRef } from "./resolution-facts-xaIKuREs.mjs"; import { G as getScopedAuthProfileEnv } from "./user-model-account-authority-CRj924IP.mjs"; import { i as DEFAULT_PROVIDER } from "./defaults-BWyoTPqn.mjs"; import { o as resolveMergedModelProviderEntry } from "./model-provider-config-Bbah_2ON.mjs"; import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { n as parseModelRef, t as findNormalizedProviderValue } from "./model-selection-normalize-DIZCRGVF.mjs"; import { t as resolveSecretRefString } from "./resolve-BYfGhigB.mjs"; import { b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs"; import { n as clearRuntimeAuthProfileStoreSnapshotCore } from "./runtime-snapshots-1lyYKb7Y.mjs"; import "./model-selection-C2A4Wyix.mjs"; import { f as listProfilesForProvider, i as resolveAuthProfileEligibility, o as resolveAuthProfileOrderWithMetadata } from "./order-jOvee2J6.mjs"; import { l as isNonSecretApiKeyMarker } from "./model-auth-markers-4YSUG71a.mjs"; import "./store-Bh2lUvOT.mjs"; import { i as externalCliDiscoveryScoped } from "./external-cli-discovery-DZ419koV.mjs"; import { t as resolveEnvApiKey } from "./model-auth-env-kbpGo8fU.mjs"; import { _ as resolveProviderEntryApiKeyBinding, a as hasUsableCustomProviderApiKey, b as resolveUsableCustomProviderApiKey, i as hasSyntheticLocalProviderAuthConfig, v as resolveProviderEntryApiKeyProfileReference } from "./model-auth-provider-config-Bnc4upRS.mjs"; import { i as ensureAuthProfileStoreAsync } from "./store-runtime-dW0pXLJI.mjs"; import { n as resolveAuthProfileDisplayLabel } from "./display-DA_6g711.mjs"; import { d as readPreparedModelCatalog } from "./prepared-model-catalog-DSktrHGK.mjs"; import { i as describeFailoverError } from "./failover-error-CbIiC30n.mjs"; import { n as recordAgentCleanupFailure } from "./run-cleanup-timeout-Bk3vN1Oh.mjs"; import { u as upsertAuthProfileWithLock } from "./profiles-DbLHYG1P.mjs"; import "./auth-profiles-VRLhewIH.mjs"; import "./model-auth-CEsyk_Yg.mjs"; import { t as FAILOVER_PROBE_STATUS } from "./probe-status-BaXI8Vaw.mjs"; import { r as formatMs } from "./shared-jZuoMzdG.mjs"; import { t as prepareLocalCapabilityAccountSecrets } from "./local-account-secrets-BZXTYYop.mjs"; import { t as redactStatusSecrets } from "./status-redaction-D9OVqm2x.mjs"; import "./format-D7dYoPZi.mjs"; import { t as disposeOpenClawAgentDatabaseByPath } from "./openclaw-agent-db-disposal-BfKVpAZC.mjs"; import path from "node:path"; import crypto from "node:crypto"; import fs from "node:fs/promises"; import os from "node:os"; import { AsyncLocalStorage } from "node:async_hooks"; import pMap from "p-map"; //#region src/commands/models/list.probe.cleanup.ts const log = createSubsystemLogger("models/probe"); /** Keep private credential files until their database and registration have settled. */ async function disposeAuthProbeDirectory(e, t) { clearRuntimeAuthProfileStoreSnapshotCore(e); try { await disposeOpenClawAgentDatabaseByPath(resolveAuthProfileDatabasePath(e), { env: t }); } catch (t) { throw new Error(`Auth probe database cleanup failed; retained ${e}: ${formatErrorMessage(t)}`, { cause: t }); } await fs.rm(e, { recursive: true, force: true }); } /** Probe-owned files and locks follow actual work without extending run admission. */ async function createAuthProbeWork(e) { const t = captureAsyncWorkTracker(); const n = getAsyncWorkSignal(); const r = createDeferredCore(); const i = createDeferredCore(); t(() => { r.resolve(); return i.promise; }).catch(r.reject); await r.promise; const a = new AsyncWorkScope(); const o = a.run(() => AsyncLocalStorage.snapshot()); const s = /* @__PURE__ */ new Map(); for (const t of [e, n]) { if (!t || s.has(t)) continue; const abort = () => o(() => a.beginClose(t.reason)); s.set(t, abort); t.addEventListener("abort", abort, { once: true }); if (t.aborted) abort(); } return { run(e) { return a.track(e); }, async settle(e) { const finish = async () => { try { await AsyncWorkScope.runWhenAllIdle(() => [a], () => o(() => a.drain())); await e(); } catch (e) { recordAgentCleanupFailure(); i.reject(e); throw e; } finally { for (const [e, t] of s) e.removeEventListener("abort", t); i.resolve(); } }; if (!a.hasPendingWork) { await finish(); return; } finish().catch((e) => { log.warn(`Auth check cleanup failed: ${redactStatusSecrets(formatErrorMessage(e))}`); }); } }; } //#endregion //#region src/commands/models/list.probe.models.ts function buildProbeCandidateMap(e) { const t = /* @__PURE__ */ new Map(); for (const n of e) { const e = parseModelRef(n ?? "", DEFAULT_PROVIDER); if (e && !t.has(e.provider)) t.set(e.provider, e.model); } return t; } function probePriority(e, t) { const n = t.trim().toLowerCase(); if (e !== "anthropic") return 50; if (/^claude-haiku-4-5-\d{8}$/.test(n)) return 0; if (n === "claude-haiku-4-5") return 1; if (n === "claude-sonnet-5" || n.startsWith("claude-sonnet-5-")) return 2; if (n === "claude-sonnet-4-6" || n.startsWith("claude-sonnet-4-6-")) return 3; if (n.startsWith("claude-sonnet-4-")) return 4; if (n.startsWith("claude-3-")) return 100; return 50; } /** Selects a requested-provider candidate before falling back to its catalog rows. */ function selectProbeModel(e) { const { provider: t, candidates: n, catalog: r } = e; const i = n.get(t); if (i) return { provider: t, model: i }; const a = r.filter((e) => normalizeProviderId(e.provider) === t && e.status !== "deprecated" && e.status !== "disabled").toSorted((e, n) => probePriority(t, e.id) - probePriority(t, n.id))[0]; return a ? { provider: t, model: a.id } : null; } //#endregion //#region src/commands/models/list.probe.ts const PROBE_PROMPT = "Reply with OK. Do not use tools."; function buildProbeResult(e, t) { return { provider: e.provider, model: e.model ? `${e.model.provider}/${e.model.model}` : void 0, profileId: e.profileId, label: e.label, source: e.source, mode: e.mode, ...t }; } function buildNoModelProbeResult(e) { return buildProbeResult(e, { status: "no_model", reasonCode: "no_model", error: "No model available for check" }); } const ELIGIBILITY_PROBE_ERRORS = { expired: "token credentials are expired.", invalid_expires: "token expires must be a positive Unix ms timestamp.", missing_credential: "no inline credential or SecretRef is configured.", unresolved_ref: "configured SecretRef could not be resolved.", ineligible_profile: "profile is incompatible with provider config." }; function mapEligibilityReasonToProbeReasonCode(e) { switch (e) { case "missing_credential": case "expired": case "invalid_expires": case "unresolved_ref": return e; default: return "ineligible_profile"; } } function resolveProbeSecretRef(e, t) { const n = t.secrets?.defaults; if (e.type === "api_key") return resolveSecretInputRef({ value: e.key, refValue: e.keyRef, defaults: n }).ref; if (e.type === "token") return resolveSecretInputRef({ value: e.token, refValue: e.tokenRef, defaults: n }).ref; return null; } function createProbeConfig(e, t) { if (!t.useRuntimeAuth && !t.boundValue) return e; const n = t.useRuntimeAuth ? void 0 : t.boundValue; const r = n ? resolveMergedModelProviderEntry(e, t.provider) : void 0; const i = { ...e, ...r?.providerConfig ? { models: { ...e.models, providers: { ...e.models?.providers, [r.providerKey]: { ...r.providerConfig, apiKey: n, auth: t.mode === "oauth" || t.mode === "token" ? t.mode : "api-key" } } } } : {}, auth: { ...e.auth, order: { ...e.auth?.order, [t.provider]: [] } } }; if (r?.providerConfig) copyConfigResolutionFactsExcept(e, i, [`${appendConfigPathSegment("models.providers", r.providerKey)}.apiKey`]); else copyConfigResolutionFacts(e, i); return i; } async function buildProbeTargets(e) { const { cfg: t, agentDir: n, providers: r, modelCandidates: i, options: a, workspaceDir: o } = e; const s = { config: t, workspaceDir: o }; const c = await ensureAuthProfileStoreAsync(n, { externalCli: externalCliDiscoveryScoped({ config: t, allowKeychainPrompt: false, providerIds: r.map((e) => resolveProviderIdForAuth(e, s)), profileIds: a.profileIds }) }); const l = a.provider?.trim(); const u = l ? normalizeProviderId(l) : null; const d = new Set(normalizeUniqueStringEntries(a.profileIds)); const f = {}; const p = buildProbeCandidateMap(i); const m = r.filter((e) => !p.has(normalizeProviderId(e))); const h = m.length ? await readPreparedModelCatalog({ config: t, ...e.agentId ? { agentId: e.agentId } : {}, ...n ? { agentDir: n } : {}, ...o ? { workspaceDir: o } : {}, readOnly: true, providerDiscoveryProviderIds: m }) : []; const g = []; const _ = []; const appendTarget = (e) => { if (e.model) g.push(e); else _.push(buildNoModelProbeResult(e)); }; for (const e of r) { const r = normalizeProviderId(e); const i = resolveProviderIdForAuth(r, s); if (u && r !== u) continue; const l = selectProbeModel({ provider: r, candidates: p, catalog: h }); const m = resolveMergedModelProviderEntry(t, r); const v = m?.providerConfig; const y = Boolean(m && resolveConfigSecretRef({ config: t, path: `${appendConfigPathSegment("models.providers", m.providerKey)}.apiKey`, value: v?.apiKey, defaults: t.secrets?.defaults })); const b = a.includeDirectKeys === true && d.size === 0; const x = b && hasConfiguredSecretInput(v?.apiKey, t.secrets?.defaults); const S = [.../* @__PURE__ */ new Set([...listProfilesForProvider(c, i), ...i === r ? [] : listProfilesForProvider(c, r)])]; const C = x ? resolveProviderEntryApiKeyProfileReference({ cfg: t, provider: r, store: c }) : { kind: "none" }; const w = C.kind === "profile" && !S.includes(C.profileId) ? await resolveProviderEntryApiKeyBinding({ cfg: t, provider: r, store: c, agentDir: n }) : null; const T = m && x && C.kind !== "profile" && C.kind !== "profile-incompatible" ? C.kind === "marker" ? resolveUsableCustomProviderApiKey({ cfg: t, provider: r, env: process.env })?.apiKey ?? null : await (async () => { const e = v?.apiKey; const n = `${appendConfigPathSegment("models.providers", m.providerKey)}.apiKey`; const r = resolveConfigSecretRef({ config: t, path: n, value: e, defaults: t.secrets?.defaults }); if (!r) return normalizeSecretInputString(e) ?? null; try { return await resolveSecretRefString(r, { config: t, env: process.env, cache: f }); } catch { return null; } })() : null; const E = v?.auth === "oauth" || v?.auth === "token" ? v.auth : "api_key"; const D = b && !y ? resolveEnvApiKey(i, process.env, { config: t, workspaceDir: o }) : null; const O = D?.apiKey === T ? null : D; const k = C.kind === "marker" && T && isNonSecretApiKeyMarker(T, { includeEnvVarName: false }) ? "provider" : "config"; const A = findNormalizedProviderValue(c.order, i) ?? findNormalizedProviderValue(c.order, r) ?? findNormalizedProviderValue(t?.auth?.order, i) ?? findNormalizedProviderValue(t?.auth?.order, r); const j = resolveAuthProfileOrderWithMetadata({ cfg: t, store: c, provider: r, forModel: l?.model }); const M = j.hasExplicitOrder ? new Set(j.profileIds) : null; const N = d.size ? S.filter((e) => d.has(e)) : S; for (const e of N) { const n = c.profiles[e]; const i = n?.type; const a = { provider: r, model: l, profileId: e, label: resolveAuthProfileDisplayLabel({ cfg: t, store: c, profileId: e }), source: "profile", mode: i }; const o = x && C.kind === "profile" && e === C.profileId; let s; if (!o && A && !A.includes(e)) s = { reasonCode: "excluded_by_auth_order", error: "Excluded by auth.order for this provider." }; else if (!o && M && !M.has(e)) { const n = mapEligibilityReasonToProbeReasonCode(resolveAuthProfileEligibility({ cfg: t, store: c, provider: r, profileId: e }).reasonCode); s = { reasonCode: n, error: `Auth profile credentials are missing or expired.\n↳ Auth reason [${n}]: ${ELIGIBILITY_PROBE_ERRORS[n]}` }; } else s = await (async () => { if (!n) return null; const e = resolveProbeSecretRef(n, t); if (!e) return null; try { await resolveSecretRefString(e, { config: t, env: process.env, cache: f }); return null; } catch { return { reasonCode: "unresolved_ref", error: `Auth profile credentials are missing or expired.\n↳ Auth reason [unresolved_ref]: could not resolve SecretRef "${`${e.source}:${e.provider}:${e.id}`}".` }; } })(); if (s) _.push(buildProbeResult(a, { status: "unknown", ...s })); else appendTarget(a); } if (N.length === 0 && d.size > 0) continue; if (x) { const e = { provider: r, model: l, ...C.kind === "profile" || C.kind === "profile-incompatible" ? { profileId: C.profileId } : {}, label: "config", source: "models.json", mode: E }; const unresolvedResult = (t) => ({ ...e, model: l ? `${l.provider}/${l.model}` : void 0, status: l ? "unknown" : "no_model", reasonCode: l ? "unresolved_ref" : "no_model", error: l ? t : "No model available for check" }); if (C.kind === "profile-incompatible") _.push({ ...e, model: l ? `${l.provider}/${l.model}` : void 0, status: "unknown", reasonCode: "ineligible_profile", error: "Configured API key references an incompatible auth profile." }); else if (C.kind === "profile") { if (!S.includes(C.profileId)) { if (w?.kind === "profile-resolved" && l) g.push({ ...e, profileId: w.auth.profileId, mode: w.auth.mode, boundValue: w.auth.apiKey }); else _.push(unresolvedResult("Configured auth profile could not be resolved.")); } } else if (!T) _.push(unresolvedResult("Configured API key could not be resolved.")); else appendTarget({ ...e, label: k, boundValue: T, ...C.kind === "marker" ? { useRuntimeAuth: true } : {} }); } if (O) { const e = v?.auth === "oauth" || v?.auth === "token" ? v.auth : O.source.includes("OAUTH_TOKEN") ? "oauth" : "api_key"; appendTarget({ provider: r, model: l, label: O.source, source: "env", mode: e, boundValue: O.apiKey }); } if (N.length > 0 || x || O) continue; const P = hasUsableCustomProviderApiKey(t, r); const F = hasSyntheticLocalProviderAuthConfig({ cfg: t, provider: r }); if (j.hasExplicitOrder && !P && !F) continue; const I = j.hasExplicitOrder || y ? null : resolveEnvApiKey(i, process.env, { config: t, workspaceDir: o }); if (!I && !P && !F) continue; const L = I ? "env" : "models.json"; appendTarget({ provider: r, model: l, label: L, source: L, mode: I?.source.includes("OAUTH_TOKEN") ? "oauth" : "api_key", ...F && !I && !P ? { useRuntimeAuth: true } : {} }); } return { targets: g, results: _ }; } function formatActiveGatewayModelsProbeRefusal(e) { return `A Gateway is running for this state directory (pid ${e.pid}, port ${e.port}). Stop the Gateway first (${formatCliCommand("openclaw gateway stop")}), then rerun models status --probe.`; } /** Own canonical state only for direct CLI probes; Gateway RPC probes already run under its lock. */ async function withAuthProbeStateOwnership(e, t) { if (!e) return await t(); const { acquireEmbeddedStateLock: n, createEmbeddedStateSignalBridge: r } = await import("./embedded-state-lock-DCwfjPhD.mjs"); const i = r(); let a; let o; try { o = await createAuthProbeWork(i.signal); a = await n({ signal: i.signal, formatActiveGatewayRefusal: formatActiveGatewayModelsProbeRefusal }); return await o.run(() => t(i.signal)); } finally { const release = async () => { try { await a?.release(); } finally { i.dispose(); } }; if (o) await o.settle(release); else await release(); } } async function runAuthProbes(e) { return await withAuthProbeStateOwnership(e.stateOwnership, async (t) => { const n = Date.now(); const r = await buildProbeTargets(e); const i = r.targets.length; e.onProgress?.({ completed: 0, total: i }); let a = []; if (i) { const n = e.cfg; const i = e.agentId; const o = e.agentDir; const s = e.workspaceDir; const c = e.options; const l = e.onProgress; const u = r.targets; const { timeoutMs: d, maxTokens: f } = c; const p = Math.max(1, Math.min(u.length || 1, c.concurrency)); const m = i ?? resolveDefaultAgentId(n); const h = o ?? resolveAgentDir(n, m); const g = s ?? resolveAgentWorkspaceDir(n, m); if (e.stateOwnership) await prepareLocalCapabilityAccountSecrets({ cfg: n, agentId: m }); await fs.mkdir(g, { recursive: true }); let _ = 0; a = await pMap(u, async (e) => { l?.({ completed: _, total: u.length, label: `Checking ${e.provider}${e.profileId ? ` (${e.label})` : ""}` }); const r = await (async () => { const r = t; const i = createProbeConfig(n, e); if (!e.model) return buildNoModelProbeResult(e); const a = e.model; let o = null; let s; let c; let l; const u = await createAuthProbeWork(r); const buildResult = (t, n) => buildProbeResult(e, { status: t, ...n ? { error: n } : {}, ...l !== void 0 ? { latencyMs: l } : {} }); try { if (e.boundValue || e.useRuntimeAuth) { o = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-auth-probe-"))); s = cloneEnvWithPlatformSemantics(getScopedAuthProfileEnv() ?? process.env); } if (e.boundValue && !e.useRuntimeAuth && o) { c = `${e.provider}:probe-${crypto.randomUUID()}`; const t = e.boundValue; const n = e.mode === "oauth" ? { type: "oauth", provider: e.provider, access: t, refresh: "not-a-real", expires: Date.now() + 36e5 } : e.mode === "token" ? { type: "token", provider: e.provider, token: t } : { type: "api_key", provider: e.provider, key: t }; if (!await upsertAuthProfileWithLock({ profileId: c, credential: n, agentDir: o })) throw new Error("Could not prepare isolated auth check profile"); } const { runIsolatedCompletion: t } = await import("./isolated-completion-BtD2xGM9.mjs"); if (!(await u.run(() => t({ config: i, agentId: m, agentDir: o ?? h, workspaceDir: g, provider: a.provider, model: a.model, authProfileId: c ?? e.profileId, ...o ? { preparedModelRuntimeMode: "isolated-read-only" } : {}, agentHarnessRuntimeOverride: "openclaw", systemPrompt: "", prompt: PROBE_PROMPT, timeoutMs: d, abortSignal: r, thinkLevel: "off", streamParams: { maxTokens: f }, outputTextPolicy: "strict-visible", onRequestComplete: (e) => { l = Math.round(e); } }))).text.trim()) return buildResult("format", "The provider returned no visible text."); return buildResult("ok"); } catch (e) { const t = describeFailoverError(e); return buildResult(t.reason ? FAILOVER_PROBE_STATUS[t.reason] ?? "unknown" : "unknown", redactStatusSecrets(t.message)); } finally { await u.settle(async () => { if (o) await disposeAuthProbeDirectory(o, s); }); } })(); _ += 1; l?.({ completed: _, total: u.length }); return r; }, { concurrency: p, stopOnError: true, ...t ? { signal: t } : {} }); } const o = Date.now(); return { startedAt: n, finishedAt: o, durationMs: o - n, totalTargets: i, options: e.options, results: [...r.results, ...a] }; }); } function sortProbeResults(e) { return e.toSorted((e, t) => { const n = e.provider.localeCompare(t.provider); if (n !== 0) return n; const r = e.label || e.profileId || ""; const i = t.label || t.profileId || ""; return r.localeCompare(i); }); } function describeProbeSummary(e) { if (e.totalTargets === 0) return "No check targets."; return `Checked ${e.totalTargets} target${e.totalTargets === 1 ? "" : "s"} in ${formatMs(e.durationMs)}`; } //#endregion export { withAuthProbeStateOwnership as a, sortProbeResults as i, describeProbeSummary as n, runAuthProbes as r, buildProbeTargets as t };