UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

518 lines (517 loc) • 21.9 kB
import { B as isRecord, F as normalizeOptionalString, N as normalizeLowercaseStringOrEmpty, a as defineChannelAliasMigration, d as normalizeAccountId, s as resolveAccountKey, u as DEFAULT_ACCOUNT_ID } from "./runtime-doctor-migrations-JGL9tD-z.js"; import "./account-resolution-D0wF8tG-.js"; import "./string-coerce-runtime-DkwxSzQP.js"; import path from "node:path"; import { isIP } from "node:net"; import { pathToFileURL } from "node:url"; //#region extensions/signal/src/account-selection.ts function resolveSignalAccountKey(e, t) { return resolveAccountKey(e, normalizeAccountId(t), void 0, void 0, { channelId: "signal" }); } //#endregion //#region extensions/signal/src/account-key-repair.ts function repairSignalAccountKeys({ cfg: e }) { const t = e.channels?.signal; const n = t?.accounts; if (!n) return { config: e, changes: [] }; const r = /* @__PURE__ */ new Map(); for (const e of Object.keys(n)) if (e) { const t = normalizeAccountId(e); const n = r.get(t); if (n) n.push(e); else r.set(t, [e]); } const i = /* @__PURE__ */ new Map(); const a = []; for (const [e, t] of r) { if (t.length > 1) { a.push(`Signal account keys ${t.map((e) => JSON.stringify(e)).join(", ")} resolve to "${e}". Doctor preserved them; rename them so each account has a unique normalized key.`); continue; } for (const r of t) if (normalizeLowercaseStringOrEmpty(r) !== e) { if (resolveSignalAccountKey(n, e) !== r) { a.push(`Signal account "${r}" is listed as "${e}" but currently uses the channel defaults. Doctor preserved it to avoid changing a working account; check its settings before renaming the key to "${e}".`); continue; } i.set(r, e); } } if (!i.size) return { config: e, changes: [], warnings: a }; const o = Object.fromEntries(Object.entries(n).map(([e, t]) => [i.get(e) ?? e, t])); return { config: { ...e, channels: { ...e.channels, signal: { ...t, accounts: o } } }, changes: [...i].map(([e, t]) => `Moved Signal account "${e}" to channels.signal.accounts.${t}.`), warnings: a }; } //#endregion //#region extensions/signal/src/legacy-transport.ts const LEGACY_SIGNAL_TRANSPORT_FIELDS = [ "configPath", "httpUrl", "httpHost", "httpPort", "cliPath", "autoStart", "startupTimeoutMs", "receiveMode", "ignoreStories" ]; function hasLegacySignalTransportFields(e) { return isRecord(e) && LEGACY_SIGNAL_TRANSPORT_FIELDS.some((t) => Object.hasOwn(e, t)); } //#endregion //#region extensions/signal/src/transport-url.ts function normalizeSignalTransportUrl(e) { const t = e.trim(); if (!t) throw new Error("Signal transport URL is required"); if (/^https?:/i.test(t) && !/^https?:\/\/[^/]/i.test(t)) throw new Error("Signal transport URL has a malformed HTTP scheme"); const n = /^([a-z][a-z0-9+.-]*):\/\//i.exec(t)?.[1]?.toLowerCase(); if (n && n !== "http" && n !== "https") throw new Error(`Signal transport URL unsupported protocol: ${n}:`); const r = new URL(/^https?:\/\//i.test(t) ? t : `http://${t}`); if (r.protocol !== "http:" && r.protocol !== "https:") throw new Error(`Signal transport URL unsupported protocol: ${r.protocol}`); if (r.username || r.password) throw new Error("Signal transport URL must not include credentials"); const i = r.pathname === "/" ? "" : r.pathname.replace(/\/+$/, ""); return `${r.protocol}//${r.host}${i}`; } function normalizeSignalTransportHost(e) { const t = e.trim(); const n = t.startsWith("["); if (n !== t.endsWith("]")) throw new Error("Signal transport host has mismatched IPv6 brackets"); const r = n ? t.slice(1, -1) : t; if (!r || /[\s/\\?#@]/.test(r)) throw new Error("Signal transport host must be a hostname or IP address"); if (isIP(r) === 0) { const e = r.endsWith(".") ? r.slice(0, -1) : r; const t = e.split("."); if (e.length > 253 || t.some((e) => !e || e.length > 63 || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(e))) throw new Error("Signal transport host must be a hostname or IP address"); } return r; } function buildSignalTransportHttpUrl(e, t) { const n = normalizeSignalTransportHost(e); return normalizeSignalTransportUrl(`http://${n.includes(":") ? `[${n}]` : n}:${t}`); } /** Validate the opt-in shape without filesystem side effects during config resolution. */ function assertSignalSocketTransport(e) { if (e.socketPath === void 0) return; if (typeof e.socketPath !== "string" || !/^\/(?!\/)[^\0]+$/.test(e.socketPath) || e.socketPath.endsWith("/") || path.posix.normalize(e.socketPath) !== e.socketPath || Buffer.byteLength(e.socketPath, "utf8") > 103) throw new Error("Signal transport.socketPath must be a normalized absolute POSIX socket file path of at most 103 UTF-8 bytes."); if (e.url !== void 0 || e.httpHost !== void 0 || e.httpPort !== void 0) throw new Error("Signal transport.socketPath cannot be combined with url, httpHost, or httpPort."); if (e.receiveMode === "on-start") throw new Error("Signal socket transport requires receiveMode manual (or omitted)."); } //#endregion //#region extensions/signal/src/transport-policy.ts const DEFAULT_SIGNAL_MANAGED_NATIVE_PORT = 8080; const DEFAULT_SIGNAL_MANAGED_NATIVE_HOST = "127.0.0.1"; const SIGNAL_LOOPBACK_HOST_ALIASES = /* @__PURE__ */ new Set([ "localhost", "127.0.0.1", "::1" ]); function normalizeSignalEndpointHost(e) { const t = e.toLowerCase().replace(/^\[|\]$/g, ""); return t.endsWith(".") ? t.slice(0, -1) : t; } function isSignalLocalEndpointHost(e) { return e === "localhost" || e.endsWith(".localhost") || e === "::1" || e === "::" || e === "0.0.0.0" || /^127(?:\.\d{1,3}){3}$/.test(e) || /^::ffff:(?:127(?:\.\d{1,3}){3}|7f[0-9a-f]{2}:[0-9a-f]{1,4})$/.test(e); } function isValidSignalManagedNativePort(e) { return Number.isInteger(e) && Number(e) >= 1 && Number(e) <= 65535; } function allocateSignalManagedNativePort(e) { if (e.preferredPort !== void 0) { if (!isValidSignalManagedNativePort(e.preferredPort)) throw new Error("Signal managed native port must be an integer between 1 and 65535."); if (!e.reservedPorts.has(e.preferredPort)) return e.preferredPort; } let t = DEFAULT_SIGNAL_MANAGED_NATIVE_PORT; while (t <= 65535 && e.reservedPorts.has(t)) t += 1; if (t > 65535) throw new Error("No available Signal managed native port remains."); return t; } function resolveLocalSignalTransportPort(e) { try { const t = new URL(e); if (!isSignalLocalEndpointHost(normalizeSignalEndpointHost(t.hostname))) return; if (t.port) return Number.parseInt(t.port, 10); return t.protocol === "https:" ? 443 : 80; } catch { return; } } function isSignalManagedNativeConnectionUrlForBind(e) { if (e.kind !== "managed-native" || !e.url) return false; const t = new URL(e.url); if (t.protocol !== "http:") return false; if ((t.port ? Number.parseInt(t.port, 10) : 80) !== (e.httpPort ?? 8080)) return false; const n = normalizeSignalEndpointHost(t.hostname); const r = normalizeSignalEndpointHost(e.httpHost ?? "127.0.0.1"); if (n === r) return true; if (r === "0.0.0.0") return n === "localhost" || /^127(?:\.\d{1,3}){3}$/.test(n); if (r === "::") return n === "localhost" || n === "::1"; return r === "localhost" && SIGNAL_LOOPBACK_HOST_ALIASES.has(n) || n === "localhost" && SIGNAL_LOOPBACK_HOST_ALIASES.has(r); } function assignSignalManagedNativePort(e, t) { if (!isValidSignalManagedNativePort(t)) throw new Error("Signal managed native port must be an integer between 1 and 65535."); const n = e.url; if (!n || !isSignalManagedNativeConnectionUrlForBind(e)) return { ...e, httpPort: t }; const r = new URL(n); r.port = String(t); return { ...e, url: normalizeSignalTransportUrl(r.toString()), httpPort: t }; } //#endregion //#region extensions/signal/src/config-compat.ts const PENDING_LEGACY_TRANSPORT_WARNING = "- channels.signal: legacy auto transport is ambiguous while its endpoint is unavailable; bring the endpoint online and rerun openclaw doctor --fix, or replace the retired fields with an explicit account-owned transport in openclaw.json."; const PENDING_LEGACY_INVALID_URL_WARNING = "- channels.signal: legacy httpUrl is invalid; keep the current config, correct httpUrl, then run openclaw doctor --fix."; const PENDING_LEGACY_INVALID_HOST_WARNING = "- channels.signal: legacy httpHost is invalid; keep the current config, correct httpHost, then run openclaw doctor --fix."; const PENDING_LEGACY_INVALID_PORT_WARNING = "- channels.signal: legacy httpPort must be an integer between 1 and 65535; correct httpPort, then run openclaw doctor --fix."; const PENDING_LEGACY_CONTAINER_ACCOUNT_WARNING = "- channels.signal: legacy container transport requires an account number; add channels.signal.account (or the relevant channels.signal.accounts.*.account) and rerun openclaw doctor --fix."; function isSignalTransportConfig(e) { if (!isRecord(e)) return false; try { if (e.kind === "managed-native") { assertSignalSocketTransport(e); if (e.httpPort !== void 0 && !isValidSignalManagedNativePort(e.httpPort)) return false; if (e.url === void 0) return true; } else if (e.kind !== "external-native" && e.kind !== "container") return false; if (typeof e.url !== "string") return false; normalizeSignalTransportUrl(e.url); return true; } catch { return false; } } function inherited(e, t, n) { return Object.hasOwn(e, n) ? e[n] : t[n]; } function legacyBaseUrl(e, t) { const n = normalizeOptionalString(inherited(e, t, "httpUrl")); if (n) return normalizeSignalTransportUrl(n); const r = normalizeOptionalString(inherited(e, t, "httpHost")) ?? "127.0.0.1"; const i = inherited(e, t, "httpPort"); return buildSignalTransportHttpUrl(r, typeof i === "number" ? i : 8080); } function wasLegacySignalAccountConfigured(e, t) { return Boolean(normalizeOptionalString(inherited(e, t, "account")) || normalizeOptionalString(inherited(e, t, "configPath")) || normalizeOptionalString(inherited(e, t, "httpUrl")) || normalizeOptionalString(inherited(e, t, "httpHost")) || normalizeOptionalString(inherited(e, t, "cliPath")) || typeof inherited(e, t, "httpPort") === "number" || typeof inherited(e, t, "autoStart") === "boolean"); } function hasInvalidLegacyHttpUrl(e, t) { return e.some((e) => { const n = normalizeOptionalString(inherited(e, t, "httpUrl")); if (!n) return false; try { normalizeSignalTransportUrl(n); return false; } catch { return true; } }); } function findInvalidLegacyDerivedEndpoint(e, t) { for (const n of e) { if (normalizeOptionalString(inherited(n, t, "httpUrl"))) continue; const e = inherited(n, t, "httpPort"); if (e !== void 0 && !isValidSignalManagedNativePort(e)) return "port"; const r = normalizeOptionalString(inherited(n, t, "httpHost")) ?? "127.0.0.1"; try { buildSignalTransportHttpUrl(r, typeof e === "number" ? e : 8080); } catch { return "host"; } } } function hasInvalidManagedTransportPort(e) { return e.some((e) => e?.kind === "managed-native" && e.httpPort !== void 0 && !isValidSignalManagedNativePort(e.httpPort)); } function requiresDetection(e, t, n) { if (n !== void 0 && n !== "auto") return false; return Boolean(normalizeOptionalString(inherited(e, t, "httpUrl"))) || !resolveLegacyAutoStart(e, t); } function resolveLegacyAutoStart(e, t) { const n = inherited(e, t, "autoStart"); if (typeof n === "boolean") return n; return !normalizeOptionalString(inherited(e, t, "httpUrl")); } function resolveManagedConnectionUrl(e, t) { const n = normalizeOptionalString(inherited(e, t, "httpUrl")); if (!n) return; const r = normalizeSignalTransportUrl(n); const i = new URL(r); const a = (normalizeOptionalString(inherited(e, t, "httpHost")) ?? "127.0.0.1").replace(/^\[|\]$/g, "").toLowerCase(); const o = inherited(e, t, "httpPort"); const s = typeof o === "number" ? o : 8080; const c = i.hostname.replace(/^\[|\]$/g, "").toLowerCase(); const l = i.port ? Number.parseInt(i.port, 10) : i.protocol === "https:" ? 443 : 80; return i.protocol === "http:" && c === a && l === s ? void 0 : r; } function buildManagedNativeTransport(e, t) { const value = (n) => inherited(e, t, n); const n = normalizeOptionalString(value("configPath")); const r = normalizeOptionalString(value("cliPath")); const i = resolveManagedConnectionUrl(e, t); const a = normalizeOptionalString(value("httpHost")); const o = value("httpPort"); const s = value("startupTimeoutMs"); const c = value("receiveMode"); const l = value("ignoreStories"); return { kind: "managed-native", ...n ? { configPath: n } : {}, ...r ? { cliPath: r } : {}, ...i ? { url: i } : {}, ...a ? { httpHost: a } : {}, ...typeof o === "number" ? { httpPort: o } : {}, ...typeof s === "number" ? { startupTimeoutMs: s } : {}, ...c === "on-start" || c === "manual" ? { receiveMode: c } : {}, ...typeof l === "boolean" ? { ignoreStories: l } : {} }; } function resolveLegacyTransportWithoutDetection(e) { if (isSignalTransportConfig(e.entry.transport)) return e.entry.transport; const t = legacyBaseUrl(e.entry, e.parent); const n = inherited(e.entry, e.parent, "autoStart"); if (e.apiMode === "container") return { kind: "container", url: t }; if (e.apiMode === "native") return resolveLegacyAutoStart(e.entry, e.parent) ? buildManagedNativeTransport(e.entry, e.parent) : { kind: "external-native", url: t }; if (requiresDetection(e.entry, e.parent, e.apiMode)) return; if (n === false) return { kind: "external-native", url: t }; return buildManagedNativeTransport(e.entry, e.parent); } function clearLegacyTransportFields(e) { for (const t of LEGACY_SIGNAL_TRANSPORT_FIELDS) delete e[t]; } function hasRootSignalAccount(e) { const t = e[0]; return e.length === 1 || Boolean(normalizeOptionalString(t?.account)) || isSignalTransportConfig(t?.transport); } function signalAccountIds(e) { const t = isRecord(e[0]?.accounts) ? e[0].accounts : {}; return Object.entries(t).filter(([, e]) => isRecord(e)).map(([e]) => e); } function resolveNestedDefaultEntryIndex(e) { const t = isRecord(e[0]?.accounts) ? e[0].accounts : {}; const n = resolveSignalAccountKey(t, DEFAULT_ACCOUNT_ID); const r = signalAccountIds(e).findIndex((e) => e === n); return r >= 0 ? r + 1 : void 0; } function isDefaultSignalAccountId(e) { return Boolean(e?.trim()) && normalizeAccountId(e) === "default"; } function nestedDefaultOwnsEffectiveTransport(e) { const t = isRecord(e[0]?.accounts) ? e[0].accounts : {}; const n = resolveSignalAccountKey(t, DEFAULT_ACCOUNT_ID); const r = n ? t[n] : void 0; return isRecord(r) && (isSignalTransportConfig(r.transport) || hasLegacySignalTransportFields(r)); } function isDiscardedTransportEntry(e, t) { if (isSignalTransportConfig(e[0]?.transport)) return t === resolveNestedDefaultEntryIndex(e); return t === 0 && (!hasRootSignalAccount(e) || nestedDefaultOwnsEffectiveTransport(e)); } function shouldMaterializeTransport(e, t) { if (isDiscardedTransportEntry(e, t)) return false; const n = e[t]; const r = e[0]; return Boolean(n && r && (isSignalTransportConfig(n.transport) || wasLegacySignalAccountConfigured(n, r))); } function hasContainerTransportWithoutEffectiveAccount(e) { const t = e.channels?.signal; if (!isRecord(t)) return false; const n = isRecord(t.accounts) ? t.accounts : {}; const r = isSignalTransportConfig(t.transport) ? t.transport : void 0; const i = resolveSignalAccountKey(n, DEFAULT_ACCOUNT_ID); const a = i ? n[i] : void 0; const o = isRecord(a) && a.account !== void 0 ? normalizeOptionalString(a.account) : normalizeOptionalString(t.account); const s = t.enabled !== false; const c = !isRecord(a) || a.enabled !== false; if (r?.kind === "container" && s && c && !o) return true; for (const [e, i] of Object.entries(n)) { if (!isRecord(i)) continue; if (!s || i.enabled === false) continue; const n = isDefaultSignalAccountId(e); if ((n && r ? r : isSignalTransportConfig(i.transport) ? i.transport : void 0)?.kind !== "container" || n && r) continue; if (!(i.account === void 0 ? normalizeOptionalString(t.account) : normalizeOptionalString(i.account))) return true; } return false; } function pendingSignalTransportMigration(e, t) { return { config: e, changes: [], warnings: [t] }; } function prepareLegacySignalTransportMigration(e) { const t = e.channels?.signal; if (!isRecord(t)) return { config: e, changes: [] }; const n = isRecord(t.accounts) ? t.accounts : {}; if (!(Object.hasOwn(t, "apiMode") || hasLegacySignalTransportFields(t) || Object.values(n).some(hasLegacySignalTransportFields))) return { config: e, changes: [] }; const r = t.apiMode; const i = [t, ...Object.values(n).filter(isRecord)]; if (i.some((e) => isRecord(e.transport) && Object.hasOwn(e.transport, "socketPath") && (e.transport.kind !== "managed-native" || !isSignalTransportConfig(e.transport)))) return pendingSignalTransportMigration(e, "- channels.signal: invalid transport.socketPath configuration; correct the socket path and remove conflicting HTTP or receiveMode on-start options, then run openclaw doctor --fix."); const a = i.filter((e, t) => shouldMaterializeTransport(i, t)).filter((e) => !isSignalTransportConfig(e.transport)); const o = findInvalidLegacyDerivedEndpoint(a, t); if (o) return pendingSignalTransportMigration(e, o === "port" ? PENDING_LEGACY_INVALID_PORT_WARNING : PENDING_LEGACY_INVALID_HOST_WARNING); if (hasInvalidLegacyHttpUrl(a, t)) return pendingSignalTransportMigration(e, PENDING_LEGACY_INVALID_URL_WARNING); return { signal: t, apiMode: r, entries: i, legacyResolutionEntries: a }; } function finishLegacySignalTransportMigration(e, t, n) { if (hasInvalidManagedTransportPort(n)) return pendingSignalTransportMigration(e, PENDING_LEGACY_INVALID_PORT_WARNING); function allocateMigratedManagedPorts() { const e = /* @__PURE__ */ new Set(); const r = hasRootSignalAccount(t); const i = resolveNestedDefaultEntryIndex(t); const a = isSignalTransportConfig(t[0]?.transport) ? 0 : i !== void 0 ? i : r ? 0 : void 0; for (const [r, i] of n.entries()) { if (!i || r === 0 && a !== 0) continue; if (i.kind === "managed-native" && i.socketPath !== void 0) continue; if (i.kind !== "managed-native") { const t = resolveLocalSignalTransportPort(i.url); if (t !== void 0) e.add(t); continue; } if (i.url && !isSignalManagedNativeConnectionUrlForBind(i)) { const t = resolveLocalSignalTransportPort(i.url); if (t !== void 0) e.add(t); } if (r === a || isRecord(t[r]?.transport)) e.add(i.httpPort ?? 8080); } return n.map((n, r) => { if (!n || r === 0 && a !== 0) return n; if (n.kind !== "managed-native" || n.socketPath !== void 0) return n; if (isRecord(t[r]?.transport) || r === a) return n; const i = t[r]?.httpPort; const o = typeof i === "number" ? i : n.httpPort; const s = allocateSignalManagedNativePort({ reservedPorts: e, ...typeof o === "number" ? { preferredPort: o } : {} }); e.add(s); return assignSignalManagedNativePort(n, s); }); } const r = allocateMigratedManagedPorts(); if (r.some((e, n) => shouldMaterializeTransport(t, n) && !e)) return pendingSignalTransportMigration(e, PENDING_LEGACY_TRANSPORT_WARNING); const i = structuredClone(e); const a = i.channels?.signal; if (!isRecord(a)) return { config: e, changes: [] }; const o = resolveNestedDefaultEntryIndex(t); const s = isRecord(a.accounts) ? a.accounts : {}; const c = [a, ...Object.values(s).filter(isRecord)]; const l = hasRootSignalAccount(t); const u = isSignalTransportConfig(t[0]?.transport) ? t[0].transport : void 0; for (const [e, t] of c.entries()) { if (e === o) { const n = u ?? r[e]; if (n) a.transport = n; else delete a.transport; delete t.transport; } else if (e === 0 && !l) delete t.transport; else if (r[e]) t.transport = r[e]; else delete t.transport; clearLegacyTransportFields(t); } delete a.apiMode; if (hasContainerTransportWithoutEffectiveAccount(i)) return pendingSignalTransportMigration(e, PENDING_LEGACY_CONTAINER_ACCOUNT_WARNING); return { config: i, changes: ["Migrated channels.signal transport settings to concrete account-owned transport objects."] }; } function migrateLegacySignalTransportConfigSync(e) { const t = prepareLegacySignalTransportMigration(e); if ("config" in t) return t; const { signal: n, apiMode: r, entries: i } = t; return finishLegacySignalTransportMigration(e, i, i.map((e, t) => { if (!shouldMaterializeTransport(i, t)) return; return resolveLegacyTransportWithoutDetection({ entry: e, parent: n, apiMode: r }); })); } //#endregion //#region extensions/signal/config-doctor-api.ts const streamingAliasMigration = defineChannelAliasMigration({ channelId: "signal", streaming: { defaultMode: "partial", deliveryOnly: true }, accountStreamingReplacesRoot: true }); const legacyConfigRules = [ ...streamingAliasMigration.legacyConfigRules, { path: ["channels", "signal"], message: "Signal transport config is now account-owned; run \"openclaw doctor --fix\" to migrate retired channels.signal transport fields.", match: (e) => isRecord(e) && (Object.hasOwn(e, "apiMode") || hasLegacySignalTransportFields(e)) }, { path: [ "channels", "signal", "accounts" ], message: "Signal transport config is now account-owned; run \"openclaw doctor --fix\" to migrate retired per-account transport fields.", match: (e) => isRecord(e) && Object.values(e).some(hasLegacySignalTransportFields) } ]; function normalizeCompatibilityConfig({ cfg: e }) { const t = repairSignalAccountKeys({ cfg: e }); const n = streamingAliasMigration.normalizeChannelConfig({ cfg: t.config }); const r = migrateLegacySignalTransportConfigSync(n.config); return { config: r.config, changes: [ ...t.changes, ...n.changes, ...r.changes ], ...r.warnings?.length ? { warnings: r.warnings } : {} }; } //#endregion export { legacyConfigRules, normalizeCompatibilityConfig };