UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

500 lines (499 loc) • 21.3 kB
import { s as isVitestRuntimeEnv } from "./env-HehwidXj.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as ok, t as err } from "./result-CV1-31DB.mjs"; import { t as isVerbose } from "./global-state-DXCtmsFO.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { o as createConfigRuntimeEnvBase, r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import { g as setConfigResolutionFacts } from "./resolution-facts-xaIKuREs.mjs"; import { n as formatConfigIssueLines } from "./issue-format-WaYQX-7p.mjs"; import { n as createMergePatch, t as applyMergePatch } from "./merge-patch-D-7aajuy.mjs"; import { n as projectLegacyWorkboardWrite, t as normalizeLegacyWorkboardDatabaseConfig } from "./legacy-workboard-database-C5tBV8hg.mjs"; import { a as hashConfigRevision, h as restoreAuthoredTildePathsForWrite, i as hashConfigRaw, m as resolveGatewayMode, n as containsConfigIncludeDirective, r as hasConfigMeta, u as resolveConfigForRead } from "./io.read-helpers-qAcqsRC0.mjs"; import { S as upsertConfigSnapshotAuditRecordAsync, _ as configSnapshotAuditRecordMatchesPath, a as capConfigAuditIssues, b as readLatestConfigSnapshotAuditRecordAsync, d as finalizeConfigWriteAuditRecord, f as formatConfigOverwriteLogMessage, i as appendConfigAuditRecord, l as createConfigWriteAuditRecordBase, o as capConfigAuditPaths, v as fingerprintConfigSnapshotAuthoredConfig, x as restoreConfigSnapshotAuditRecordAsync } from "./io.audit-Bump5vFv.mjs"; import { C as resolveConfigStatMetadata, D as rollbackConfigFileWriteIfUnchanged, E as resolveConfigWriteSuspiciousReasons, N as restoreLoggedConfigWarningFingerprint, S as resolveConfigSizeBaselineBytes, T as resolveConfigWriteDirectory, _ as captureConfigRootWriteTarget, a as advanceConfigHealthBaselineForAcceptedWrite, b as createConfigFileWriteGuard, j as loggedConfigWarningFingerprints, l as restoreConfigHealthBaselineForRolledBackWrite, m as assertBaseSnapshotStillCurrent, o as captureConfigHealthBaselineForWrite, t as captureConfigWriteLockGuard, w as resolveConfigWriteBlockingReasons, x as formatConfigArtifactTimestamp } from "./write-lock-Bg9nHsHM.mjs"; import { t as readExistingStateRootMode } from "./private-dir-mode-D4XRpa8Z.mjs"; import { m as preflightRuntimeSnapshotWrite } from "./runtime-snapshot-WbwbY5b7.mjs"; import { a as resolveConfigWriteStateSelection, i as recordConfigWriteMetadata, o as stampConfigWriteMetadata, r as projectWebhookMigrationIncludeWrite, s as withConfigWriteState } from "./io.meta-BrkFioo1.mjs"; import { i as mergeConfigWriteOptions, t as bindConfigWriteLockGuard } from "./write-authority-l37tp55r.mjs"; import { h as withDeferredPluginMigrationsCurrent, m as withDeferredPluginConfigRollback } from "./deferred-plugin-migrations-C_CU0aKR.mjs"; import { a as preserveDeferredPluginMigrationConfig, c as setDeferredPluginMigrationConfigFacts, l as applyUnsetPathsForWrite, o as readConfigWriteMigrationFacts, u as resolveManagedUnsetPathsForWrite } from "./deferred-plugin-migration-config-B3TJC-SY.mjs"; import { r as validateConfigObjectRawWithPlugins } from "./validation-DSwgLhC7.mjs"; import { r as initializeNativeSessionCatalogPreferences } from "./native-session-catalog-config-CCzXMHUi.mjs"; import { r as warnIfJSON5CommentsWillBeStripped, t as logConfigWarningsOnce } from "./io.warnings-BbJvBO5E.mjs"; import { m as getUpdateDoctorConfigWriteAuthority, s as assertUpdateDoctorConfigInputHash, v as recordUpdateDoctorConfigWrite } from "./update-doctor-result-DwaI51On.mjs"; import { r as assertConfigWriteAllowedInCurrentMode } from "./config-write-guard-CxNxfJ_I.mjs"; import { n as configWriteCommittedSnapshot, r as configWritePostCommitRollback, t as ConfigRuntimeRefreshError } from "./io.types-tZoWfCaZ.mjs"; import { i as createConfigWriteSafetyRejectionError, r as createConfigValidationFailedError, t as ConfigWritePostCommitError } from "./io.write-errors-CuPAqPbq.mjs"; import { i as resolveKeyedAgentEntryIncludePreservation } from "./include-write-boundary-Dpj_7ftL.mjs"; import { a as resolvePersistCandidateForWrite, t as injectExplicitlySetPaths } from "./io.write-prepare-B19yEmrf.mjs"; import { n as prepareConfigFileWrite } from "./backup-rotation-DIugSdzV.mjs"; import { t as rejectConfigNonFiniteNumbers } from "./value-tree-Deh4eoFD.mjs"; import { n as assertAgentDeletionTargetsUnchanged } from "./agent-workspace-roster-transition-B9fDuucP.mjs"; import { o as resolveCronJobsStorePathFromConfigAsync } from "./paths-CY4cvrR6.mjs"; import { t as prepareConfigWriteTopology } from "./io.write-topology-B__9tFVE.mjs"; import "./store-DaG-8LOU.mjs"; import { n as collectConfigWriteChangedPaths, t as collectChangedPaths } from "./config-change-paths-ZDrHUVSI.mjs"; import { i as prepareCronOwnerWriteRefusal, t as canDeferRehearsalCronMigration } from "./io.cron-owner-refusal-D4hqLyjp.mjs"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; //#region src/config/io.write-preflight.ts function preflightConfigRuntimeWrite(e, t, n) { return preflightRuntimeSnapshotWrite({ nextSourceConfig: t, refreshOptions: n, formatRefreshError: (e) => formatErrorMessage(e), createRefreshError: (t, n) => new ConfigRuntimeRefreshError(`Config write blocked before committing ${e}: active SecretRef resolution failed: ${t}`, { cause: n }) }); } //#endregion //#region src/config/io.write-rejected.ts /** * Reject a blocked write: persist the rejected payload, audit, and throw. * * The rejected payload is saved with an exclusive create next to the config so * operators can inspect the exact bytes that were refused; the write audit * records the rejection before the caller-visible error propagates. */ async function rejectConfigWriteForBlockingReasons(e) { const { deps: t, configPath: n, json: r, blockingReasons: i } = e; if (i.length === 0 || e.allowDestructiveWrite === true) return; const a = `${n}.rejected.${formatConfigArtifactTimestamp((/* @__PURE__ */ new Date()).toISOString())}`; e.assertConfigPathForWrite?.(); const o = await t.fs.promises.writeFile(a, r, { encoding: "utf-8", mode: 384, flag: "wx" }).then(ok, err); const s = o.ok ? `Rejected payload saved to ${a}.` : `Rejected payload could not be saved to ${a}: ${formatErrorMessage(o.error)}.`; const c = `Config write rejected: ${n} (${i.join(", ")}). ${s}`; const l = Object.assign(new Error(c), { code: "CONFIG_WRITE_REJECTED", ...o.ok ? { rejectedPath: a } : {}, reasons: i }); const u = createConfigWriteSafetyRejectionError({ reasons: i, ...o.ok ? { rejectedPath: a } : {} }); t.logger.warn(c); await e.appendWriteAudit("rejected", l); throw u; } //#endregion //#region src/config/io.write.ts async function writeConfigFileFromContext(e, t, n, r) { const { deps: i, configPath: a, options: o } = e; const s = captureConfigWriteLockGuard(a); const c = getUpdateDoctorConfigWriteAuthority(a); let l = bindConfigWriteLockGuard(n, s); const u = l.databaseAccess !== "none"; l.assertConfigPathForWrite?.(); assertConfigWriteAllowedInCurrentMode({ configPath: a, env: i.env }); const { path: d, pathProof: f } = captureConfigRootWriteTarget(a, i.fs); l = mergeConfigWriteOptions(l, { assertConfigPathForWrite: f.assertCurrent }); const p = resolveManagedUnsetPathsForWrite(l.unsetPaths); const m = l.baseSnapshot ? { snapshot: l.baseSnapshot, pluginMetadataSnapshot: l.basePluginMetadataSnapshot } : await r(); const h = m.snapshot; const g = u ? await readConfigWriteMigrationFacts(h, i.env, o) : void 0; const _ = preserveDeferredPluginMigrationConfig({ sourceConfig: h.sourceConfig, nextConfig: normalizeLegacyWorkboardDatabaseConfig(t, i.env), pending: g ?? [], writeOptions: l }); if (c) { s?.(); assertUpdateDoctorConfigInputHash(a, hashConfigRaw(h.raw)); l = { ...l, baseSnapshot: h }; } if (l.baseSnapshot) assertBaseSnapshotStillCurrent(h, a, i.fs); const { nextConfig: ee, clearedSessionStoreOwner: te, authoredConfig: v, authoredSourceConfig: y, authoredRuntimeConfig: b, explicitSetPaths: x, explicitSetValueSource: ne, persistCanonicalAgentRoster: re, preserveLegacyAgentRoster: ie, cronOwner: S } = await prepareConfigWriteTopology({ ...m, nextConfig: _, options: l, unsetPaths: p, env: i.env, lowerPrecedenceEnv: i.lowerPrecedenceEnv, homedir: i.homedir }); const C = { kind: l.inputBase ?? "runtime", config: l.inputBase === "source" ? y : b }; const ae = h.sourceConfigBeforeMigrations ?? h.sourceConfig; const oe = S && !await canDeferRehearsalCronMigration(ae, a, i.env) ? await prepareCronOwnerWriteRefusal(h.config, { storePath: await resolveCronJobsStorePathFromConfigAsync(ee, i.env), ...S, env: i.env }) : void 0; let w = v; const T = collectConfigWriteChangedPaths(C.config, v, [...x, ...l.unsetPaths ?? []]); const E = containsConfigIncludeDirective(h.parsed); const D = projectLegacyWorkboardWrite(h, _, i.env); if (h.valid || h.exists && E) { const e = E ? projectWebhookMigrationIncludeWrite(y, v) : void 0; const t = resolveKeyedAgentEntryIncludePreservation({ configPath: h.path, provenance: h.includeProvenance }); w = resolvePersistCandidateForWrite({ inputBasis: C, runtimeConfig: b, sourceConfig: y, sourceConfigValid: h.valid, sourceConfigBeforeMigrations: h.sourceConfigBeforeMigrations, nextConfig: e?.config ?? v, rootAuthoredConfig: D, agentRosterIncludeOwned: h.agentRosterIncludeOwned, keyedAgentEntryIncludePaths: t?.includePaths, unsetPaths: p, explicitSetPaths: x.filter((t) => !e?.paths.some((e) => isDeepStrictEqual(e, t))), explicitSetValueSource: ne, persistCanonicalAgentRoster: re, allowedAgentRosterRemovals: l.allowedAgentRosterRemovals, allowIncludeAncestorExplicitSetPaths: l.allowIncludeAncestorExplicitSetPaths, preserveLegacyAgentRoster: ie }); if (e) w = injectExplicitlySetPaths({ valueSource: v, persistedCandidate: w, runtimeConfig: b, sourceConfig: y, rootAuthoredConfig: D, explicitSetPaths: e.paths, allowIncludeAncestorExplicitSetPaths: true }); } const O = createConfigRuntimeEnvBase(h.sourceConfigBeforeMigrations ?? h.sourceConfig, i.env); const resolveValidationCandidate = (t) => { const n = applyUnsetPathsForWrite(t, p); if (containsConfigIncludeDirective(n)) return e.resolveRuntimePreflightSourceConfig(n, void 0, void 0, O); const r = resolveConfigForRead(n, cloneEnvWithPlatformSemantics(O), i.lowerPrecedenceEnv); setConfigResolutionFacts(r.resolvedConfigRaw, r.resolutionFacts); return r.resolvedConfigRaw; }; const k = resolveValidationCandidate(w); const validateCandidate = (t) => { const n = validateConfigObjectRawWithPlugins(t, { ...e.pathResolution, pluginValidation: l.skipPluginValidation ? "skip" : "full", semanticValidation: "strict", preservedLegacyRootKeys: l.preservedLegacyRootKeys, deferredPluginMigrations: g }); if (!n.ok) throw createConfigValidationFailedError(n.issues); return n; }; validateCandidate(k); const A = k; const se = h.authoredConfig ?? h.sourceConfigBeforeMigrations ?? h.sourceConfig; const ce = stampConfigWriteMetadata(h.exists ? A : initializeNativeSessionCatalogPreferences(A), l.lastTouchedVersionOverride, h.exists ? se : null, i.env); w = applyMergePatch(w, createMergePatch(k, ce)); const j = validateCandidate(resolveValidationCandidate(w)); const M = loggedConfigWarningFingerprints.get(a); l.assertConfigPathForWrite?.(); let N = u ? await resolveConfigWriteStateSelection(h.sourceConfig, i.env) : void 0; const P = await withConfigWriteState(N, () => readLatestConfigSnapshotAuditRecordAsync(i, l.assertConfigPathForWrite)); l.assertConfigPathForWrite?.(); await i.fs.promises.mkdir(path.dirname(a), { recursive: true, mode: 448 }); const le = restoreAuthoredTildePathsForWrite(w, h.parsed, void 0, i.homedir()); const F = stampConfigWriteMetadata(preserveDeferredPluginMigrationConfig({ sourceConfig: h.parsed, nextConfig: applyUnsetPathsForWrite(le, p), pending: g ?? [], writeOptions: { unsetPaths: l.unsetPaths } }), l.lastTouchedVersionOverride, void 0, i.env); rejectConfigNonFiniteNumbers(F); const I = JSON.stringify(F, null, 2).trimEnd().concat("\n"); const L = hashConfigRaw(I); const R = hashConfigRaw(h.raw); const ue = typeof h.raw === "string" ? Buffer.byteLength(h.raw, "utf-8") : null; const z = resolveConfigSizeBaselineBytes({ raw: h.raw, lastTouchedVersionOverride: l.lastTouchedVersionOverride, env: i.env }); const B = Buffer.byteLength(I, "utf-8"); const V = h.exists ? await i.fs.promises.stat(a).catch(() => null) : null; const H = hasConfigMeta(h.parsed); const U = resolveGatewayMode(h.resolved); const W = {}; const G = {}; const K = e.resolveRuntimePreflightSourceConfig(JSON.parse(I), W, G, O); const de = hashConfigRevision(I, W, G); const q = resolveGatewayMode(K); const J = resolveConfigWriteSuspiciousReasons({ existsBefore: h.exists, unreadableBefore: h.readError != null, sizeBaselineBytes: z, nextBytes: B, hasMetaBefore: H, gatewayModeBefore: U, gatewayModeAfter: q }); const readTestLogFlag = (e) => isVitestRuntimeEnv(i.env) && i.env[e] === "1"; const logConfigOverwrite = () => { const e = readTestLogFlag("OPENCLAW_TEST_CONFIG_WRITE_LOG"); if (!h.exists || l.skipOutputLogs || isVitestRuntimeEnv(i.env) && !e) return; if (!isVerbose() && i.env.OPENCLAW_CONFIG_OVERWRITE_LOG !== "1" && !e) return; i.logger.warn(formatConfigOverwriteLogMessage({ configPath: a, previousHash: R ?? null, nextHash: L, changedPathCount: T.size })); }; const logConfigWriteAnomalies = () => { const e = readTestLogFlag("OPENCLAW_TEST_CONFIG_WRITE_LOG"); if (J.length === 0 || l.skipOutputLogs || isVitestRuntimeEnv(i.env) && !e) return; const t = isVerbose() || i.env.OPENCLAW_CONFIG_WRITE_ANOMALY_LOG === "1" || e ? J : J.filter((e) => e !== "missing-meta-before-write"); if (t.length > 0) i.logger.warn(`Config write anomaly: ${a} (${t.join(", ")})`); }; const fe = createConfigWriteAuditRecordBase({ configPath: a, env: i.env, existsBefore: h.exists, previousHash: R ?? null, nextHash: L, previousBytes: ue, nextBytes: B, previousMetadata: resolveConfigStatMetadata(V), changedPathCount: T.size, changedPaths: [...T], origin: l.auditOrigin, hasMetaBefore: H, hasMetaAfter: hasConfigMeta(F), gatewayModeBefore: U, gatewayModeAfter: q, suspicious: J }); const appendWriteAudit = async (e, t, n) => { l.assertConfigPathForWrite?.(); await withConfigWriteState(N, () => appendConfigAuditRecord({ ...i, record: finalizeConfigWriteAuditRecord({ base: fe, result: e, err: t, nextMetadata: resolveConfigStatMetadata(n ?? null) }) })); }; const Y = resolveConfigWriteBlockingReasons(J, l); await rejectConfigWriteForBlockingReasons({ deps: i, configPath: a, json: I, blockingReasons: Y, allowDestructiveWrite: l.allowDestructiveWrite, assertConfigPathForWrite: l.assertConfigPathForWrite, appendWriteAudit }); if (l.preCommitRuntimePreflight) await l.preCommitRuntimePreflight(K); else await preflightConfigRuntimeWrite(a, K, l.runtimeRefresh); const X = { phase: "unpublished" }; let restoreFile; let Z = "not-restored"; const Q = resolveConfigWriteDirectory(a, d, i); try { try { var $ = _usingCtx(); if (l.baseSnapshot) assertBaseSnapshotStillCurrent(h, a, i.fs); l.assertConfigPathForWrite?.(); await oe?.recheck(); l.assertConfigPathForWrite?.(); warnIfJSON5CommentsWillBeStripped({ raw: h.raw, filePath: a, warn: (e) => i.logger.warn(e), skipOutputLogs: l.skipOutputLogs }); const e = { ...h, path: d }; const t = createConfigFileWriteGuard(d, i.fs, l.assertConfigPathForWrite, { snapshot: e, stateDirectory: Q, targetPathProof: f, includeGraph: { hashes: W, targets: G }, validateUtf8: l.allowDestructiveWrite !== true, onRootRemoved: () => { X.phase = "removed"; }, onRootPublished: () => { X.phase = "published"; } }); restoreFile = (n) => rollbackConfigFileWriteIfUnchanged({ configPath: d, previousSnapshot: e, committedHash: X.phase === "removed" ? hashConfigRaw(null) : L, fsModule: i.fs, stateDirectory: Q, ...t.captureRollbackProof(n), withPublication: (e, t) => u ? withDeferredPluginConfigRollback({ configPath: a, env: i.env, assertCurrent: n }, e, t) : e() }); const n = $.a(await prepareConfigFileWrite({ configPath: d, dirMode: readExistingStateRootMode(path.dirname(d), Q.path, i.fs), content: I, previousRaw: h.raw, warn: (e) => l.skipOutputLogs ? void 0 : i.logger.warn(e), fsModule: t.fileSystem, assertCurrent: t.assertCurrent, assertBeforeMutation: t.assertBeforeMutation, onDestinationState: t.onDestinationState })); await assertAgentDeletionTargetsUnchanged(h.config, K, i.env); await l.beforeCommit?.(); const r = u ? await captureConfigHealthBaselineForWrite(i, a) : null; const publish = () => { l.assertBeforePublish?.(); const e = n.publish(); X.phase = "published"; return e; }; const o = u ? withDeferredPluginMigrationsCurrent({ env: i.env, configPath: a, expectedPending: g }, publish) : publish(); l.assertConfigPathForWrite?.(); X.phase = "accepted"; recordUpdateDoctorConfigWrite(a, R, L, h.parsed, I); const s = u ? await resolveConfigWriteStateSelection(K, i.env) : void 0; N = s; l.assertConfigPathForWrite?.(); await recordConfigWriteMetadata(i, s); logConfigOverwrite(); logConfigWriteAnomalies(); await appendWriteAudit(o.method, void 0, await i.fs.promises.stat(a).catch(() => null)); const c = await withConfigWriteState(s, () => advanceConfigHealthBaselineForAcceptedWrite(i, r, { sourceSnapshot: h, raw: I, parsed: F, resolved: K })); l.assertConfigPathForWrite?.(); if (s?.ok && configSnapshotAuditRecordMatchesPath(P, a) && P.rawHash !== R) { const e = /* @__PURE__ */ new Set(); collectChangedPaths(P.fingerprintedAuthoredConfig, await fingerprintConfigSnapshotAuthoredConfig(h.parsed, i), "", e); await withConfigWriteState(s, () => appendConfigAuditRecord({ ...i, record: { ts: (/* @__PURE__ */ new Date()).toISOString(), source: "config-io", event: "config.external", detectedBy: "write", configPath: a, previousHash: P.rawHash, nextHash: R ?? null, valid: h.valid, ...h.valid ? e.size > 0 ? { changedPaths: capConfigAuditPaths([...e]) } : { opaqueChange: true } : { issues: capConfigAuditIssues(formatConfigIssueLines(h.issues, "", { normalizeRoot: true })) } } })); } l.assertConfigPathForWrite?.(); const p = await withConfigWriteState(s, () => upsertConfigSnapshotAuditRecordAsync({ ...i, configPath: a, rawHash: L, authoredConfig: F, expectedSnapshot: P }, l.assertConfigPathForWrite)); l.assertConfigPathForWrite?.(); if (!l.skipPluginValidation) logConfigWarningsOnce({ configPath: a, warnings: j.warnings, logger: i.logger }); if (te && !l.skipOutputLogs) i.logger.warn("Cleared agents.defaults.sessionStore.agentId because session.store changed. Set that owner path explicitly to assign the destination store's owner."); setDeferredPluginMigrationConfigFacts(K, g); return { persistedHash: L, persistedConfig: F, persistedSourceConfig: K, [configWriteCommittedSnapshot]: { hash: de, sourceConfig: K }, [configWritePostCommitRollback]: { restoreFile, restoreEffects: async (e) => { e(); await withConfigWriteState(s, () => restoreConfigSnapshotAuditRecordAsync({ ...i, snapshot: P, expectedSnapshot: p }, e)); e(); restoreLoggedConfigWarningFingerprint(a, M); await withConfigWriteState(s, () => restoreConfigHealthBaselineForRolledBackWrite(i, c)); } } }; } catch (e) { $.e = e; } finally { await $.d(); } } catch (e) { let t = e; if (restoreFile && (X.phase === "removed" || X.phase === "published")) try { Z = await restoreFile(() => s?.()) ? "restored" : "not-restored"; } catch (n) { Z = "unknown"; t = new AggregateError([e, n], `${formatErrorMessage(e)} Recovery failed: ${formatErrorMessage(n)}`); } try { try { s?.(); } catch (t) { if (t === e) throw e; throw new AggregateError([e, t], `Config write failed after source ownership changed: ${formatErrorMessage(e)}`, { cause: t }); } try { n.assertConfigPathForWrite?.(); f.assertCurrent(); } catch { throw e; } try { await appendWriteAudit("failed", e); } catch (t) { throw new AggregateError([e, t], `${formatErrorMessage(e)} Failure auditing failed: ${formatErrorMessage(t)}`, { cause: t }); } } catch (e) { t = e; } if (X.phase === "unpublished") throw t; throw new ConfigWritePostCommitError({ configPath: a, rollbackStatus: Z, cause: t, publication: X.phase === "removed" ? "partial" : "complete" }); } } //#endregion export { writeConfigFileFromContext as t };