openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
418 lines (417 loc) • 14.9 kB
JavaScript
import { n as coerceErrorMessage } from "./error-coercion-hDrHOSGy.mjs";
import { n as formatConcreteConfigPath } from "./dot-path-BJ4tyWKJ.mjs";
import { i as resolveConfigEnvVars, n as containsEnvVarReference } from "./env-substitution-CgVeOqUd.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { n as listAgentEntries, r as listAgentEntriesWithSource, t as hasAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs";
import { A as tryResolveLegacyCompatibilityAgentId, _ as resolveDefaultAgentId, a as resolveAgentDir, c as resolveAgentNativeModelPrimary, f as resolveAgentWorkspaceDir, s as resolveAgentModelConfigForRuntime } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as dedupeByKey } from "./dedupe-by-key-Cpowmfct.mjs";
import { t as applyImplicitAgentRosterDefaults } from "./implicit-agent-roster-DtoGie9T.mjs";
import { d as loadPinnedRuntimeConfigAsync } from "./runtime-snapshot-WbwbY5b7.mjs";
import { i as DEFAULT_PROVIDER } from "./defaults-BWyoTPqn.mjs";
import { t as splitTrailingAuthProfile } from "./model-ref-profile-C7DWqVP0.mjs";
import { l as resolveAgentModelFallbacksOverride } from "./agent-scope-BwB8YH6y.mjs";
import { h as resolveConfiguredModelRef, i as buildModelAliasIndex, y as resolveModelRefFromString } from "./model-selection-shared-9Kz63Hhm.mjs";
import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs";
//#region src/cli/config-model-validation.ts
function isPathPrefix(e, t) {
return e.length <= t.length && e.every((e, n) => t[n] === e);
}
function pathMayAffectTextModelRefs(e) {
if (e[0] !== "agents" || e.length === 1) return e[0] === "agents";
if (e[1] === "defaults") return e.length === 2 || e[2] === "model";
return e[1] === "entries" || e[1] === "list";
}
function collectTextModelConfigRefs(e) {
const t = typeof e.model === "string";
const n = t ? { primary: e.model } : e.model;
if (!n || typeof n !== "object" || Array.isArray(n)) return [];
const { primary: r, fallbacks: i } = n;
const a = [];
if (typeof r === "string") {
const n = r.trim();
const i = splitTrailingAuthProfile(n).profile;
a.push({
path: t ? e.path : `${e.path}.primary`,
value: n,
...e.agentId ? { agentId: e.agentId } : {},
fallback: false,
...i ? { authProfileId: i } : {}
});
}
if (Array.isArray(i)) for (const [t, n] of i.entries()) {
if (typeof n !== "string") continue;
a.push({
path: `${e.path}.fallbacks.${t}`,
value: n.trim(),
...e.agentId ? { agentId: e.agentId } : {},
fallback: true
});
}
return a;
}
function collectTextModelRefs(e) {
const t = collectTextModelConfigRefs({
model: e.agents?.defaults?.model,
path: "agents.defaults.model"
});
for (const { entry: n, source: r } of listAgentEntriesWithSource(e)) {
const e = n.id;
const i = r.kind === "entries" ? `agents.entries.${r.key}` : `agents.list.${r.index}`;
t.push(...collectTextModelConfigRefs({
model: resolveAgentModelConfigForRuntime(n),
path: `${i}.model`,
agentId: e
}));
}
return t;
}
function modelRefComparisonKey(e) {
if (e.agentId) {
const t = e.path.indexOf(".model");
const n = t >= 0 ? e.path.slice(t + 1) : e.path;
return `agent:${normalizeAgentId(e.agentId)}:${n}`;
}
return `path:${e.path}`;
}
function inheritsDefaultModelRef(e, t, n) {
return (n.fallback ? resolveAgentModelFallbacksOverride : resolveAgentNativeModelPrimary)(e, t) === void 0;
}
function collectTouchedTextModelRefs(e) {
const t = listAgentEntriesWithSource(e.config);
const n = [
"agents",
"defaults",
"model",
"primary"
];
const r = e.touchedPaths.some((e) => isPathPrefix(e, n) || isPathPrefix(n, e));
const i = collectTextModelRefs(e.config);
const a = e.previousConfig ? collectTextModelRefs(e.previousConfig) : void 0;
const o = a ? new Map(a.map((e) => [modelRefComparisonKey(e), e])) : void 0;
const s = e.previousConfig ? tryResolveLegacyCompatibilityAgentId(e.previousConfig) : void 0;
const c = r && (!a || s === void 0 || resolveDefaultModelForAgent({ cfg: e.config }).provider !== resolveDefaultModelForAgent({
cfg: e.previousConfig,
agentId: s
}).provider);
const l = i.filter((t) => {
if (t.fallback && c) {
const n = o?.get(modelRefComparisonKey(t));
const r = resolveFallbackRef(e.config, t.value)?.ref;
const i = e.previousConfig && n ? resolveFallbackRef(e.previousConfig, n.value)?.ref : void 0;
if (!r || !i || r.provider !== i.provider || r.model !== i.model) {
t.dependency = true;
return true;
}
}
const n = t.path.split(".");
const r = e.touchedPaths.some((e) => isPathPrefix(e, n) || isPathPrefix(n, e));
if (!r || !o) return r;
const i = o.get(modelRefComparisonKey(t));
const a = i !== void 0 && i.agentId !== t.agentId;
if (a) t.dependency = true;
return i?.value !== t.value || a;
});
const u = i.filter((e) => e.agentId === void 0);
if (u.length === 0) return l;
for (const { entry: n, source: r } of t) {
const t = n.id;
const i = [
"agents",
r.kind,
r.kind === "entries" ? r.key : String(r.index)
];
if (!e.touchedPaths.some((e) => isPathPrefix(e, i) || isPathPrefix(i, e))) continue;
for (const n of u) {
const r = inheritsDefaultModelRef(e.config, t, n);
const i = (e.previousConfig ? listAgentEntries(e.previousConfig) : []).some((e) => normalizeAgentId(e.id) === normalizeAgentId(t)) && e.previousConfig && inheritsDefaultModelRef(e.previousConfig, t, n);
if (r && !i) l.push({
...n,
agentId: t,
dependency: true
});
}
}
return l;
}
function resolveFallbackRef(e, t, n, r) {
const i = resolveDefaultModelForAgent({
cfg: e,
agentId: r,
manifestPlugins: n
}).provider;
return resolveModelRefFromString({
cfg: e,
agentId: r,
raw: t,
defaultProvider: i,
aliasIndex: buildModelAliasIndex({
cfg: e,
agentId: r,
defaultProvider: i,
allowPluginNormalization: true,
manifestPlugins: n
}),
allowPluginNormalization: true,
manifestPlugins: n
});
}
function resolveCanonicalModelRef(e, t, n) {
const r = t.agentId ?? tryResolveLegacyCompatibilityAgentId(e);
if (t.fallback) return resolveFallbackRef(e, t.value, n, r)?.ref;
const i = {
...e,
agents: {
...e.agents,
defaults: {
...e.agents?.defaults,
model: t.value
}
}
};
const a = resolveConfiguredModelRef({
cfg: i,
agentId: r,
defaultProvider: DEFAULT_PROVIDER,
defaultModel: "",
allowPluginNormalization: true,
manifestPlugins: n
});
return a.model ? a : void 0;
}
function scopedModelRefComparisonKey(e, t) {
return modelRefComparisonKey({
...t,
agentId: t.agentId ?? tryResolveLegacyCompatibilityAgentId(e)
});
}
function expandInheritedDefaultRefs(e, t) {
const n = listAgentEntries(e);
const r = tryResolveLegacyCompatibilityAgentId(e);
const i = [];
for (const a of t) {
if (a.agentId !== void 0) {
i.push(a);
continue;
}
if (r) {
if (!n.some((e) => normalizeAgentId(e.id) === normalizeAgentId(r)) || inheritsDefaultModelRef(e, r, a)) i.push(a);
}
for (const { id: t } of n) {
if (r && normalizeAgentId(t) === normalizeAgentId(r)) continue;
if (inheritsDefaultModelRef(e, t, a)) i.push({
...a,
agentId: t
});
}
}
return dedupeByKey(i, (e) => `${e.path}\u0000${e.agentId ?? ""}`);
}
async function createRuntimeModelRefResolver() {
const e = await import("./model-selection-MVvzg347.mjs");
const loadModelModules = () => Promise.all([import("./model-BGxC_MMq.mjs"), import("./prepared-model-runtime-D6x7ghYr.mjs")]);
let t;
return async ({ config: n, ref: r }) => {
try {
var i = _usingCtx();
let a = resolveCanonicalModelRef(n, r);
if (!a) return `Unknown model: ${r.value}`;
if (e.isCliProvider(a.provider, n)) return;
const o = r.agentId ?? tryResolveLegacyCompatibilityAgentId(n) ?? resolveDefaultAgentId(n);
const s = resolveAgentDir(n, o);
const c = resolveAgentWorkspaceDir(n, o);
const [l, u] = await (t ??= loadModelModules());
await loadPinnedRuntimeConfigAsync(async () => ({ config: n }));
const d = i.a(await u.acquireReadOnlyPreparedModelRuntime({
agentId: o,
agentDir: s,
config: n,
workspaceDir: c,
loadRuntimePlugins: true
}, { deriveRuntimePluginSelections: ({ config: e, metadataSnapshot: t }) => {
a = resolveCanonicalModelRef(e, r, t);
if (!a) return [];
const { provider: n, model: i } = a;
return [{
provider: n,
modelId: i,
agentId: o
}];
} }));
if (!a) return `Unknown model: ${r.value}`;
const { provider: f, model: p } = a;
const m = d.snapshot.createStores();
const h = await l.resolveModelAsync(f, p, s, n, {
...m,
modelIdSource: "selected",
agentId: o,
allowBundledStaticCatalogFallback: true,
...r.authProfileId ? { authProfileId: r.authProfileId } : {},
preparedModelRuntime: d.snapshot,
workspaceDir: c
});
return h.model ? void 0 : h.error ?? `Unknown model: ${f}/${p}`;
} catch (e) {
i.e = e;
} finally {
await i.d();
}
};
}
function materializeValidationRoster(e) {
return hasAgentRosterProperty(e) ? e : applyImplicitAgentRosterDefaults(e);
}
/** Checks authored mutations before admission, preserving legacy roster alias paths. */
async function checkTouchedTextModelRefs(e) {
const t = e.touchedPaths;
const n = t.some((e) => e[0] === "env" || e[0] === "agents" && (e.length === 1 || e[1] === "defaults" && (e.length === 2 || e[2] === "models" || e[2] === "model" && (e.length === 3 || e[3] === "primary")) || (e[1] === "entries" || e[1] === "list") && (e.length <= 3 || e[3] === "models" || e[3] === "runtime" || e[3] === "model" && (e.length === 4 || e[4] === "primary"))));
if (!n && !t.some(pathMayAffectTextModelRefs)) return {
refsChecked: 0,
refsTotal: 0,
errors: []
};
const r = materializeValidationRoster(e.config);
const i = e.previousConfig ? materializeValidationRoster(e.previousConfig) : void 0;
const a = collectTouchedTextModelRefs({
...e,
config: r,
previousConfig: i,
touchedPaths: t
});
const o = new Map(collectTextModelRefs(e.config).map((e) => [e.path, e.value]));
const s = new Map(collectTextModelRefs(e.previousConfig ?? {}).map((e) => [e.path, e.value]));
let c;
let l;
const u = /* @__PURE__ */ new Set();
try {
const t = e.env ?? process.env;
c = resolveConfigEnvVars(e.config, t, { onMissing: ({ configPath: e }) => u.add(e) });
l = e.previousConfig ? resolveConfigEnvVars(e.previousConfig, e.previousEnv ?? t, { onMissing: () => {} }) : void 0;
} catch (e) {
const t = coerceErrorMessage(e);
return {
refsChecked: 0,
refsTotal: a.length,
errors: [`Unable to validate changed model references before writing: ${t}`]
};
}
const d = new Map(collectTextModelRefs(c).map((e) => [e.path, e]));
const f = [...o].some(([e, t]) => d.get(e)?.value !== t);
const formatError = (t, n) => {
const r = Boolean(e.redactDependencyValues && t.dependency);
const i = (r ? "<configured model reference>" : o.get(t.path)) ?? t.value;
const a = f || r || i !== t.value ? "Unable to resolve authored model reference" : n;
const s = a.endsWith(".") ? a : `${a}.`;
return `Cannot set model reference "${i}" at ${t.path}: ${s} Run ${formatCliCommand("openclaw models list")} to list available models.`;
};
const p = materializeValidationRoster(c);
const m = l ? materializeValidationRoster(l) : void 0;
const h = new Map(collectTouchedTextModelRefs({
config: p,
previousConfig: m,
touchedPaths: t
}).map((e) => [modelRefComparisonKey(e), e]));
for (const e of a) {
if (e.dependency && s.get(e.path) === e.value) continue;
const t = d.get(e.path);
if (!t) continue;
const n = modelRefComparisonKey(t);
const r = h.get(n);
h.set(n, {
...t,
...e.dependency || r?.dependency ? { dependency: true } : {}
});
}
const g = new Map(expandInheritedDefaultRefs(p, [...h.values()]).map((e) => [scopedModelRefComparisonKey(p, e), e]));
if (n && m) {
const e = new Map(expandInheritedDefaultRefs(m, collectTextModelRefs(m)).map((e) => [scopedModelRefComparisonKey(m, e), e]));
for (const t of expandInheritedDefaultRefs(p, collectTextModelRefs(p))) {
const n = scopedModelRefComparisonKey(p, t);
if (g.has(n)) continue;
const r = e.get(n);
const i = r ? resolveCanonicalModelRef(m, r) : void 0;
const a = resolveCanonicalModelRef(p, t);
if (r?.value !== t.value || i?.provider !== a?.provider || i?.model !== a?.model) g.set(n, {
...t,
dependency: true
});
}
}
const _ = [...g.values()];
if (_.length === 0) return {
refsChecked: 0,
refsTotal: 0,
errors: []
};
const v = _.filter((e) => {
if (!e.fallback || e.value.includes("/")) return true;
const t = e.agentId ?? tryResolveLegacyCompatibilityAgentId(r);
const n = collectTextModelRefs(r).filter((e) => !e.fallback);
const i = n.find((e) => e.agentId === t) ?? n.find((e) => e.agentId === void 0);
if (!i || !u.has(formatConcreteConfigPath(i.path.split("."), r))) return true;
const a = splitTrailingAuthProfile(i.value).model;
const o = a.indexOf("/");
const s = o > 0 ? a.slice(0, o) : a;
const c = resolveFallbackRef(r, e.value, void 0, t);
return !(c && !c.alias && containsEnvVarReference(s));
}).map((e) => {
if (!e.value) return {
ref: e,
error: "Model reference is empty"
};
const t = formatConcreteConfigPath(e.path.split("."), c);
if (u.has(t)) return {
ref: e,
error: "Model reference contains an unresolved environment variable"
};
return {
ref: e,
error: resolveCanonicalModelRef(c, e) ? void 0 : "Invalid model reference or configured model alias target"
};
});
const y = v.filter((e) => Boolean(e.error));
const b = v.filter((e) => !e.error).map((e) => e.ref);
const x = y.map(({ ref: e, error: t }) => formatError(e, t));
if (b.length === 0) return {
refsChecked: y.length,
refsTotal: _.length,
errors: x
};
let S = e.resolveModelRef;
if (!S) try {
S = await (e.createModelRefResolver ?? createRuntimeModelRefResolver)();
} catch (t) {
const n = f || Boolean(e.redactDependencyValues && _.some((e) => e.dependency)) ? "model resolver setup failed" : coerceErrorMessage(t);
return {
refsChecked: y.length,
refsTotal: _.length,
errors: [...x, `Unable to validate changed model references before writing: ${n}`]
};
}
let C = y.length;
for (const e of b) {
let t;
try {
t = await S({
config: c,
ref: e
});
C += 1;
} catch (t) {
const n = coerceErrorMessage(t);
x.push(formatError(e, `Unable to validate model reference: ${n}`));
continue;
}
if (!t) continue;
x.push(formatError(e, t));
}
return {
refsChecked: C,
refsTotal: _.length,
errors: x
};
}
//#endregion
export { checkTouchedTextModelRefs };