UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

451 lines (450 loc) • 15.5 kB
import { s as raceWithTimeout } from "./src-BPmQBLJp.mjs"; import "./session-key-CqAyZeVk.mjs"; import { t as DEFAULT_ACCOUNT_ID } from "./account-id-BqKT3GuY.mjs"; import { ao as validateChannelsStartParams, oo as validateChannelsStatusParams, so as validateChannelsStopParams, to as validateChannelsLogoutParams } from "./src-BX8OAe1J.mjs"; import { s as readConfigFileSnapshot } from "./io.runtime-DsJ2dLCQ.mjs"; import { t as runTasksWithConcurrency } from "./run-with-concurrency-B34GDKXE.mjs"; import { t as normalizeAnyChannelId } from "./registry-normalize-guW5_4yo.mjs"; import { t as getChannelPlugin } from "./registry-ByqVE5S3.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import "./plugins-BoMiRtiY.mjs"; import "./config-CMA-J084.mjs"; import { r as resolveChannelAccount } from "./account-resolution-D7u1J1M0.mjs"; import { t as formatForLog } from "./ws-log-CbOV6uhk.mjs"; import { a as resolveChannelHealthState, n as DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS, t as DEFAULT_CHANNEL_CONNECT_GRACE_MS } from "./channel-health-policy-Czg3cLcH.mjs"; import { r as respondUnavailableOnThrow, t as respondError } from "./response-C7fEiIN1.mjs"; import { t as assertValidParams } from "./validation-DwNk6A-B.mjs"; import { a as readGatewayRequestMutationAuthority } from "./session-mutation-guards-Bjnk_O0z.mjs"; import { t as buildChannelUiCatalog } from "./catalog-B7x9RZv9.mjs"; import { n as listReadOnlyChannelPluginsForConfigAsync } from "./read-only-idsFCBWl.mjs"; import { t as getChannelActivity } from "./channel-activity-elw91nA1.mjs"; import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs"; import { s as redactChannelStatusSummaryBaseUrl } from "./account-snapshot-fields-B0Zypjh2.mjs"; import { a as resolveUnavailableChannelAccountSnapshot } from "./account-state-CG07Qq4V.mjs"; import { n as buildChannelAccountSnapshotFromInspection, r as buildChannelAccountSnapshotFromRuntime } from "./account-summary-RVgW5Dlx.mjs"; import { t as isAccountEnabled } from "./account-enabled-CulIMLY0.mjs"; import { t as buildChannelAccountSnapshotFromAccount } from "./status-Dia8exqk.mjs"; import { t as collectChannelStatusIssues } from "./channels-status-issues-DbdoQjaU.mjs"; import { n as resolveChannelGatewayAccountId, r as resolveRuntimeAccountSnapshot, t as logoutChannelAccount } from "./channels-account-DYSu3htW.mjs"; //#region src/gateway/server-methods/channels.ts function resolveChannelOperationParams(e) { const t = e.rawParams; if (!assertValidParams(t, e.validate, e.method, e.respond)) return null; const n = t.channel; const r = normalizeAnyChannelId(n); if (!r) { respondError(e.respond, ErrorCodes.INVALID_REQUEST, `invalid ${e.method} channel`); return null; } const i = getChannelPlugin(r); if (!i) { const t = e.method === "channels.start" ? `unknown channel: ${formatForLog(n)}` : e.method === "channels.stop" ? `unknown channel ${r}` : `channel ${r} does not support logout`; respondError(e.respond, ErrorCodes.INVALID_REQUEST, t); return null; } const a = e.method === "channels.start" && !i.gateway?.startAccount ? "start" : e.method === "channels.logout" && !i.gateway?.logoutAccount ? "logout" : void 0; if (a) { respondError(e.respond, ErrorCodes.INVALID_REQUEST, `channel ${r} does not support ${a}`); return null; } return { params: t, channelId: r, plugin: i }; } function channelAccountOperationHandler(e, t, n) { return async ({ params: r, respond: i, context: a }) => { const o = resolveChannelOperationParams({ method: e, rawParams: r, respond: i, validate: t }); if (!o) return; await respondUnavailableOnThrow(i, async () => { i(true, await n({ channelId: o.channelId, accountId: o.params.accountId, cfg: a.getRuntimeConfig(), context: a, plugin: o.plugin }), void 0); }); }; } const CHANNEL_STATUS_MAX_TIMEOUT_MS = 3e4; const CHANNEL_STATUS_PROBE_CONCURRENCY = 5; async function runChannelStatusHook(e) { const t = e.timeoutMs; const n = `${e.channelId}${e.accountId === void 0 ? "" : `:${e.accountId}`} ${e.step}`; try { const r = Promise.resolve().then(e.run).then((e) => ({ ok: true, value: e })); const i = t === void 0 ? await r : await raceWithTimeout(r, t, () => ({ ok: false, timedOut: true, error: `${e.step} timed out after ${t}ms` }), { ref: false }); if (!i.ok) e.warnings.push(`${n} timed out after ${t}ms`); return i; } catch (t) { const r = formatForLog(t); e.warnings.push(`${n} failed: ${r}`); return { ok: false, error: r }; } } function channelStatusFailureMessage(e) { if (!e || typeof e !== "object") return null; const t = e; if (t.ok !== false || typeof t.error !== "string" || t.error.length === 0) return null; return t.error; } async function changeChannelAccount(e, t) { const n = resolveChannelGatewayAccountId(e, () => e.context.getRuntimeSnapshot({ channelId: e.channelId, inspectAccounts: false })); const r = t === "start" ? await e.context.startChannel(e.channelId, n, { manual: true }) : await e.context.stopChannel(e.channelId, n); const i = t === "start" && r ? r.get(n) : void 0; if (t === "start" && !i) throw new Error(`Channel ${e.channelId} did not report a start outcome for ${n}`); const a = e.context.getRuntimeSnapshot({ channelId: e.channelId, inspectAccounts: false }); const o = resolveRuntimeAccountSnapshot({ runtime: a, channelId: e.channelId, accountId: n })?.running === true; const s = { channel: e.channelId, accountId: n }; if (t === "stop") return { ...s, stopped: !o }; const c = resolveDeferredChannelReloadIssue(e.context, e.channelId, n); return { ...s, started: o, outcome: i, ...c ? { statusIssues: [c] } : {} }; } const channelsHandlers = { "channels.status": async ({ params: e, respond: t, context: n }) => { if (!assertValidParams(e, validateChannelsStatusParams, "channels.status", t)) return; const r = e.probe === true; const i = Math.min(Math.max(1e3, e.timeoutMs ?? (r ? CHANNEL_STATUS_MAX_TIMEOUT_MS : 1e4)), CHANNEL_STATUS_MAX_TIMEOUT_MS); const a = e.channel; const o = n.getRuntimeConfig(); const s = await listReadOnlyChannelPluginsForConfigAsync(o); const c = a !== void 0 ? normalizeAnyChannelId(a) ?? s.find((e) => e.id === a.trim().toLowerCase())?.id : void 0; const l = c ? s.filter((e) => e.id === c) : s; const u = l.toSorted((e, t) => e.id < t.id ? -1 : e.id > t.id ? 1 : 0); if (a !== void 0 && !c) { respondError(t, ErrorCodes.INVALID_REQUEST, `unknown channel: ${formatForLog(a)}`); return; } const d = n.getRuntimeSnapshot({ channelId: c, inspectAccounts: false }); const f = []; const buildAccountSnapshot = async (e, t, n, r, i) => { const a = resolveRuntimeAccountSnapshot({ runtime: d, channelId: e, accountId: n }); if (!r && a) { const t = buildChannelAccountSnapshotFromRuntime(a); return { accountId: n, snapshot: resolveUnavailableChannelAccountSnapshot(o, { channelId: e, accountId: n, runtime: t }) ?? t }; } const s = resolveUnavailableChannelAccountSnapshot(o, { channelId: e, accountId: n, runtime: a }) ?? (a?.enabled === false ? a : void 0); if (s) return { accountId: n, snapshot: s }; if (!i) return { accountId: n, snapshot: buildChannelAccountSnapshotFromInspection({ account: t.config.inspectAccount?.(o, n), accountId: n, runtime: a }) }; i(); const c = await resolveChannelAccount({ plugin: t, cfg: o, accountId: n }); i(); const l = t.config.isEnabled?.(c, o) ?? isAccountEnabled(c); let u; let p; let m = null; for (const r of ["probe", "audit"]) { if (!l || !t.status?.[`${r}Account`]) continue; i(); if (t.config.isConfigured && !await t.config.isConfigured(c, o)) continue; i(); const a = await runChannelStatusHook({ channelId: e, accountId: n, step: r, warnings: f, run: () => { return t.status[`${r}Account`]({ account: c, timeoutMs: i(), cfg: o, ...r === "audit" ? { probe: u } : {} }); } }); if (r === "probe") { u = a.ok ? a.value : a; m = Date.now(); } else p = a.ok ? a.value : a; } i(); const h = await buildChannelAccountSnapshotFromAccount({ plugin: t, cfg: o, accountId: n, account: c, runtime: a, probe: u, audit: p, assertActive: i }); const g = channelStatusFailureMessage(p) ?? channelStatusFailureMessage(u); if (g && !h.lastError) h.lastError = g; if (m) h.lastProbeAt = m; return { accountId: n, account: c, snapshot: h }; }; const buildChannelAccounts = async (e, t) => { const n = e.id; if (d.reloadingChannels?.has(n)) { const e = d.channels[n]; f.push(`${n}: plugin runtime is paused for reload; reporting recorded account state`); return { accounts: Object.values(d.channelAccounts[n] ?? {}), defaultAccountId: d.reloadingChannels.get(n) ?? "default", defaultAccount: e, resolvedAccounts: {} }; } const r = e.config.listAccountIds(o); const i = new Set(r); const a = [.../* @__PURE__ */ new Set([...r, ...Object.keys(d.channelAccounts[n] ?? {})])]; const s = resolveChannelDefaultAccountId({ plugin: e, cfg: o, accountIds: r }); const c = {}; const { results: l } = await runTasksWithConcurrency({ tasks: a.map((r) => async () => await buildAccountSnapshot(n, e, r, i.has(r), t)), limit: t ? CHANNEL_STATUS_PROBE_CONCURRENCY : a.length || 1, onTaskError: (e, t) => { const r = a[t] ?? `account ${t + 1}`; f.push(`${n}:${r} status failed: ${formatForLog(e)}`); } }); const u = []; for (const e of l) if (e) { const { snapshot: t, accountId: r } = e; const i = getChannelActivity({ channel: n, accountId: r }); t.lastInboundAt ??= i.inboundAt; t.lastOutboundAt ??= i.outboundAt; t.healthState = resolveChannelHealthState(t, { channelId: n, now: Date.now(), staleEventThresholdMs: DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS, channelConnectGraceMs: DEFAULT_CHANNEL_CONNECT_GRACE_MS }); if ("account" in e) c[e.accountId] = e.account; u.push(e.snapshot); } return { accounts: u, defaultAccountId: s, defaultAccount: u.find((e) => e.accountId === s) ?? u.find((e) => i.has(e.accountId)), resolvedAccounts: c }; }; const p = buildChannelUiCatalog(l); const m = {}; const h = {}; const g = {}; const _ = { ts: Date.now(), channelOrder: p.order, channelLabels: p.labels, channelDetailLabels: p.detailLabels, channelSystemImages: p.systemImages, channelMeta: p.entries, ...n.getEventLoopHealth ? { eventLoop: n.getEventLoopHealth() } : {}, channels: m, channelAccounts: h, channelDefaultAccountId: g }; const { results: v } = await runTasksWithConcurrency({ tasks: u.map((e) => async () => { const t = performance.now() + i; const n = r ? new AbortController() : void 0; const remainingBudget = () => { n?.signal.throwIfAborted(); const e = t - performance.now(); if (e <= 0) throw new Error(`status timed out after ${i}ms`); return Math.floor(e); }; const build = async (n, r) => { const { accounts: i, defaultAccountId: a, defaultAccount: s, resolvedAccounts: c } = await buildChannelAccounts(e, n ? remainingBudget : void 0); if (r) for (const e of i) e.lastError ||= r; const fallbackSummary = (e = s?.lastError) => ({ ...!n ? s : void 0, configured: s?.configured ?? (n ? false : void 0), ...e ? { lastError: e } : {} }); let l = fallbackSummary(); if (performance.now() < t && e.status?.buildChannelSummary && Object.hasOwn(c, a)) { const t = await runChannelStatusHook({ step: "summary", channelId: e.id, warnings: f, run: () => { remainingBudget(); return e.status.buildChannelSummary({ account: c[a], cfg: o, defaultAccountId: a, snapshot: s ?? { accountId: a } }); } }); l = t.ok ? redactChannelStatusSummaryBaseUrl(t.value) : fallbackSummary(t.error); } return { pluginId: e.id, summary: l, accounts: i, defaultAccountId: a }; }; if (!r) return await build(false); const a = await runChannelStatusHook({ step: "status", channelId: e.id, timeoutMs: i, warnings: f, run: () => build(true) }); if (a.ok && performance.now() < t) return a.value; n?.abort(); const s = a.ok ? `status timed out after ${i}ms` : a.error; if (a.ok) f.push(`${e.id} ${s}`); return await build(false, s); }), limit: r ? CHANNEL_STATUS_PROBE_CONCURRENCY : l.length || 1, onTaskError: (e, t) => { const n = u[t]?.id ?? `channel ${t + 1}`; f.push(`${n} channel status failed: ${formatForLog(e)}`); } }); for (const e of v) if (e) { m[e.pluginId] = e.summary; h[e.pluginId] = e.accounts; g[e.pluginId] = e.defaultAccountId; } const y = []; for (const e of u) { try { y.push(...collectChannelStatusIssues(_, [d.reloadingChannels?.has(e.id) ? { id: e.id } : e])); } catch (t) { f.push(`${e.id} status diagnostics failed: ${formatForLog(t)}`); } const t = g[e.id]; const r = resolveDeferredChannelReloadIssue(n, e.id, typeof t === "string" ? t : DEFAULT_ACCOUNT_ID); if (r) y.push(r); } _.statusIssues = y.slice(0, 50); if (f.length > 0) { _.partial = true; _.warnings = f.toSorted().slice(0, 50); } t(true, _, void 0); }, "channels.start": channelAccountOperationHandler("channels.start", validateChannelsStartParams, (e) => changeChannelAccount(e, "start")), "channels.stop": channelAccountOperationHandler("channels.stop", validateChannelsStopParams, (e) => changeChannelAccount(e, "stop")), "channels.logout": async (e) => { const { params: t, respond: n, context: r } = e; const i = resolveChannelOperationParams({ method: "channels.logout", rawParams: t, respond: n, validate: validateChannelsLogoutParams }); if (!i) return; const { params: a, channelId: o, plugin: s } = i; const c = a.accountId; const l = r.getGatewayMethodRegistry?.(); const u = readGatewayRequestMutationAuthority(e); if (!(await readConfigFileSnapshot()).valid) { respondError(n, ErrorCodes.INVALID_REQUEST, "config invalid; fix it before logging out"); return; } await respondUnavailableOnThrow(n, async () => { n(true, await logoutChannelAccount({ channelId: o, accountId: c, cfg: r.getRuntimeConfig(), context: r, plugin: s, methodRegistry: l, assertRequestCurrent: u.assertCurrent }), void 0); }); } }; function resolveDeferredChannelReloadIssue(e, t, n) { const r = e.getDeferredChannelReloads?.().find((e) => e.channel === t); if (!r) return; return { channel: t, accountId: n, kind: "config", message: r.publicationPending ? "Channel configuration reload is deferred while active work finishes. The previous configuration is still in use." : "Channel reload is deferred while active work finishes.", fix: "Wait for active work to finish, then refresh channel status. Stopping and starting the channel does not apply unpublished configuration." }; } //#endregion export { channelsHandlers };