openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
421 lines (420 loc) • 19.1 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as appendConfigPathSegment } from "./dot-path-BJ4tyWKJ.mjs";
import { g as parseSecretRef } from "./types.secrets-BmNLLnHp.mjs";
import { n as getShellEnvAppliedKeys } from "./shell-env-Dbjy7T84.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { d as hasUnresolvedConfigPath, p as resolveConfigSecretRef, u as getResolvedConfigEnvSecretRef } from "./resolution-facts-xaIKuREs.mjs";
import { n as normalizeSecretInput, t as normalizeOptionalSecretInput } from "./normalize-secret-input-Cxkx67Fv.mjs";
import { E as readInlineProviderApiKeyUsage } from "./user-model-account-authority-CRj924IP.mjs";
import { a as getRuntimeConfigSnapshot, c as getRuntimeConfigSourceSnapshot, j as hashRuntimeConfigValue } from "./runtime-snapshot-WbwbY5b7.mjs";
import { a as resolveMergedModelProviderConfig, o as resolveMergedModelProviderEntry } from "./model-provider-config-Bbah_2ON.mjs";
import { c as mintSecretSentinel } from "./sentinel-BfPjneyJ.mjs";
import { n as SecretSurfaceUnavailableError } from "./runtime-degraded-state-BSnwk5PQ.mjs";
import { n as isStoredCredentialCompatibleWithAuthProvider, t as isConfiguredAwsSdkAuthProfileForProvider } from "./order-jOvee2J6.mjs";
import { t as NON_ENV_SECRETREF_MARKER } from "./provider-credential-values-pLjdcwQh.mjs";
import { a as SECRETREF_ENV_HEADER_MARKER_PREFIX, c as isKnownEnvApiKeyMarker, l as isNonSecretApiKeyMarker, n as CUSTOM_LOCAL_AUTH_MARKER } from "./model-auth-markers-4YSUG71a.mjs";
import { t as canResolveEnvSecretRefInReadOnlyPath } from "./secret-ref-readonly.internal-CHEvk9t0.mjs";
import { t as resolveEnvApiKey } from "./model-auth-env-kbpGo8fU.mjs";
import { t as isLocalProviderBaseUrl } from "./model-provider-local-KHvcGobn.mjs";
import { isDeepStrictEqual } from "node:util";
//#region src/agents/model-auth-runtime-shared.ts
/**
* Shared provider-auth runtime types and errors. Provider calls use these
* helpers to fail with actionable auth provenance while keeping secret
* normalization local.
*/
const AWS_BEARER_ENV = "AWS_BEARER_TOKEN_BEDROCK";
const AWS_ACCESS_KEY_ENV = "AWS_ACCESS_KEY_ID";
const AWS_SECRET_KEY_ENV = "AWS_SECRET_ACCESS_KEY";
const AWS_PROFILE_ENV = "AWS_PROFILE";
function resolveDirectProviderCredentialMode(e) {
const t = resolveMergedModelProviderEntry(e.cfg, e.provider)?.providerConfig.auth;
return t === "oauth" || t === "token" ? t : e.inferredMode;
}
const authErrorInstances = resolveGlobalSingleton(Symbol.for("openclaw.providerAuthErrorInstances"), () => ({
provider: /* @__PURE__ */ new WeakSet(),
missing: /* @__PURE__ */ new WeakSet()
}));
var ProviderAuthError = class extends Error {
constructor(e, t, n, r) {
super(n);
this.name = "ProviderAuthError";
this.code = e;
this.provider = t;
this.providerGuidance = r?.providerGuidance === true;
authErrorInstances.provider.add(this);
}
};
/** Native login is availability evidence, never an HTTP credential. */
function assertProviderAuthSupportsHttp(e, t) {
if (e.nativeAuth) throw new ProviderAuthError("missing-provider-auth", t, `Native authentication for provider "${t}" belongs to the "${e.nativeAuth.runtime}" runtime and cannot authorize an HTTP request. Select that runtime or configure an API key.`);
}
var MissingProviderAuthError = class extends ProviderAuthError {
constructor(e, t) {
super("missing-api-key", e, formatMissingAuthError(t, e));
this.name = "MissingProviderAuthError";
this.mode = t.mode;
this.source = t.source;
authErrorInstances.missing.add(this);
}
};
function isProviderAuthError(e, t) {
return isProviderAuthErrorInstance(e) && (!t || e.code === t);
}
function isProviderAuthErrorInstance(e) {
return typeof e === "object" && e !== null && authErrorInstances.provider.has(e);
}
function isMissingProviderAuthError(e) {
return typeof e === "object" && e !== null && authErrorInstances.missing.has(e);
}
function resolveAwsSdkEnvVarName(e = process.env) {
if (e[AWS_BEARER_ENV]?.trim()) return AWS_BEARER_ENV;
if (e[AWS_ACCESS_KEY_ENV]?.trim() && e[AWS_SECRET_KEY_ENV]?.trim()) return AWS_ACCESS_KEY_ENV;
if (e[AWS_PROFILE_ENV]?.trim()) return AWS_PROFILE_ENV;
}
function formatMissingAuthError(e, t) {
return `No API key resolved for provider "${t}" (auth mode: ${e.mode}, checked: ${e.source}).`;
}
function requireApiKey(e, t) {
assertProviderAuthSupportsHttp(e, t);
const n = normalizeSecretInput(e.apiKey);
if (n) return n;
throw new MissingProviderAuthError(t, e);
}
//#endregion
//#region src/agents/model-auth-provider-config.ts
/**
* Provider-entry configuration and stored-profile binding for model auth.
*/
const MODEL_AUTH_LOCAL_HOST_ALIASES = /* @__PURE__ */ new Set([
"docker.orb.internal",
"host.docker.internal",
"host.orb.internal"
]);
function projectResolvedProfileAuth(e) {
const t = e.store.profiles[e.profileId];
return {
apiKey: (t?.type === "api_key" ? parseSecretRef(t.keyRef) : t?.type === "token" ? parseSecretRef(t.tokenRef) : null) && e.enabled ? mintSecretSentinel(e.apiKey, { label: `model-auth:${e.provider}` }) : e.apiKey,
profileId: e.profileId,
source: `profile:${e.profileId}`,
mode: e.mode,
...e.authFlow ? { authFlow: e.authFlow } : {}
};
}
function resolveConfigAwareEnvApiKey(e, t, n, r) {
return resolveEnvApiKey(t, process.env, {
config: e,
workspaceDir: n,
...r ? { skipSetupProviderFallback: true } : {}
});
}
function resolveProviderSourceConfig(e, t) {
const n = getRuntimeConfigSourceSnapshot();
if (e === n) return e;
return providerConfigMatchesRuntimeSnapshot({
inputConfig: e,
runtimeConfig: getRuntimeConfigSnapshot(),
provider: t
}) ? n ?? e : e;
}
/** Keeps authored references distinct from opaque bytes in a matching runtime provider. */
function resolveProviderConfigSecretInput(e, t, n = resolveProviderSourceConfig(e, t)) {
const r = resolveMergedModelProviderEntry(n, t);
const i = r ? `${appendConfigPathSegment("models.providers", r.providerKey)}.apiKey` : "";
const a = r ? getResolvedConfigEnvSecretRef(n, i) : null;
return {
path: i,
providerConfig: resolveMergedModelProviderConfig(e, t),
resolvedEnvRef: a,
ref: r ? a ?? resolveConfigSecretRef({
config: n,
path: i,
value: r.providerConfig.apiKey,
defaults: n?.secrets?.defaults
}) : null
};
}
/** Reads a literal or env-secret marker for a custom provider entry. */
function getCustomProviderApiKey(e, t) {
const { providerConfig: n, ref: r } = resolveProviderConfigSecretInput(e, t);
if (!r) return normalizeOptionalSecretInput(n?.apiKey);
return r.source === "env" && r.id.trim() || "secretref-managed";
}
/** Resolves custom provider API keys that are usable without mutating secret stores. */
function resolveUsableCustomProviderApiKey(e) {
const t = resolveProviderConfigSecretInput(e.cfg, e.provider);
const { providerConfig: n, ref: r } = t;
if (r) {
const i = r.source === "env" ? r.id.trim() : "";
if (!i) return null;
if (!(t.resolvedEnvRef || canResolveEnvSecretRefInReadOnlyPath({
cfg: e.cfg,
provider: r.provider,
id: i
}))) return null;
const a = normalizeOptionalSecretInput(t.resolvedEnvRef ? n?.apiKey : (e.env ?? process.env)[i]);
if (!a) return null;
const o = t.resolvedEnvRef ? "models.json" : resolveEnvSourceLabel([i], `${i} (models.json secretref)`);
return {
apiKey: e.secretSentinels ? mintSecretSentinel(a, { label: `model-auth:${e.provider}` }) : a,
source: o
};
}
const i = normalizeOptionalSecretInput(n?.apiKey);
if (!i) return null;
if (!isNonSecretApiKeyMarker(i)) return {
apiKey: i,
source: "models.json"
};
if (isKnownEnvApiKeyMarker(i)) {
const t = normalizeOptionalSecretInput((e.env ?? process.env)[i]);
if (!t) return null;
return {
apiKey: t,
source: resolveEnvSourceLabel([i], `${i} (models.json marker)`)
};
}
if (n && (n.api === "openai-completions" || n.api === "ollama") && n.baseUrl && isLocalAuthProviderBaseUrl(n.baseUrl)) return {
apiKey: n.api === "ollama" ? i : CUSTOM_LOCAL_AUTH_MARKER,
source: "models.json (local marker)"
};
return null;
}
/** True when a custom provider has a literal/env/local key available now. */
const hasUsableCustomProviderApiKey = (e, t, n) => Boolean(resolveUsableCustomProviderApiKey({
cfg: e,
provider: t,
env: n
}));
/** True when explicit provider config should outrank profile/environment auth. */
function shouldPreferExplicitConfigApiKeyAuth(e, t) {
const n = resolveMergedModelProviderConfig(e, t);
return resolveProviderAuthOverride(e, t) === "api-key" && n !== void 0 && hasExplicitProviderApiKeyConfig(n);
}
/** True when configured or prepared route facts prove a no-auth provider. */
function hasSyntheticLocalProviderAuthConfig(e) {
const t = resolveMergedModelProviderConfig(e.cfg, e.provider);
const n = resolveProviderAuthOverride(e.cfg, e.provider);
const r = e.route ?? {
api: e.modelApi ?? t?.api,
baseUrl: t?.baseUrl
};
if (n === "none") return r.api === "openai-completions" && typeof r.baseUrl === "string";
if (n && n !== "api-key") return false;
if (!e.route && (!t || !isCustomLocalProviderConfig(t)) || t !== void 0 && hasExplicitProviderApiKeyConfig(t)) return false;
return typeof r.api === "string" && r.api.trim().length > 0 && typeof r.baseUrl === "string" && isLocalAuthProviderBaseUrl(r.baseUrl);
}
function resolveProviderAuthOverride(e, t) {
const n = resolveMergedModelProviderConfig(e, t)?.auth;
if (n === "api-key" || n === "aws-sdk" || n === "oauth" || n === "token" || n === "none") return n;
}
function shouldUseImplicitAwsSdkAuth(e) {
if (e.modelApi !== "bedrock-converse-stream") return false;
if (normalizeProviderId(e.provider) !== "amazon-bedrock") return false;
const t = resolveMergedModelProviderConfig(e.cfg, e.provider);
return resolveProviderAuthOverride(e.cfg, e.provider) === void 0 && (t === void 0 || !hasExplicitProviderApiKeyConfig(t));
}
function profileTypeToAuthMode(e) {
return e === "oauth" ? "oauth" : e === "token" ? "token" : "api-key";
}
function normalizeProviderEntryBaseUrlForBinding(e) {
const t = e?.trim();
if (!t) return;
const n = URL.parse(t);
if (!n) return t.toLowerCase().replace(/\/+$/, "");
n.hash = "";
n.search = "";
n.pathname = n.pathname.replace(/\/+$/, "");
return n.toString().replace(/\/+$/, "");
}
function providerEntriesShareBaseUrl(e) {
const t = normalizeProviderEntryBaseUrlForBinding(resolveMergedModelProviderConfig(e.cfg, e.provider)?.baseUrl);
const n = normalizeProviderEntryBaseUrlForBinding(resolveMergedModelProviderConfig(e.cfg, e.credentialProvider)?.baseUrl);
return Boolean(t && n && t === n);
}
function isBearerProfileCredential(e) {
return e.type === "api_key" || e.type === "token";
}
/** True when a bearer auth profile can safely satisfy a provider-entry apiKey reference. */
function canUseProfileAsProviderEntryApiKey(e) {
if (!isBearerProfileCredential(e.credential)) return false;
if (isStoredCredentialCompatibleWithAuthProvider(e)) return true;
return providerEntriesShareBaseUrl({
cfg: e.cfg,
provider: e.provider,
credentialProvider: e.credential.provider
});
}
/** Classifies a provider entry apiKey as literal/profile/marker before resolving secrets. */
function resolveProviderEntryApiKeyProfileReference(e) {
const { providerConfig: t, ref: n } = resolveProviderConfigSecretInput(e.cfg, e.provider, e.sourceConfig);
if (n) return { kind: "none" };
const r = normalizeOptionalSecretInput(t?.apiKey);
if (!r) return { kind: "none" };
if (isNonSecretApiKeyMarker(r)) return {
kind: "marker",
evidence: isKnownEnvApiKeyMarker(r) ? "environment" : "synthetic"
};
const i = e.store.profiles[r];
if (!i) return {
kind: "literal",
apiKey: r,
source: "models.json"
};
const a = !isBearerProfileCredential(i) ? "credential-class" : !canUseProfileAsProviderEntryApiKey({
cfg: e.cfg,
authAliasLookupParams: e.authAliasLookupParams,
provider: e.provider,
credential: i
}) ? "provider-binding" : void 0;
if (a) return {
kind: "profile-incompatible",
profileId: r,
credentialProvider: i.provider,
credentialType: i.type,
reason: a
};
return {
kind: "profile",
profileId: r,
credential: i,
mode: profileTypeToAuthMode(i.type)
};
}
/** Resolves a provider-entry apiKey profile reference into runtime auth when possible. */
async function resolveProviderEntryApiKeyBinding(e) {
e.signal?.throwIfAborted();
const t = resolveProviderEntryApiKeyProfileReference(e);
if (t.kind === "none" || t.kind === "marker") return { kind: "none" };
if (t.kind === "literal" || t.kind === "profile-incompatible") return t;
try {
const { resolveApiKeyForProfile: n } = await import("./oauth-I5nvh-hv.mjs");
const r = await n({
cfg: e.cfg,
store: e.store,
profileId: t.profileId,
agentDir: e.agentDir,
signal: e.signal
});
e.signal?.throwIfAborted();
if (!r) return {
kind: "profile-unresolved",
profileId: t.profileId
};
const i = r.profileId ?? t.profileId;
const a = r.credential ?? t.credential;
return {
kind: "profile-resolved",
auth: projectResolvedProfileAuth({
apiKey: r.apiKey,
enabled: e.secretSentinels,
profileId: i,
provider: e.provider,
store: e.store,
mode: r.profileType ? profileTypeToAuthMode(r.profileType) : t.mode,
authFlow: a.type === "oauth" ? a.authFlow : void 0
})
};
} catch (n) {
e.signal?.throwIfAborted();
if (n instanceof SecretSurfaceUnavailableError) throw n;
return {
kind: "profile-unresolved",
profileId: t.profileId,
error: n
};
}
}
function resolveConfiguredAwsSdkProfileAuth(e) {
if (!isConfiguredAwsSdkAuthProfileForProvider(e)) return null;
return {
...resolveAwsSdkAuthInfo(),
profileId: e.profileId,
source: `profile:${e.profileId}`
};
}
function isLocalAuthProviderBaseUrl(e) {
return isLocalProviderBaseUrl(e, MODEL_AUTH_LOCAL_HOST_ALIASES);
}
function hasExplicitProviderApiKeyConfig(e) {
return normalizeOptionalSecretInput(e.apiKey) !== void 0 || parseSecretRef(e.apiKey) !== null;
}
function isInlineProviderApiKeySource(e) {
return e === "models.json" || e.endsWith(" (models.json secretref)") || e.endsWith(" (models.json marker)");
}
/** True when a resolved credential came from an inline `models.providers.<id>.apiKey`. */
function isConfigBackedInlineProviderApiKey(e) {
if (isInlineProviderApiKeySource(e.source)) return true;
const { providerConfig: t, ref: n } = resolveProviderConfigSecretInput(e.cfg, e.provider);
if (!t || !hasExplicitProviderApiKeyConfig(t)) return false;
if (n) return true;
const r = normalizeOptionalSecretInput(t.apiKey);
return Boolean(r && !e.store?.profiles[r]);
}
function resolveInlineProviderApiKeyCooldownUntil(e, t) {
return readInlineProviderApiKeyUsage(e, t).unusableUntil;
}
/** Fails closed while an inline provider API key is inside its billing/auth cooldown. */
function assertInlineProviderApiKeyUsable(e) {
const t = resolveInlineProviderApiKeyCooldownUntil(e.store, e.provider);
if (typeof t !== "number" || t <= Date.now()) return;
const n = Math.max(0, t - Date.now());
const r = Math.max(1, Math.ceil(n / 6e4));
throw new Error(`Inline API key for provider "${e.provider}" is temporarily disabled after a provider auth/billing failure. Retry after about ${r} minute${r === 1 ? "" : "s"}, or switch to a different auth profile/API key.`);
}
function isCustomLocalProviderConfig(e) {
return Boolean(e.baseUrl?.trim() && e.api?.trim() && e.models?.length);
}
function isManagedSecretRefApiKeyMarker(e) {
return e?.trim() === NON_ENV_SECRETREF_MARKER;
}
function hasSecretRefProviderApiKey(e, t) {
const { providerConfig: n, ref: r } = resolveProviderConfigSecretInput(e, t);
const i = n?.apiKey;
if (r) return true;
return typeof i === "string" && (isManagedSecretRefApiKeyMarker(i) || i.trim().startsWith("secretref-env:"));
}
function providerConfigMatchesRuntimeSnapshot(e) {
const t = resolveMergedModelProviderConfig(e.inputConfig, e.provider);
const n = resolveMergedModelProviderConfig(e.runtimeConfig ?? void 0, e.provider);
const toComparableConfig = (t) => ({ models: { providers: { [e.provider]: t } } });
return t && n ? e.inputConfig === e.runtimeConfig || t === n || isDeepStrictEqual(t, n) || hashRuntimeConfigValue(toComparableConfig(t)) === hashRuntimeConfigValue(toComparableConfig(n)) : false;
}
function sentinelizeConfigSecretRefEnvApiKey(e) {
if (!e.enabled) return e.apiKey;
const t = resolveProviderSourceConfig(e.cfg, e.provider);
const n = resolveMergedModelProviderConfig(t, e.provider)?.apiKey;
const r = parseSecretRef(n);
const i = r?.source === "env" ? r.id : typeof n === "string" && n.trim().startsWith("secretref-env:") ? n.trim().slice(SECRETREF_ENV_HEADER_MARKER_PREFIX.length) : void 0;
return i && e.source.includes(i) ? mintSecretSentinel(e.apiKey, { label: `model-auth:${e.provider}` }) : e.apiKey;
}
function resolveRuntimeProviderConfigApiKeyAuth(e) {
const t = resolveProviderConfigSecretInput(e.cfg, e.provider);
if (hasUnresolvedConfigPath(e.cfg, t.path)) return;
const { providerConfig: n, ref: r } = t;
const i = resolveProviderConfigSecretInput(e.sourceConfig, e.provider).ref;
const a = i ? n?.apiKey : r ? void 0 : normalizeOptionalSecretInput(n?.apiKey);
if (typeof a !== "string" || !a.trim() || !i && isNonSecretApiKeyMarker(a)) return;
return {
apiKey: a,
source: `models.providers.${e.provider}`,
mode: resolveDirectProviderCredentialMode({
cfg: e.cfg,
provider: e.provider,
inferredMode: "api-key"
})
};
}
function resolveEnvSourceLabel(e, t = e.join(" + ")) {
const n = new Set(getShellEnvAppliedKeys());
return `${e.some((e) => n.has(e)) ? "shell env: " : "env: "}${t}`;
}
function resolveAwsSdkAuthInfo() {
const e = resolveAwsSdkEnvVarName();
return {
mode: "aws-sdk",
source: e ? resolveEnvSourceLabel(e === "AWS_ACCESS_KEY_ID" ? [e, "AWS_SECRET_ACCESS_KEY"] : e ? [e] : []) : "aws-sdk default chain"
};
}
//#endregion
export { requireApiKey as A, shouldUseImplicitAwsSdkAuth as C, formatMissingAuthError as D, assertProviderAuthSupportsHttp as E, resolveDirectProviderCredentialMode as M, isMissingProviderAuthError as O, shouldPreferExplicitConfigApiKeyAuth as S, ProviderAuthError as T, resolveProviderEntryApiKeyBinding as _, hasUsableCustomProviderApiKey as a, resolveUsableCustomProviderApiKey as b, profileTypeToAuthMode as c, resolveAwsSdkAuthInfo as d, resolveConfigAwareEnvApiKey as f, resolveProviderConfigSecretInput as g, resolveProviderAuthOverride as h, hasSyntheticLocalProviderAuthConfig as i, resolveAwsSdkEnvVarName as j, isProviderAuthError as k, projectResolvedProfileAuth as l, resolveInlineProviderApiKeyCooldownUntil as m, getCustomProviderApiKey as n, isConfigBackedInlineProviderApiKey as o, resolveConfiguredAwsSdkProfileAuth as p, hasSecretRefProviderApiKey as r, isManagedSecretRefApiKeyMarker as s, assertInlineProviderApiKeyUsable as t, providerConfigMatchesRuntimeSnapshot as u, resolveProviderEntryApiKeyProfileReference as v, MissingProviderAuthError as w, sentinelizeConfigSecretRefEnvApiKey as x, resolveRuntimeProviderConfigApiKeyAuth as y };