openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
570 lines (569 loc) • 22 kB
JavaScript
import { o as asDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { g as normalizeUniqueStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { o as hasConfiguredSecretInput } from "./types.secrets-BmNLLnHp.mjs";
import { r as normalizeProviderId, t as findNormalizedProviderKey } from "./provider-id-b5XGSf9C.mjs";
import { O as tryResolveAmbientOwnerAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { Hc as validateModelsAuthSetApiKeyParams, Vc as validateModelsAuthRefreshParams } from "./src-BX8OAe1J.mjs";
import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs";
import { s as resolveProviderAuthLookupMaps } from "./provider-env-vars-DPvuIf4v.mjs";
import { d as hasGatewayAdminScope } from "./operator-scopes-CULmYfyY.mjs";
import { t as DEFAULT_OAUTH_REFRESH_MARGIN_MS } from "./credential-state-BiAE74F8.mjs";
import { m as getRuntimeAuthProfileStoreSnapshotsRevision, r as clearRuntimeAuthProfileStoreSnapshots, w as refreshRuntimeAuthProfileStoreSources } from "./runtime-snapshots-1lyYKb7Y.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { t as getOrCreateWeakOwnerMap } from "./weak-owner-map-BGsaUABm.mjs";
import { f as listProfilesForProvider, m as resolveExplicitAuthOrderSelection } from "./order-jOvee2J6.mjs";
import { t as NON_ENV_SECRETREF_MARKER } from "./provider-credential-values-pLjdcwQh.mjs";
import { c as isKnownEnvApiKeyMarker, l as isNonSecretApiKeyMarker } from "./model-auth-markers-4YSUG71a.mjs";
import { t as isExternalCliAuthProfileInScope } from "./external-cli-sync-_MwEKD82.mjs";
import { t as externalCliDiscoveryForConfigStatus } from "./external-cli-discovery-DZ419koV.mjs";
import { i as listProviderEnvAuthLookupKeys, r as resolveProviderEnvAuthEvidence } from "./model-auth-env-kbpGo8fU.mjs";
import { b as resolveUsableCustomProviderApiKey, g as resolveProviderConfigSecretInput, v as resolveProviderEntryApiKeyProfileReference } from "./model-auth-provider-config-Bnc4upRS.mjs";
import { c as ensureAuthProfileStoreWithoutExternalProfilesAsync } from "./store-runtime-dW0pXLJI.mjs";
import { c as resolveUsageProviderId, o as providerUsageLabel } from "./provider-usage.shared-ChpSZtTb.mjs";
import { n as resolveAuthProfileMetadata } from "./identity-CABffsHJ.mjs";
import { n as buildAuthHealthSummary, r as formatRemainingShort, t as DEFAULT_OAUTH_WARN_MS } from "./auth-health-sVoXFBMP.mjs";
import { n as readPreparedCatalog, t as loadDeferredCatalog } from "./server-model-catalog-auth-DPSO0-N0.mjs";
import { t as formatForLog } from "./ws-log-CbOV6uhk.mjs";
import { r as respondUnavailableOnThrow, t as respondError } from "./response-C7fEiIN1.mjs";
import { n as defineValidatedGatewayHandler, t as assertValidParams } from "./validation-DwNk6A-B.mjs";
import "./auth-profiles-VRLhewIH.mjs";
import "./model-auth-CEsyk_Yg.mjs";
import { n as localStateOwnerChangedError, t as captureLocalStateMutationGuard } from "./local-state-owner-CnxUSfeW.mjs";
import { n as abortChatRunsForProvider } from "./chat-abort-DHc0iNFP.mjs";
import { n as createChatAbortOps } from "./chat-abort-ops-BGjSJRNq.mjs";
import { s as refreshActiveProviderAuthRuntimeSnapshot } from "./runtime-Dc04zUgW.mjs";
import { t as resolveModelAuthAgentScope } from "./model-auth-agent-scope-D5aeJRSp.mjs";
import { i as getProviderUsageRuntimeSnapshot, r as readProviderUsage } from "./models-auth-status-usage-cache-D9ndF6BR.mjs";
import { t as refreshModelAuthStateAfterMutation } from "./model-auth-refresh-0zj3uFap.mjs";
import { t as resolveConfigBoundProfileIds } from "./models-auth-status-config-DnhTF941.mjs";
import { t as resolveModelProviderCapabilities } from "./model-provider-capabilities-ChRIXSeJ.mjs";
//#region src/gateway/server-methods/models-auth-refresh.ts
const modelsAuthRefreshHandlers = { "models.authRefresh": defineValidatedGatewayHandler("models.authRefresh", validateModelsAuthRefreshParams, async ({ params: e, respond: t, context: n }) => {
const r = n.getRuntimeConfig();
const i = resolveModelAuthAgentScope(r, e.agentId === void 0 || e.agentId === "" ? tryResolveAmbientOwnerAgentId(r) : e.agentId);
if (!i.ok) {
t(false, void 0, i.error);
return;
}
await respondUnavailableOnThrow(t, async () => {
clearRuntimeAuthProfileStoreSnapshots();
await refreshModelAuthStateAfterMutation(n.getRuntimeConfig, i.agentId);
t(true, { refreshed: true }, void 0);
});
}) };
//#endregion
//#region src/gateway/server-methods/models-auth-status-facts.ts
const apiKeyUsageStatusProviders = /* @__PURE__ */ new Set(["clawrouter", "deepseek"]);
const authStatusFacts = /* @__PURE__ */ new WeakMap();
function resolveEnvVarName(e) {
return /^(?:shell env|env): ([A-Z][A-Z0-9_]*)$/u.exec(e)?.[1];
}
function buildModelAuthStatusFacts(e, t) {
const { config: n, authStore: r, workspaceDir: i } = e;
const a = {
config: n,
workspaceDir: i,
metadataSnapshot: e.metadataSnapshot,
includeUntrustedWorkspacePlugins: false
};
const o = resolveProviderAuthLookupMaps({
...a,
config: n,
env: process.env
});
const s = /* @__PURE__ */ new Set([
...Object.keys(n.models?.providers ?? {}),
...Object.values(n.auth?.profiles ?? {}).map((e) => e?.provider).filter((e) => typeof e === "string"),
...listProviderEnvAuthLookupKeys(o)
]);
const c = /* @__PURE__ */ new Map();
for (const e of s) {
const t = normalizeProviderId(e);
if (!t) continue;
const { providerConfig: i, ref: s } = resolveProviderConfigSecretInput(n, t);
if (hasConfiguredSecretInput(i?.apiKey, n.secrets?.defaults)) {
const e = resolveProviderEntryApiKeyProfileReference({
cfg: n,
authAliasLookupParams: a,
provider: t,
store: r
});
if (e.kind !== "profile" && e.kind !== "profile-incompatible") {
if (s && s.source !== "env") {
c.set(t, { source: "config" });
continue;
}
const r = resolveUsableCustomProviderApiKey({
cfg: n,
provider: t,
env: process.env
});
if (r) {
const n = typeof i?.apiKey === "string" ? i.apiKey.trim() : "";
if (n && isNonSecretApiKeyMarker(n, { includeEnvVarName: false })) continue;
const a = s?.source === "env" ? s.id : e.kind === "marker" && isKnownEnvApiKeyMarker(n) ? n : resolveEnvVarName(r.source);
c.set(t, a ? {
source: "env",
envVar: a
} : { source: "config" });
continue;
}
}
}
const l = resolveProviderEnvAuthEvidence(t, process.env, {
aliasMap: o.aliasMap,
candidateMap: o.envCandidateMap,
authEvidenceMap: o.authEvidenceMap
});
if (l?.mode === "api-key") {
const e = resolveEnvVarName(l.source);
c.set(t, {
source: "env",
...e ? { envVar: e } : {}
});
}
}
const l = /* @__PURE__ */ new Set();
const u = /* @__PURE__ */ new Set();
const includeConfiguredAuthProvider = (e, t) => {
if (c.has(e)) return;
l.add(e);
if (t === "oauth") u.add(e);
};
for (const [e, t] of Object.entries(n.models?.providers ?? {})) {
const r = normalizeProviderId(e);
if (!r) continue;
const i = typeof t?.apiKey === "string" ? t.apiKey.trim() : "";
const a = hasConfiguredSecretInput(t?.apiKey, n.secrets?.defaults) && (i === "secretref-managed" || !isNonSecretApiKeyMarker(i, { includeEnvVarName: false }));
const o = t?.auth;
if (o !== "oauth" && o !== "token" && !a) continue;
includeConfiguredAuthProvider(r, o);
}
for (const e of Object.values(n.auth?.profiles ?? {})) {
const t = e?.provider;
const n = e?.mode;
if (typeof t !== "string" || t.length === 0 || n !== "oauth" && n !== "token") continue;
const r = normalizeProviderId(t);
if (!r) continue;
includeConfiguredAuthProvider(r, n);
}
for (const e of c.keys()) l.add(e);
for (const e of Object.values(r.profiles)) {
const t = normalizeProviderId(e.provider);
if (t) l.add(t);
}
const readAuthHealth = () => buildAuthHealthSummary({
store: r,
cfg: n,
providers: l.size > 0 ? [...l] : void 0,
authAliasLookupParams: a
});
const d = readAuthHealth();
const f = d.profiles.some((e) => e.type === "oauth" && isExternalCliAuthProfileInScope({
store: r,
profileId: e.profileId
}));
const p = [...new Set(d.profiles.flatMap((e) => {
const t = resolveUsageProviderId(e.provider, { credentialType: e.type });
return t && (e.type === "oauth" || e.type === "token" || apiKeyUsageStatusProviders.has(t)) ? [t] : [];
}))];
const m = new Set(r.runtimeExternalProfileIds ?? []);
const h = new Set(Object.entries(r.profiles).filter(([e, t]) => !m.has(e) && (t.type !== "api_key" || !t.keyRef)).map(([e]) => e));
const g = resolveConfigBoundProfileIds(n, r, a);
const _ = new Set(Object.entries(r.profiles).filter(([e]) => g.has(e)).map(([, e]) => resolveProviderIdForAuth(e.provider, {
...a,
storedCredential: true
})));
const v = resolveModelProviderCapabilities({
config: n,
workspaceDir: i,
metadataSnapshot: e.metadataSnapshot
}).capabilities;
let y = Infinity;
for (const e of d.profiles) {
if (e.expiresAt === void 0) continue;
for (const n of [
DEFAULT_OAUTH_WARN_MS,
DEFAULT_OAUTH_REFRESH_MARGIN_MS,
0
]) {
const r = e.expiresAt - n;
if (r > t) y = Math.min(y, r);
}
}
return {
authAliasLookupParams: a,
apiKeys: c,
expectsOAuth: u,
authHealth: d,
readAuthHealth: f ? readAuthHealth : void 0,
usageProviderIds: p,
externalProfileIds: m,
logoutProfileIds: h,
configBoundProfileIds: g,
configBoundAuthProviders: _,
providerCapabilities: v,
refreshAt: y
};
}
function readModelAuthStatusFacts(e, t, n) {
const r = getOrCreateWeakOwnerMap(authStatusFacts, e.config);
const i = getRuntimeAuthProfileStoreSnapshotsRevision();
const a = r.get(e.agentId);
if (!t && a && a.revision === i && a.profiles === e.authStore.profiles && a.owner === e.isCurrent && a.metadata === e.metadataSnapshot && a.agentDir === e.agentDir && a.workspaceDir === e.workspaceDir && n < a.facts.refreshAt) return a.facts.readAuthHealth ? {
...a.facts,
authHealth: a.facts.readAuthHealth()
} : a.facts;
const o = buildModelAuthStatusFacts(e, n);
r.set(e.agentId, {
profiles: e.authStore.profiles,
owner: e.isCurrent,
metadata: e.metadataSnapshot,
agentDir: e.agentDir,
workspaceDir: e.workspaceDir,
revision: i,
facts: o
});
return o;
}
//#endregion
//#region src/gateway/server-methods/models-auth-status.ts
const log = createSubsystemLogger("models-auth-status");
function resolveAuthRefreshScope(e) {
const t = externalCliDiscoveryForConfigStatus({ cfg: e });
if (t.mode !== "scoped") return { providerIds: [] };
const n = [...t.providerIds ?? []];
const r = [...t.profileIds ?? []];
return {
providerIds: n,
...r.length > 0 ? { profileIds: r } : {}
};
}
function readProviderParam(e) {
const t = e.provider;
if (typeof t !== "string") return null;
return normalizeProviderId(t) || null;
}
function readLogoutProfileSelection(e) {
if (!("profileIds" in e)) return { ok: true };
if (!Array.isArray(e.profileIds) || e.profileIds.length === 0) return {
ok: false,
message: "profileIds must be a non-empty string array"
};
for (const t of e.profileIds) if (typeof t !== "string" || !t.trim()) return {
ok: false,
message: "profileIds must be a non-empty string array"
};
return {
ok: true,
profileIds: normalizeUniqueStringEntries(e.profileIds)
};
}
function buildExpiry(e, t) {
const n = asDateTimestampMs(t);
if (n === void 0 || typeof e !== "number") return;
return {
at: n,
remainingMs: e,
label: formatRemainingShort(e)
};
}
function providerDisplayName(e) {
const t = resolveUsageProviderId(e);
return t && providerUsageLabel(t) || e;
}
function aggregateProfileStatus(e, t) {
const n = new Set(e.map((e) => e.status));
const r = [
"expired",
"missing",
"expiring",
"ok",
"static"
].find((e) => n.has(e));
const i = e.map((e) => e.expiresAt).filter((e) => asDateTimestampMs(e) !== void 0);
const a = i.length > 0 ? Math.min(...i) : void 0;
const o = a !== void 0 ? a - t : void 0;
return {
status: r ?? "static",
expiresAt: a,
remainingMs: o
};
}
/**
* Aggregate the effective refreshable credential status for the dashboard.
* OAuth remains authoritative when present; token credentials are the
* supported fallback after an OAuth-to-token migration. Explicit auth-order
* exclusions remain authoritative through `effectiveProfiles`.
*
* `expectsOAuth` keeps an API-key-only provider `missing` after config switches
* to OAuth but login has not completed.
*/
function aggregateRefreshableAuthStatus(e, t = Date.now(), n = false) {
const r = e.effectiveProfiles ?? e.profiles;
for (const e of ["oauth", "token"]) {
const n = r.filter((t) => t.type === e);
if (n.length > 0) return aggregateProfileStatus(n, t);
}
if (n) return { status: "missing" };
return {
status: e.status,
expiresAt: e.expiresAt,
remainingMs: e.remainingMs
};
}
async function refreshAfterCredentialMutation(e, t) {
try {
await refreshModelAuthStateAfterMutation(e.getRuntimeConfig, t);
return;
} catch (e) {
log.warn(`credential change saved but auth refresh failed: ${formatForLog(e)}`);
return "Model auth changes were saved, but the Gateway could not refresh them. Run `openclaw gateway restart` to apply the saved changes.";
}
}
const modelsAuthStatusHandlers = {
...modelsAuthRefreshHandlers,
"models.authSetApiKey": async (e) => {
const { params: t, respond: n, context: r, client: i } = e;
const a = t.expectedOwnerId;
if (!assertValidParams(t, validateModelsAuthSetApiKeyParams, "models.authSetApiKey", n)) return;
let o;
if (a !== void 0) {
if (typeof a !== "string" || !a.trim()) {
respondError(n, ErrorCodes.INVALID_REQUEST, "expectedOwnerId must be a non-empty string");
return;
}
if (!hasGatewayAdminScope(i)) {
respondError(n, ErrorCodes.FORBIDDEN, "missing scope: operator.admin");
return;
}
try {
o = captureLocalStateMutationGuard(a, e);
} catch (e) {
n(false, void 0, localStateOwnerChangedError(e));
return;
}
}
const s = normalizeProviderId(t.provider);
await respondUnavailableOnThrow(n, async () => {
const e = r.getRuntimeConfig();
const i = o ? {
ok: true,
...(await import("./shared-BLkGfkPx.mjs")).resolveModelsTargetAgent(e, t.agentId, { kind: "mutation" })
} : resolveModelAuthAgentScope(e, t.agentId);
if (!i.ok) {
n(false, void 0, i.error);
return;
}
const { saveModelProviderApiKey: a } = await import("./auth-api-key-SWgmtVc2.mjs");
const { profileId: c, warning: l } = await a({
config: e,
provider: s,
apiKey: t.apiKey,
agentDir: i.agentDir,
assertCurrent: o
});
const u = [l, await refreshAfterCredentialMutation(r, i.agentId)].filter(Boolean).join(" ");
const d = {
provider: s,
profileId: c,
...u ? { warning: u } : {}
};
n(true, d, void 0);
});
},
"models.authLogout": async ({ params: e, respond: t, context: n }) => {
const r = readProviderParam(e);
if (!r) {
respondError(t, ErrorCodes.INVALID_REQUEST, "provider is required");
return;
}
const i = readLogoutProfileSelection(e);
if (!i.ok) {
respondError(t, ErrorCodes.INVALID_REQUEST, i.message);
return;
}
if (e.credentialType !== void 0 && e.credentialType !== "api_key" || e.credentialType !== void 0 && i.profileIds !== void 0) {
respondError(t, ErrorCodes.INVALID_REQUEST, "Choose either API keys or specific profiles");
return;
}
const a = e.credentialType === "api_key";
await respondUnavailableOnThrow(t, async () => {
const o = n.getRuntimeConfig();
const s = resolveModelAuthAgentScope(o, e.agentId);
if (!s.ok) {
t(false, void 0, s.error);
return;
}
const { agentDir: c } = s;
const l = resolveProviderIdForAuth(r, { config: o });
const u = await ensureAuthProfileStoreWithoutExternalProfilesAsync(c);
const d = listProfilesForProvider(u, r);
const f = i.profileIds ?? d.filter((e) => {
const t = u.profiles[e];
return !a || t?.type === "api_key" && !t.keyRef;
});
if (i.profileIds && i.profileIds.some((e) => !d.includes(e))) {
respondError(t, ErrorCodes.INVALID_REQUEST, "profileIds contain unavailable auth profiles");
return;
}
const { removeModelAuthCredentials: p } = await import("./auth-logout-B6kuM0jE.mjs");
const m = await p({
cfg: o,
agentDir: c,
profileIds: f,
...a ? { apiKeyProvider: r } : {},
...!a && !i.profileIds ? { provider: r } : {}
});
const { runIds: h } = i.profileIds || a ? { runIds: [] } : abortChatRunsForProvider(createChatAbortOps(n), {
cfg: o,
providerId: l,
agentId: s.agentId
});
const g = [m, await refreshAfterCredentialMutation(n, s.agentId)].filter(Boolean).join(" ");
t(true, {
provider: r,
removedProfiles: f,
abortedRunIds: h,
...g ? { warning: g } : {}
}, void 0);
});
},
"models.authStatus": async ({ params: e, respond: t, context: n, client: r }) => {
const i = Date.now();
const a = Boolean(e.refresh);
const o = hasGatewayAdminScope(r);
const resolveScope = (t) => resolveModelAuthAgentScope(t, e.agentId === void 0 || e.agentId === "" ? tryResolveAmbientOwnerAgentId(t) : e.agentId);
await respondUnavailableOnThrow(t, async () => {
let r = n.getRuntimeConfig();
let s = resolveScope(r);
if (!s.ok) {
t(false, void 0, s.error);
return;
}
if (a) {
await refreshRuntimeAuthProfileStoreSources();
await refreshActiveProviderAuthRuntimeSnapshot();
r = n.getRuntimeConfig();
s = resolveScope(r);
if (!s.ok) {
t(false, void 0, s.error);
return;
}
}
const c = a ? await loadDeferredCatalog(n, s.agentId, {
readOnly: true,
authScope: resolveAuthRefreshScope(r),
refreshAuth: true,
refreshFullCatalog: false
}) : await readPreparedCatalog(n, s.agentId);
if (!c) {
t(true, {
ts: i,
providers: [],
unavailable: {
code: "PREPARED_MODEL_AUTH_UNAVAILABLE",
message: "Model authentication status is unavailable. Refresh Models after setup finishes; restart the Gateway if it persists."
}
}, void 0);
return;
}
r = c.config;
const { agentId: l, agentDir: u } = c;
const d = c.authStore;
const { authAliasLookupParams: f, apiKeys: p, expectsOAuth: m, authHealth: h, usageProviderIds: g, externalProfileIds: _, logoutProfileIds: v, configBoundProfileIds: y, configBoundAuthProviders: b, providerCapabilities: x } = readModelAuthStatusFacts(c, a, i);
const S = await getProviderUsageRuntimeSnapshot({
config: r,
agentId: l,
agentDir: u,
store: d
});
const C = {
agentId: l,
agentDir: u,
authStore: S.store,
configRef: r,
credentialKey: S.credentialKey,
forceRefresh: a,
providerIds: g,
now: i
};
const { usageByProvider: w, refreshAt: T } = await readProviderUsage({
...C,
awaitRefresh: Boolean(e.refreshUsage)
});
const E = [];
for (const e of h.providers) {
const t = normalizeProviderId(e.provider);
const n = resolveProviderIdForAuth(e.provider, f);
const i = resolveExplicitAuthOrderSelection({
storeOrder: d.order,
configuredOrder: r.auth?.order,
providerKey: t,
providerAuthKey: n
});
const a = findNormalizedProviderKey(d.order, n) ?? findNormalizedProviderKey(d.order, t);
const s = a !== void 0 && d.runtimeLocalOrderProviderIds?.includes(a);
const c = new Set(d.runtimeLocalProfileIds ?? Object.keys(d.profiles).filter((e) => !_.has(e)));
const l = b.has(n);
const u = i.order !== void 0 && !i.fromStore;
const h = e.profiles.find((e) => e.type === "oauth" || e.type === "token") ?? e.profiles.find((e) => e.type === "api_key");
const g = resolveUsageProviderId(e.provider, { credentialType: h?.type });
const x = g ? w.get(g) : void 0;
const S = aggregateRefreshableAuthStatus(e, Date.now(), m.has(e.provider));
const C = p.get(normalizeProviderId(e.provider));
const T = e.profiles.some((e) => e.type === "oauth" || e.type === "token");
E.push({
provider: e.provider,
authProvider: n,
displayName: providerDisplayName(e.provider),
status: C && !T && S.status === "missing" ? "static" : S.status,
expiry: buildExpiry(S.remainingMs, S.expiresAt),
profiles: e.profiles.map((e) => {
const t = resolveAuthProfileMetadata({
cfg: r,
store: d,
profileId: e.profileId
});
const n = d.usageStats?.[e.profileId]?.lastUsed;
const i = {
profileId: e.profileId,
type: e.type,
status: e.status,
reasonCode: e.reasonCode,
source: y.has(e.profileId) ? "config" : _.has(e.profileId) ? "external" : c.has(e.profileId) ? "saved" : "inherited",
expiry: buildExpiry(e.expiresAt === void 0 ? e.remainingMs : e.expiresAt - Date.now(), e.expiresAt)
};
if (o && t.displayName) i.displayName = t.displayName;
if (e.reasonCode === "setup_inactive") i.displayName = "Saved sign-in (inactive)";
if (o && t.email) i.email = t.email;
if (o && n) i.lastUsedAt = n;
if (v.has(e.profileId)) i.logoutSupported = true;
return i;
}),
...i.order !== void 0 ? { profileOrder: i.order } : {},
...i.fromStore && s ? { profileOrderStored: true } : {},
...l ? { profileOrderLocked: "provider-config" } : u ? { profileOrderLocked: "auth-config" } : {},
...C ? { apiKey: C } : {},
usage: x && g ? {
providerId: g,
windows: x.windows,
...x.summary ? { summary: x.summary } : {},
...x.plan ? { plan: x.plan } : {},
...x.billing?.length ? { billing: x.billing } : {},
...o && x.accountEmail ? { accountEmail: x.accountEmail } : {}
} : void 0
});
}
t(true, {
ts: i,
providers: E,
providerCapabilities: x,
usageRefreshAt: T
}, void 0);
});
}
};
//#endregion
export { modelsAuthStatusHandlers };