UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,279 lines (1,278 loc) • 45.2 kB
import { i as collectNestedErrorCandidates } from "./error-coercion-hDrHOSGy.mjs"; import { n as ignoreMissingPath, t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { r as resolvePathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs"; import { n as ConfigIncludeError, r as ConfigIncludeReadError } from "./includes-wjVi5Ymt.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { S as resolveIsConfigReadOnly } from "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { w as root } from "./fs-safe-BbWvmdVn.mjs"; import { a as getProcessGatewayPluginMetadataSnapshot } from "./current-plugin-metadata-state-BmYo9Q7A.mjs"; import { n as OpenClawStateOwnershipError } from "./sqlite-lifecycle-errors-D8BU4VLa.mjs"; import { u as isSqliteSchemaMismatchError } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import { r as findStartupMaintenanceRequiredError } from "./startup-maintenance-required-DEn4Krys.mjs"; import { r as withArtifactPreservingStateReads } from "./artifact-preserving-state-reads-BfhmBr-V.mjs"; import { f as restoreEnvChangesIfUnchanged, n as captureConfigReadEnvMutation, o as createConfigRuntimeEnvBase, p as snapshotEnv, r as cloneEnvWithPlatformSemantics, s as getPublishedConfigRuntimeEnvState } from "./config-env-vars-ByeGN-9N.mjs"; import { _ as withSynchronousArtifactPreservingStateSnapshot } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { g as setConfigResolutionFacts } from "./resolution-facts-xaIKuREs.mjs"; import { o as preparePluginMetadataMachineStateAsync } from "./installed-plugin-index-record-state-euCqi7PU.mjs"; import { l as withPluginMetadataSnapshotScope } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs"; import { S as findDuplicateAgentDirs, d as materializeRuntimeConfig, l as asResolvedSourceConfig, p as hasAnthropicDefaultSignal, u as asRuntimeConfig, x as DuplicateAgentDirError } from "./validation-core-1Fx8ByEb.mjs"; import { t as applyImplicitAgentRosterDefaults } from "./implicit-agent-roster-DtoGie9T.mjs"; import { a as createConfigIoContext, f as resolveConfigIoEffect, i as persistBoundedClobberedConfigSnapshotSync, m as runConfigIoSync, n as recoverConfigFromJsonRootSuffixWithContext, p as runConfigIoAsync, r as persistBoundedClobberedConfigSnapshot } from "./io.recovery-BpeT7cx2.mjs"; import { r as formatConfigIssueSummary } from "./issue-format-WaYQX-7p.mjs"; import { a as isConfigReadFailure, c as throwInvalidConfig, n as createConfigReadError } from "./io.invalid-config-DK-BYZ4Y.mjs"; import { a as hashConfigRevision, c as readConfigFileIfPresent, d as resolveConfigIncludesForRead, f as resolveConfigPathForDeps, i as hashConfigRaw, m as resolveGatewayMode, n as containsConfigIncludeDirective, s as parseConfigJson5, t as coerceConfig, u as resolveConfigForRead } from "./io.read-helpers-qAcqsRC0.mjs"; import { c as createConfigObserveAuditRecord, s as captureConfigAuditAppender, u as enqueueConfigAuditRecord } from "./io.audit-Bump5vFv.mjs"; import { A as readConfigHealthStateFromStore, M as loggedInvalidConfigs, O as captureConfigHealthStateStore, d as createConfigHealthFingerprint, f as extractRestoreErrorDetails, g as captureConfigFileWritePathProof, i as withConfigWriteLock, j as loggedConfigWarningFingerprints, k as patchConfigHealthEntryToStore, p as readConfigHealthEntry, s as observeConfigSnapshot, t as captureConfigWriteLockGuard, u as resolveConfigObserveSuspiciousReasons, v as chmodConfigBestEffort, y as chmodConfigBestEffortSync } from "./write-lock-Bg9nHsHM.mjs"; import { t as readExistingStateRootMode } from "./private-dir-mode-D4XRpa8Z.mjs"; import { c as getRuntimeConfigSourceSnapshot } from "./runtime-snapshot-WbwbY5b7.mjs"; import { t as ConfigMutationConflictError } from "./mutation-conflict-Bs0nsNWn.mjs"; import { n as composeConfigWriteAssertions, r as createConfigWriteAuthorityGuard } from "./write-authority-l37tp55r.mjs"; import { c as setDeferredPluginMigrationConfigFacts, u as resolveManagedUnsetPathsForWrite } from "./deferred-plugin-migration-config-B3TJC-SY.mjs"; import { r as resolveDirectBundledProviderPolicySurface } from "./provider-policy-surface-BZUMxVkz.mjs"; import { a as validateConfigObjectWithPluginsAsync, i as validateConfigObjectWithPlugins, o as validateConfigObjectWithStrictFactsAsync } from "./validation-DSwgLhC7.mjs"; import { n as loadDotEnvAsync, t as loadDotEnv } from "./dotenv-qUrr6GRR.mjs"; import { n as warnIfConfigFromFuture, r as warnIfJSON5CommentsWillBeStripped, t as logConfigWarningsOnce } from "./io.warnings-BbJvBO5E.mjs"; import { i as shouldAttemptLastKnownGoodRecovery, n as isPluginLocalInvalidConfigSnapshot, t as collectPollutedSecretPlaceholders } from "./recovery-policy-CixJJb9O.mjs"; import { t as GATEWAY_CONFIG_SELECTION_ENV_KEYS } from "./gateway-env-selection-yOcr26em.mjs"; import { a as includeContributionOwnsBindings, i as includeContributionOwnsAgentRoster } from "./agent-roster-provenance-DiT1dDed.mjs"; import path from "node:path"; import { isMainThread } from "node:worker_threads"; import JSON5 from "json5"; import { replaceFileAtomic, replaceFileAtomicSync } from "@openclaw/fs-safe/atomic"; //#region src/config/io.observe-recovery-effects.ts async function commitConfigRecoveryFile(e) { await e.write(() => { e.beforeCommit?.(); e.health.assertCurrent(); }); } /** Recheck original external bytes at mutation, not process-local observation order. */ function createConfigRecoverySourceGuard(e, t, n = false) { return () => { for (const [r, i, a] of t) { const t = createConfigBackupReadEffect(e, r).sync(); const o = createConfigRecoveryStatEffect(e, r, n).sync(); if (t !== i || n && (!o || !a) || o && a && (o.dev !== a.dev || o.ino !== a.ino || o.mtimeMs !== a.mtimeMs || o.size !== a.size)) throw new ConfigMutationConflictError("config recovery source changed since preparation", { retryable: false }); } }; } function createConfigRecoveryStatEffect(e, t, n = false) { const unavailable = (e) => { if (n && !hasErrnoCode(e, "ENOENT")) throw e; return null; }; return { sync: () => { try { return e.fs.statSync(t, { throwIfNoEntry: false }) ?? null; } catch (e) { return unavailable(e); } }, async: () => e.fs.promises.stat(t).catch(unavailable) }; } function createConfigBackupMissingEffect(e, t) { return { sync: () => { try { e.fs.statSync(t); return false; } catch (e) { return hasErrnoCode(e, "ENOENT"); } }, async: () => e.fs.promises.stat(t).then(() => false, (e) => hasErrnoCode(e, "ENOENT")) }; } function createConfigBackupReadEffect(e, t) { const unavailable = (e) => { ignoreMissingPath(e); return null; }; return { sync: () => { try { return e.fs.readFileSync(t, "utf-8"); } catch (e) { return unavailable(e); } }, async: () => e.fs.promises.readFile(t, "utf-8").catch(unavailable) }; } //#endregion //#region src/config/io.observe-recovery.ts function createRecoveryCommitEffect(e) { const t = { filePath: e.configPath, content: e.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: e.deps.fs }; return { sync: () => { e.beforeCommit?.(); replaceFileAtomicSync(t); }, async: (n) => commitConfigRecoveryFile({ health: n, beforeCommit: e.beforeCommit, write: (n) => replaceFileAtomic({ ...t, copyFallbackOnPermissionError: false, fileSystem: { promises: { ...e.deps.fs.promises, rename: (t, r) => { n(); return e.deps.fs.promises.rename(t, r); } } } }) }) }; } function parseBackupConfigRaw(e) { try { return { parsed: JSON5.parse(e) }; } catch { return null; } } async function maybeRecoverSuspiciousConfigRead(e) { const t = captureConfigHealthStateStore(e.deps, e.configPath, e.assertCurrent); return await runConfigRecoveryAsync(recoverSuspiciousConfigRead(e), t, captureConfigAuditAppender(e.deps, e.assertCurrent), e.assertCurrent); } async function runConfigRecoveryAsync(e, t, n, r) { r?.(); let i = e.next(); while (!i.done) try { r?.(); const a = await i.value.async(t, n); r?.(); i = e.next(a); } catch (n) { r?.(); try { t.assertCurrent(); } catch { throw n; } i = e.throw(n); } return i.value; } function maybeRecoverSuspiciousConfigReadSync(e) { const t = recoverSuspiciousConfigRead(e); let n = t.next(); while (!n.done) try { n = t.next(n.value.sync()); } catch (e) { n = t.throw(e); } return n.value; } /** Prepare the existing recovery without observing or writing the selected config. */ async function prepareSuspiciousConfigRead(e) { const t = captureConfigHealthStateStore(e.deps, e.configPath, e.assertCurrent); const n = captureConfigAuditAppender(e.deps, e.assertCurrent); const r = await runConfigRecoveryAsync(planSuspiciousConfigRead(e, true), t, n); return r && { candidate: r.candidate, apply: async (e) => { const i = await runConfigRecoveryAsync(r.apply(e), t, n); if (!i.restored) throw i.error; } }; } function* recoverSuspiciousConfigRead(e) { const { raw: t, parsed: n } = e; const r = yield* planSuspiciousConfigRead(e); if (!r) return { raw: t, parsed: n }; if (e.allowBackupRecovery) { if (!(yield { sync: () => true, async: () => e.allowBackupRecovery?.() ?? true })) return { raw: t, parsed: n }; } return (yield* r.apply()).error instanceof ConfigMutationConflictError ? { raw: t, parsed: n } : r.candidate; } function* planSuspiciousConfigRead(e, t = false) { const { deps: n, configPath: r, raw: i, parsed: a } = e; if (resolveIsConfigReadOnly(n.env)) return null; const o = `${r}.bak`; const s = e.intent === "doctor-repair"; const c = yield createConfigBackupMissingEffect(n, o); if (c && !s) return null; const l = yield createConfigRecoveryStatEffect(n, r, t); const u = (/* @__PURE__ */ new Date()).toISOString(); const d = createConfigHealthFingerprint({ raw: i, parsed: a, stat: l, observedAt: u }); const f = yield { sync: () => ({ state: readConfigHealthStateFromStore(n), basis: null }), async: (t) => e.measure ? e.measure("config.recovery.health-read", () => t.read()) : t.read() }; const p = readConfigHealthEntry(f.state, r); let m = null; if (!p.lastKnownGood && !c) m = yield createConfigBackupReadEffect(n, o); const h = p.lastKnownGood ?? (m ? createConfigHealthFingerprint({ raw: m, parsed: parseBackupConfigRaw(m)?.parsed ?? {}, stat: null }) : void 0); const g = resolveConfigObserveSuspiciousReasons({ ...d, parsed: a, lastObservedSuspiciousSignature: p.lastObservedSuspiciousSignature, lastKnownGood: h }); const _ = `${d.hash}:${g.join(",")}`; if (g.length === 0 || !s && p.lastObservedSuspiciousSignature === _) return null; const v = `${r}.last-good`; const y = [...!c ? [o] : [], ...s && p.lastPromotedGood?.hash ? [v] : []]; let b; for (const t of y) { const r = (t === o ? m : null) ?? (yield createConfigBackupReadEffect(n, t)); if (!r) continue; const i = parseBackupConfigRaw(r); if (!i) continue; const a = hashConfigRaw(r); const c = a === p.lastKnownGood?.hash || a === p.lastPromotedGood?.hash; const l = t === v; if (l) { if (a !== p.lastPromotedGood?.hash) continue; } else if (!resolveGatewayMode(i.parsed) || s && p.lastKnownGood && !c) continue; const u = { raw: r, parsed: i.parsed }; const d = yield { sync: () => e.prepareBackup(u), async: () => e.prepareBackupAsync?.(u) ?? e.prepareBackup(u) }; if (!d.ok || l && collectPollutedSecretPlaceholders(d.candidate.parsed).length > 0) continue; b = { path: t, original: u, prepared: d.candidate }; break; } if (!b) return null; const { path: x, original: S, prepared: C } = b; const w = S.raw; const T = yield createConfigRecoveryStatEffect(n, x, t); const E = createConfigHealthFingerprint({ raw: w, parsed: S.parsed, stat: T }); const D = x === v ? { lastKnownGood: p.lastPromotedGood, lastObservedSuspiciousSignature: null } : { lastObservedSuspiciousSignature: _ }; const O = createConfigRecoverySourceGuard(n, [[ r, i, l ], [ x, w, T ]], t); return { candidate: C, *apply(e) { const t = { deps: n, configPath: r, raw: i, observedAt: u }; const a = yield { sync: () => { e?.(); O(); return persistBoundedClobberedConfigSnapshotSync(t); }, async: (n) => { e?.(); O(); n.assertCurrent(); return persistBoundedClobberedConfigSnapshot(t); } }; if (a === null) { const e = /* @__PURE__ */ new Error(`Config backup recovery deferred: ${r}; original config snapshot could not be saved. Retry recovery.`); n.logger.warn(e.message); return { restored: false, error: e }; } let o = false; let s; try { if (C.raw !== w) warnIfJSON5CommentsWillBeStripped({ raw: w, filePath: r, warn: (e) => n.logger.warn(e) }); yield createRecoveryCommitEffect({ deps: n, configPath: r, raw: C.raw, beforeCommit: () => { e?.(); O(); } }); const t = { deps: n, configPath: r, context: "backup restore" }; yield { sync: () => chmodConfigBestEffortSync(t), async: () => chmodConfigBestEffort(t) }; o = true; } catch (e) { s = e; } const c = o ? { code: null, message: null } : extractRestoreErrorDetails(s); const l = o ? "auto-restored from backup" : "auto-restore from backup failed"; const m = !o && c.message ? `; ${c.message}` : ""; n.logger.warn(`Config ${l}: ${r} (${g.join(", ")}${m}). Original config kept at ${a}; to undo, stop the Gateway and copy it back to ${r} after correcting the reported problem.`); const h = { env: n.env, homedir: n.homedir, record: createConfigObserveAuditRecord({ configPath: r, valid: o, current: d, suspicious: g, lastKnownGood: p.lastKnownGood, backup: E, clobberedPath: a, restoredFromBackup: o, restoredBackupPath: x, restoreErrorCode: c.code, restoreErrorMessage: c.message }) }; yield { sync: () => enqueueConfigAuditRecord(h), async: (e, t) => t(h.record) }; if (o) yield { sync: () => patchConfigHealthEntryToStore(n, r, D), async: (e) => e.updateAfterFileCommit(D, f) }; return { restored: o, error: s }; } }; } /** True lets recovery callers reread the changed file even if newer health facts win. */ async function recoverConfigFromLastKnownGoodCore(e) { const { deps: t, snapshot: n } = e; if (resolveIsConfigReadOnly(t.env)) return false; if (!n.exists || typeof n.raw !== "string") return false; if (!shouldAttemptLastKnownGoodRecovery(n)) { if (isPluginLocalInvalidConfigSnapshot(n)) t.logger.warn(`Config last-known-good recovery skipped: invalidity is scoped to stale plugin config (${e.reason})`); return false; } const r = captureConfigHealthStateStore(t, n.path); const i = captureConfigAuditAppender(t); const a = await r.read(); const o = readConfigHealthEntry(a.state, n.path).lastPromotedGood; if (!o?.hash) return false; const s = `${n.path}.last-good`; const c = await t.fs.promises.readFile(s, "utf-8").catch(() => null); if (!c || hashConfigRaw(c) !== o.hash) return false; const l = await t.fs.promises.stat(s).catch(() => null); const u = parseBackupConfigRaw(c); if (!u) return false; const d = { raw: c, parsed: u.parsed }; const f = e.prepareCandidate(d); if (!f.ok) { t.logger.warn(`Config last-known-good recovery skipped: ${f.reason} (${e.reason})`); return false; } const p = f.candidate; const m = collectPollutedSecretPlaceholders(p.parsed); if (m.length > 0) { t.logger.warn(`Config last-known-good recovery skipped: redacted secret placeholder at ${m[0]}`); return false; } const h = (/* @__PURE__ */ new Date()).toISOString(); const g = await t.fs.promises.stat(n.path).catch(() => null); const _ = createConfigHealthFingerprint({ raw: n.raw, parsed: n.parsed, resolved: n.resolved, stat: g, observedAt: h }); const v = createConfigRecoverySourceGuard(t, [[ n.path, n.raw, g ], [ s, c, l ]]); v(); r.assertCurrent(); const y = await persistBoundedClobberedConfigSnapshot({ deps: t, configPath: n.path, raw: n.raw, observedAt: h }); r.assertCurrent(); if (y === null) { t.logger.warn(`Config last-known-good recovery deferred: ${n.path}; original config snapshot could not be saved. Retry recovery.`); return false; } if (p.raw !== c) warnIfJSON5CommentsWillBeStripped({ raw: c, filePath: n.path, warn: (e) => t.logger.warn(e) }); await createRecoveryCommitEffect({ deps: t, configPath: n.path, raw: p.raw, beforeCommit: v }).async(r, i); await chmodConfigBestEffort({ deps: t, configPath: n.path, context: "last-known-good recovery" }); const b = formatConfigIssueSummary([...n.issues, ...n.legacyIssues]); t.logger.warn(`Config auto-restored from last-known-good: ${n.path} (${e.reason})${b ? `; Rejected validation details: ${b}.` : ""} Original config kept at ${y}; to undo, stop the Gateway and copy it back to ${n.path} after correcting the reported problem.`); await i(createConfigObserveAuditRecord({ configPath: n.path, valid: n.valid, current: _, suspicious: [e.reason], lastKnownGood: o, backup: o, clobberedPath: y, restoredFromBackup: true, restoredBackupPath: s })); await r.updateAfterFileCommit({ lastKnownGood: o, lastPromotedGood: o, lastObservedSuspiciousSignature: null }, a); return true; } //#endregion //#region src/config/io.runtime-env.ts function maybeLoadDotEnvForConfig(e) { if (e === process.env) loadDotEnv(); } function resolveManagedRuntimeEnvBaseline() { const e = getPublishedConfigRuntimeEnvState(); return { publication: e, sourceConfig: e.sourceConfig ?? getRuntimeConfigSourceSnapshot() ?? {} }; } function assertManagedRuntimeEnvPublicationCurrent(e) { if (getPublishedConfigRuntimeEnvState() !== e) throw new ConfigMutationConflictError("active config environment changed while preparing write"); } function createManagedRuntimeEnvBase(e = process.env) { return createConfigRuntimeEnvBase(resolveManagedRuntimeEnvBaseline().sourceConfig, e, { ownedEnv: getPublishedConfigRuntimeEnvState().ownedEnv, preservedKeys: GATEWAY_CONFIG_SELECTION_ENV_KEYS }); } //#endregion //#region src/config/io.snapshot-preparation.ts /** Preserve the ordinary reader's lazy defaults, including an unused manifest loader. */ function materializeConfigSnapshotDefaults(e, t, n) { return materializeRuntimeConfig(t, { ...e.pathResolution, ...e.options.pluginValidation === "core-only" ? { manifestRegistry: { plugins: [] } } : { loadManifestRegistry: () => n.load(t).manifestRegistry } }); } async function materializeConfigSnapshotDefaultsAsync(e, t, n) { if (e.options.pluginValidation !== "core-only" && (t.models?.providers || hasAnthropicDefaultSignal(t, e.deps.env) && !resolveDirectBundledProviderPolicySurface("anthropic"))) await n.loadAsync(t); return materializeConfigSnapshotDefaults(e, t, n); } /** Runtime validation consumes canonical config; Doctor supplies its own pending facts. */ async function prepareConfigSnapshotValidation(e) { const { context: t, metadata: n } = e; const r = t.options.deferredPluginMigrations; return { deferredPluginMigrations: r, validated: await (e.prepareValidation === "strict" ? validateConfigObjectWithStrictFactsAsync : validateConfigObjectWithPluginsAsync)(e.raw, { ...t.pathResolution, pluginValidation: t.options.pluginValidation, loadPluginMetadataSnapshotAsync: n.loadAsync, sourceRaw: e.sourceRaw, preservedLegacyRootKeys: t.options.preservedLegacyRootKeys, deferredPluginMigrations: r }) }; } //#endregion //#region src/config/io.snapshot-shared.ts function createConfigFileSnapshot(e) { const t = e.sourceConfigBeforeMigrations ? asResolvedSourceConfig(e.sourceConfigBeforeMigrations) : void 0; const n = asResolvedSourceConfig(e.sourceConfig); setDeferredPluginMigrationConfigFacts(n, e.deferredPluginMigrations); const r = asRuntimeConfig(e.runtimeConfig); if (e.resolutionFacts !== void 0) { setConfigResolutionFacts(t, e.resolutionFacts); setConfigResolutionFacts(n, e.resolutionFacts); setConfigResolutionFacts(r, e.resolutionFacts); } return { path: e.path, includedPaths: [...e.includedPaths ?? []], ...e.includeProvenance ? { includeProvenance: e.includeProvenance } : {}, ...e.agentRosterIncludeOwned !== void 0 ? { agentRosterIncludeOwned: e.agentRosterIncludeOwned } : {}, ...e.bindingsIncludeOwned !== void 0 ? { bindingsIncludeOwned: e.bindingsIncludeOwned } : {}, exists: e.exists, raw: e.raw, parsed: e.parsed, ...e.authoredConfig ? { authoredConfig: e.authoredConfig } : {}, ...t ? { sourceConfigBeforeMigrations: t } : {}, sourceConfig: n, resolved: n, valid: e.valid, runtimeConfig: r, config: r, hash: e.hash, ...e.readError ? { readError: e.readError } : {}, issues: e.issues, warnings: e.warnings, legacyIssues: e.legacyIssues }; } async function finalizeReadConfigSnapshotInternalResult(e, t, n) { if (e.observe && n?.observe !== false) await observeConfigSnapshot(e, t.snapshot); return t; } //#endregion //#region src/config/io.load.ts function loadConfigFromContext(e, t = {}) { return runConfigIoSync(loadConfigWithEffects(e, t), t.assertCurrent); } async function loadConfigFromContextAsync(e, t = {}) { if (!isMainThread) return loadConfigFromContext(e, t); return await runConfigIoAsync(loadConfigWithEffects(e, t), t.assertCurrent); } function* loadConfigWithEffects(e, t) { const { deps: n, configPath: r, pathResolution: i } = e; let a; try { yield* resolveConfigIoEffect({ sync: () => maybeLoadDotEnvForConfig(n.env), async: async () => { if (n.env === process.env) await loadDotEnvAsync({ env: n.env }); } }); a = snapshotEnv(n.env); const o = yield* resolveConfigIoEffect({ sync: () => readConfigFileIfPresent(n, r), async: () => n.fs.promises.readFile(r, "utf-8").catch(ignoreMissingPath) }); if (o === void 0) { loggedConfigWarningFingerprints.delete(r); const a = coerceConfig(applyImplicitAgentRosterDefaults({})); const o = e.createValidationPluginMetadataSnapshotLoader({ env: n.env }); const s = yield* resolveConfigIoEffect({ sync: () => materializeConfigSnapshotDefaults(e, a, o), async: async () => materializeRuntimeConfig(a, { ...i, manifestRegistry: e.options.pluginValidation === "core-only" ? { plugins: [] } : (await o.loadAsync(a)).manifestRegistry }) }); return yield* resolveConfigIoEffect({ sync: () => e.finalizeLoadedRuntimeConfig(s), async: () => e.finalizeLoadedRuntimeConfigAsync(s, o, t.assertCurrent) }); } const s = JSON5.parse(o); const c = resolveConfigForRead(resolveConfigIncludesForRead(s, r, n), n.env, n.lowerPrecedenceEnv); const l = applyImplicitAgentRosterDefaults(c.resolvedConfigRaw); const u = hashConfigRaw(o); for (const e of c.envWarnings) n.logger.warn(`Config (${r}): missing env var "${e.varName}" at ${e.configPath} - feature using this value will be unavailable`); if (typeof l === "object" && l !== null) { const e = findDuplicateAgentDirs(l, i); if (e.length > 0) throw new DuplicateAgentDirError(e); } const d = e.createValidationPluginMetadataSnapshotLoader({ env: n.env }); const f = { ...i, pluginValidation: e.options.pluginValidation, sourceRaw: s, preservedLegacyRootKeys: e.options.preservedLegacyRootKeys }; const { deferredPluginMigrations: p, validated: m } = yield* resolveConfigIoEffect({ sync: () => withSynchronousArtifactPreservingStateSnapshot(() => { const t = e.options.deferredPluginMigrations; return { deferredPluginMigrations: t, validated: validateConfigObjectWithPlugins(l, { ...f, deferredPluginMigrations: t, loadPluginMetadataSnapshot: d.load }) }; }), async: () => prepareConfigSnapshotValidation({ context: e, metadata: d, raw: l, sourceRaw: s }) }); if (!m.ok) { const i = createConfigFileSnapshot({ path: r, exists: true, raw: o, parsed: s, sourceConfig: coerceConfig(l), valid: false, runtimeConfig: coerceConfig(l), hash: u, issues: m.issues, deferredPluginMigrations: p, warnings: m.warnings, resolutionFacts: c.resolutionFacts, legacyIssues: [] }); yield* resolveConfigIoEffect({ sync: () => e.observeLoadConfigSnapshot(i), async: () => e.observeLoadConfigSnapshotAsync(i, t.assertCurrent) }); throwInvalidConfig({ configPath: r, issues: m.issues, logger: n.logger, loggedConfigPaths: loggedInvalidConfigs }); } if (e.options.pluginValidation !== "skip") logConfigWarningsOnce({ configPath: r, warnings: m.warnings, logger: n.logger }); if (!n.suppressFutureVersionWarning) warnIfConfigFromFuture(m.config, n.logger); if (n.observe && !t.skipSuspiciousRecovery && !containsConfigIncludeDirective(s)) { const i = { deps: n, configPath: r, raw: o, parsed: s, prepareBackup: e.prepareRecoveryBackupCandidate }; if ((yield* resolveConfigIoEffect({ sync: () => maybeRecoverSuspiciousConfigReadSync(i), async: () => maybeRecoverSuspiciousConfigRead({ ...i, prepareBackupAsync: e.prepareRecoveryBackupCandidateAsync, assertCurrent: t.assertCurrent }) })).raw !== o) { restoreEnvChangesIfUnchanged({ env: n.env, before: a, after: snapshotEnv(n.env) }); return yield* loadConfigWithEffects(e, { ...t, skipSuspiciousRecovery: true }); } } const h = materializeRuntimeConfig(m.config, { ...i, manifestRegistry: e.options.pluginValidation === "core-only" ? { plugins: [] } : d.getSnapshot()?.manifestRegistry }); const g = createConfigFileSnapshot({ path: r, exists: true, raw: o, parsed: s, sourceConfig: coerceConfig(l), valid: true, runtimeConfig: h, deferredPluginMigrations: p, hash: u, issues: [], warnings: m.warnings, resolutionFacts: c.resolutionFacts, legacyIssues: [] }); yield* resolveConfigIoEffect({ sync: () => e.observeLoadConfigSnapshot(g), async: () => e.observeLoadConfigSnapshotAsync(g, t.assertCurrent) }); return yield* resolveConfigIoEffect({ sync: () => e.finalizeLoadedRuntimeConfig(h), async: () => e.finalizeLoadedRuntimeConfigAsync(h, d, t.assertCurrent) }); } catch (e) { if (a) restoreEnvChangesIfUnchanged({ env: n.env, before: a, after: snapshotEnv(n.env) }); if (e instanceof DuplicateAgentDirError) { n.logger.error(e.message); throw e; } if (e?.code === "INVALID_CONFIG") throw e; n.logger.error(`Failed to read config at ${r}: ${formatErrorMessage(e)}`); throw e; } } //#endregion //#region src/config/io.snapshot.ts let legacyIssuesModule; async function readConfigFileSnapshotInternal(e, t = {}, n) { const read = () => readConfigSnapshot(e, t, n); return await (e.deps.observe ? read() : withArtifactPreservingStateReads(read)); } async function readConfigSnapshot(e, t, n) { const { deps: r, configPath: i, pathResolution: a } = e; const o = createConfigWriteAuthorityGuard(captureConfigWriteLockGuard(i)); o(); captureConfigReadEnvMutation(r.env, () => maybeLoadDotEnvForConfig(r.env)); let s; let c = null; let l = {}; let u = {}; let d = hashConfigRaw(null); let f; const p = {}; const m = {}; const h = /* @__PURE__ */ new Set(); const g = []; let _ = false; let v = false; const invalidSourceSnapshot = (e, t = u, n, r) => { if (r !== void 0) Object.defineProperty(e, "cause", { value: r }); return createConfigFileSnapshot({ path: i, includedPaths: [...h].toSorted(), exists: true, raw: c, parsed: l, sourceConfig: u, valid: false, runtimeConfig: t, hash: d, ...n ? { readError: n } : {}, issues: [e], warnings: [], legacyIssues: [] }); }; try { const y = await r.measure("config.snapshot.read.file", () => n ?? readConfigFileIfPresent(r, i)); if (y === void 0) { const n = coerceConfig(applyImplicitAgentRosterDefaults({})); const a = e.createValidationPluginMetadataSnapshotLoader({ env: r.env, allowCurrentPluginMetadata: t.allowCurrentPluginMetadata }); return await finalizeReadConfigSnapshotInternalResult(r, { snapshot: createConfigFileSnapshot({ path: i, exists: false, raw: null, parsed: {}, sourceConfig: n, valid: true, runtimeConfig: await materializeConfigSnapshotDefaultsAsync(e, n, a), hash: hashConfigRaw(null), issues: [], warnings: [], legacyIssues: [] }), pluginMetadataSnapshot: a.getSnapshot() }); } const b = await r.measure("config.snapshot.read.hash", () => hashConfigRaw(y)); c = y; d = b; const x = await r.measure("config.snapshot.read.parse", () => parseConfigJson5(y)); if (!x.ok) return await finalizeReadConfigSnapshotInternalResult(r, { snapshot: invalidSourceSnapshot({ path: "", errorCode: "CONFIG_SOURCE_INVALID", message: `JSON5 parse failed: ${x.error}` }, {}) }); const S = x.parsed; l = S; u = coerceConfig(S); let C; try { C = await r.measure("config.snapshot.read.includes", () => resolveConfigIncludesForRead(S, i, r, p, m, h, (e) => { const { value: t, ...n } = e; g.push(n); _ ||= includeContributionOwnsAgentRoster(e); v ||= includeContributionOwnsBindings(e); })); } catch (e) { if (findStartupMaintenanceRequiredError(e)) throw e; const t = e instanceof ConfigIncludeError ? e.message : `Include resolution failed at ${i}: ${String(e)}`; return await finalizeReadConfigSnapshotInternalResult(r, { snapshot: invalidSourceSnapshot({ path: "", errorCode: e instanceof ConfigIncludeReadError || !(e instanceof ConfigIncludeError) ? "CONFIG_READ_FAILED" : "CONFIG_SOURCE_INVALID", message: t }, coerceConfig(S), void 0, e), includeFileHashesForWrite: p, includeFileTargetsForWrite: m }); } const w = await r.measure("config.snapshot.read.env", () => { o(); return captureConfigReadEnvMutation(r.env, () => resolveConfigForRead(C, r.env, r.lowerPrecedenceEnv), (e) => { s = e; t.onSourceEnvApplied?.(e); }); }); f = w.envSnapshotForRestore; const T = w.envWarnings.map((e) => ({ path: e.configPath, message: `Missing env var "${e.varName}" - feature using this value will be unavailable` })); const E = applyImplicitAgentRosterDefaults(w.resolvedConfigRaw); const D = hashConfigRevision(y, p, m); d = D; u = coerceConfig(E); const O = e.createValidationPluginMetadataSnapshotLoader({ env: r.env, allowCurrentPluginMetadata: t.allowCurrentPluginMetadata }); const k = { prepareValidation: t.prepareValidation, context: e, metadata: O, raw: E, sourceRaw: S }; const { deferredPluginMigrations: A, validated: j } = await r.measure("config.snapshot.read.validate", () => prepareConfigSnapshotValidation(k)); const snapshotSource = () => ({ path: i, includedPaths: [...h].toSorted(), exists: true, raw: y, parsed: S, authoredConfig: coerceConfig(C), includeProvenance: g, agentRosterIncludeOwned: _, bindingsIncludeOwned: v, sourceConfigBeforeMigrations: coerceConfig(w.resolvedConfigRaw), sourceConfig: coerceConfig(E), hash: D, deferredPluginMigrations: A, warnings: [...j.warnings, ...T], resolutionFacts: w.resolutionFacts }); if (!j.ok) { const n = O.getSnapshot() ?? (e.options.pluginValidation !== "core-only" && t.allowCurrentPluginMetadata !== false ? getProcessGatewayPluginMetadataSnapshot() : void 0); const i = n ? void 0 : () => preparePluginMetadataMachineStateAsync({ env: r.env }); const collect = async () => { const { collectInvalidConfigLegacyIssues: t } = await (legacyIssuesModule ??= import("./io.legacy-issues.runtime.js")); return t(E, S, { coreOnly: e.options.pluginValidation === "core-only", preparePluginDiagnostics: i }); }; const a = await r.measure("config.snapshot.read.legacy-issues", () => n ? withPluginMetadataSnapshotScope(n, collect, { config: coerceConfig(E), env: r.env, trustConfigIdentity: true }) : collect()); o(); s?.(); return await finalizeReadConfigSnapshotInternalResult(r, { snapshot: createConfigFileSnapshot({ ...snapshotSource(), valid: false, runtimeConfig: coerceConfig(E), issues: j.issues, legacyIssues: a }), envSnapshotForRestore: w.envSnapshotForRestore, includeFileHashesForWrite: p, includeFileTargetsForWrite: m }); } if (!r.suppressFutureVersionWarning) warnIfConfigFromFuture(j.config, r.logger); let M = false; if (t.recoverSuspicious === true && r.observe && !t.skipSuspiciousRecovery && !containsConfigIncludeDirective(S)) { const n = t.allowSuspiciousRecovery; let a = null; if ((await r.measure("config.snapshot.read.recover-suspicious", () => maybeRecoverSuspiciousConfigRead({ deps: r, configPath: i, raw: y, parsed: S, prepareBackup: (t) => { const n = e.prepareRecoveryBackupCandidate(t); a = n.ok ? n.candidate.config ?? null : null; return n; }, ...n ? { allowBackupRecovery: async () => { const e = a !== null && await n(a, j.config); M = !e; return e; } } : {} }))).raw !== y) { o(); s?.(); return await readConfigFileSnapshotInternal(e, { prepareValidation: t.prepareValidation, allowCurrentPluginMetadata: t.allowCurrentPluginMetadata, recoverSuspicious: t.recoverSuspicious, skipSuspiciousRecovery: true }); } } const N = await r.measure("config.snapshot.read.materialize", () => materializeRuntimeConfig(j.config, { ...a, manifestRegistry: O.getSnapshot()?.manifestRegistry ?? (e.options.pluginValidation === "core-only" ? { plugins: [] } : void 0) })); return await r.measure("config.snapshot.read.observe", () => finalizeReadConfigSnapshotInternalResult(r, { snapshot: createConfigFileSnapshot({ ...snapshotSource(), valid: true, runtimeConfig: N, issues: [], legacyIssues: [] }), envSnapshotForRestore: w.envSnapshotForRestore, includeFileHashesForWrite: p, includeFileTargetsForWrite: m, pluginMetadataSnapshot: O.getSnapshot(), ...j.strictIssues ? { strictIssues: j.strictIssues } : {} }, { observe: !M })); } catch (e) { o(); s?.(); if (findStartupMaintenanceRequiredError(e) || collectNestedErrorCandidates(e).some((e) => e instanceof OpenClawStateOwnershipError || isSqliteSchemaMismatchError(e))) throw e; const t = e; let n; if (t?.code === "EACCES") { const t = process.getuid?.(); const a = typeof t === "number" ? String(t) : "$(id -u)"; n = [ `read failed at ${i}: ${String(e)}`, "", "Config file is not readable by the current process. If running in a container", "or 1-click deployment, fix ownership with:", ` chown ${a} "${i}"`, "Then restart the gateway." ].join("\n"); r.logger.error(n); } else n = `read failed at ${i}: ${String(e)}`; return await finalizeReadConfigSnapshotInternalResult(r, { snapshot: invalidSourceSnapshot({ path: "", errorCode: "CONFIG_READ_FAILED", message: n }, u, c === null ? { code: t?.code ?? null } : void 0, e), envSnapshotForRestore: f, includeFileHashesForWrite: p, includeFileTargetsForWrite: m }); } } /** Preview recovery through the ordinary snapshot pipeline at the selected config path. */ async function prepareConfigRecoveryFromContext(e, t, n) { return await withArtifactPreservingStateReads(async () => { if (!t.exists || !t.valid || typeof t.raw !== "string" || containsConfigIncludeDirective(t.parsed)) return null; if (t.path !== e.configPath) throw new ConfigMutationConflictError("config recovery path changed since last load", { retryable: false }); const r = createConfigIoContext({ ...e.options, configPath: e.configPath, env: cloneEnvWithPlatformSemantics(e.deps.env), observe: false }, e.transformRecoveryCandidate); const i = await prepareSuspiciousConfigRead({ intent: n, deps: r.deps, measure: r.deps.measure, configPath: e.configPath, raw: t.raw, parsed: t.parsed, prepareBackup: r.prepareRecoveryBackupCandidate, prepareBackupAsync: r.prepareRecoveryBackupCandidateAsync }); if (!i) return null; const a = snapshotEnv(r.deps.env); try { const { snapshot: e, pluginMetadataSnapshot: t } = await readConfigFileSnapshotInternal(r, { allowCurrentPluginMetadata: false }, i.candidate.raw); if (isConfigReadFailure(e)) throw createConfigReadError(e); return e.valid ? { snapshot: e, pluginMetadataSnapshot: t, apply: i.apply } : null; } finally { restoreEnvChangesIfUnchanged({ env: r.deps.env, before: a, after: snapshotEnv(r.deps.env) }); } }); } async function readConfigFileSnapshotFromContext(e, t = {}) { return (await readConfigFileSnapshotInternal(e, { recoverSuspicious: t.recoverSuspicious === true, allowSuspiciousRecovery: t.allowSuspiciousRecovery, onSourceEnvApplied: t.onSourceEnvApplied })).snapshot; } async function readConfigFileSnapshotWithPluginMetadataFromContext(e, t = {}) { const read = () => readConfigSnapshotWithPluginMetadata(e, t); return e.deps.observe ? read() : withArtifactPreservingStateReads(read); } async function readConfigSnapshotWithPluginMetadata(e, t) { const n = await readConfigFileSnapshotInternal(e, { prepareValidation: t.prepareValidation, allowCurrentPluginMetadata: t.allowCurrentPluginMetadata, recoverSuspicious: t.recoverSuspicious === true, allowSuspiciousRecovery: t.allowSuspiciousRecovery, onSourceEnvApplied: t.onSourceEnvApplied }); let r = n.pluginMetadataSnapshot; if (t.completePluginMetadata !== false && !r && n.snapshot.valid) { const i = e.createValidationPluginMetadataSnapshotLoader({ env: e.deps.env, allowCurrentPluginMetadata: t.allowCurrentPluginMetadata }); await i.loadAsync(n.snapshot.sourceConfig); r = i.getSnapshot(); } return { snapshot: n.snapshot, ...n.strictIssues ? { strictIssues: n.strictIssues } : {}, ...r ? { pluginMetadataSnapshot: r } : {} }; } async function readConfigFileSnapshotForWriteFromContext(e, t = {}) { const assertConfigSelection = () => { if (resolveConfigPathForDeps(e.deps) !== e.configPath) throw new ConfigMutationConflictError("config path changed since last load", { retryable: false }); }; assertConfigSelection(); const n = captureConfigFileWritePathProof(e.configPath, resolvePathViaExistingAncestorSync(e.configPath), e.deps.fs); const r = composeConfigWriteAssertions(assertConfigSelection, n.assertCurrent); r(); const i = t.observe === false ? { ...e, deps: { ...e.deps, observe: false } } : e; const read = () => readConfigFileSnapshotInternal(i); const a = await (i.deps.observe ? read() : withArtifactPreservingStateReads(read)); r(); return { snapshot: a.snapshot, writeOptions: { assertConfigPathForWrite: r, basePluginMetadataSnapshot: a.pluginMetadataSnapshot, envSnapshotForRestore: a.envSnapshotForRestore, expectedConfigPath: e.configPath, ownedConfigPathForWrite: e.configPath, includeFileHashesForWrite: a.includeFileHashesForWrite, includeFileTargetsForWrite: a.includeFileTargetsForWrite, unsetPaths: resolveManagedUnsetPathsForWrite(void 0) } }; } async function readBestEffortConfigSnapshotFromContext(e) { const operation = async () => { const { snapshot: t } = await readConfigFileSnapshotInternal(e); return { config: t.valid ? e.finalizeLoadedRuntimeConfig(t.config) : t.config, sourceConfig: t.sourceConfig, configDiagnostics: t.valid ? null : { path: t.path, issues: t.issues } }; }; return await (e.deps.observe ? operation() : withArtifactPreservingStateReads(operation)); } async function readSourceConfigBestEffortFromContext(e) { const { deps: t, configPath: n } = e; maybeLoadDotEnvForConfig(t.env); if (!t.fs.existsSync(n)) return {}; try { const e = t.fs.readFileSync(n, "utf-8"); const r = parseConfigJson5(e); if (!r.ok) { t.logger.warn(`Config (${n}): best-effort read ignored unparseable config: ${r.error}`); return {}; } let i; try { i = resolveConfigIncludesForRead(r.parsed, n, t); } catch (e) { t.logger.warn(`Config (${n}): best-effort read skipped $include resolution: ${formatErrorMessage(e)}`); return coerceConfig(r.parsed); } const a = resolveConfigForRead(i, t.env, t.lowerPrecedenceEnv); return coerceConfig(a.resolvedConfigRaw); } catch (e) { t.logger.warn(`Config (${n}): best-effort read failed: ${formatErrorMessage(e)}`); return {}; } } //#endregion //#region src/config/io.factory.ts function createConfigIO(e = {}) { const t = createConfigIoContext(e); const readInternal = (e) => readConfigFileSnapshotInternal(e === false ? { ...t, deps: { ...t.deps, observe: false } } : t); return { configPath: t.configPath, env: t.deps.env, logger: t.deps.logger, loadConfig: (e) => loadConfigFromContext(t, e), loadConfigAsync: (e) => loadConfigFromContextAsync(t, e), readBestEffortConfig: async () => (await readBestEffortConfigSnapshotFromContext(t)).config, readBestEffortConfigSnapshot: () => readBestEffortConfigSnapshotFromContext(t), readSourceConfigBestEffort: () => readSourceConfigBestEffortFromContext(t), readConfigFileSnapshot: (e = {}) => readConfigFileSnapshotFromContext(t, e), readConfigFileSnapshotFromRaw: async (e) => (await readConfigFileSnapshotInternal(t, {}, e)).snapshot, readConfigFileSnapshotWithPluginMetadata: (e = {}) => readConfigFileSnapshotWithPluginMetadataFromContext(t, e), readConfigFileSnapshotForWrite: (e) => readConfigFileSnapshotForWriteFromContext(t, e), prepareConfigRecovery: (e) => prepareConfigRecoveryFromContext(t, e), /** True reports committed file work; health metadata remains best-effort. */ promoteConfigSnapshotToLastKnownGood: async (e) => { const { deps: n } = t; if (resolveIsConfigReadOnly(n.env)) return false; if (!e.exists || !e.valid || typeof e.raw !== "string") return false; const r = collectPollutedSecretPlaceholders(e.parsed); if (r.length > 0) { n.logger.warn(`Config last-known-good promotion skipped: redacted secret placeholder at ${r[0]}`); return false; } const i = captureConfigHealthStateStore(n, e.path); const a = await i.read(); const o = await n.fs.promises.stat(e.path).catch(() => null); const s = (/* @__PURE__ */ new Date()).toISOString(); const c = createConfigHealthFingerprint({ raw: e.raw, parsed: e.parsed, resolved: e.resolved, stat: o, observedAt: s }); const l = `${e.path}.last-good`; i.assertCurrent(); const u = readConfigHealthEntry(a.state, e.path); const d = resolveConfigObserveSuspiciousReasons({ hash: c.hash, lastObservedSuspiciousSignature: u.lastObservedSuspiciousSignature, bytes: c.bytes, gatewayMode: c.gatewayMode, parsed: e.parsed, lastKnownGood: u.lastKnownGood }); if (d.length > 0) { n.logger.warn(`Config last-known-good promotion skipped: ${e.path} (${d.join(", ")})`); return false; } const f = e.raw; const p = createConfigRecoverySourceGuard(n, [[ e.path, f, o ]]); await commitConfigRecoveryFile({ health: i, beforeCommit: p, write: async (e) => { await (await root(path.dirname(l))).write(path.basename(l), f, { mkdir: false, mode: 384, durable: false, encoding: "utf8", overwrite: true, assertBeforeMutation: e }); } }); await chmodConfigBestEffort({ deps: n, configPath: l, context: "last-known-good promotion" }); await i.updateAfterFileCommit({ lastKnownGood: c, lastPromotedGood: c, lastObservedSuspiciousSignature: null }, a); return true; }, recoverConfigFromLastKnownGood: (e) => recoverConfigFromLastKnownGoodCore({ deps: t.deps, snapshot: e.snapshot, reason: e.reason, prepareCandidate: t.prepareRecoveryBackupCandidate }), recoverConfigFromJsonRootSuffix: (e, n) => recoverConfigFromJsonRootSuffixWithContext(t, e, n), writeConfigFile: async (e, n = {}) => { n.assertConfigPathForWrite?.(); const { writeConfigFileFromContext: r } = await import("./io.write-C3Yz_1ez.mjs"); n.assertConfigPathForWrite?.(); return withConfigWriteLock(t.configPath, () => r(t, e, n, () => readInternal(n.observe)), t.deps.env, n.assertCurrent); } }; } //#endregion export { createManagedRuntimeEnvBase as a, recoverConfigFromLastKnownGoodCore as c, assertManagedRuntimeEnvPublicationCurrent as i, prepareConfigRecoveryFromContext as n, maybeLoadDotEnvForConfig as o, createConfigFileSnapshot as r, resolveManagedRuntimeEnvBaseline as s, createConfigIO as t };