UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

542 lines (541 loc) • 22.3 kB
import { n as tryProcessCwd } from "./safe-cwd-CZqaxroH.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { l as writeRootConsoleLine } from "./console-BkI11Tqj.mjs"; import { f as restoreEnvChangesIfUnchanged, o as createConfigRuntimeEnvBase, p as snapshotEnv, r as cloneEnvWithPlatformSemantics, u as prepareConfigRuntimeEnvLoad } from "./config-env-vars-ByeGN-9N.mjs"; import { r as formatConfigIssueSummary } from "./issue-format-WaYQX-7p.mjs"; import { n as createMergePatch, r as mergePatchConflicts } from "./merge-patch-D-7aajuy.mjs"; import { i as hashConfigRaw, l as replaceEnvSnapshot } from "./io.read-helpers-qAcqsRC0.mjs"; import { i as withConfigWriteLock, m as assertBaseSnapshotStillCurrent, t as captureConfigWriteLockGuard } from "./write-lock-Bg9nHsHM.mjs"; import { a as getRuntimeConfigSnapshot, c as getRuntimeConfigSourceSnapshot, d as loadPinnedRuntimeConfigAsync, f as notifyRuntimeConfigWriteListeners, g as registerManagedRuntimeConfigWriteOwner, j as hashRuntimeConfigValue, l as hasManagedRuntimeConfigWriteOwner, m as preflightRuntimeSnapshotWrite, o as getRuntimeConfigSnapshotMetadata, p as preflightManagedRuntimeConfigWrite, r as finalizeRuntimeSnapshotWrite, s as getRuntimeConfigSnapshotRefreshHandler, u as loadPinnedRuntimeConfig, v as registerRuntimeConfigWriteListener } from "./runtime-snapshot-WbwbY5b7.mjs"; import { t as ConfigMutationConflictError } from "./mutation-conflict-Bs0nsNWn.mjs"; import { g as withLeasePinnedDeferredPluginMigrations } from "./deferred-plugin-migrations-C_CU0aKR.mjs"; import { n as getDeferredPluginMigrationConfigFacts, u as resolveManagedUnsetPathsForWrite } from "./deferred-plugin-migration-config-B3TJC-SY.mjs"; import { r as projectLegacyRuntimeConfigWrite } from "./runtime-source-projection-DTwMWCo9.mjs"; import { n as loadDotEnvAsync, t as loadDotEnv } from "./dotenv-qUrr6GRR.mjs"; import { a as createManagedRuntimeEnvBase, s as resolveManagedRuntimeEnvBaseline, t as createConfigIO } from "./io.factory-DEa_bi2j.mjs"; import { t as logConfigWarningsOnce } from "./io.warnings-BbJvBO5E.mjs"; import { t as GATEWAY_CONFIG_SELECTION_ENV_KEYS } from "./gateway-env-selection-yOcr26em.mjs"; import { v as recordUpdateDoctorConfigWrite } from "./update-doctor-result-DwaI51On.mjs"; import { r as assertConfigWriteAllowedInCurrentMode } from "./config-write-guard-CxNxfJ_I.mjs"; import { t as resolveWriteEnvSnapshotForPath } from "./env-preserve-D_8K8swo.mjs"; import { r as configWritePostCommitRollback, t as ConfigRuntimeRefreshError } from "./io.types-tZoWfCaZ.mjs"; import { s as recoverConfigWriteFailure } from "./io.write-errors-CuPAqPbq.mjs"; import fs from "node:fs"; import { isMainThread } from "node:worker_threads"; import { format } from "node:util"; //#region src/config/runtime-write-application.ts const runtimeConfigWriteApplications = /* @__PURE__ */ new WeakMap(); /** Creates a single-owner receipt for one persisted config write. */ function createRuntimeConfigWriteApplication(e, t) { let n = false; let r = false; let isCarriedBy; const i = createDeferredCore(); return { result: i.promise, get claimed() { return n; }, recordConfigChange: (e, n) => { if (!t?.prepare && !t?.requireImmediateApplication) { const t = createMergePatch(e, n); isCarriedBy = (e) => !r && !mergePatchConflicts(n, e, t); } }, claim: () => { if (n) return null; n = true; const a = { settle: (e) => { r = true; delete a.runTransaction; i.resolve(e); }, ...e ? { runTransaction: e } : {}, ...t, ...isCarriedBy ? { isCarriedBy } : {} }; return a; } }; } /** Attaches a private application receipt without changing the config notification contract. */ function attachRuntimeConfigWriteApplication(e, t) { if (t) runtimeConfigWriteApplications.set(e, t); return e; } /** Copies a private application receipt when rebuilding an internal write carrier. */ function copyRuntimeConfigWriteApplication(e, t) { return attachRuntimeConfigWriteApplication(t, e ? runtimeConfigWriteApplications.get(e) : void 0); } /** Returns the private application receipt attached to a write or notification. */ function getRuntimeConfigWriteApplication(e) { return runtimeConfigWriteApplications.get(e); } function publishRuntimeConfigWrite(e) { const t = e.deferRuntimeActivation ? e.runtimeConfig : getRuntimeConfigSnapshot(); if (!t) return; const n = e.writeOptions && getRuntimeConfigWriteApplication(e.writeOptions); const r = e.afterWrite ?? e.writeOptions?.afterWrite; const i = e.writeOptions?.runtimeRefresh; if ((!r || r.mode === "auto") && !i?.includeAuthStoreRefs && !i?.requireImmediateApplication) n?.recordConfigChange(e.previousSourceConfig, e.writtenSourceConfig); const a = new Map([...e.preparedCandidates].map(([t, n]) => [t, { ...n, runtimeConfig: n.reapplyRuntimeOverlays?.(e.runtimeConfig) ?? n.runtimeConfig, compareConfig: n.reapplyCompareOverlays?.(e.sourceConfig) ?? n.compareConfig }])); const o = getRuntimeConfigSnapshotMetadata(); const s = t === getRuntimeConfigSnapshot() && o ? o : { revision: o?.revision ?? 0, fingerprint: hashRuntimeConfigValue(t), sourceFingerprint: hashRuntimeConfigValue(e.sourceConfig) }; notifyRuntimeConfigWriteListeners(copyRuntimeConfigWriteApplication(e.writeOptions, { configPath: e.configPath, snapshot: e.snapshot, sourceConfig: e.sourceConfig, runtimeConfig: t, persistedHash: e.persistedHash, revision: s.revision, fingerprint: s.fingerprint, sourceFingerprint: s.sourceFingerprint, afterWrite: e.afterWrite ?? e.writeOptions?.afterWrite, ...e.writeOptions?.runtimeRefresh ? { runtimeRefresh: e.writeOptions.runtimeRefresh } : {}, ...a.size > 0 ? { preparedCandidatesByOwner: a } : {} })); } //#endregion //#region src/config/io.runtime-write-finalization.ts async function finalizeCommittedConfigWrite(e) { const { io: t, options: n, writeResult: r, baseSnapshot: i, deferRuntimeActivation: a, managedPreparedCandidates: o } = e; let s = e.nextCfg; let c = e.nextCfg; let l = r.persistedHash; let u; let d = snapshotEnv(t.env); let f; let p = null; try { let e = !a; for (let n = 0; n < 3; n += 1) { const n = resolveManagedRuntimeEnvBaseline(); if (a) { replaceEnvSnapshot(t.env, createConfigRuntimeEnvBase(n.sourceConfig, process.env, { preservedKeys: GATEWAY_CONFIG_SELECTION_ENV_KEYS })); d = snapshotEnv(t.env); } u = await t.readConfigFileSnapshotForWrite(); const r = u.snapshot; if (r.exists && r.valid) { s = r.sourceConfig; c = r.config; l = expectDefined(r.hash, "canonical config snapshot hash"); } else { const e = formatConfigIssueSummary(r.issues); t.logger.warn(`Config (${t.configPath}): canonical reread after write was ${r.exists ? "invalid" : "missing"}; runtime keeps the written config${e ? `: ${e}` : ""}`); } if (!a || resolveManagedRuntimeEnvBaseline().publication === n.publication) { e = true; break; } } if (!e) p = new ConfigRuntimeRefreshError("the active config environment changed during every canonical reread"); } catch (e) { p = new ConfigRuntimeRefreshError(`canonical reread failed: ${formatErrorMessage(e)}`, { cause: e }); } finally { f = snapshotEnv(t.env); } const notifyCommittedWrite = () => { publishRuntimeConfigWrite({ configPath: t.configPath, snapshot: expectDefined(u, "canonical config reread").snapshot, sourceConfig: s, previousSourceConfig: i.sourceConfig, writtenSourceConfig: e.nextCfg, runtimeConfig: c, persistedHash: l, deferRuntimeActivation: a, preparedCandidates: o, writeOptions: n }); }; try { if (p) throw p; n.assertConfigPathForWrite?.(); await finalizeRuntimeSnapshotWrite({ assertCurrent: () => { e.assertPostCommitCurrent?.(); const n = expectDefined(u, "canonical config reread"); n.writeOptions.assertConfigPathForWrite?.(); assertBaseSnapshotStillCurrent(n.snapshot, t.configPath, fs, { hashes: n.writeOptions.includeFileHashesForWrite ?? {}, targets: n.writeOptions.includeFileTargetsForWrite ?? {} }); }, nextSourceConfig: s, refreshOptions: n.runtimeRefresh, hadBothSnapshots: e.hadBothSnapshots, freshConfig: async (n) => { n(); const r = prepareConfigRuntimeEnvLoad({ previousConfig: resolveManagedRuntimeEnvBaseline().sourceConfig, env: t.env, preservedKeys: GATEWAY_CONFIG_SELECTION_ENV_KEYS }); const i = createConfigIO({ ...e.ioOptions, configPath: t.configPath, env: r.env }); try { if (isMainThread) await loadDotEnvAsync({ env: r.env }); else loadDotEnv({ env: r.env }); } finally { r.captureDotEnvBaseline(); n(); r.prepareFailure().publish().commit(); } const a = await i.loadConfigAsync({ assertCurrent: n }); n(); return { config: a, runtimeEnv: r.prepare(a) }; }, notifyCommittedWrite, formatRefreshError: (e) => formatErrorMessage(e), preflightResult: e.runtimePreflightResult, deferRuntimeActivation: a, createRefreshError: (e, t) => new ConfigRuntimeRefreshError(`runtime snapshot refresh failed: ${e}`, { cause: t }) }); } catch (n) { const a = r[configWritePostCommitRollback]; return await recoverConfigWriteFailure({ configPath: t.configPath, cause: n, restoreFile: async () => a?.restoreFile(() => e.assertPostCommitCurrent?.()), restoreEffects: async () => { e.assertPostCommitCurrent?.(); recordUpdateDoctorConfigWrite(t.configPath, r.persistedHash, hashConfigRaw(i.raw), r.persistedConfig, JSON.stringify(isRecord(i.parsed) ? i.parsed : {})); restoreEnvChangesIfUnchanged({ env: t.env, before: d, after: f }); await a?.restoreEffects(() => e.assertPostCommitCurrent?.()); } }); } return r; } //#endregion //#region src/config/io.runtime.ts function clearConfigCache() {} function registerConfigWriteListener(e, t = {}) { const n = t.ownsRuntimeActivationFor ? registerManagedRuntimeConfigWriteOwner(t.ownsRuntimeActivationFor, t.preCommitRuntimePreflight) : void 0; const r = registerRuntimeConfigWriteListener((t) => { const { preparedCandidate: r, preparedCandidatesByOwner: i, ...a } = t; const o = n ? t.preparedCandidatesByOwner?.get(n.ownerId) : void 0; e(copyRuntimeConfigWriteApplication(t, { ...a, ...o ? { preparedCandidate: o } : {} })); }); return () => { r(); n?.(); }; } /** @deprecated Use the prepared runtime snapshot or await captureRuntimeConfigAsyncReader()(). */ function loadConfig(e) { const loadFresh = () => createConfigIO({ ...e?.skipPluginValidation ? { pluginValidation: "skip" } : {}, ...e?.skipShellEnvFallback ? { shellEnvFallback: "defer" } : {} }).loadConfig(); return e?.pin === false ? loadFresh() : loadPinnedRuntimeConfig(loadFresh); } function captureRuntimeConfigAsyncReader(e = {}) { const t = tryProcessCwd(); const n = prepareConfigRuntimeEnvLoad({ previousConfig: {} }); const r = createConfigIO({ env: n.env, ...e.observe === false ? { observe: false } : {}, ...e.skipPluginValidation ? { pluginValidation: "skip" } : {} }); const assertCurrent = () => e.assertCurrent?.(); let i; const read = () => { assertCurrent(); const loadFresh = async (e) => { try { e(); try { await loadDotEnvAsync({ env: n.env, cwd: t }); } finally { n.captureDotEnvBaseline(); } e(); const i = await r.loadConfigAsync({ assertCurrent: e }); e(); return { config: i, runtimeEnv: n.prepare(i) }; } catch (t) { e(); n.prepareFailure().publish().commit(); throw t; } }; return i ??= e.capture ? loadPinnedRuntimeConfigAsync(loadFresh, { assertCurrent, capture: true }) : loadPinnedRuntimeConfigAsync(loadFresh, { assertCurrent }); }; return Object.assign(read, { assertCurrent }); } function createCurrentConfigReader(e) { return createConfigIO({ configPath: e.configPath, env: cloneEnvWithPlatformSemantics(e.env ?? process.env), observe: false, pluginValidation: "core-only", deferredPluginMigrations: e.deferredPluginMigrations, shellEnvFallback: "defer", suppressFutureVersionWarning: true, logger: { warn: () => {}, error: () => {} } }); } /** Inspection may degrade location selection; it never admits invalid config for state repairs. */ function readCurrentConfigForResolution(e = {}) { if (e.config) return { config: e.config, env: e.env ?? process.env, configDiagnostics: null }; const t = createCurrentConfigReader(e); let n; let r; try { const e = t.loadConfig({ skipSuspiciousRecovery: true }); if (fs.existsSync(t.configPath)) n = e; } catch (e) { r = e; } const i = n ? [] : [{ path: t.configPath, message: r ? `Config unavailable; using environment and default agent directory settings. (${formatErrorMessage(r)})` : "Config unavailable; using environment and default agent directory settings." }]; logConfigWarningsOnce({ configPath: `${t.configPath}#directory-resolution`, warnings: i, logger: console }); return { config: n ?? {}, env: t.env, configDiagnostics: n ? null : { path: t.configPath, issues: i } }; } /** Revalidate disk policy at a synchronous effect boundary without observing or repairing state. */ function readCurrentConfigForPolicyCheck(e) { return createCurrentConfigReader(e).loadConfig({ skipSuspiciousRecovery: true }); } /** Keep the Template Add policy reader bound to its admitted plugin-state lease. */ async function withCurrentConfigPolicyReader(e, t) { return await withLeasePinnedDeferredPluginMigrations(e, async (n, r) => t(() => { r(); const t = readCurrentConfigForPolicyCheck({ ...e, deferredPluginMigrations: n }); r(); return t; })); } /** Read canonical disk policy asynchronously without inspecting migration state. */ async function readCurrentConfigForPolicyCheckAsync(e) { const t = e.configPath; return await createCurrentConfigReader({ configPath: t, env: cloneEnvWithPlatformSemantics(e.env) }).loadConfigAsync({ skipSuspiciousRecovery: true }); } async function readBestEffortConfig(e) { return await createConfigIO({ ...e?.isolateEnv ? { env: cloneEnvWithPlatformSemantics(process.env) } : {}, ...e?.observe === false ? { observe: false } : {}, pluginValidation: e?.pluginValidation ?? (e?.skipPluginValidation ? "skip" : void 0) }).readBestEffortConfig(); } async function readBestEffortConfigSnapshot(e) { return await createConfigIO({ ...e?.observe === false ? { observe: false } : {}, pluginValidation: e?.pluginValidation ?? (e?.skipPluginValidation ? "skip" : void 0) }).readBestEffortConfigSnapshot(); } async function readSourceConfigBestEffort() { const diagnostic = (e, t) => { if (!writeRootConsoleLine(e, format(...t))) console[e](...t); }; return await createConfigIO({ logger: { warn: (...e) => diagnostic("warn", e), error: (...e) => diagnostic("error", e) } }).readSourceConfigBestEffort(); } async function readConfigFileSnapshot(e = {}) { return await createConfigIO({ deferredPluginMigrations: e.deferredPluginMigrations, measure: e.measure, observe: e.observe === false ? false : void 0, env: e.isolateEnv ? cloneEnvWithPlatformSemantics(process.env) : void 0, lowerPrecedenceEnv: e.lowerPrecedenceEnv, pluginValidation: e.pluginValidation ?? (e.skipPluginValidation ? "skip" : void 0), suppressFutureVersionWarning: e.suppressFutureVersionWarning || void 0, preservedLegacyRootKeys: e.preservedLegacyRootKeys }).readConfigFileSnapshot({ recoverSuspicious: e.recoverSuspicious === true, allowSuspiciousRecovery: e.allowSuspiciousRecovery }); } async function readConfigFileSnapshotWithPluginMetadata(e) { return await createConfigIO({ deferredPluginMigrations: e?.deferredPluginMigrations, measure: e?.measure, observe: e?.observe === false ? false : void 0, env: e?.isolateEnv ? cloneEnvWithPlatformSemantics(process.env) : void 0, lowerPrecedenceEnv: e?.lowerPrecedenceEnv, pluginValidation: e?.skipPluginValidation ? "skip" : void 0 }).readConfigFileSnapshotWithPluginMetadata({ completePluginMetadata: e?.completePluginMetadata, prepareValidation: e?.prepareValidation, allowCurrentPluginMetadata: e?.allowCurrentPluginMetadata, recoverSuspicious: e?.recoverSuspicious === true, allowSuspiciousRecovery: e?.allowSuspiciousRecovery }); } async function promoteConfigSnapshotToLastKnownGood(e) { return await createConfigIO().promoteConfigSnapshotToLastKnownGood(e); } async function recoverConfigFromLastKnownGood(e) { return await createConfigIO().recoverConfigFromLastKnownGood(e); } async function recoverConfigFromJsonRootSuffix(e, t) { return await createConfigIO().recoverConfigFromJsonRootSuffix(e, t); } async function readSourceConfigSnapshot() { return await readConfigFileSnapshot(); } async function readConfigFileSnapshotForRuntimeTransaction(e) { return await createConfigIO({ env: createConfigRuntimeEnvBase(e, process.env, { preservedKeys: GATEWAY_CONFIG_SELECTION_ENV_KEYS }) }).readConfigFileSnapshot(); } async function readConfigFileSnapshotForWrite(e) { const t = { ...e?.pluginValidation ? { pluginValidation: e.pluginValidation } : e?.skipPluginValidation ? { pluginValidation: "skip" } : {}, ...e?.observe === false ? { observe: false } : {}, ...e?.deferredPluginMigrations !== void 0 ? { deferredPluginMigrations: e.deferredPluginMigrations } : {}, ...e?.preservedLegacyRootKeys ? { preservedLegacyRootKeys: e.preservedLegacyRootKeys } : {} }; for (let e = 0; e < 3; e += 1) try { const e = createConfigIO(t); const n = await (hasManagedRuntimeConfigWriteOwner(e.configPath) ? createConfigIO({ ...t, env: createManagedRuntimeEnvBase() }) : e).readConfigFileSnapshotForWrite(); n.writeOptions.assertConfigPathForWrite?.(); return n; } catch (t) { if (!(t instanceof ConfigMutationConflictError) || t.retryable || e === 2) throw t; } throw new Error("unreachable"); } async function readSourceConfigSnapshotForWrite() { return await readConfigFileSnapshotForWrite(); } async function writeConfigFile(e, t = {}) { t.assertConfigPathForWrite?.(); const n = t.deferredPluginMigrations ?? getDeferredPluginMigrationConfigFacts(t.baseSnapshot?.sourceConfig); const r = { ...n !== void 0 ? { deferredPluginMigrations: n } : {}, ...t.ownedConfigPathForWrite ? { configPath: t.ownedConfigPathForWrite } : {}, ...t.skipPluginValidation ? { pluginValidation: "skip" } : {}, ...t.observe === false ? { observe: false } : {}, ...t.preservedLegacyRootKeys ? { preservedLegacyRootKeys: t.preservedLegacyRootKeys } : {} }; const i = createConfigIO(r); return await withConfigWriteLock(i.configPath, async () => { t.assertConfigPathForWrite?.(); const n = hasManagedRuntimeConfigWriteOwner(i.configPath); const a = n ? createConfigIO({ ...r, env: createManagedRuntimeEnvBase() }) : i; assertConfigWriteAllowedInCurrentMode({ configPath: a.configPath }); const o = getRuntimeConfigSnapshot(); const s = getRuntimeConfigSourceSnapshot(); const c = Boolean(o); const l = Boolean(o && s); let u = t.inputBase === void 0 ? projectLegacyRuntimeConfigWrite(e, o, s) : e; const d = t.baseSnapshot ? { snapshot: t.baseSnapshot, pluginMetadataSnapshot: t.basePluginMetadataSnapshot } : await a.readConfigFileSnapshotWithPluginMetadata(); const f = d.snapshot; if (n) replaceEnvSnapshot(a.env, createManagedRuntimeEnvBase()); let p; let m = /* @__PURE__ */ new Map(); const h = captureConfigWriteLockGuard(a.configPath); const g = await a.writeConfigFile(u, { ...t, baseSnapshot: f, basePluginMetadataSnapshot: d.pluginMetadataSnapshot, envSnapshotForRestore: resolveWriteEnvSnapshotForPath({ actualConfigPath: a.configPath, expectedConfigPath: t.expectedConfigPath, envSnapshotForRestore: t.envSnapshotForRestore }), unsetPaths: resolveManagedUnsetPathsForWrite(t.unsetPaths), explicitSetValueSource: t.explicitSetPaths ? t.explicitSetValueSource ?? e : void 0, preCommitRuntimePreflight: async (e) => { u = e; if (n) m = await preflightManagedRuntimeConfigWrite(a.configPath, e, t.runtimeRefresh); else p = await preflightRuntimeSnapshotWrite({ nextSourceConfig: e, refreshOptions: t.runtimeRefresh, formatRefreshError: (e) => formatErrorMessage(e), createRefreshError: (e, t) => new ConfigRuntimeRefreshError(`Config write blocked before committing ${a.configPath}: active SecretRef resolution failed: ${e}`, { cause: t }) }); await t.preCommitRuntimePreflight?.(e); } }); if (t.skipRuntimeSnapshotRefresh && !c && !getRuntimeConfigSnapshotRefreshHandler()) return g; if (n) replaceEnvSnapshot(a.env, createManagedRuntimeEnvBase()); return await finalizeCommittedConfigWrite({ io: a, ioOptions: r, options: t, nextCfg: u, writeResult: g, baseSnapshot: f, hadBothSnapshots: l, deferRuntimeActivation: n, runtimePreflightResult: p, managedPreparedCandidates: m, assertPostCommitCurrent: h }); }, i.env, t.assertCurrent); } //#endregion export { copyRuntimeConfigWriteApplication as C, publishRuntimeConfigWrite as E, attachRuntimeConfigWriteApplication as S, getRuntimeConfigWriteApplication as T, recoverConfigFromJsonRootSuffix as _, readBestEffortConfig as a, withCurrentConfigPolicyReader as b, readConfigFileSnapshotForRuntimeTransaction as c, readCurrentConfigForPolicyCheck as d, readCurrentConfigForPolicyCheckAsync as f, readSourceConfigSnapshotForWrite as g, readSourceConfigSnapshot as h, promoteConfigSnapshotToLastKnownGood as i, readConfigFileSnapshotForWrite as l, readSourceConfigBestEffort as m, clearConfigCache as n, readBestEffortConfigSnapshot as o, readCurrentConfigForResolution as p, loadConfig as r, readConfigFileSnapshot as s, captureRuntimeConfigAsyncReader as t, readConfigFileSnapshotWithPluginMetadata as u, recoverConfigFromLastKnownGood as v, createRuntimeConfigWriteApplication as w, writeConfigFile as x, registerConfigWriteListener as y };