UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

546 lines (545 loc) • 19.3 kB
import { t as isPlainObject } from "./plain-object-CGY5w7fM.mjs"; import { t as isBlockedObjectKey } from "./prototype-keys-CLGi5xDj.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { n as ConfigIncludeError, r as ConfigIncludeReadError } from "./includes-wjVi5Ymt.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import "./utils-C8YECn2Q.mjs"; import { t as sleep } from "./sleep-CkI3nkiJ.mjs"; import { S as resolveIsConfigReadOnly } from "./paths-DAcAg5aV.mjs"; import { c as shouldDeferShellEnvFallback, i as loadShellEnvFallback, l as shouldEnableShellEnvFallback, s as resolveShellEnvFallbackTimeoutMs } from "./shell-env-Dbjy7T84.mjs"; import { n as ok, t as err } from "./result-CV1-31DB.mjs"; import { u as getPluginMetadataSnapshotCache, w as withPluginCache } from "./plugin-cache-B_eRuqTM.mjs"; import { n as isArtifactPreservingStateRead } from "./artifact-preserving-state-reads-BfhmBr-V.mjs"; import { r as cloneEnvWithPlatformSemantics, t as applyConfigEnvVars } from "./config-env-vars-ByeGN-9N.mjs"; import { _ as withSynchronousArtifactPreservingStateSnapshot } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { g as setConfigResolutionFacts, i as copyConfigResolutionFacts } from "./resolution-facts-xaIKuREs.mjs"; import { r as loadInstalledPluginIndexInstallRecords } from "./installed-plugin-index-record-reader-B-7uGQZ9.mjs"; import { l as withPluginMetadataSnapshotScope } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs"; import { S as findDuplicateAgentDirs, b as attachAgentListProjection, x as DuplicateAgentDirError } from "./validation-core-1Fx8ByEb.mjs"; import { t as applyImplicitAgentRosterDefaults } from "./implicit-agent-roster-DtoGie9T.mjs"; import { r as formatConfigIssueSummary } from "./issue-format-WaYQX-7p.mjs"; import { s as isInvalidConfigError } from "./io.invalid-config-DK-BYZ4Y.mjs"; import { d as resolveConfigIncludesForRead, f as resolveConfigPathForDeps, o as normalizeConfigIoDeps, s as parseConfigJson5, t as coerceConfig, u as resolveConfigForRead } from "./io.read-helpers-qAcqsRC0.mjs"; import { t as createDedupeCache } from "./dedupe-DxT0h2gR.mjs"; import { b as createConfigFileWriteGuard, c as observeConfigSnapshotSync, i as withConfigWriteLock, s as observeConfigSnapshot, t as captureConfigWriteLockGuard, x as formatConfigArtifactTimestamp } from "./write-lock-Bg9nHsHM.mjs"; import { t as readExistingStateRootMode } from "./private-dir-mode-D4XRpa8Z.mjs"; import { i as unsetConfigValueAtPath, n as parseConfigPath, r as setConfigValueAtPath } from "./config-paths-DTAbnrwT.mjs"; import { i as resolveConfigWidePluginMetadataSnapshotAsync, r as resolveConfigWidePluginMetadataSnapshot } from "./io.plugin-metadata-CBwzHw3m.mjs"; import { t as resolveShellEnvExpectedKeys } from "./shell-env-expected-keys-BnJworuw.mjs"; import { a as validateConfigObjectWithPluginsAsync, i as validateConfigObjectWithPlugins } from "./validation-DSwgLhC7.mjs"; import { t as KeyedAsyncQueue } from "./keyed-async-queue-DewLnYvW.mjs"; import path from "node:path"; import { replaceFileAtomic } from "@openclaw/fs-safe/atomic"; //#region src/config/io.effects.ts function* resolveConfigIoEffect(e) { let t; yield { sync: () => { t = e.sync(); }, async: async () => { t = await e.async(); } }; return t; } function runConfigIoSync(e, t) { let n = e.next(); while (!n.done) try { t?.(); n.value.sync(); t?.(); n = e.next(); } catch (t) { n = e.throw(t); } return n.value; } async function runConfigIoAsync(e, t) { let n = e.next(); while (!n.done) try { t?.(); await n.value.async(); t?.(); n = e.next(); } catch (t) { n = e.throw(t); } return n.value; } //#endregion //#region src/config/runtime-overrides.ts let overrides = {}; function sanitizeOverrideValue(e, t = /* @__PURE__ */ new WeakSet()) { if (Array.isArray(e)) return e.map((e) => sanitizeOverrideValue(e, t)); if (!isPlainObject(e)) return e; if (t.has(e)) return {}; t.add(e); const n = {}; for (const [r, i] of Object.entries(e)) { if (i === void 0 || isBlockedObjectKey(r)) continue; n[r] = sanitizeOverrideValue(i, t); } t.delete(e); return n; } function mergeOverrides(e, t) { if (!isPlainObject(e) || !isPlainObject(t)) return t; const n = { ...e }; for (const [r, i] of Object.entries(t)) { if (i === void 0 || isBlockedObjectKey(r)) continue; n[r] = mergeOverrides(e[r], i); } return n; } function applyOverrideTree(e, t) { const n = mergeOverrides(e, t); if (n.agents === e.agents) return n; return attachAgentListProjection(n); } /** Return the process-local runtime override tree used by debug config commands. */ function getConfigOverrides() { return overrides; } /** Clear all process-local runtime overrides. Intended for debug reset flows and tests. */ function resetConfigOverrides() { overrides = {}; } /** Set one runtime override at a parsed config path after sanitizing object values. */ function setConfigOverride(e, t) { const n = parseConfigPath(e); if (!n.ok) return err(n.error); setConfigValueAtPath(overrides, n.path, sanitizeOverrideValue(t)); return ok(n.path); } /** Remove one runtime override path and report whether an override was present. */ function unsetConfigOverride(e) { const t = parseConfigPath(e); if (!t.ok) return err(t.error); return ok(unsetConfigValueAtPath(overrides, t.path)); } /** Merge the current runtime overrides over a loaded config without mutating the input config. */ function applyConfigOverrides(e) { if (Object.keys(overrides).length === 0) return e; return applyOverrideTree(e, overrides); } /** Capture an immutable applier for the process-local overrides active at this instant. */ function captureConfigOverrideApplier() { const e = structuredClone(overrides); if (Object.keys(e).length === 0) return (e) => e; return (t) => applyOverrideTree(t, e); } //#endregion //#region src/config/io.context.ts function createConfigIoContext(e = {}, t) { const n = normalizeConfigIoDeps(isArtifactPreservingStateRead("agent") ? { ...e, observe: false } : e); const r = resolveConfigPathForDeps(n); const i = { env: n.env, homedir: e.homedir }; function observeLoadConfigSnapshot(e) { if (n.observe) observeConfigSnapshotSync(n, e); return e; } async function observeLoadConfigSnapshotAsync(e, t) { if (n.observe) await observeConfigSnapshot(n, e, t); return e; } function shouldLoadShellEnv(t, n) { return (shouldEnableShellEnvFallback(n) || t.env?.shellEnv?.enabled === true) && e.shellEnvFallback !== "defer" && !shouldDeferShellEnvFallback(n); } async function finalizeLoadedRuntimeConfigAsync(e, t, r) { if (!t.getSnapshot()) { const r = cloneEnvWithPlatformSemantics(n.env); applyConfigEnvVars(e, r); if (shouldLoadShellEnv(e, r)) await t.loadAsync(e); } r?.(); const i = t.getSnapshot(); return i ? withPluginMetadataSnapshotScope(i, () => finalizeLoadedRuntimeConfig(e), { config: e, env: n.env }) : finalizeLoadedRuntimeConfig(e); } function finalizeLoadedRuntimeConfig(e) { const t = findDuplicateAgentDirs(e, i); if (t.length > 0) throw new DuplicateAgentDirError(t); applyConfigEnvVars(e, n.env); if (shouldLoadShellEnv(e, n.env)) loadShellEnvFallback({ env: n.env, expectedKeys: resolveShellEnvExpectedKeys(n.env, e), logger: n.logger, timeoutMs: e.env?.shellEnv?.timeoutMs ?? resolveShellEnvFallbackTimeoutMs(n.env) }); const r = applyConfigOverrides(e); copyConfigResolutionFacts(e, r); return r; } function createValidationPluginMetadataSnapshotLoader(e) { let t; let n; return { load: (n) => { t ??= resolveConfigWidePluginMetadataSnapshot({ config: n, env: e.env, allowCurrent: e.allowCurrentPluginMetadata }); return { manifestRegistry: t.manifestRegistry }; }, loadAsync: (r) => n ??= (async () => { t ??= await resolveConfigWidePluginMetadataSnapshotAsync({ config: r, env: e.env, allowCurrent: e.allowCurrentPluginMetadata }); const n = await withPluginCache(getPluginMetadataSnapshotCache(t), () => loadInstalledPluginIndexInstallRecords({ env: e.env })).catch(() => ({})); return { manifestRegistry: t.manifestRegistry, installedPluginRecordIds: new Set(Object.keys(n)) }; })(), getSnapshot: () => t }; } function resolveRuntimePreflightSourceConfig(e, t, i, a = n.env) { const o = cloneEnvWithPlatformSemantics(a); const s = resolveConfigIncludesForRead(e, r, { ...n, env: o }, t, i); const c = resolveConfigForRead(s, o, n.lowerPrecedenceEnv); const l = coerceConfig(applyImplicitAgentRosterDefaults(c.resolvedConfigRaw)); setConfigResolutionFacts(l, c.resolutionFacts); return l; } function* prepareRecoveryBackupCandidateSteps(a) { try { const o = cloneEnvWithPlatformSemantics(n.env); const s = []; const c = resolveConfigIncludesForRead(a.parsed, r, { ...n, env: o }, void 0, void 0, void 0, (e) => { const { value: t, ...n } = e; s.push(n); }); const l = resolveConfigForRead(c, o, n.lowerPrecedenceEnv); const prepareValidation = () => { const o = e.deferredPluginMigrations; const c = t ? t({ candidate: a, configPath: r, includeProvenance: s, resolvedConfig: l.resolvedConfigRaw, deferredPluginMigrations: o ?? [] }) : a.parsed; const u = cloneEnvWithPlatformSemantics(n.env); const d = resolveConfigIncludesForRead(c, r, { ...n, env: u }); return { authoredCandidate: c, effectiveConfigRaw: resolveConfigForRead(d, u, n.lowerPrecedenceEnv).resolvedConfigRaw, pluginMetadata: createValidationPluginMetadataSnapshotLoader({ env: u }), validationOptions: { ...i, env: u, pluginValidation: e.pluginValidation, sourceRaw: c, preservedLegacyRootKeys: e.preservedLegacyRootKeys, deferredPluginMigrations: o } }; }; const { authoredCandidate: u, validated: d } = yield* resolveConfigIoEffect({ sync: () => withSynchronousArtifactPreservingStateSnapshot(() => { const e = prepareValidation(); return { authoredCandidate: e.authoredCandidate, validated: validateConfigObjectWithPlugins(e.effectiveConfigRaw, { ...e.validationOptions, loadPluginMetadataSnapshot: e.pluginMetadata.load }) }; }), async: async () => { const e = prepareValidation(); return { authoredCandidate: e.authoredCandidate, validated: await validateConfigObjectWithPluginsAsync(e.effectiveConfigRaw, { ...e.validationOptions, loadPluginMetadataSnapshotAsync: e.pluginMetadata.loadAsync }) }; } }); if (!d.ok) { const e = formatConfigIssueSummary(d.issues.slice(0, 3)) ?? ""; const t = e.length > 800 ? `${e.slice(0, 799)}…` : e; return { ok: false, reason: `candidate is not valid current config${t ? `: ${t}` : ""}` }; } return { ok: true, candidate: { config: d.config, parsed: u, raw: u !== a.parsed ? JSON.stringify(u, null, 2).trimEnd().concat("\n") : a.raw } }; } catch (e) { if (e instanceof ConfigIncludeReadError || !(e instanceof ConfigIncludeError || isInvalidConfigError(e))) throw e; return { ok: false, reason: `candidate preparation failed: ${e.message}` }; } } return { deps: n, pathResolution: i, configPath: r, options: e, ...t ? { transformRecoveryCandidate: t } : {}, observeLoadConfigSnapshot, observeLoadConfigSnapshotAsync, finalizeLoadedRuntimeConfig, finalizeLoadedRuntimeConfigAsync, createValidationPluginMetadataSnapshotLoader, resolveRuntimePreflightSourceConfig, prepareRecoveryBackupCandidate: (e) => runConfigIoSync(prepareRecoveryBackupCandidateSteps(e)), prepareRecoveryBackupCandidateAsync: async (e) => await runConfigIoAsync(prepareRecoveryBackupCandidateSteps(e)) }; } //#endregion //#region src/config/io.clobber-snapshot.ts const CONFIG_CLOBBER_SNAPSHOT_LIMIT = 32; const CONFIG_CLOBBER_LOCK_STALE_MS = 3e4; const CONFIG_CLOBBER_LOCK_RETRY_MS = 10; const CONFIG_CLOBBER_LOCK_TIMEOUT_MS = 2e3; const clobberSnapshotQueue = new KeyedAsyncQueue(); const clobberCapWarnedPaths = createDedupeCache({ ttlMs: 0, maxSize: 4096 }); function isFsErrorCode(e, t) { return e instanceof Error && hasErrnoCode(e, t); } function resolveClobberPaths(e) { const t = path.dirname(e); const n = path.basename(e); return { dir: t, prefix: `${n}.clobbered.`, lockPath: path.join(t, `${n}.clobber.lock`) }; } function shouldRemoveStaleLock(e, t) { return typeof e === "number" && t - e > CONFIG_CLOBBER_LOCK_STALE_MS; } async function acquireClobberLock(e, t) { const n = Date.now(); while (Date.now() - n < CONFIG_CLOBBER_LOCK_TIMEOUT_MS) try { await e.fs.promises.mkdir(t, { mode: 448 }); return true; } catch (n) { if (!isFsErrorCode(n, "EEXIST")) return false; if (shouldRemoveStaleLock((await e.fs.promises.stat(t).catch(() => null))?.mtimeMs, Date.now())) { await e.fs.promises.rmdir(t).catch(() => {}); continue; } await sleep(CONFIG_CLOBBER_LOCK_RETRY_MS); } return false; } function acquireClobberLockSync(e, t) { for (let n = 0; n < 2; n++) try { e.fs.mkdirSync(t, { mode: 448 }); return true; } catch (n) { if (!isFsErrorCode(n, "EEXIST")) return false; if (!shouldRemoveStaleLock(e.fs.statSync(t, { throwIfNoEntry: false })?.mtimeMs, Date.now())) return false; try { e.fs.rmdirSync(t); } catch { return false; } } return false; } function* listClobberedSiblings(e, t, n) { try { const r = yield* resolveConfigIoEffect({ sync: () => e.fs.readdirSync(t), async: () => e.fs.promises.readdir(t) }); const i = []; for (const a of r) { if (!a.startsWith(n)) continue; const r = path.join(t, a); const o = yield* resolveConfigIoEffect({ sync: () => e.fs.statSync(r, { throwIfNoEntry: false }), async: () => e.fs.promises.stat(r).catch(() => null) }); i.push({ name: a, path: r, timestampKey: a.slice(n.length).replace(/-\d{2}$/, ""), mtimeMs: o?.mtimeMs ?? 0 }); } return i.toSorted((e, t) => e.timestampKey.localeCompare(t.timestampKey) || e.mtimeMs - t.mtimeMs || e.name.localeCompare(t.name)); } catch { return []; } } function* persistClobberedConfigSnapshot(e, t) { const { deps: n } = e; const r = yield* listClobberedSiblings(n, t.dir, t.prefix); if (r.length >= CONFIG_CLOBBER_SNAPSHOT_LIMIT) { if (!clobberCapWarnedPaths.check(e.configPath)) n.logger.warn(`Config clobber snapshot cap reached for ${e.configPath}: ${r.length} existing .clobbered.* files; rotating oldest snapshots to preserve the latest forensic copy.`); const t = r.length - CONFIG_CLOBBER_SNAPSHOT_LIMIT + 1; for (const e of r.slice(0, t)) try { yield* resolveConfigIoEffect({ sync: () => n.fs.unlinkSync(e.path), async: () => n.fs.promises.unlink(e.path) }); } catch (e) { if (!isFsErrorCode(e, "ENOENT")) return null; } } const i = `${e.configPath}.clobbered.${formatConfigArtifactTimestamp(e.observedAt)}`; for (let t = 0; t < CONFIG_CLOBBER_SNAPSHOT_LIMIT; t++) { const r = t === 0 ? i : `${i}-${String(t).padStart(2, "0")}`; const a = { encoding: "utf-8", mode: 384, flag: "wx" }; try { yield* resolveConfigIoEffect({ sync: () => n.fs.writeFileSync(r, e.raw, a), async: () => n.fs.promises.writeFile(r, e.raw, a) }); return r; } catch (e) { if (!isFsErrorCode(e, "EEXIST")) return null; } } return null; } async function persistBoundedClobberedConfigSnapshot(e) { const t = resolveClobberPaths(e.configPath); return await clobberSnapshotQueue.enqueue(t.lockPath, async () => { if (!await acquireClobberLock(e.deps, t.lockPath)) return null; try { return await runConfigIoAsync(persistClobberedConfigSnapshot(e, t)); } finally { await e.deps.fs.promises.rmdir(t.lockPath).catch(() => {}); } }); } function persistBoundedClobberedConfigSnapshotSync(e) { const t = resolveClobberPaths(e.configPath); if (!acquireClobberLockSync(e.deps, t.lockPath)) return null; try { return runConfigIoSync(persistClobberedConfigSnapshot(e, t)); } finally { try { e.deps.fs.rmdirSync(t.lockPath); } catch {} } } //#endregion //#region src/config/io.recovery.ts function findJsonRootSuffix(e) { if (/^\s*(?:\{|\[)/.test(e)) return null; let t = 0; while (t < e.length) { const n = e.indexOf("\n", t); const r = n === -1 ? e.length : n + 1; const i = e.slice(t, r); if (/^\s*(?:\{|\[)/.test(i)) { const n = e.slice(t); const r = parseConfigJson5(n); return r.ok ? { raw: n, parsed: r.parsed } : null; } t = r; } return null; } function inspectConfigJsonRootSuffixWithContext(e, t, n) { const r = findJsonRootSuffix(t); if (!r) return null; n?.(r.parsed); let i; try { i = resolveConfigIncludesForRead(r.parsed, e.configPath, e.deps); } catch { return null; } const a = resolveConfigForRead(i, e.deps.env, e.deps.lowerPrecedenceEnv); n?.(a.resolvedConfigRaw); return { ...r, resolvedConfigRaw: a.resolvedConfigRaw }; } async function recoverConfigFromJsonRootSuffixWithContext(e, t, n) { if (resolveIsConfigReadOnly(e.deps.env)) return false; if (!t.exists || t.valid || typeof t.raw !== "string") return false; const r = t.raw; return withConfigWriteLock(e.configPath, () => recoverConfigJsonRootSuffixUnderLock(e, t, r, n), e.deps.env); } async function recoverConfigJsonRootSuffixUnderLock(e, t, n, r) { const i = inspectConfigJsonRootSuffixWithContext(e, n, r); if (!i) return false; if (!validateConfigObjectWithPlugins(i.resolvedConfigRaw, { ...e.pathResolution, pluginValidation: e.options.pluginValidation, sourceRaw: i.parsed }).ok) return false; const a = createConfigFileWriteGuard(e.configPath, e.deps.fs, captureConfigWriteLockGuard(e.configPath), { snapshot: t, includeGraph: { hashes: {}, targets: {} } }); a.assertBeforeMutation(); const o = await persistBoundedClobberedConfigSnapshot({ deps: e.deps, configPath: e.configPath, raw: n, observedAt: (/* @__PURE__ */ new Date()).toISOString() }); if (o === null) { e.deps.logger.warn(`Config prefix recovery deferred: ${e.configPath}; original config snapshot could not be saved. Retry recovery.`); return false; } await replaceFileAtomic({ filePath: e.configPath, content: i.raw, dirMode: readExistingStateRootMode(path.dirname(e.configPath), resolveStateDir(e.deps.env, e.deps.homedir), e.deps.fs) ?? 448, mode: 384, tempPrefix: path.basename(e.configPath), fileSystem: a.fileSystem, assertBeforeMutation: a.assertBeforeMutation, onDestinationState: a.onDestinationState }); e.deps.logger.warn(`Config auto-stripped non-JSON prefix: ${e.configPath} (original saved as ${o})`); return true; } //#endregion export { createConfigIoContext as a, getConfigOverrides as c, unsetConfigOverride as d, resolveConfigIoEffect as f, persistBoundedClobberedConfigSnapshotSync as i, resetConfigOverrides as l, runConfigIoSync as m, recoverConfigFromJsonRootSuffixWithContext as n, applyConfigOverrides as o, runConfigIoAsync as p, persistBoundedClobberedConfigSnapshot as r, captureConfigOverrideApplier as s, inspectConfigJsonRootSuffixWithContext as t, setConfigOverride as u };