UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

481 lines (480 loc) • 19.3 kB
import { n as MAX_TIMER_TIMEOUT_MS } from "./number-coercion-D6u-4YD8.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import { _ as resolveDefaultAgentId, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { s as readConfigFileSnapshot } from "./io.runtime-DsJ2dLCQ.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import { i as parseHealthFindingSeverity, n as healthFindingMeetsSeverity } from "./health-checks-BFk2VaFq.mjs"; import { t as exitCodeFromFindings } from "./doctor-lint-flow-BvruTNfX.mjs"; import "./health-C4weL4aU.mjs"; import "./number-runtime-W4chuk8B.mjs"; import "./routing-DmgGYTrU.mjs"; import { t as listAgentIdsCompatibility } from "./agent-scope-runtime-CDpr-vor.mjs"; import "./runtime-DnKMstZp.mjs"; import "./setup-tools-NrA1nFHA.mjs"; import "./terminal-safe-text-DY8-BpAj.mjs"; import { _ as POLICY_RULE_METADATA, a as scopedPolicyFields, c as policyRuleValueIsValid, g as POLICY_FIX_METADATA_BY_CHECK_ID, i as normalizePolicySelectorValues, l as createPolicyAttestation, m as getPolicyPath, n as toAttestedFinding, o as scopedPolicyOverlays, p as ocPathSegment, r as policyContainerShapeFindings, s as isPolicyValueAtLeastAsStrict, t as evaluatePolicy, y as POLICY_CHECK_IDS } from "./evaluation-D-A2UvW9.mjs"; import { promises } from "node:fs"; import { basename, isAbsolute, resolve } from "node:path"; import { setTimeout } from "node:timers/promises"; import JSON5 from "json5"; //#region extensions/policy/src/policy-conformance.ts const POLICY_CONFORMANCE_CHECK_IDS = { missing: "policy/policy-conformance-missing", weaker: "policy/policy-conformance-weaker", invalid: "policy/policy-conformance-invalid" }; async function buildPolicyConformanceReport(e) { const t = resolvePolicyPath(e.baselinePath); const n = resolvePolicyPath(e.policyPath); const r = await readPolicyDocument(t); const i = await readPolicyDocument(n); const report = (e, t = 0) => ({ ok: e.length === 0, baselinePath: r.displayName, policyPath: i.displayName, rulesChecked: t, findings: e }); if (!r.ok || !i.ok) return report([r, i].filter((e) => { return !e.ok; }).map((e) => invalidConformanceFinding(e.displayName, e.message, e.target, `Fix ${e.displayName} so it contains valid policy JSONC.`))); const a = r; const o = i; const s = collectPolicyRuleClaims(a); const c = collectPolicyRuleClaims(o); const l = [a, o]; const u = uniqueConformanceFindings([ ...l.flatMap((e) => policyContainerShapeFindings(e.value, e.displayName, e.displayName).map((t) => invalidConformanceFinding(e.displayName, t.message, t.target ?? `oc://${e.displayName}`, t.fixHint ?? `Fix ${e.displayName} so it uses the documented policy syntax.`))), ...l.flatMap(collectInvalidScopedPolicyFindings), ...[[a, s], [o, c]].flatMap(([e, t]) => t.filter((e) => !policyRuleValueIsValid(e.metadata, e.value)).map((t) => invalidConformanceFinding(e.displayName, `${e.displayName} ${t.propertyPath} is not valid policy conformance syntax.`, t.target, `Fix ${t.propertyPath} so it uses the documented policy syntax.`))) ]); if (u.length > 0) return report(u); return report(s.map((e) => conformanceFinding(e, c, o.displayName)).filter((e) => e !== void 0), s.length); } function uniqueConformanceFindings(e) { const t = /* @__PURE__ */ new Set(); return e.filter((e) => { const n = `${e.checkId}\n${e.target}`; if (t.has(n)) return false; t.add(n); return true; }); } function collectInvalidScopedPolicyFindings(e) { if (!isRecord(e.value) || e.value.scopes === void 0) return []; if (!isRecord(e.value.scopes)) return [invalidConformanceFinding(e.displayName, `${e.displayName} scopes must be an object.`, `oc://${e.displayName}/scopes`, "Fix scopes so it uses the documented policy syntax.")]; const t = []; for (const [n, r] of Object.entries(e.value.scopes)) { const i = `scopes.${n}`; const a = `oc://${e.displayName}/scopes/${ocPathSegment(n)}`; if (!isRecord(r)) { t.push(invalidConformanceFinding(e.displayName, `${e.displayName} ${i} must be an object.`, a, `Fix ${i} so it uses the documented policy syntax.`)); continue; } for (const n of POLICY_RULE_METADATA) { if (getPolicyPath(r, n.policyPath) === void 0) continue; if ((n.scopeSelectors ?? []).some((e) => normalizePolicySelectorValues(r[e], e).length > 0)) continue; const o = `${i}.${n.policyPath.join(".")}`; t.push(invalidConformanceFinding(e.displayName, `${e.displayName} ${o} needs a valid selector for policy conformance.`, `${a}/${n.policyPath.map(ocPathSegment).join("/")}`, `Fix ${o} so it uses the documented policy syntax.`)); } } return t; } function invalidConformanceFinding(e, t, n, r) { return { checkId: POLICY_CONFORMANCE_CHECK_IDS.invalid, severity: "error", message: t, source: "policy", path: e, target: n, requirement: n, fixHint: r }; } function conformanceFinding(e, t, n) { if (baselineRuleIsNoOp(e.metadata, e.value)) return; const r = t.filter((t) => t.key === e.key); const i = e.scoped === void 0 || r.length > 0 ? r : t.filter((t) => t.scoped === void 0 && t.metadata === e.metadata); if (i.length === 0) return unsatisfiedConformanceFinding(e, n); const satisfies = (t) => isPolicyValueAtLeastAsStrict(e.metadata, t.value, e.value); if (e.scoped !== void 0 && r.length === 0 && i.some(satisfies)) return; const a = i.find((e) => !satisfies(e)); if (a !== void 0) return unsatisfiedConformanceFinding(e, n, a); if (e.scoped === void 0) { const r = t.find((t) => t.scoped !== void 0 && t.metadata === e.metadata && !satisfies(t)); if (r !== void 0) return unsatisfiedConformanceFinding(e, n, r); } } function baselineRuleIsNoOp(e, t) { switch (e.strictness) { case "allowlist-subset": return e.emptyList === "disabled" && policyRuleListIsEmpty(t); case "denylist-superset": case "routing-probes": return policyRuleListIsEmpty(t); case "requires-true": return t !== true; case "requires-false": return t !== false; case "exact-list": case "ordered-string": return false; } return false; } function policyRuleListIsEmpty(e) { return Array.isArray(e) && e.length === 0; } function unsatisfiedConformanceFinding(e, t, n) { return { checkId: n === void 0 ? POLICY_CONFORMANCE_CHECK_IDS.missing : POLICY_CONFORMANCE_CHECK_IDS.weaker, severity: "error", message: n === void 0 ? `${t} is missing ${e.propertyPath}.` : `${t} ${e.propertyPath} is weaker than the baseline policy.`, source: "policy", path: t, target: n?.target ?? `oc://${t}/${e.propertyPath.replaceAll(".", "/")}`, requirement: e.target, fixHint: n === void 0 ? `Add an equally or more restrictive ${e.propertyPath} rule, or update the baseline policy after review.` : `Use an equally or more restrictive ${e.propertyPath} value, or update the baseline policy after review.` }; } function collectPolicyRuleClaims(e) { return [...collectTopLevelPolicyRuleClaims(e), ...collectScopedPolicyRuleClaims(e)]; } function collectTopLevelPolicyRuleClaims(e) { const t = []; for (const n of POLICY_RULE_METADATA) { const r = getPolicyPath(e.value, n.policyPath); if (r === void 0) continue; const i = n.policyPath.join("."); t.push({ key: `global:${i}`, metadata: n, value: r, target: `oc://${e.displayName}/${n.policyPath.map(ocPathSegment).join("/")}`, propertyPath: i }); } return t; } function collectScopedPolicyRuleClaims(e) { const t = []; for (const [n, r] of scopedPolicyOverlays(e.value)) for (const i of ["agentIds", "channelIds"]) { const a = normalizePolicySelectorValues(r[i], i); if (a.length === 0) continue; for (const { metadata: o, value: s, propertyPath: c, targetPath: l } of scopedPolicyFields(n, r, i)) for (const r of a) t.push({ key: `${i}:${r}:${c}`, metadata: o, value: s, target: `oc://${e.displayName}/${l}`, propertyPath: `scopes.${n}.${c}`, scoped: true }); } return coalesceScopedPolicyRuleClaims(t); } function coalesceScopedPolicyRuleClaims(e) { const t = /* @__PURE__ */ new Map(); for (const n of e) { const e = t.get(n.key); if (e === void 0 || isPolicyValueAtLeastAsStrict(e.metadata, n.value, e.value)) t.set(n.key, n); } return [...t.values()]; } async function readPolicyDocument(e) { const t = basename(e); let n = "read"; try { const r = await promises.readFile(e, "utf-8"); n = "parsed"; return { ok: true, displayName: t, value: JSON5.parse(r) }; } catch (e) { const r = e instanceof Error ? e.message : String(e); return { ok: false, displayName: t, message: `${t} could not be ${n}: ${r}`, target: `oc://${t}` }; } } function resolvePolicyPath(e) { return isAbsolute(e) ? e : resolve(e); } //#endregion //#region extensions/policy/src/cli.ts function registerPolicyCli(e) { const t = e.command("policy").description("Verify workspace policy conformance"); t.command("compare").description("Compare policy.jsonc against an authored baseline policy file").requiredOption("--baseline <path>", "Baseline policy file to compare against").option("--policy <path>", "Policy file to check; defaults to configured policy path").option("--agent <id>", "Agent id for relative policy workspace paths").option("--json", "Emit JSON output").action(async (e) => { process.exitCode = await runPolicyCommand(e, async () => { if (e.baseline === void 0 || e.baseline.trim() === "") throw new Error("Missing required --baseline value."); const t = await policyCompareCandidatePath(e); const n = await buildPolicyConformanceReport({ baselinePath: e.baseline, policyPath: t }); writePolicyConformanceReport(n, e); return n.ok ? 0 : 1; }); }); t.command("check").description("Check policy requirements and emit an audit attestation").option("--agent <id>", "Agent id (required when multiple agents are configured)").option("--json", "Emit JSON output").option("--severity-min <severity>", "Minimum severity: info, warning, or error").action(async (e) => { process.exitCode = await runPolicyCommand(e, async () => { const t = await buildPolicyCheckReport(e, "policy check"); writePolicyCheckReport(t, e); return t.exitCode; }); }); t.command("watch").description("Watch policy evidence and report accepted-attestation drift").option("--agent <id>", "Agent id (required when multiple agents are configured)").option("--json", "Emit JSON output").option("--severity-min <severity>", "Minimum severity: info, warning, or error").option("--interval-ms <ms>", "Polling interval in milliseconds").option("--once", "Run one watch evaluation and exit").action(async (e) => { process.exitCode = await runPolicyCommand(e, async () => { const t = normalizeWatchIntervalMs(e.intervalMs); const n = new AbortController(); let r = 0; const stop = (e) => { if (!n.signal.aborted) { r = e; n.abort(); } }; const onSigint = () => stop(130); const onSigterm = () => stop(143); process.on("SIGINT", onSigint); process.on("SIGTERM", onSigterm); let i; try { while (!n.signal.aborted) { const r = await buildPolicyCheckReport(e, "policy watch"); if (n.signal.aborted) break; const a = policyWatchStatus(r); const o = `${a}:${r.attestation?.attestationHash ?? ""}:${r.exitCode}`; if (i !== o || e.once === true) { writePolicyWatchReport(r, a, e); i = o; } if (e.once === true) return a === "stale" ? 1 : r.exitCode; try { await setTimeout(t, void 0, { signal: n.signal }); } catch (e) { if (!n.signal.aborted || !(e instanceof Error) || e.name !== "AbortError") throw e; } } return r; } finally { process.off("SIGINT", onSigint); process.off("SIGTERM", onSigterm); } }); }); } async function runPolicyCommand(e, t) { try { return await t(); } catch (t) { const n = t instanceof Error ? t.message : String(t); if (e.json === true || !process.stdout.isTTY) defaultRuntime.writeJson({ ok: false, error: { type: "cli_error", message: n } }, 0); defaultRuntime.error(terminalText`${n}`); return 2; } } async function buildPolicyCheckReport(e, t) { const n = e.severityMin === void 0 ? "info" : parseHealthFindingSeverity(e.severityMin); if (n === null) throw new Error("Invalid --severity-min value. Expected one of: info, warning, error."); const r = await readConfigFileSnapshot({ observe: false }); if (!r.valid) { const e = r.issues.map((e) => ({ checkId: "policy/config-invalid", severity: "error", message: e.message, source: "policy", path: e.path })).filter((e) => healthFindingMeetsSeverity(e, n)); return { ok: e.length === 0, evidence: { channels: [] }, checksRun: 1, checksSkipped: POLICY_CHECK_IDS.length, findings: e.map(toJsonFinding), exitCode: e.length === 0 ? 0 : 1 }; } const i = policyCommandConfig(r.config); const a = { mode: "lint", runtime: { log(e) { process.stdout.write(terminalText`${String(e)}\n`); }, error(e) { defaultRuntime.error(terminalText`${String(e)}`); }, exit(e) { process.exitCode = e; } }, cfg: i, cwd: resolveAgentWorkspaceDir(i, resolvePolicyCommandAgentId(i, e.agent, t)), ...r.path !== void 0 ? { configPath: r.path } : {} }; const o = await evaluatePolicy(a); const s = o.findings.filter((e) => healthFindingMeetsSeverity(e, n)).map(toJsonFinding); const c = o.attestedFindings.map(toAttestedJsonFinding); const l = exitCodeFromFindings(o.findings, n); const u = createPolicyAttestation({ ok: o.attestedFindings.length === 0, checkedAt: (/* @__PURE__ */ new Date()).toISOString(), policyPath: o.policyPath, policyHash: o.policy?.hash, evidence: o.evidence, findings: c }); return { ok: l === 0, attestation: u, evidence: o.evidence, checksRun: POLICY_CHECK_IDS.length, checksSkipped: 0, findings: s, expectedAttestationHash: o.expectedAttestationHash, exitCode: l }; } function policyCommandConfig(e) { return { ...e, plugins: { ...e.plugins, entries: { ...e.plugins?.entries, policy: { ...e.plugins?.entries?.["policy"], enabled: true, config: { enabled: true, ...typeof e.plugins?.entries?.["policy"]?.config === "object" && e.plugins.entries["policy"].config !== null ? e.plugins.entries["policy"].config : {} } } } } }; } function resolvePolicyCommandAgentId(e, t, n) { const r = t?.trim(); if (t !== void 0 && !r) throw new Error("--agent must not be blank"); if (r) { const t = normalizeAgentId(r); if (!listAgentIdsCompatibility(e).includes(t)) throw new Error(`Unknown agent id "${r}". Run ${formatCliCommand("openclaw agents list")} to see configured agents.`); return t; } return resolveDefaultAgentId(e, { surface: n, hint: "Pass --agent <id>." }); } async function policyCompareCandidatePath(e) { if (e.policy !== void 0 && e.policy.trim() !== "") return e.policy; const t = await readConfigFileSnapshot({ observe: false }); if (!t.valid) return "policy.jsonc"; const n = t.config.plugins?.entries?.["policy"]?.config; const r = typeof n === "object" && n !== null && "path" in n ? n.path : void 0; const i = typeof r === "string" && r.trim() !== "" ? r.trim() : "policy.jsonc"; if (isAbsolute(i)) return i; const a = resolveAgentWorkspaceDir(t.config, resolvePolicyCommandAgentId(t.config, e.agent, "policy compare")); return resolve(a, i); } function writePolicyCheckReport(e, t) { if (t.json === true || !process.stdout.isTTY) process.stdout.write(JSON.stringify({ ok: e.ok, attestation: e.attestation, evidence: e.evidence, checksRun: e.checksRun, checksSkipped: e.checksSkipped, findings: e.findings }) + "\n"); else if (e.findings.length === 0) { const t = e.attestation?.policy?.hash ?? "missing"; const n = e.attestation?.workspace.hash ?? "unavailable"; process.stdout.write(terminalText`policy check: no findings (policy ${t}, evidence ${n})\n`); } else { process.stdout.write(terminalText`policy check: ${e.findings.length} finding(s)\n`); for (const t of e.findings) { const e = t.path !== void 0 ? ` ${t.path}` : ""; const n = t.line !== void 0 ? `:${t.line}` : ""; process.stdout.write(terminalText` [${t.severity}] ${t.checkId}${e}${n} - ${t.message}\n`); } } } function writePolicyConformanceReport(e, t) { if (t.json === true || !process.stdout.isTTY) { process.stdout.write(JSON.stringify(e) + "\n"); return; } if (e.findings.length === 0) { process.stdout.write(terminalText`policy compare: no findings (${e.policyPath} is at least as strict as ${e.baselinePath}; ${e.rulesChecked} rule(s) checked)\n`); return; } process.stdout.write(terminalText`policy compare: ${e.findings.length} finding(s) (${e.rulesChecked} rule(s) checked)\n`); for (const t of e.findings) process.stdout.write(terminalText` [${t.severity}] ${t.checkId} - ${t.message}\n`); } function writePolicyWatchReport(e, t, n) { if (n.json === true || !process.stdout.isTTY) { process.stdout.write(JSON.stringify({ status: t, ok: e.ok, expectedAttestationHash: e.expectedAttestationHash, attestation: e.attestation, findings: e.findings }) + "\n"); return; } if (t === "stale") { process.stdout.write(terminalText`policy watch: accepted attestation is stale (current ${e.attestation?.attestationHash}, expected ${e.expectedAttestationHash}). Review policy check output, then update the supervisor/gateway accepted attestation.\n`); return; } if (t === "findings") { process.stdout.write(terminalText`policy watch: ${e.findings.length} finding(s); accepted attestation cannot be updated until policy check is clean.\n`); return; } process.stdout.write(terminalText`policy watch: clean (attestation ${e.attestation?.attestationHash}, evidence ${e.attestation?.workspace.hash})\n`); } function policyWatchStatus(e) { if (!e.ok && e.findings.some((e) => e.checkId !== "policy/attestation-hash-mismatch")) return "findings"; const t = e.expectedAttestationHash?.trim(); if (t && e.attestation !== void 0 && e.attestation.attestationHash !== t) return "stale"; return e.ok ? "clean" : "findings"; } function normalizeWatchIntervalMs(e) { if (e === void 0) return 2e3; const t = typeof e === "number" ? e : /^\+?\d+$/.test(e.trim()) ? Number(e.trim()) : NaN; if (!Number.isSafeInteger(t) || t < 250) throw new Error("--interval-ms must be an integer >= 250."); return Math.min(t, MAX_TIMER_TIMEOUT_MS); } function toAttestedJsonFinding(e) { const { column: t, ...n } = toAttestedFinding(e); return n; } function toJsonFinding(e) { return { ...toAttestedJsonFinding(e), ...policyFindingMetadata(e) }; } function policyFindingMetadata(e) { const t = POLICY_FIX_METADATA_BY_CHECK_ID.get(e.checkId); if (t === void 0) return {}; return { policy: { fixRecommendation: { fixClass: t.fixClass, ...t.policyPath !== void 0 ? { policyPath: t.policyPath } : {}, ...t.configTargets !== void 0 ? { configTargets: t.configTargets } : {}, summary: t.summary } } }; } //#endregion export { registerPolicyCli };