UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

436 lines (435 loc) • 14.9 kB
import { b as uniqueStrings } from "./string-normalization-DLmfYZXI.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as ok, t as err } from "./result-CV1-31DB.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs"; import { i as getLoadedChannelPluginForRead } from "./registry-loaded-NYWUyLLC.mjs"; import { t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-constants-CkbqRgGl.mjs"; import { t as runTasksWithConcurrency } from "./run-with-concurrency-B34GDKXE.mjs"; import "./message-channel-DTYVLJT1.mjs"; import { l as normalizeSessionDeliveryState } from "./delivery-context.shared-CRlipPTj.mjs"; import { r as resolveAgentMainSessionKey } from "./main-session-BNL3-mRV.mjs"; import { n as stripOutboundTargetKindPrefix, r as stripTargetProviderPrefix } from "./channel-target-prefix-tRLuyxKs.mjs"; import { n as readSessionEntriesFromStoreInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { n as foldedSessionKeyAliasCandidates } from "./store-entry-BTUJi0xl.mjs"; import { n as extractDeliveryInfoBatch } from "./delivery-info-DGIoojvH.mjs"; import { i as resolveChannelAllowFrom } from "./account-resolution-D7u1J1M0.mjs"; import { t as resolveCronAgentSessionKey } from "./session-key-BQPSZVRH.mjs"; import { r as isReservedTargetLiteralError } from "./target-errors-DefLZSM6.mjs"; import { n as hasExplicitCronDeliveryTarget } from "./delivery-target-validation-BQd2iGZZ.mjs"; import { t as resolveSessionDeliveryTarget } from "./targets-session--uC0H76w.mjs"; import { t as resolveOutboundTargetWithPlugin } from "./targets-resolve-shared-Z8Zbcy7N.mjs"; //#region src/infra/outbound/targets-loaded.ts /** Resolves targets through an already-loaded channel plugin without bootstrap discovery. */ async function tryResolveLoadedOutboundTarget(e) { return resolveOutboundTargetWithPlugin({ plugin: getLoadedChannelPluginForRead(e.channel), target: e }); } //#endregion //#region src/cron/isolated-agent/delivery-route-session-key.ts /** Only a matching conversation may supply provider-specific routing context. */ function selectCronRouteCurrentSessionKey(e, t, n, r) { const i = parseAgentSessionKey(e); if (!i || i.agentId !== t) return; const a = /^([^:]+):(direct|group|channel):([^:]+)(?::(?:thread|topic):.+)?$/i.exec(i.rest); const o = stripOutboundTargetKindPrefix(stripTargetProviderPrefix(r, n)); return a?.[1]?.toLowerCase() === n.toLowerCase() && a[3] === o ? e : void 0; } //#endregion //#region src/cron/isolated-agent/delivery-target-context.ts /** Prepare owned delivery facts through the session worker; no borrowed view survives the read. */ async function readCronDeliveryTargetContexts(e, t) { const n = /* @__PURE__ */ new Map(); const r = t.map(({ agentId: t, sessionKey: r }) => { try { const i = r?.trim(); const a = JSON.stringify([t, i]); let o = n.get(a); if (!o) { o = { agentId: t, rawSessionKey: i, mainSessionKey: resolveAgentMainSessionKey({ cfg: e, agentId: t }), storePath: resolveSessionStorePathCore(e.session?.store, { agentId: t }), threadSessionKey: i ? resolveCronAgentSessionKey({ sessionKey: i, agentId: t, mainKey: e.session?.mainKey, cfg: e }) : void 0 }; n.set(a, o); } return ok(o); } catch (e) { return err(e); } }); const i = await extractDeliveryInfoBatch(r.map((e) => e.ok ? { sessionKey: e.value.threadSessionKey, agentId: e.value.agentId } : {}), { cfg: e }); const a = /* @__PURE__ */ new Set(); for (const [e, t] of r.entries()) if (t.ok && !i[e]?.deliveryContext) a.add(t.value); const o = /* @__PURE__ */ new Map(); for (const e of a) { const t = JSON.stringify([e.agentId, e.storePath]); const n = o.get(t); if (n) n.push(e); else o.set(t, [e]); } const read = async (e) => { const { agentId: t, storePath: n } = e[0]; try { const r = await readSessionEntriesFromStoreInWorker({ agentId: t, storePath: n, projection: "list", snapshotFields: [], sessionKeys: [...new Set(e.flatMap(({ threadSessionKey: e, mainSessionKey: t }) => [e, t].flatMap((e) => e ? [e].concat(foldedSessionKeyAliasCandidates(e)) : [])))] }); return ok(new Map(r.entries.map(({ sessionKey: e, entry: t }) => [e, t]))); } catch (e) { return err(e); } }; const s = /* @__PURE__ */ new Map(); await runTasksWithConcurrency({ limit: 8, tasks: [...o.values()].map((e) => async () => { const t = await read(e); for (const n of e) s.set(n, !t.ok && e.length > 1 ? await read([n]) : t); }) }); return r.map((e, t) => { if (!e.ok) return e; const { mainSessionKey: n, rawSessionKey: r, threadSessionKey: a } = e.value; const o = i[t]; const c = o?.deliveryContext; const l = c && o?.threadId ? { ...c, threadId: o.threadId } : c; const u = l ? void 0 : s.get(e.value); if (u && !u.ok) return u; const d = a ? u?.value.get(a) : void 0; const f = u?.value.get(n); const p = d ?? f; return ok({ mainSessionKey: n, rawSessionKey: r, threadSessionKey: a, main: l || p ? { sessionId: l ? a ?? n : p.sessionId, updatedAt: l ? 0 : p.updatedAt, delivery: l ? normalizeSessionDeliveryState({ context: l }) : structuredClone(p?.delivery) } : void 0, usedSharedMainFallback: !l && !d && f !== void 0 }); }); } //#endregion //#region src/cron/isolated-agent/delivery-target.ts /** Resolves isolated cron delivery requests into concrete outbound targets. */ function requiresExternalCronDelivery(e, t) { return hasExplicitCronDeliveryTarget(e) || t.channel !== void 0 && t.channel !== "webchat"; } const targetsRuntimeLoader = createLazyImportLoader(() => import("./targets.runtime.js")); async function resolveOutboundTargetWithRuntime(e) { try { const t = await tryResolveLoadedOutboundTarget(e); if (t) return t; const { resolveOutboundTarget: n } = await targetsRuntimeLoader.load(); return await n({ ...e, allowBootstrap: true }); } catch (e) { return { ok: false, error: /* @__PURE__ */ new Error(`Invalid delivery target: ${formatErrorMessage(e)}`) }; } } const channelSelectionRuntimeLoader = createLazyImportLoader(() => import("./channel-selection.runtime.js")); const deliveryTargetRuntimeLoader = createLazyImportLoader(() => import("./delivery-target.runtime.js")); const sessionGenerationRuntimeLoader = createLazyImportLoader(() => import("./session-delivery-generation-Dd-bLIoi.mjs")); /** Read one preview batch after runtime loading, then release all source read ownership. */ async function prepareCronDeliveryTargetContexts(e, t) { if (t.length === 0) return []; await deliveryTargetRuntimeLoader.load(); return readCronDeliveryTargetContexts(e, t); } function isNonEmptyThreadId(e) { return e != null && e !== ""; } function routesSharePeer(e, t) { return Boolean(e && t && e.baseSessionKey === t.baseSessionKey && e.peer.kind === t.peer.kind && e.peer.id === t.peer.id); } function shouldCarrySessionThread(e) { if (!isNonEmptyThreadId(e.resolved.threadId)) return false; if (!e.explicitTo) return e.resolved.channel === e.resolved.lastChannel && e.resolved.to === e.resolved.lastTo; return routesSharePeer(e.route, e.lastRoute); } function stripSelectedProviderPrefix(e) { const t = e.to?.trim(); if (!t) return; return stripTargetProviderPrefix(t, e.channel).trim() || void 0; } /** Resolves cron delivery config into a concrete channel target and optional thread/account. */ async function resolveDeliveryTarget(e, t, n, r) { const i = typeof n.channel === "string" ? n.channel : "last"; const a = typeof n.to === "string" ? n.to : void 0; const o = i === "last"; const s = await deliveryTargetRuntimeLoader.load(); const c = n.sourceConversation; if (c && !hasExplicitCronDeliveryTarget(n)) try { const { prepareSessionGenerationFacts: n } = await sessionGenerationRuntimeLoader.load(); const r = await n({ agentId: t, storePath: resolveSessionStorePathCore(e.session?.store, { agentId: t }), sessionKey: c.sessionKey, sessionId: c.sessionId, lifecycleRevision: null }); try { r.assertCurrent(); } finally { r.release(); } } catch (e) { return { ok: false, mode: "implicit", sourceConversationUnavailable: true, error: /* @__PURE__ */ new Error(`Creating conversation unavailable: ${formatErrorMessage(e)}`) }; } const l = r?.sessionContext ?? await (async () => { const r = (await readCronDeliveryTargetContexts(e, [{ agentId: t, sessionKey: n.sessionKey }]))[0]; if (!r.ok) throw r.error; return r.value; })(); const { rawSessionKey: u, threadSessionKey: d, usedSharedMainFallback: f } = l; const p = n.sessionTarget === "current" || n.sourceConversation !== void 0; const m = p && f ? void 0 : l.main; if (n.target === "owner") { const r = await s.resolveProactiveDeliveryTargetWithSessionRoute({ cfg: e, agentId: t, entry: m, currentSessionKey: d, policy: { target: "owner", channel: i === "last" ? void 0 : i, accountId: n.accountId, directPolicy: n.directPolicy } }); return r.channel !== "none" && r.to ? { ok: true, channel: r.channel, to: r.to, accountId: r.accountId, threadId: r.threadId, mode: "explicit" } : { ok: false, channel: r.channel, accountId: r.accountId, mode: "explicit", ...r.reason === "dm-blocked" ? { deliverySuppressionReason: "channel_transform" } : {}, error: /* @__PURE__ */ new Error(`Owner delivery unavailable (${r.reason ?? "no-route"}); configure an authorized owner DM or edit this automation's delivery`) }; } const h = resolveSessionDeliveryTarget({ entry: m, requestedChannel: i, explicitTo: a, explicitThreadId: n.threadId, allowMismatchedLastTo: o }); let g; let _; if (!h.channel) { if (h.lastChannel) g = h.lastChannel; else if (!p || hasExplicitCronDeliveryTarget(n)) try { const { resolveMessageChannelSelection: t } = await channelSelectionRuntimeLoader.load(); g = (await t({ cfg: e })).channel; } catch (e) { const t = formatErrorMessage(e); _ = /* @__PURE__ */ new Error(`${t} Set delivery.channel explicitly or use a main session with a previous channel.`); } } const v = g ? resolveSessionDeliveryTarget({ entry: m, requestedChannel: i, explicitTo: a, explicitThreadId: n.threadId, fallbackChannel: g, allowMismatchedLastTo: o, mode: h.mode }) : h; const y = v.channel ?? g; const b = v.mode; let x = v.to; let S = (typeof n.accountId === "string" ? n.accountId.trim() || void 0 : void 0) ?? v.accountId; if (!S && y) S = s.resolveFirstBoundAccountId({ cfg: e, channelId: y, agentId: t }) ?? s.resolveChannelDefaultAccountIdForDelivery({ cfg: e, channel: y, agentId: t }); if (!y) return { ok: false, channel: void 0, to: void 0, accountId: S, threadId: void 0, mode: b, error: _ ?? /* @__PURE__ */ new Error("Channel is required when delivery.channel=last has no previous channel.") }; const C = isNonEmptyThreadId(n.threadId) ? n.threadId : void 0; const failTarget = (e) => ({ ok: false, channel: y, to: void 0, accountId: S, threadId: C, mode: b, error: e }); let w; if (b === "implicit") { const { getLoadedChannelPluginForRead: t, mapAllowFromEntries: n } = s; const r = t(y); const i = normalizeAccountId(S); const a = r ? await resolveChannelAllowFrom({ plugin: r, cfg: e, accountId: i }) : void 0; const o = a ? n(a) : []; const c = uniqueStrings(o); w = c; if (x && c.length > 0) { if (!(await resolveOutboundTargetWithRuntime({ channel: y, to: x, cfg: e, accountId: S, mode: b, allowFrom: w })).ok) x = c[0]; } } if (!u && b === "implicit" && !a && f && x != null && x === v.lastTo) return failTarget(/* @__PURE__ */ new Error("Refusing implicit isolated cron delivery: the target would be inherited from the shared agent-main session bucket's last recipient, which is ambiguous across conversations and can deliver to the wrong room (and replay there after a restart). Set delivery.channel and delivery.to explicitly, or run the cron from a session that carries its own delivery context.")); const T = x; const E = await resolveOutboundTargetWithRuntime({ channel: y, to: x, cfg: e, accountId: S, mode: b, allowFrom: w }); if (!E.ok) { if (!x || !isReservedTargetLiteralError(E.error)) return failTarget(E.error); } else x = E.to; const D = await s.resolveChannelTargetForDelivery({ cfg: e, channel: y, agentId: t, input: x, accountId: S }); if (!D.ok) return failTarget(D.error); const O = D.target; const k = O.source === "directory" ? O.to : T ?? x; const A = O.resolutionSource === "normalized" ? stripSelectedProviderPrefix({ channel: y, to: O.to }) : O.to.trim(); if (!A) return failTarget(/* @__PURE__ */ new Error("Target is required")); x = A; const resolveRoute = async (n) => { try { return await s.resolveOutboundSessionRouteForDelivery({ cfg: e, channel: y, agentId: t, ...n, currentSessionKey: selectCronRouteCurrentSessionKey(u, t, y, n.target) }); } catch { return null; } }; const j = await resolveRoute({ accountId: S, target: k, resolvedTarget: O, threadId: C }); const M = s.channelCanResolveOutboundSessionRoute({ cfg: e, channel: y, agentId: t }); const N = j && (j.threadId !== void 0 || j.to !== k); if (j && M && N) { const e = stripSelectedProviderPrefix({ channel: y, to: j.to }); if (!e) return failTarget(/* @__PURE__ */ new Error("Target is required")); x = e; } const P = v.lastTo; const F = P && v.lastChannel === y ? await resolveRoute({ accountId: v.lastAccountId ?? S, target: P, threadId: v.lastThreadId }) : null; const I = r?.inheritSessionThread !== false && shouldCarrySessionThread({ resolved: v, explicitTo: a, route: j, lastRoute: F }); const L = C ?? j?.threadId ?? (I ? v.threadId : void 0); const R = j && j.threadId === L ? j : await resolveRoute({ accountId: S, target: x, resolvedTarget: O, threadId: L }); if (n.directPolicy === "block" && (O.kind === "user" || j?.chatType === "direct" || j?.peer.kind === "direct")) return { ...failTarget(/* @__PURE__ */ new Error("Automation delivery to direct messages is blocked by delivery.directPolicy")), deliverySuppressionReason: "channel_transform" }; return { ok: true, channel: y, to: x, accountId: S, threadId: L, mode: b, ...R ? { sessionRoute: R } : {} }; } //#endregion export { requiresExternalCronDelivery as n, resolveDeliveryTarget as r, prepareCronDeliveryTargetContexts as t };