UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

429 lines (428 loc) • 16.9 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { g as normalizeUniqueStringEntries } from "./string-normalization-DLmfYZXI.mjs"; import { n as formatConcreteConfigPath } from "./dot-path-BJ4tyWKJ.mjs"; import { _ as resolveSecretInputRef } from "./types.secrets-BmNLLnHp.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { a as copyConfigResolutionFactsExcept, n as cloneConfigWithResolutionFacts, p as resolveConfigSecretRef } from "./resolution-facts-xaIKuREs.mjs"; import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs"; import { na as validateSecretsResolveResult } from "./src-BX8OAe1J.mjs"; import { i as resolveManifestContractOwnerPluginId } from "./plugin-registry-contributions-iAw3gSDD.mjs"; import { a as createResolverContext, p as assertExpectedResolvedSecretValue } from "./runtime-shared-BVJ4BbUu.mjs"; import { i as setPathExistingStrict, n as getPath } from "./path-utils-A4pcYa4R.mjs"; import { r as discoverConfigSecretTargetsByIds } from "./target-registry-query-le6rMGHo.mjs"; import "./target-registry-C0PdHjLu.mjs"; import { n as resolveSecretRefValue } from "./resolve-BYfGhigB.mjs"; import { o as readGatewaySecretInputValue, t as ALL_GATEWAY_SECRET_INPUT_PATHS } from "./secret-input-paths-k_sABTwS.mjs"; import { t as gatewaySecretInputPathCanWin } from "./credentials-secret-inputs-BBRl7DaH.mjs"; import { t as bindAgentToolGatewayRequest } from "./in-process-gateway-Cy0xoBmg.mjs"; import { t as analyzeCommandSecretAssignmentsFromSnapshot } from "./command-config-RZeCunsN.mjs"; import { t as collectConfigAssignments } from "./runtime-config-collectors-CtT_L4hE.mjs"; import { t as resolveRuntimeWebTools } from "./runtime-web-tools-B_FvzJZ-.mjs"; //#region src/cli/command-secret-gateway.ts function classifyRuntimeWebTarget(e) { const t = /^plugins\.entries\.([^.]+)\.config\.(webSearch|webFetch)\.apiKey$/.exec(e.path); if (!t) return { state: "unknown" }; const n = t[2] === "webFetch" ? "fetch" : "search"; const r = e.config.tools?.web?.[n]; if (r?.enabled === false) return { state: "inactive", detail: `tools.web.${n} is disabled.` }; const i = normalizeLowercaseStringOrEmpty(r?.provider); if (!i) return { state: "active" }; const a = resolveManifestContractOwnerPluginId({ contract: n === "fetch" ? "webFetchProviders" : "webSearchProviders", value: i, origin: "bundled", config: e.config }); if (!a) return { state: "unknown" }; return a === t[1] ? { state: "active" } : { state: "inactive", detail: `tools.web.${n}.provider is "${i}".` }; } function targetsRuntimeWebPath(e) { return e.startsWith("plugins.entries."); } function inactiveSurfaceDiagnosticPath(e) { const t = e.indexOf(": secret ref is configured on an inactive surface;"); return t > 0 ? e.slice(0, t).trim() : void 0; } function isAllowedPathsSecretsResolveCompatError(e) { const t = normalizeLowercaseStringOrEmpty(formatErrorMessage(e)); if (!t.includes("secrets.resolve")) return false; return t.includes("invalid request") || t.includes("invalid secrets.resolve params"); } function collectActiveGatewayExecSecretRefCredentialPaths(e) { const t = e.secrets?.defaults; return ALL_GATEWAY_SECRET_INPUT_PATHS.filter((n) => { const { ref: r } = resolveSecretInputRef({ value: readGatewaySecretInputValue(e, n), defaults: t }); return r?.source === "exec" && gatewaySecretInputPathCanWin({ config: e, path: n, env: process.env }); }); } async function callGatewaySecretsResolve(e) { const t = bindAgentToolGatewayRequest({ hostedOnly: true }); const n = { config: e.config, method: "secrets.resolve", requiredMethods: ["secrets.resolve"], params: { commandName: e.commandName, targetIds: [...e.targetIds], ...e.allowedPaths ? { allowedPaths: [...e.allowedPaths] } : {}, ...e.forcedActivePaths ? { forcedActivePaths: [...e.forcedActivePaths] } : {}, ...e.optionalActivePaths ? { optionalActivePaths: [...e.optionalActivePaths] } : {} }, timeoutMs: e.gatewaySecretResolveTimeoutMs ?? 3e4, clientName: GATEWAY_CLIENT_NAMES.CLI, mode: GATEWAY_CLIENT_MODES.CLI }; try { return await t(n); } catch (r) { if (!e.allowedPaths && !e.forcedActivePaths && !e.optionalActivePaths || Boolean(e.forcedActivePaths?.size) || !isAllowedPathsSecretsResolveCompatError(r)) throw r; return t({ ...n, params: { commandName: e.commandName, targetIds: [...e.targetIds] } }); } } async function resolveCommandSecretRefsLocally(e) { const t = e.config; const n = cloneConfigWithResolutionFacts(e.config); const r = createResolverContext({ sourceConfig: t, env: process.env }); const i = []; const a = discoverConfigSecretTargetsByIds(t, e.targetIds).filter((t) => !e.allowedPaths || e.allowedPaths.has(t.path)); const o = a.filter((e) => targetsRuntimeWebPath(e.path)); await collectConfigAssignments({ config: cloneConfigWithResolutionFacts(e.config), context: r, agentId: e.agentId }); if ([...e.allowedPaths ?? e.targetIds].some(targetsRuntimeWebPath) && !o.every((e) => /^plugins\.entries\.[^.]+\.config\.(webSearch|webFetch)\.apiKey$/.test(e.path))) try { await resolveRuntimeWebTools({ sourceConfig: t, resolvedConfig: n, context: r }); } catch (t) { if (e.enforceResolved) throw t; i.push(`${e.commandName}: failed to resolve web tool secrets locally (${formatErrorMessage(t)}).`); } const s = r.warnings.filter((t) => t.code === "SECRETS_REF_IGNORED_INACTIVE_SURFACE" && (!e.allowedPaths || e.allowedPaths.has(t.path)) && !e.forcedActivePaths?.has(t.path) && !e.optionalActivePaths?.has(t.path)); const c = new Set(s.map((e) => e.path)); const l = /* @__PURE__ */ new Set(); const u = []; for (const n of o) { if (e.forcedActivePaths?.has(n.path) || e.optionalActivePaths?.has(n.path)) { l.add(n.path); continue; } const r = classifyRuntimeWebTarget({ config: t, path: n.path }); if (r.state === "inactive") { c.add(n.path); if (r.detail) u.push(`${n.path}: ${r.detail}`); continue; } if (r.state === "active") l.add(n.path); } const d = new Set(r.assignments.map((e) => e.path)); for (const o of a) { const a = t.secrets?.defaults; const { ref: s } = resolveSecretInputRef({ value: resolveConfigSecretRef({ config: t, path: o.path, value: o.value, defaults: a }), refValue: o.refValue, defaults: a }); if (!s || c.has(o.path) || !d.has(o.path) && !l.has(o.path) && !e.forcedActivePaths?.has(o.path) && !e.optionalActivePaths?.has(o.path)) continue; if (s.source === "exec" && !e.resolutionPolicy.allowExecSecretRefs) { if (!e.enforceResolved) i.push(`${e.commandName}: skipped local exec SecretRef resolution for ${o.path}; rerun with --allow-exec to execute configured exec providers.`); continue; } try { const e = await resolveSecretRefValue(s, { config: t, env: r.env, cache: r.cache }); assertExpectedResolvedSecretValue({ value: e, expected: o.entry.expectedResolvedValue, errorMessage: o.entry.expectedResolvedValue === "string" ? `${o.path} resolved to a non-string or empty value.` : `${o.path} resolved to an unsupported value type.` }); setPathExistingStrict(n, o.pathSegments, e); copyConfigResolutionFactsExcept(n, n, [o.path]); } catch (t) { if (!e.enforceResolved) i.push(`${e.commandName}: failed to resolve ${o.path} locally (${formatErrorMessage(t)}).`); } } const f = analyzeCommandSecretTargets({ sourceConfig: t, resolvedConfig: n, targetIds: e.targetIds, inactiveRefPaths: c, allowedPaths: e.allowedPaths, optionalActivePaths: e.optionalActivePaths }); const p = buildTargetStatesByPath({ analyzed: f, resolvedState: "resolved_local" }); const m = handleUnresolvedAssignments(e, n, f.unresolved); return { resolvedConfig: n, diagnostics: normalizeUniqueStringEntries([ ...e.preflightDiagnostics, ...u, ...s.map((e) => e.message), ...filterInactiveSurfaceDiagnostics({ diagnostics: f.diagnostics, inactiveRefPaths: c }), ...i, ...m ]), targetStatesByPath: p, hadUnresolvedTargets: f.unresolved.length > 0 }; } function analyzeCommandSecretTargets(e) { const { optionalActivePaths: t, ...n } = e; const r = analyzeCommandSecretAssignmentsFromSnapshot(n); const i = r.unresolved.filter((e) => t?.has(e.path)); if (i.length === 0) return r; for (const { path: e } of i) n.inactiveRefPaths.add(e); return analyzeCommandSecretAssignmentsFromSnapshot(n); } function buildTargetStatesByPath(e) { const t = {}; for (const n of e.analyzed.assignments) t[n.path] = e.resolvedState; for (const n of e.analyzed.inactive) t[n.path] = "inactive_surface"; for (const n of e.analyzed.unresolved) t[n.path] = "unresolved"; return t; } function handleUnresolvedAssignments(e, t, n) { if (n.length > 0 && e.enforceResolved) throw new Error(`${e.commandName}: ${n[0]?.path ?? "target"} is unresolved in the active runtime snapshot.`); if (e.resolutionPolicy.scrubUnresolvedSecretRefs) for (const e of n) setPathExistingStrict(t, e.pathSegments, void 0); return n.map((t) => `${e.commandName}: ${t.path} is unavailable in this command path; continuing with degraded read-only config.`); } function filterInactiveSurfaceDiagnostics(e) { return e.diagnostics.filter((t) => { const n = inactiveSurfaceDiagnosticPath(t); return n === void 0 || !e.inactiveRefPaths.has(n); }); } async function resolveCommandSecretRefsViaGateway(e) { const t = !e.mode || e.mode === "enforce_resolved" || e.mode === "strict"; const n = { allowExecSecretRefs: e.allowLocalExecSecretRefs !== false, scrubUnresolvedSecretRefs: e.scrubUnresolvedSecretRefs !== false }; const r = { ...e, enforceResolved: t, resolutionPolicy: n }; const i = e.config.secrets?.defaults; const a = /* @__PURE__ */ new Set(); for (const t of discoverConfigSecretTargetsByIds(e.config, e.targetIds)) { if (e.allowedPaths && !e.allowedPaths.has(t.path)) continue; const { ref: n } = resolveSecretInputRef({ value: resolveConfigSecretRef({ config: e.config, path: t.path, value: t.value, defaults: i }), refValue: t.refValue, defaults: i }); if (n) a.add(t.path); } let o = { needsResolution: false, diagnostics: [] }; if (a.size > 0) { const t = { ...e, configuredTargetRefPaths: a }; const n = createResolverContext({ sourceConfig: t.config, env: process.env }); await collectConfigAssignments({ config: cloneConfigWithResolutionFacts(t.config), context: n, agentId: t.agentId }); const r = new Set(n.assignments.map((e) => e.path)); const i = /* @__PURE__ */ new Map(); for (const e of n.warnings) { if (e.code !== "SECRETS_REF_IGNORED_INACTIVE_SURFACE") continue; i.set(e.path, e.message); } const s = /* @__PURE__ */ new Set(); let c = false; for (const e of t.configuredTargetRefPaths) { const n = !r.has(e) && !t.forcedActivePaths?.has(e) && !t.optionalActivePaths?.has(e) ? i.get(e) : void 0; if (n) s.add(n); else c = true; } o = { needsResolution: c, diagnostics: [...s] }; } if (!o.needsResolution) return { resolvedConfig: e.config, diagnostics: o.diagnostics, targetStatesByPath: {}, hadUnresolvedTargets: false }; const resolveLocally = (t = e.allowedPaths, n = o.diagnostics) => resolveCommandSecretRefsLocally({ ...r, preflightDiagnostics: n, allowedPaths: t }); const s = n.allowExecSecretRefs ? [] : collectActiveGatewayExecSecretRefCredentialPaths(e.config); if (s.length > 0) { const t = await resolveLocally(); return { ...t, diagnostics: normalizeUniqueStringEntries([...t.diagnostics, `${e.commandName}: skipped gateway secrets.resolve because gateway credentials use exec SecretRefs at ${s.join(", ")}; rerun with --allow-exec to execute configured exec providers.`]) }; } let c; try { c = await callGatewaySecretsResolve(e); } catch (t) { const n = Boolean(e.forcedActivePaths?.size) && isAllowedPathsSecretsResolveCompatError(t); let r = "Local resolution also failed."; try { const r = await resolveLocally(); const i = Object.values(r.targetStatesByPath).some((e) => e === "resolved_local"); if (!n || i && !r.hadUnresolvedTargets) { const n = i && !r.hadUnresolvedTargets ? "resolved command secrets locally." : "attempted local command-secret resolution."; return { ...r, diagnostics: normalizeUniqueStringEntries([...r.diagnostics, `${e.commandName}: gateway secrets.resolve unavailable (${formatErrorMessage(t)}); ${n}`]) }; } } catch (e) { r = `Local resolution also failed (${formatErrorMessage(e)}).`; } if (n) throw new Error(`${e.commandName}: active gateway does not support command-scoped secret resolution (${formatErrorMessage(t)}). Update the gateway or run this command where the configured SecretRefs can be resolved locally.`, { cause: t }); const i = normalizeLowercaseStringOrEmpty(formatErrorMessage(t)); if (i.includes("secrets.resolve") && (i.includes("does not support required method") || i.includes("unknown method") || i.includes("method not found") || i.includes("invalid request"))) throw new Error(`${e.commandName}: active gateway does not support secrets.resolve (${formatErrorMessage(t)}). Update the gateway or run without SecretRefs.`, { cause: t }); throw new Error(`${e.commandName}: failed to resolve secrets from the active gateway snapshot (${formatErrorMessage(t)}). ${r} Check the configured secret sources and gateway access, then retry.`, { cause: t }); } if (!validateSecretsResolveResult(c)) throw new Error("gateway returned invalid secrets.resolve payload."); const l = { assignments: c.assignments ?? [], diagnostics: (c.diagnostics ?? []).filter((e) => e.trim().length > 0), inactiveRefPaths: (c.inactiveRefPaths ?? []).filter((e) => e.trim().length > 0) }; const u = { ...e, diagnostics: l.diagnostics }; const d = u.diagnostics.filter((e) => { const t = e.indexOf(":"); if (t <= 0) return true; const n = e.slice(0, t).trim(); if (!n.includes(".")) return true; if (u.forcedActivePaths?.has(n) || u.optionalActivePaths?.has(n)) return false; return !u.allowedPaths || u.allowedPaths.has(n); }); const f = e.allowedPaths ? l.inactiveRefPaths.filter((t) => e.allowedPaths?.has(t)) : l.inactiveRefPaths; const p = cloneConfigWithResolutionFacts(e.config); const m = []; for (const { pathSegments: t, value: n } of l.assignments) { if (t.length === 0) continue; const r = formatConcreteConfigPath(t, p); if (e.allowedPaths && !e.allowedPaths.has(r)) continue; try { setPathExistingStrict(p, t, n); m.push(r); } catch (t) { throw new Error(`${e.commandName}: failed to apply resolved secret assignment at ${r} (${formatErrorMessage(t)}).`, { cause: t }); } } copyConfigResolutionFactsExcept(p, p, m); const h = new Set(f.length > 0 ? f : d.flatMap((e) => { const t = inactiveSurfaceDiagnosticPath(e); return t ? [t] : []; })); for (const t of e.forcedActivePaths ?? []) h.delete(t); for (const t of e.optionalActivePaths ?? []) h.delete(t); const g = analyzeCommandSecretTargets({ sourceConfig: e.config, resolvedConfig: p, targetIds: e.targetIds, inactiveRefPaths: h, allowedPaths: e.allowedPaths, optionalActivePaths: e.optionalActivePaths }); let _ = normalizeUniqueStringEntries(d); const v = buildTargetStatesByPath({ analyzed: g, resolvedState: "resolved_gateway" }); if (g.unresolved.length > 0) try { const t = await resolveLocally(new Set(g.unresolved.map((e) => e.path)), []); const n = /* @__PURE__ */ new Set(); for (const e of g.unresolved) { const r = t.targetStatesByPath[e.path]; if (r !== "resolved_local" && r !== "inactive_surface") continue; if (r === "resolved_local") { setPathExistingStrict(p, e.pathSegments, getPath(t.resolvedConfig, e.pathSegments)); n.add(e.path); } v[e.path] = r; } copyConfigResolutionFactsExcept(p, p, [...n]); _ = normalizeUniqueStringEntries([..._, ...t.diagnostics]); const i = g.unresolved.filter((e) => v[e.path] === "unresolved"); if (i.length > 0) _ = normalizeUniqueStringEntries([..._, ...handleUnresolvedAssignments(r, p, i)]); else if (n.size > 0) _ = normalizeUniqueStringEntries([..._, `${e.commandName}: resolved ${n.size} secret ${n.size === 1 ? "path" : "paths"} locally after the gateway snapshot was incomplete.`]); } catch (n) { if (t) throw n; _ = normalizeUniqueStringEntries([ ..._, `${e.commandName}: local fallback after incomplete gateway snapshot failed (${formatErrorMessage(n)}).`, ...handleUnresolvedAssignments(r, p, g.unresolved) ]); } return { resolvedConfig: p, diagnostics: _, targetStatesByPath: v, hadUnresolvedTargets: Object.values(v).includes("unresolved") }; } //#endregion export { resolveCommandSecretRefsViaGateway as t };