openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
290 lines (289 loc) • 10.9 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { x as uniqueValues } from "./string-normalization-DLmfYZXI.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { _ as secretRefKey, c as isSecretRef, o as formatExecSecretRefIdValidationMessage, u as isValidExecSecretRefId } from "./ref-contract-b8L-9DrQ.mjs";
import { _ as resolveSecretInputRef, a as coerceSecretRef } from "./types.secrets-BmNLLnHp.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as dedupeByKey } from "./dedupe-by-key-Cpowmfct.mjs";
import { i as collectUnsupportedSecretRefPolicyIssues } from "./validation-core-1Fx8ByEb.mjs";
import { n as formatConfigIssueLines } from "./issue-format-WaYQX-7p.mjs";
import { t as configFailureHeading } from "./io.invalid-config-DK-BYZ4Y.mjs";
import { c as loadPluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs";
import { t as assertDeferredPluginMigrationConfigEditAllowed } from "./deferred-plugin-migration-config-B3TJC-SY.mjs";
import { r as validateConfigObjectRawWithPlugins } from "./validation-DSwgLhC7.mjs";
import { n as discoverConfigSecretTargets } from "./target-registry-query-le6rMGHo.mjs";
import "./target-registry-C0PdHjLu.mjs";
import { l as readConfigFileSnapshotForWrite } from "./io.runtime-DsJ2dLCQ.mjs";
import { i as assertSecureExecCommandPath, r as resolveSecretProviderIntegrationConfig, t as isPluginIntegrationSecretProviderConfig } from "./provider-integrations-YWHLMzFF.mjs";
import { n as visitConfigValueTree } from "./value-tree-Deh4eoFD.mjs";
import "./config-CMA-J084.mjs";
import { t as exitCliAfterOutput } from "./one-shot-exit-DkbGSQD5.mjs";
import { i as getAtPath } from "./config-cli-path-rYPQt5Be.mjs";
import { t as formatConfigFilePath } from "./logging-D0RirHBi.mjs";
import { n as formatInvalidConfigRepairHint } from "./config-recovery-hints-DL4KuQ2q.mjs";
import { t as renderConfigValidationIssueLines } from "./issue-location-B-4mXR06.mjs";
import { t as writeInvalidConfigCliJson } from "./config-validation-output-B90Zi0oH.mjs";
//#region src/cli/config-cli-validation.ts
function ensureValidConfigSnapshotForCli(e, t, n = {}) {
if (e.valid) return;
if (n.json) {
writeInvalidConfigCliJson(t, e);
exitCliAfterOutput(t, 1);
}
t.error(`${configFailureHeading(e)}: ${formatConfigFilePath(e.path)}`);
for (const n of renderConfigValidationIssueLines(e)) t.error(n);
t.error(formatInvalidConfigRepairHint(e, "to repair, then retry."));
exitCliAfterOutput(t, 1);
}
async function loadValidConfigForWrite(e = defaultRuntime, t) {
const n = await readConfigFileSnapshotForWrite({
observe: false,
...t?.databaseOnly ? { pluginValidation: "core-only" } : {}
});
ensureValidConfigSnapshotForCli(n.snapshot, e);
return {
...n,
writeOptions: {
...n.writeOptions,
observe: false,
...t?.databaseOnly ? {
databaseAccess: "none",
skipPluginValidation: true,
skipRuntimeSnapshotRefresh: true
} : {}
}
};
}
async function finishConfigValidationForCli(e) {
const { snapshot: t, strictIssues: n } = e;
if (!t.valid || !t.exists) return t;
if (!n) throw new Error("Config validation requires its prepared source result.");
const r = n.length === 0 ? await collectConfigSecretProviderErrors({ config: t.runtimeConfig }) : n;
return r.length === 0 ? t : {
...t,
valid: false,
issues: r
};
}
function pathContains(e, t) {
return e.length <= t.length && e.every((e, n) => e === t[n]);
}
function selectConfigMutationSecrets(e, t) {
const n = t.map(({ setPath: e }) => e);
const r = /* @__PURE__ */ new Set();
const i = /* @__PURE__ */ new Set();
let a = false;
for (const e of n) {
if (e[0] !== "secrets") continue;
if (e.length === 1 || e[1] === "providers") {
const t = e[2];
if (t === void 0) a = true;
else r.add(t);
}
if (e.length === 1 || e[1] === "defaults") i.add(e[2] ?? "*");
}
const o = /* @__PURE__ */ new Map();
const record = (e) => o.set(secretRefKey(e), e);
const s = e.secrets?.defaults;
const c = [];
const overlaps = (e) => n.some((t) => pathContains(t, e) || pathContains(e, t));
for (const t of discoverConfigSecretTargets(e)) {
c.push(t.pathSegments);
if (t.refPathSegments) c.push(t.refPathSegments);
const { explicitRef: e, ref: n } = resolveSecretInputRef({
value: t.value,
refValue: t.refValue,
defaults: s
});
if (!n) continue;
const o = !isSecretRef(e ? t.refValue : t.value);
if (a || r.has(n.provider) || overlaps(t.pathSegments) || t.refPathSegments && overlaps(t.refPathSegments) || o && (i.has("*") || i.has(n.source))) record(n);
}
for (const t of n) visitConfigValueTree(getAtPath(e, t).value, (e, t) => {
if (c.some((e) => pathContains(e, t))) return false;
const n = coerceSecretRef(e, s);
if (n) {
record(n);
return false;
}
return true;
}, t);
const l = [...o.values()];
return {
refs: l,
providerAliases: a ? void 0 : /* @__PURE__ */ new Set([...r, ...l.map((e) => e.provider)])
};
}
function collectStrictConfigErrors(e, t, n, r) {
const i = validateConfigObjectRawWithPlugins(e, {
semanticValidation: "strict",
pluginMetadataSnapshot: t,
deferredPluginMigrations: n,
...r ? { pluginValidation: "skip" } : {}
});
if (i.ok) return [];
return formatConfigIssueLines(i.issues, "-", { normalizeRoot: true }).map((e) => ({
kind: "schema",
message: e
}));
}
function assertStrictConfigForMutation(e, t, n, r) {
const i = collectStrictConfigErrors(e, t, n, r);
if (i.length === 0) return;
throw new Error(["Config validation failed.", ...i.map((e) => `- ${e.message}`)].join("\n"));
}
async function collectConfigSecretProviderErrors(e) {
const t = e.config.secrets?.providers ?? {};
const n = [];
let r;
for (const [i, a] of Object.entries(t)) {
if (e.selection?.providerAliases && !e.selection.providerAliases.has(i)) continue;
const t = `secrets.providers.${i}`;
if (isPluginIntegrationSecretProviderConfig(a)) {
if (!e.selection) continue;
r ??= loadPluginMetadataSnapshot({
config: e.config,
env: process.env
}).manifestRegistry;
const o = resolveSecretProviderIntegrationConfig({
manifestRegistry: r,
providerAlias: i,
providerConfig: a,
config: e.config,
env: process.env
});
if (!o.ok) n.push({
path: t,
message: o.reason
});
} else if (isRecord(a) && "command" in a) try {
await assertSecureExecCommandPath({
command: a.command,
label: `${t}.command`,
trustedDirs: a.trustedDirs
});
} catch (e) {
n.push({
path: `${t}.command`,
message: formatErrorMessage(e)
});
}
}
return n;
}
/** Validates one final candidate and decides whether the runner may preview, skip, or write it. */
async function validateConfigMutation(e) {
const { config: t, operations: n, options: r, pluginMetadataSnapshot: i } = e;
assertDeferredPluginMigrationConfigEditAllowed({
sourceConfig: e.previousConfig,
nextConfig: t,
pending: e.deferredPluginMigrations ?? [],
editedPaths: n.map((e) => e.setPath),
unsetPaths: n.filter((e) => e.mutation === "delete").map((e) => e.setPath)
});
const a = formatConfigIssueLines(collectUnsupportedSecretRefPolicyIssues(t), "", { normalizeRoot: true }).map((e) => e.trim());
const o = selectConfigMutationSecrets(e.databaseOnly ? {
database: t.database,
secrets: t.secrets
} : t, n);
const s = formatConfigIssueLines(await collectConfigSecretProviderErrors({
config: t,
selection: o
}), "").map((e) => ({
kind: "schema",
message: e
}));
if (!r.dryRun) {
if (a.length > 0) throw new Error([
"Config policy validation failed: unsupported SecretRef usage was detected.",
...a.slice(0, 5).map((e) => `- ${e}`),
...a.length > 5 ? [`- ... ${a.length - 5} more`] : []
].join("\n"));
if (s.length > 0) throw new Error(["Config validation failed: SecretRef provider configuration is invalid.", ...s.map((e) => `- ${e.message}`)].join("\n"));
if (e.unchanged) {
assertStrictConfigForMutation(t, i, e.deferredPluginMigrations, e.databaseOnly);
return { kind: "unchanged" };
}
}
const { checkTouchedTextModelRefs: c } = await import("./config-model-validation-CHSbOaPV.mjs");
const l = await c({
...e.modelValidation ?? {
config: t,
previousConfig: e.previousConfig
},
touchedPaths: n.map(({ setPath: e }) => e),
redactDependencyValues: true
});
if (!r.dryRun) {
if (l.errors[0]) throw new Error(l.errors[0]);
return { kind: "write" };
}
const u = uniqueValues(n.map(({ inputMode: e }) => e));
const d = u.some((e) => e !== "value");
const f = n.some((e) => e.inputMode === "unset" || (e.inputMode === "json" || e.inputMode === "builder") && e.schemaValidated !== true);
const p = [];
const m = [];
for (const e of d ? o.refs : []) (e.source === "exec" && !r.allowExec ? m : p).push(e);
const h = l.errors.map((e) => ({
kind: "model",
message: e
}));
if (!f) h.push(...a.map((e) => ({
kind: "schema",
message: e
})));
h.push(...s);
if (f) h.push(...collectStrictConfigErrors(t, i, e.deferredPluginMigrations, e.databaseOnly));
if (d) {
h.push(...m.flatMap((e) => {
const n = e.id.trim();
const r = `${e.source}:${e.provider}:${n}`;
let i;
if (!n) i = "Error: Secret reference id is empty.";
else if (!isValidExecSecretRefId(n)) i = `Error: ${formatExecSecretRefIdValidationMessage()} (ref: ${r}).`;
else {
const n = t.secrets?.providers?.[e.provider];
if (!n) i = `Error: Secret provider "${e.provider}" is not configured (ref: ${r}).`;
else if (n.source !== e.source) i = `Error: Secret provider "${e.provider}" has source "${n.source}" but ref requests "${e.source}".`;
}
return i ? [{
kind: "resolvability",
message: i,
ref: r
}] : [];
}));
const { resolveSecretRefValue: e } = await import("./resolve-fZfTRJfv.mjs");
for (const n of p) try {
await e(n, {
config: t,
env: process.env
});
} catch (e) {
h.push({
kind: "resolvability",
message: formatErrorMessage(e),
ref: `${n.source}:${n.provider}:${n.id}`
});
}
}
const g = dedupeByKey(h, (e) => e.kind === "resolvability" ? `${e.kind}\u0000${e.ref ?? ""}\u0000${e.message}` : `${e.kind}\u0000${e.message}`);
return {
kind: "dry-run",
result: {
ok: g.length === 0,
operations: n.length,
configPath: e.configPath,
inputModes: u,
checks: {
schema: f || a.length > 0 || s.length > 0,
resolvability: d || l.refsTotal > 0,
resolvabilityComplete: (d || l.refsTotal > 0) && m.length === 0 && l.refsChecked === l.refsTotal
},
refsChecked: p.length + l.refsChecked,
skippedExecRefs: m.length,
...g.length > 0 ? { errors: g } : {}
}
};
}
//#endregion
export { validateConfigMutation as a, loadValidConfigForWrite as i, ensureValidConfigSnapshotForCli as n, finishConfigValidationForCli as r, assertStrictConfigForMutation as t };