openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
964 lines (963 loc) • 36.4 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { l as redactToolDetail } from "./redact-Mj7pppxC.mjs";
import { t as isPlainObject } from "./plain-object-CGY5w7fM.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { s as readAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs";
import "./agent-scope-config-DmXgFGKP.mjs";
import { i as getCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs";
import { n as formatConfigIssueLines } from "./issue-format-WaYQX-7p.mjs";
import { i as normalizeConfigPatchReplacePaths, n as formatConfigPatchPath, r as isMergePatchObjectKeyAllowed, t as collectBaseArrayPaths } from "./patch-replace-paths-GzVnRbCn.mjs";
import { n as createMergePatch, t as applyMergePatch } from "./merge-patch-D-7aajuy.mjs";
import { p as resolveConfigSnapshotHash, s as parseConfigJson5 } from "./io.read-helpers-qAcqsRC0.mjs";
import { r as collectConfiguredModelRefs } from "./configured-model-refs-DtaDJ1Vw.mjs";
import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs";
import { $r as validateConfigSetParams, Jr as validateConfigGetParams, Qr as validateConfigSchemaParams, Xr as validateConfigSchemaLookupParams, Yr as validateConfigPatchParams, qr as validateConfigApplyParams } from "./src-BX8OAe1J.mjs";
import { n as normalizeSubmittedConfigModelRefs } from "./model-input-normalization-BSpz0kXV.mjs";
import { t as ConfigMutationConflictError } from "./mutation-conflict-Bs0nsNWn.mjs";
import { K as isBuiltInModelProviderOverlayId } from "./zod-schema.core-BWFCYYML.mjs";
import { t as projectRuntimeChangesOntoSource } from "./source-value-projection-Dw6wBBVW.mjs";
import { i as validateConfigObjectWithPlugins, r as validateConfigObjectRawWithPlugins } from "./validation-DSwgLhC7.mjs";
import { t as createConfigIO } from "./io.factory-DEa_bi2j.mjs";
import { t as ConfigWritePostCommitError } from "./io.write-errors-CuPAqPbq.mjs";
import { S as attachRuntimeConfigWriteApplication, l as readConfigFileSnapshotForWrite, w as createRuntimeConfigWriteApplication } from "./io.runtime-DsJ2dLCQ.mjs";
import "./io-4QsrsWTJ.mjs";
import { a as captureGatewayRootWorkAdmissionContinuationScope } from "./gateway-work-admission-79pid1hQ.mjs";
import { g as redactSecretDegradationReason, u as isRetryableSecretDegradationReason } from "./runtime-degraded-state-BSnwk5PQ.mjs";
import { u as getActiveSecretsRuntimeSnapshotState } from "./runtime-state-Dq_fFDZp.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs";
import "./config-CMA-J084.mjs";
import "./sessions-D5Vvu3AE.mjs";
import { t as extractDeliveryInfo } from "./delivery-info-DGIoojvH.mjs";
import { r as resolveGatewayAuth } from "./auth-resolve-C6_i-P4T.mjs";
import "./auth-dV1bLOjr.mjs";
import { n as holdGatewayPolicyResponse } from "./ws-policy-close-Cspv0w92.mjs";
import { r as SerializedJsonPayload } from "./serialized-json-Ji3ULdJD.mjs";
import { t as resolveGatewayReloadSettings } from "./config-reload-settings-CcAkiFrq.mjs";
import { t as resolveSharedGatewaySessionGeneration } from "./ws-shared-generation-BWsSp-Zl.mjs";
import { u as scheduleGatewayRestart } from "./restart-LzysM26p.mjs";
import { i as resolveConfigReloadMetadata, n as isNoopGatewayReloadPlan, o as diffConfigPaths, r as listConfigReloadRefinementPrefixes, s as diffGatewayReloadPaths, t as buildGatewayReloadPlan } from "./config-reload-plan-BWeZCeX8.mjs";
import { t as respondError } from "./response-C7fEiIN1.mjs";
import { n as defineValidatedGatewayHandler, t as assertValidParams } from "./validation-DwNk6A-B.mjs";
import { s as formatDoctorNonInteractiveHint, w as writeRestartSentinel } from "./restart-sentinel-DinoFPf6.mjs";
import { a as readGatewayRequestMutationAuthority } from "./session-mutation-guards-Bjnk_O0z.mjs";
import { r as restoreRedactedValues, t as redactConfigObject } from "./redact-snapshot-HHllfRSn.mjs";
import { i as lookupConfigSchema } from "./schema-B2vHhxPS.mjs";
import { i as loadGatewayRuntimeConfigSchema, n as invalidateGatewayRuntimeConfigSchema, r as loadGatewayConfigRedactionHints } from "./runtime-schema-XjYfZSYY.mjs";
import { i as summarizeChangedPaths, r as resolveControlPlaneActor, t as formatControlPlaneActor } from "./control-plane-audit-Deey8Q_Y.mjs";
import { n as parseRestartRequestParams } from "./restart-request-CgKElxx7.mjs";
import { a as sanitizePathForLog, i as resolveOpenPathCommand, n as formatOpenPathError, r as isHeadlessOpenPathError, t as execOpenPath } from "./open-path-CDsSHAWf.mjs";
import { a as prepareSecretsRuntimeSnapshot } from "./runtime-Dc04zUgW.mjs";
import { n as readConfigGetResponse, t as invalidateConfigGetResponseCache } from "./config-get-response-CKV1rrmh.mjs";
import { t as resolveBaseHashParam } from "./base-hash-C6Uj-zyN.mjs";
import { isDeepStrictEqual } from "node:util";
//#region src/gateway/server-methods/config-patch-intent.ts
function isHashlessPatchLwwPath(e) {
return e === "ui.prefs" || e.startsWith("ui.prefs.");
}
function hasHashlessPatchLwwStructure(e) {
if (!isPlainObject(e)) return false;
if (!Object.hasOwn(e, "ui")) return true;
const t = e.ui;
return isPlainObject(t) && (!Object.hasOwn(t, "prefs") || isPlainObject(t.prefs));
}
function diffConfigLeafPaths(e, t, n = "") {
if (isPlainObject(e) || isPlainObject(t)) {
const r = isPlainObject(e) ? e : {};
const i = isPlainObject(t) ? t : {};
const a = [.../* @__PURE__ */ new Set([...Object.keys(r), ...Object.keys(i)])];
if (a.length === 0) return isDeepStrictEqual(e, t) ? [] : [n || "<root>"];
return a.flatMap((e) => diffConfigLeafPaths(r[e], i[e], n ? `${n}.${e}` : e));
}
return diffConfigPaths(e, t, n);
}
//#endregion
//#region src/gateway/server-methods/config-submission-validation.ts
const MAX_CONFIG_ISSUES_IN_ERROR_SUMMARY = 3;
function summarizeConfigValidationIssues(e) {
const t = e.slice(0, MAX_CONFIG_ISSUES_IN_ERROR_SUMMARY);
const n = normalizeStringEntries(formatConfigIssueLines(t, "", { normalizeRoot: true }));
if (n.length === 0) return "invalid config";
const r = Math.max(0, e.length - n.length);
return `invalid config: ${n.join("; ")}${r > 0 ? ` (+${r} more issue${r === 1 ? "" : "s"})` : ""}`;
}
function validateSubmittedConfigOrRespond(e) {
const t = e.candidate;
const n = normalizeSubmittedConfigModelRefs(t, e.pluginMetadataSnapshot?.owners.modelIdNormalizationPolicies);
const respondInvalid = (t) => {
e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, summarizeConfigValidationIssues(t), { details: { issues: t } }));
};
const r = { pluginMetadataSnapshot: e.pluginMetadataSnapshot };
const i = validateConfigObjectRawWithPlugins(n, r);
if (!i.ok) {
respondInvalid(i.issues);
return null;
}
const a = validateConfigObjectWithPlugins(n, r);
if (!a.ok) {
respondInvalid(a.issues);
return null;
}
return {
validationCandidate: n,
config: a.config
};
}
//#endregion
//#region src/gateway/server-methods/config-write-reply.ts
/**
* Success replies carry and log the write's billing-route warnings. Error replies, including a
* write that persisted but was not applied, moved no route and stay unchanged.
*/
function replyWithBillingRouteWarnings(e, t, n) {
return (...r) => {
const [i, a] = r;
if (i && t.length > 0 && isRecord(a)) {
for (const e of t) n?.logGateway?.warn(e);
r[1] = {
...a,
billingRouteWarnings: t
};
}
e?.(...r);
};
}
//#endregion
//#region src/gateway/server-methods/config-write-flow.ts
function resolveGatewayConfigPath(e) {
return e?.path ?? createConfigIO().configPath;
}
/** Compares the effective shared Gateway auth surface that active clients use. */
function didSharedGatewayAuthChange(e, t) {
const n = resolveGatewayAuth({
authConfig: e.gateway?.auth,
env: process.env,
tailscaleMode: e.gateway?.tailscale?.mode
});
const r = resolveGatewayAuth({
authConfig: t.gateway?.auth,
env: process.env,
tailscaleMode: t.gateway?.tailscale?.mode
});
return n.mode !== r.mode || n.mode !== "trusted-proxy" && resolveSharedGatewaySessionGeneration(n, e.gateway?.trustedProxies) !== resolveSharedGatewaySessionGeneration(r, t.gateway?.trustedProxies);
}
function projectAuthoredValuesOntoRuntimeOverlay(e) {
const { source: t, active: n } = e;
if (n === void 0) return structuredClone(e.fallback);
if (!isRecord(t) || !isRecord(n)) return structuredClone(isDeepStrictEqual(t, e.activeSource) ? n : e.fallback);
const r = isRecord(e.fallback) ? e.fallback : {};
const i = isRecord(e.activeSource) ? e.activeSource : {};
const a = new Set(Object.keys(t));
return Object.fromEntries([...Object.entries(r).filter(([e]) => !a.has(e)), ...Object.keys(t).map((e) => [e, projectAuthoredValuesOntoRuntimeOverlay({
source: t[e],
activeSource: i[e],
active: n[e],
fallback: r[e]
})])]);
}
/** Compares against the active secrets-expanded config when one is available. */
function didActiveSharedGatewayAuthChange(e) {
const t = getActiveSecretsRuntimeSnapshotState();
if (!t) return didSharedGatewayAuthChange(e.fallbackPrev, e.next);
const n = (e.fallbackSource ?? t.sourceConfig).gateway;
const r = t.sourceConfig.gateway;
const i = t.config.gateway;
const a = e.fallbackPrev.gateway;
const selectOwnedGatewayValue = (e) => n && Object.hasOwn(n, e) ? projectAuthoredValuesOntoRuntimeOverlay({
source: n[e],
activeSource: r?.[e],
active: i?.[e],
fallback: a?.[e]
}) : a?.[e];
return didSharedGatewayAuthChange({
...e.fallbackPrev,
gateway: {
...a,
auth: selectOwnedGatewayValue("auth"),
tailscale: selectOwnedGatewayValue("tailscale"),
trustedProxies: selectOwnedGatewayValue("trustedProxies")
}
}, e.next);
}
function resolveConfigRestartRequirement(e) {
const t = resolveGatewayReloadSettings(e.nextConfig);
const n = buildGatewayReloadPlan(e.changedPaths, {
previousConfig: e.previousConfig,
candidateConfig: e.nextConfig
});
const r = !isNoopGatewayReloadPlan(n) && (t.mode === "off" || n.restartGateway);
return {
requiresRestart: r,
scheduleDirectRestart: r && t.mode === "off" && !e.deferRestartWhenReloadOff
};
}
/**
* `openclaw config set/patch/unset` route here while a Gateway owns the state and keep the
* offline write's outcomes. Stable Gateways close the request schema, so the connection
* identity carries this rather than a request field.
*/
function isCliRoutedConfigPatch(e, t) {
const n = t?.connect?.client;
return e === "config.patch" && n?.id === GATEWAY_CLIENT_NAMES.CLI && n.mode === GATEWAY_CLIENT_MODES.CLI;
}
/**
* Responds when an awaited runtime application did not fully apply, and reports whether it
* did. A CLI-routed write keeps the offline outcome: persisted and restarting is success.
*/
function respondConfigWriteApplicationOutcome(e) {
const { outcome: t, mode: n } = e;
if (t === "applied") return false;
if (t === "restart-pending" && isCliRoutedConfigPatch(n, e.client)) {
e.respond(true, {
...e.success,
restartPending: true
}, void 0);
return true;
}
const r = t === "applied-restart-required" ? `${n} persisted and updated the active Gateway, but a recovery restart is required; wait for the Gateway to restart, then run config.get to confirm the active revision` : t === "restart-pending" ? `${n} persisted and was accepted for restart; wait for the Gateway to restart, then run config.get to confirm the active revision` : `${n} persisted but was not applied to the active Gateway (${t}); run config.get, then use config.apply to reapply the saved config or restart the Gateway`;
e.respond(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, r, { details: { persistedConfig: e.persistedConfig } }));
return true;
}
/** Returns whether a managed config write can settle without restarting the Gateway. */
function shouldAwaitGatewayConfigApplication(e) {
return resolveGatewayReloadSettings(e.nextConfig).mode !== "off" && !resolveConfigRestartRequirement(e).requiresRestart;
}
const pickModelRouteKeys = (e) => [
e?.model,
e?.models,
e?.subagents,
e?.heartbeat
];
/** The config inputs a billing route depends on; workspace, tools, and identity edits are not. */
function billingRouteInputs(e) {
return {
models: e.models,
auth: e.auth,
requiredProfile: e.cloudWorkers?.requiredProfile,
defaults: pickModelRouteKeys(e.agents?.defaults),
entries: Object.entries(e.agents?.entries ?? {}).map(([e, t]) => [e, pickModelRouteKeys(t)]),
refs: collectConfiguredModelRefs(e)
};
}
/**
* Names model consumers whose billing route (API key, subscription, or a CLI runtime's own
* login) the committed write moved. Advisory: the write already succeeded, so a comparison
* failure is logged and never fails the response.
*/
async function collectConfigWriteBillingRouteWarnings(e) {
const t = e.before ?? {};
const { after: n } = e;
try {
if (isDeepStrictEqual(billingRouteInputs(t), billingRouteInputs(n))) return [];
const { collectModelBillingRouteMigrationWarnings: e } = await import("./model-billing-route-migration-DtDPMCck.mjs");
return e({
before: t,
after: n,
metadataSnapshot: getCurrentPluginMetadataSnapshot({ config: n })
});
} catch (t) {
e.context?.logGateway?.warn(`billing route comparison skipped: ${String(t)}`);
return [];
}
}
/** Persists a gateway config write and returns follow-up work that must run after response. */
async function commitGatewayConfigWrite(e) {
const t = e.context?.getCommittedRuntimeConfig?.() ?? e.snapshot.config;
const n = e.awaitRuntimeApplication ? createRuntimeConfigWriteApplication(captureGatewayRootWorkAdmissionContinuationScope()?.run) : void 0;
holdGatewayPolicyResponse(e.respond);
const r = await replaceConfigFile({
sourceConfig: e.nextConfig,
baseHash: resolveConfigSnapshotHash(e.snapshot) ?? void 0,
writeOptions: attachRuntimeConfigWriteApplication({
...e.writeOptions,
auditOrigin: "config-rpc",
runtimeRefresh: {
...e.writeOptions.runtimeRefresh,
includeAuthStoreRefs: false
}
}, n),
afterWrite: { mode: "auto" }
});
const i = await collectConfigWriteBillingRouteWarnings({
before: e.snapshot.sourceConfig,
after: e.nextConfig,
context: e.context
});
return {
path: resolveGatewayConfigPath(e.snapshot),
config: r.nextConfig,
...i.length > 0 ? { billingRouteWarnings: i } : {},
reply: replyWithBillingRouteWarnings(e.respond, i, e.context),
hash: r.persistedHash,
...n ? { application: n.claimed ? n.result : Promise.resolve("unclaimed") } : {},
queueFollowUp: () => {
if (!n?.claimed) queueMicrotask(() => {
e.context?.enforceSharedGatewayAuthGenerationForConfigWrite?.(r.nextConfig, t);
if (e.disconnectSharedAuthClients) e.context?.disconnectClientsUsingSharedGatewayAuth?.();
});
}
};
}
async function resolveGatewayConfigRestartWriteResult(e) {
const { sessionKey: t, note: n, restartDelayMs: r, deliveryContext: i, threadId: a } = parseRestartRequestParams(e.requestParams);
const o = await extractDeliveryInfo(t);
const s = resolveControlPlaneActor(e.client);
const c = resolveConfigRestartRequirement({
...e,
deferRestartWhenReloadOff: isCliRoutedConfigPatch(e.mode, e.client)
});
const l = {
kind: e.kind,
status: "ok",
ts: Date.now(),
sessionKey: t,
deliveryContext: i ?? o.deliveryContext,
threadId: a ?? o.threadId,
message: n ?? null,
doctorHint: formatDoctorNonInteractiveHint(),
stats: {
mode: e.mode,
root: e.configPath,
requiresRestart: c.requiresRestart
}
};
const u = await writeRestartSentinel(l).then(() => true, () => false);
const d = c.scheduleDirectRestart ? scheduleGatewayRestart({
delayMs: r,
reason: e.mode,
audit: {
actor: s.actor,
deviceId: s.deviceId,
clientIp: s.clientIp,
changedPaths: e.changedPaths
}
}) : void 0;
if (d?.coalesced) e.context?.logGateway?.warn(`${e.mode} restart coalesced ${formatControlPlaneActor(s)} delayMs=${d.delayMs}`);
return {
payload: l,
sentinelPersisted: u,
restart: d
};
}
//#endregion
//#region src/gateway/server-methods/config-write-snapshot.ts
function requireConfigBaseHash(e, t, n, r) {
if (!t.exists) return true;
const i = resolveConfigSnapshotHash(t);
const a = resolveBaseHashParam(e);
if (!i || !a) {
respondError(n, ErrorCodes.INVALID_REQUEST, `config base hash ${i ? "required" : "unavailable"}; re-run config.get and retry`);
return false;
}
if (a !== r.projectRawHash(i)) {
invalidateConfigGetResponseCache();
respondError(n, ErrorCodes.INVALID_REQUEST, "config changed since last load; re-run config.get and retry");
return false;
}
return true;
}
async function readConfigWriteSnapshotOrRespond(e, t, n) {
const r = await readConfigFileSnapshotForWrite();
if (!requireConfigBaseHash(e, r.snapshot, t, n)) return null;
return r;
}
//#endregion
//#region src/gateway/server-methods/config.ts
const configWriteRecovery = /* @__PURE__ */ new WeakMap();
const serializedConfigReads = /* @__PURE__ */ new WeakMap();
function configReadPayload(e, t) {
if (!t) return e;
let n = serializedConfigReads.get(e);
if (!n) {
n = new SerializedJsonPayload(e);
serializedConfigReads.set(e, n);
}
return n;
}
function collectDestructiveArrayPatchPaths(e) {
if (!isPlainObject(e.patch) || !isPlainObject(e.base)) return [];
const t = isPlainObject(e.merged) ? e.merged : {};
const n = [];
for (const [r, i] of Object.entries(e.patch)) {
const a = formatConfigPatchPath(e.path ?? "", r);
if (!isMergePatchObjectKeyAllowed(r, e.path)) continue;
const o = e.base[r];
const s = t[r];
if (Array.isArray(o)) {
if (i === null || !Array.isArray(i)) {
n.push(a);
continue;
}
if (Array.isArray(s)) {
if (isConfigPatchIdKeyedArray(o)) {
if (!idKeyedArrayPreservesBaseIds(o, s)) {
n.push(a);
continue;
}
n.push(...collectDestructiveIdKeyedArrayEntryPatchPaths({
base: o,
patch: i,
merged: s,
path: a
}));
} else if (!arrayPreservesBaseEntries(o, s)) {
n.push(a);
continue;
}
}
} else if (isPlainObject(o) && !isPlainObject(i)) {
n.push(...collectBaseArrayPaths(o, a));
continue;
}
if (isPlainObject(i)) n.push(...collectDestructiveArrayPatchPaths({
base: o,
patch: i,
merged: s,
path: a
}));
}
return n;
}
function isConfigPatchObjectWithStringId(e) {
return isPlainObject(e) && typeof e.id === "string" && e.id.length > 0;
}
function assertNoDuplicateConfigPatchIds(e) {
const t = e.path ?? "";
if (Array.isArray(e.patch)) {
if (!Array.isArray(e.current) || e.replacePaths.has(t) || !isConfigPatchIdKeyedArray(e.current)) return;
const n = /* @__PURE__ */ new Set();
for (const r of e.current) {
if (n.has(r.id)) throw new Error(`Cannot ID-merge array at ${t || "<root>"}: current config contains duplicate ID ${r.id}; use replacePaths for an explicit replacement.`);
n.add(r.id);
}
const r = /* @__PURE__ */ new Set();
for (const n of e.patch) {
if (!isConfigPatchObjectWithStringId(n)) continue;
if (r.has(n.id)) throw new Error(`Ambiguous duplicate ID ${n.id} in array at ${t || "<root>"}.`);
r.add(n.id);
}
const i = new Map(e.current.map((e) => [e.id, e]));
for (const n of e.patch) {
if (!isConfigPatchObjectWithStringId(n)) continue;
const r = i.get(n.id);
if (r) assertNoDuplicateConfigPatchIds({
patch: n,
current: r,
replacePaths: e.replacePaths,
path: `${t}[]`
});
}
return;
}
if (!isRecord(e.patch) || !isRecord(e.current)) return;
for (const [n, r] of Object.entries(e.patch)) assertNoDuplicateConfigPatchIds({
patch: r,
current: e.current[n],
replacePaths: e.replacePaths,
path: formatConfigPatchPath(t, n)
});
}
function isConfigPatchIdKeyedArray(e) {
return e.every(isConfigPatchObjectWithStringId);
}
function idKeyedArrayPreservesBaseIds(e, t) {
const n = new Set(t.filter(isConfigPatchObjectWithStringId).map((e) => e.id));
return e.every((e) => n.has(e.id));
}
function arrayPreservesBaseEntries(e, t) {
const n = [...t];
for (const t of e) {
const e = n.findIndex((e) => isDeepStrictEqual(e, t));
if (e === -1) return false;
n.splice(e, 1);
}
return true;
}
function collectDestructiveIdKeyedArrayEntryPatchPaths(e) {
const t = new Map(e.base.map((e) => [e.id, e]));
const n = new Map(e.merged.filter(isConfigPatchObjectWithStringId).map((e) => [e.id, e]));
const r = [];
for (const i of e.patch) {
if (!isConfigPatchObjectWithStringId(i)) continue;
const a = t.get(i.id);
const o = n.get(i.id);
if (!a || !o) continue;
r.push(...collectDestructiveArrayPatchPaths({
base: a,
patch: i,
merged: o,
path: `${e.path}[]`
}));
}
return r;
}
function rejectDestructiveArrayPatchWithoutIntent(e) {
const t = collectDestructiveArrayPatchPaths({
base: e.currentConfig,
patch: e.patch,
merged: e.mergedConfig
}).filter((t) => !e.replacePaths.has(t));
if (t.length === 0) return false;
respondError(e.respond, ErrorCodes.INVALID_REQUEST, `config.patch would remove entries from array path(s): ${t.join(", ")}. Pass replacePaths with the exact path(s) when this is intentional, or use config.apply for full-config replacement.`);
return true;
}
function hasOwnRecordValue(e, t) {
return isRecord(e) && Object.hasOwn(e, t);
}
function stripBundledProviderRuntimeDefaults(e) {
if (!isRecord(e.candidate)) return e.candidate;
const t = e.candidate.models;
if (!isRecord(t) || !isRecord(t.providers)) return e.candidate;
const n = isRecord(e.sourceConfig) ? e.sourceConfig.models : void 0;
const r = isRecord(n) ? n.providers : void 0;
let i;
for (const [e, n] of Object.entries(t.providers)) {
if (!isBuiltInModelProviderOverlayId(e) || !isRecord(n)) continue;
const a = isRecord(r) ? r[e] : void 0;
let o;
if (n.baseUrl === "" && !hasOwnRecordValue(a, "baseUrl")) {
o = { ...n };
delete o.baseUrl;
}
if (Array.isArray(n.models) && n.models.length === 0 && !hasOwnRecordValue(a, "models")) {
o ??= { ...n };
delete o.models;
}
if (o) {
i ??= { ...t.providers };
i[e] = o;
}
}
if (!i) return e.candidate;
return {
...e.candidate,
models: {
...t,
providers: i
}
};
}
async function prepareConfigReplacementOrRespond(e, t, n) {
const r = await readConfigWriteSnapshotOrRespond(e, t, n);
if (!r) return null;
const { snapshot: i, writeOptions: a } = r;
const o = parseConfigJson5(e.raw);
if (!o.ok) {
respondError(t, ErrorCodes.INVALID_REQUEST, o.error);
return null;
}
const s = loadGatewayConfigRedactionHints();
const c = restoreRedactedValues(o.parsed, i.config, s);
if (!c.ok) {
respondError(t, ErrorCodes.INVALID_REQUEST, c.humanReadableMessage ?? "invalid config");
return null;
}
const l = i.valid ? projectRuntimeChangesOntoSource(i.resolved, i.config, c.result) : c.result;
const u = validateSubmittedConfigOrRespond({
candidate: stripBundledProviderRuntimeDefaults({
candidate: l,
sourceConfig: i.sourceConfig
}),
pluginMetadataSnapshot: a.basePluginMetadataSnapshot,
respond: t
});
if (!u) return null;
return {
writeSnapshot: r,
config: u.config,
writeConfig: u.validationCandidate,
uiHints: s
};
}
function listExplicitAgentRosterIds(e) {
const t = readAgentRosterProperty(e);
if (t?.kind === "entries" && isRecord(t.value)) return Object.keys(t.value);
if (t?.kind !== "list" || !Array.isArray(t.value)) return [];
return t.value.flatMap((e) => isRecord(e) && typeof e.id === "string" ? [e.id] : []);
}
function rejectDroppedAgentRosterEntries(e) {
const t = new Set(listExplicitAgentRosterIds(e.submittedConfig).map((e) => normalizeAgentId(e)));
const n = listExplicitAgentRosterIds(e.currentConfig).filter((e) => !t.has(normalizeAgentId(e))).toSorted();
if (n.length === 0) return false;
respondError(e.respond, ErrorCodes.INVALID_REQUEST, `config.set would remove existing agent entries: ${n.join(", ")}. Use the agents.delete RPC or \`openclaw agents delete <id>\` for intentional deletion.`);
return true;
}
async function ensureResolvableSecretRefsOrRespond(e) {
try {
const t = await prepareSecretsRuntimeSnapshot({
config: e.config,
includeAuthStoreRefs: false,
allowUnavailableSecretOwners: true
});
for (const e of t.degradedOwners ?? []) {
const t = redactSecretDegradationReason(e.reason);
if (!isRetryableSecretDegradationReason(t)) throw new Error(t);
}
return t;
} catch (t) {
const n = formatErrorMessage(t);
e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `invalid config: active SecretRef resolution failed (${n})`));
return null;
}
}
function preparedSecretDegradationPayload(e) {
const t = (e.degradedOwners ?? []).map((e) => ({
ownerKind: e.ownerKind,
ownerId: e.ownerId,
state: e.degradationState ?? "cold",
paths: [...e.paths],
reason: redactSecretDegradationReason(e.reason)
}));
return t.length > 0 ? { degradedSecretOwners: t } : {};
}
async function commitConfigRestartWrite(e) {
const { snapshot: t, writeOptions: n } = e.writeSnapshot;
const r = diffGatewayReloadPaths(t.config, e.nextConfig, listConfigReloadRefinementPrefixes());
e.context?.logGateway?.info(`${e.mode} write ${formatControlPlaneActor(resolveControlPlaneActor(e.client))} changedPaths=${summarizeChangedPaths(r)} restartReason=${e.mode}`);
const i = didSharedGatewayAuthChange(t.config, e.nextConfig) || didActiveSharedGatewayAuthChange({
fallbackPrev: t.config,
fallbackSource: t.sourceConfig,
next: e.preparedSecretsSnapshot.config
});
const a = await commitGatewayConfigWriteOrRespond({
snapshot: t,
writeOptions: n,
nextConfig: e.writeConfig,
context: e.context,
disconnectSharedAuthClients: i,
awaitRuntimeApplication: shouldAwaitGatewayConfigApplication({
changedPaths: r,
previousConfig: t.config,
nextConfig: e.nextConfig
}),
respond: e.respond
});
if (!a) return;
const o = {
...a.hash ? { hash: e.context.configRevisionProjector.projectRawHash(a.hash) } : {},
...!e.summary ? { config: redactConfigObject(a.config, e.uiHints) } : {}
};
if (a.application && respondConfigWriteApplicationOutcome({
outcome: await a.application,
mode: e.mode,
client: e.client,
respond: a.reply,
success: {
ok: true,
path: a.path,
...o,
changedPaths: r
},
persistedConfig: o
})) {
a.queueFollowUp();
return;
}
const s = isNoopGatewayReloadPlan(buildGatewayReloadPlan(r, {
previousConfig: t.config,
candidateConfig: e.nextConfig
}));
if (!s) invalidateGatewayRuntimeConfigSchema();
if (e.summary && s) {
a.reply(true, {
ok: true,
path: a.path,
...o,
changedPaths: r
});
a.queueFollowUp();
return;
}
const { payload: c, sentinelPersisted: l, restart: u } = await resolveGatewayConfigRestartWriteResult({
requestParams: e.requestParams,
kind: e.mode === "config.patch" ? "config-patch" : "config-apply",
mode: e.mode,
configPath: a.path,
changedPaths: r,
previousConfig: t.config,
nextConfig: e.nextConfig,
client: e.client,
context: e.context
});
a.reply(true, {
ok: true,
path: a.path,
...o,
...e.mode === "config.patch" ? { changedPaths: r } : {},
...preparedSecretDegradationPayload(e.preparedSecretsSnapshot),
restart: u,
sentinel: {
persisted: l,
payload: c
}
}, void 0);
a.queueFollowUp();
}
async function commitGatewayConfigWriteOrRespond(e) {
const t = e.context.configRevisionProjector;
const n = configWriteRecovery.get(t);
try {
const r = await commitGatewayConfigWrite(e);
if (configWriteRecovery.get(t) === n) configWriteRecovery.delete(t);
return r;
} catch (n) {
if (n instanceof ConfigWritePostCommitError) {
const r = errorShape(ErrorCodes.UNAVAILABLE, redactToolDetail(formatErrorMessage(n)), { details: {
publication: n.publication,
rollbackStatus: n.rollbackStatus,
configPath: n.configPath,
...n.recoveryBackupPath !== void 0 ? { recoveryBackupPath: n.recoveryBackupPath } : {}
} });
if (n.rollbackStatus !== "restored") {
configWriteRecovery.set(t, {
configPath: n.configPath,
error: r
});
invalidateConfigGetResponseCache();
}
e.respond(false, void 0, r);
return null;
}
if (!(n instanceof ConfigMutationConflictError)) throw n;
if (n.retryable) invalidateConfigGetResponseCache();
e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, n.retryable ? `${n.message}; re-run config.get and retry` : n.message));
return null;
}
}
const configHandlers = {
"config.get": async ({ params: e, respond: t, context: n, acceptsSerializedJson: r }) => {
if (!assertValidParams(e, validateConfigGetParams, "config.get", t)) return;
const i = n.configRevisionProjector;
const a = configWriteRecovery.get(i);
const o = await readConfigGetResponse({
getHotReloadStatus: n.getConfigReloaderHotReloadStatus,
revisionProjector: n.configRevisionProjector
});
const s = configWriteRecovery.get(i);
if (s?.configPath === o.path) {
if (s === a && o.exists && o.valid) configWriteRecovery.delete(i);
else {
t(true, {
...o,
writeError: s.error
}, void 0);
return;
}
}
t(true, configReadPayload(o, r), void 0);
},
"config.schema": ({ params: e, respond: t, acceptsSerializedJson: n }) => {
if (!assertValidParams(e, validateConfigSchemaParams, "config.schema", t)) return;
t(true, configReadPayload(loadGatewayRuntimeConfigSchema(), n), void 0);
},
"config.schema.lookup": defineValidatedGatewayHandler("config.schema.lookup", validateConfigSchemaLookupParams, ({ params: e, respond: t }) => {
const { path: n } = e;
const r = loadGatewayRuntimeConfigSchema();
const i = lookupConfigSchema(r, n, resolveConfigReloadMetadata);
if (!i) {
respondError(t, ErrorCodes.INVALID_REQUEST, "config schema path not found");
return;
}
t(true, i, void 0);
}),
"config.set": async ({ params: e, respond: t, context: n }) => {
if (!assertValidParams(e, validateConfigSetParams, "config.set", t)) return;
const r = await prepareConfigReplacementOrRespond(e, t, n.configRevisionProjector);
if (!r) return;
const { snapshot: i, writeOptions: a } = r.writeSnapshot;
if (rejectDroppedAgentRosterEntries({
currentConfig: i.config,
submittedConfig: r.config,
respond: t
})) return;
const o = await ensureResolvableSecretRefsOrRespond({
config: r.config,
respond: t
});
if (!o) return;
const s = await commitGatewayConfigWriteOrRespond({
snapshot: i,
writeOptions: a,
nextConfig: r.writeConfig,
context: n,
respond: t
});
if (!s) return;
invalidateGatewayRuntimeConfigSchema();
s.reply(true, {
ok: true,
path: s.path,
...s.hash ? { hash: n.configRevisionProjector.projectRawHash(s.hash) } : {},
config: redactConfigObject(s.config, r.uiHints),
...preparedSecretDegradationPayload(o)
}, void 0);
s.queueFollowUp();
},
"config.patch": async (e) => {
const { params: t, respond: n, client: r, context: i } = e;
const a = readGatewayRequestMutationAuthority(e);
if (!assertValidParams(t, validateConfigPatchParams, "config.patch", n)) return;
const o = resolveBaseHashParam(t) === null;
const s = o ? await readConfigFileSnapshotForWrite() : await readConfigWriteSnapshotOrRespond(t, n, i.configRevisionProjector);
if (!s) return;
const { snapshot: c, writeOptions: l } = s;
const u = l.basePluginMetadataSnapshot?.owners.modelIdNormalizationPolicies;
if (!c.valid) {
n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `${summarizeConfigValidationIssues(c.issues)}; fix (openclaw doctor) before patching`, { details: { issues: c.issues } }));
return;
}
const d = parseConfigJson5(t.raw);
if (!d.ok) {
respondError(n, ErrorCodes.INVALID_REQUEST, d.error);
return;
}
if (!isRecord(d.parsed)) {
respondError(n, ErrorCodes.INVALID_REQUEST, "config.patch raw must be an object");
return;
}
const f = normalizeSubmittedConfigModelRefs(d.parsed, u);
if (o && !hasHashlessPatchLwwStructure(f)) {
respondError(n, ErrorCodes.INVALID_REQUEST, "config base hash required; re-run config.get and retry");
return;
}
const p = normalizeConfigPatchReplacePaths(t.replacePaths);
try {
assertNoDuplicateConfigPatchIds({
patch: f,
current: c.config,
replacePaths: p
});
} catch (e) {
n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, formatErrorMessage(e)));
return;
}
const m = normalizeSubmittedConfigModelRefs(c.sourceConfig, u);
const h = applyMergePatch(m, f, {
mergeObjectArraysById: true,
replaceArrayPaths: p
});
const g = loadGatewayConfigRedactionHints();
const _ = restoreRedactedValues(h, c.config, g);
if (!_.ok) {
respondError(n, ErrorCodes.INVALID_REQUEST, _.humanReadableMessage ?? "invalid config");
return;
}
if (rejectDestructiveArrayPatchWithoutIntent({
currentConfig: c.config,
mergedConfig: applyMergePatch(c.config, createMergePatch(m, _.result)),
patch: f,
replacePaths: p,
respond: n
})) return;
const v = diffConfigLeafPaths(m, _.result);
if (o && !v.every(isHashlessPatchLwwPath)) {
const e = v.filter((e) => !isHashlessPatchLwwPath(e));
respondError(n, ErrorCodes.INVALID_REQUEST, `config base hash required for ${e.join(", ")}; re-run config.get and retry with baseHash`);
return;
}
const y = resolveControlPlaneActor(r);
if (v.length === 0) {
i?.logGateway?.info(`config.patch noop ${formatControlPlaneActor(y)} (no changed paths)`);
n(true, {
ok: true,
noop: true,
changedPaths: [],
path: resolveGatewayConfigPath(c),
...t.response !== "summary" ? { config: redactConfigObject(c.config, g) } : {}
}, void 0);
return;
}
const b = validateSubmittedConfigOrRespond({
candidate: _.result,
pluginMetadataSnapshot: l.basePluginMetadataSnapshot,
respond: n
});
if (!b) return;
const x = b.validationCandidate;
const S = b.config;
const C = await ensureResolvableSecretRefsOrRespond({
config: S,
respond: n
});
if (!C) return;
const w = [];
const T = m.agents?.entries;
const E = f.agents?.entries;
if (!o && T && E) {
for (const [e, t] of Object.entries(E)) if (t === null && Object.hasOwn(T, e)) w.push(e);
}
await commitConfigRestartWrite({
requestParams: t,
mode: "config.patch",
writeSnapshot: {
...s,
writeOptions: {
...l,
allowedAgentRosterRemovals: w,
assertBeforePublish: () => {
l.assertBeforePublish?.();
a.assertCurrent();
}
}
},
writeConfig: x,
nextConfig: S,
client: r,
context: i,
respond: n,
uiHints: g,
preparedSecretsSnapshot: C,
summary: t.response === "summary"
});
},
"config.apply": async ({ params: e, respond: t, client: n, context: r }) => {
if (!assertValidParams(e, validateConfigApplyParams, "config.apply", t)) return;
const i = await prepareConfigReplacementOrRespond(e, t, r.configRevisionProjector);
if (!i) return;
const a = await ensureResolvableSecretRefsOrRespond({
config: i.config,
respond: t
});
if (!a) return;
await commitConfigRestartWrite({
requestParams: e,
mode: "config.apply",
writeSnapshot: i.writeSnapshot,
writeConfig: i.writeConfig,
nextConfig: i.config,
client: n,
context: r,
respond: t,
uiHints: i.uiHints,
preparedSecretsSnapshot: a
});
},
"config.openFile": async ({ params: e, respond: t, context: n }) => {
if (!assertValidParams(e, validateConfigGetParams, "config.openFile", t)) return;
const r = createConfigIO().configPath;
const i = resolveOpenPathCommand(r);
try {
await execOpenPath(i);
t(true, {
ok: true,
path: r
}, void 0);
} catch (e) {
const a = formatOpenPathError(e);
const o = isHeadlessOpenPathError(e, i) ? `Cannot open file in headless environment. File path: ${r}. This environment appears to lack a graphical or terminal browser handler.` : `Failed to open config file: ${a}`;
n?.logGateway?.warn(`config.openFile failed path=${sanitizePathForLog(r)}: ${a}`);
t(true, {
ok: false,
path: r,
error: o
}, void 0);
}
}
};
//#endregion
export { configHandlers };