openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
155 lines (154 loc) • 7.67 kB
JavaScript
import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs";
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { S as resolveIsConfigReadOnly, m as resolveConfigPath } from "./paths-DAcAg5aV.mjs";
import { r as normalizeOptionalAccountId } from "./account-id-BqKT3GuY.mjs";
import { a as executeSqliteQueryTakeFirstSync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract-DfPjvL0M.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { m as withStateDatabaseColdAdmission } from "./gateway-state-owner-Bnv5owvG.mjs";
import { a as resolveUpdateRehearsalRoot } from "./update-rehearsal-paths-Dr1MbUA_.mjs";
import { m as withExistingOpenClawStateDatabaseReadOnly } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { a as isStatePostgres } from "./openclaw-state-db-engine-sM0tpxNy.mjs";
import { t as readConfigMachineState } from "./config-machine-state-DzLVE1Wy.mjs";
import { u as normalizePluginsConfig, w as resolveChannelConfigEnablement } from "./config-state-B1JlHgba.mjs";
import { n as cloneConfigWithResolutionFacts } from "./resolution-facts-xaIKuREs.mjs";
import { t as readConfigMachineStateAsync } from "./config-machine-state-async-DBzEhTyN.mjs";
import { r as setConfigValueAtPath, t as getConfigValueAtPath } from "./config-paths-DTAbnrwT.mjs";
import { i as passesManifestOwnerBasePolicy } from "./manifest-owner-policy-B8Brw4Zo.mjs";
import { a as writeConfigMachineState } from "./config-machine-state-write-DanSUxEP.mjs";
import { isDeepStrictEqual } from "node:util";
//#region src/commands/doctor/shared/legacy-webhook-pins.ts
const HISTORICAL_WEBHOOK_CHANNELS = [
"telegram",
"feishu",
"msteams",
"nextcloud-talk"
];
function webhookCompletionKey(e) {
return `webhookListeners:${resolveConfigPath(e)}`;
}
/**
* Doctor records decisions in config; startup records them in machine state, including a
* channel Doctor left pending. Config decisions win per channel.
*/
function mergeWebhookCompletion(e, t) {
return e && e !== true && t && t !== true ? {
...t,
...e
} : e ?? t;
}
async function readWebhookCompletion(e, t) {
const n = e.meta?.migrations?.webhookListeners;
return n === true ? n : mergeWebhookCompletion(n, await readConfigMachineStateAsync(webhookCompletionKey(t), { env: t }));
}
/** No config bytes changed, so this completion does not depend on config rollback. */
function prepareUnwrittenWebhookCompletion(e, t, n) {
const r = t.config.meta?.migrations?.webhookListeners;
if (r === void 0) return;
const i = resolveIsConfigReadOnly(n);
const a = cloneConfigWithResolutionFacts(e.sourceConfig);
a.meta ??= {};
a.meta.migrations ??= {};
a.meta.migrations.webhookListeners = r;
if (!isDeepStrictEqual(a, t.config)) {
if (!i) return;
throw new Error(`Webhook listeners need migration in the externally managed config. Add the required legacyWebhook endpoints and meta.migrations.webhookListeners completion marker in that source, then restart.\n${t.changes.join("\n")}`);
}
return {
key: webhookCompletionKey(n),
value: a.meta.migrations.webhookListeners
};
}
function recordUnwrittenWebhookCompletion(e, t, n) {
const r = prepareUnwrittenWebhookCompletion(e, t, n);
if (!r) return false;
writeConfigMachineState(r.key, r.value, { env: n });
return true;
}
/** One synchronous pass shares its receipt, including its own rehearsal writes. */
function createHistoricalWebhookPinMigration(e = process.env, t, n = false) {
const r = {
env: e,
completion: t,
preserveConfiguredListeners: n
};
return applyHistoricalWebhookPins.bind(void 0, r);
}
function hasHistoricalInstallation(e) {
const read = () => Boolean(withExistingOpenClawStateDatabaseReadOnly(({ db: e }) => {
const t = getNodeSqliteKysely(e);
let n = t.selectFrom("gateway_boot_lifecycle").select("boot_id as evidence").unionAll(t.selectFrom("channel_ingress_events").select("event_id as evidence"));
if (tableExists(e, "update_runs")) n = n.unionAll(t.selectFrom("update_runs").select("run_id as evidence"));
return executeSqliteQueryTakeFirstSync(e, n.limit(1));
}, { env: e }));
if (isStatePostgres()) return read();
return withStateDatabaseColdAdmission({
databasePath: resolveOpenClawStateSqlitePath(e),
busyTimeoutMs: OPENCLAW_SQLITE_BUSY_TIMEOUT_MS
}, read);
}
/** Pins and completion travel together through Doctor's config backup and publication. */
function applyHistoricalWebhookPins(e, t, n, r = {}) {
const { env: i } = e;
const a = t.config.meta?.migrations?.webhookListeners;
const o = a === true ? a : mergeWebhookCompletion(a, (e.completion ??= { marker: readConfigMachineState(webhookCompletionKey(i), { env: i }) }).marker);
if (o === true || t.warnings?.length) return t;
const s = r.startup && t.historicalWebhookAccountIds === null || r.pluginId && !passesManifestOwnerBasePolicy({
plugin: { id: r.pluginId },
normalizedConfig: normalizePluginsConfig(t.config.plugins),
allowRestrictiveAllowlistBypass: r.origin === "bundled" && resolveChannelConfigEnablement(t.config, n?.channelId ?? r.pluginId) === true
}) ? [] : t.historicalWebhookAccountIds;
const c = e.preserveConfiguredListeners || o !== void 0 || isTruthyEnvValue(i.OPENCLAW_UPDATE_IN_PROGRESS) || (e.existingInstallation ??= hasHistoricalInstallation(i));
const l = { ...o };
const u = n?.channelId;
if (c && (!u || !s || Object.hasOwn(l, u))) return t;
const d = cloneConfigWithResolutionFacts(t.config);
const f = [...t.changes];
if (c && n) {
const e = ["channels", n.channelId];
const r = asNullableRecord(getConfigValueAtPath(d, e));
const i = Object.keys(asNullableRecord(r?.accounts) ?? {});
const a = [];
const { channelId: o, preserveAuthoredActivation: c, ...u } = n;
if (c && r?.legacyWebhook !== void 0 && r.enabled === void 0) {
setConfigValueAtPath(d, [...e, "enabled"], true);
a.push([...e, "enabled"]);
f.push(`Set ${e.join(".")}.enabled to preserve authored webhook activation.`);
}
for (const o of s ?? []) {
if (r?.legacyWebhook !== void 0) continue;
const s = [...e];
if (o !== void 0) {
const e = i.includes(o) ? [o] : i.filter((e) => normalizeOptionalAccountId(e) === normalizeOptionalAccountId(o));
if (e.length > 1) return {
...t,
warnings: [`Ambiguous ${n.channelId} account ${JSON.stringify(o)} matches ${e.map((e) => JSON.stringify(e)).join(", ")}; no pins were written for this channel. Pin the intended account manually: channels.${n.channelId}.accounts[<exact account key>].legacyWebhook = ${JSON.stringify(u)}.`]
};
s.push("accounts", e[0] ?? o);
}
const c = [...s, "legacyWebhook"];
if (getConfigValueAtPath(d, c) !== void 0) continue;
setConfigValueAtPath(d, c, u);
a.push(c);
f.push(`Pinned ${s.join(".")}.legacyWebhook. Move the callback or proxy to the Gateway route, then remove the pin.`);
}
l[n.channelId] = a;
}
d.meta ??= {};
d.meta.migrations ??= {};
d.meta.migrations.webhookListeners = c ? l : true;
f.push("Recorded webhook listener decisions; removed pins will not be recreated.");
const p = {
...t,
config: d,
changes: f
};
if (resolveUpdateRehearsalRoot(i) && recordUnwrittenWebhookCompletion({ sourceConfig: t.config }, p, i)) {
e.completion = { marker: p.config.meta?.migrations?.webhookListeners };
return t;
}
return p;
}
//#endregion
export { readWebhookCompletion as i, createHistoricalWebhookPinMigration as n, prepareUnwrittenWebhookCompletion as r, HISTORICAL_WEBHOOK_CHANNELS as t };