UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

351 lines (350 loc) • 13 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs"; import { t as AgentSelectionRequiredError } from "./agent-scope-config-DmXgFGKP.mjs"; import { n as normalizeRouteBindingId } from "./binding-scope-C3Xc3l9P.mjs"; import { t as normalizeChatType } from "./chat-type-CL5nBDaO.mjs"; import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs"; import { t as normalizeAnyChannelId } from "./registry-normalize-guW5_4yo.mjs"; import { n as getLoadedChannelPlugin } from "./registry-ByqVE5S3.mjs"; import "./plugins-BoMiRtiY.mjs"; import { t as assertConversationAuthority } from "./conversation-authority-B_Nl9_uN.mjs"; import { r as getGlobalPluginRegistry } from "./hook-runner-global-DmYyIVDp.mjs"; import { i as listRouteBindings } from "./bindings-C2C-UuI7.mjs"; import { r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs"; import { a as readConversation, d as withConversationAuthority } from "./conversation-registry-DTUa0zh7.mjs"; import { r as getConversationDeliveryOperation } from "./conversation-delivery-store-CwDySUK3.mjs"; import { c as peerKindMatches, o as resolveAgentRoute } from "./resolve-route-DBnTWpM6.mjs"; import { s as prepareSessionBindingInspections } from "./session-binding-service-Bn-zGfS9.mjs"; import { n as inspectRuntimeConversationBindingRoute, r as resolveConfiguredBindingRoute } from "./binding-routing-CKOszfof.mjs"; //#region src/gateway/conversation-errors.ts /** Terminal caller/input failure for Gateway-owned conversation operations. */ var ConversationInputError = class extends Error { constructor(e) { super(e); this.name = "ConversationInputError"; } }; /** Durable operation id already belongs to a different request identity. */ var ConversationOperationConflictError = class extends ConversationInputError { constructor(e) { super(e); this.name = "ConversationOperationConflictError"; } }; //#endregion //#region src/gateway/conversation-route-ownership.ts function hasActivePluginClaimOwner(e) { return getGlobalPluginRegistry()?.typedHooks.some((t) => t.pluginId === e && t.hookName === "inbound_claim") === true; } function pluginRouteOwnerInput(e, t) { return { cfg: e, accountId: normalizeAccountId(t.accountId), conversation: { kind: t.kind, peerId: t.peerId, target: t.target, ...t.threadId ? { threadId: t.threadId } : {}, ...t.nativeChannelId ? { nativeChannelId: t.nativeChannelId } : {}, ...t.routeContext ? { context: t.routeContext } : {} } }; } function resolvePluginRouteOwner(e, t, n) { const r = normalizeAnyChannelId(t.channel); const i = n ?? (r ? getLoadedChannelPlugin(r)?.messaging?.resolveConversationRouteOwner : void 0); if (!i) return; if (!n) warnPluginSdkDeprecation({ family: "conversation-route-ownership", method: "ChannelMessagingAdapter.resolveConversationRouteOwner", replacement: "ChannelMessagingAdapter.prepareConversationRouteOwnersAsync" }); try { const n = i(pluginRouteOwnerInput(e, t)); if (n === void 0) return; if (n === null) return { kind: "available" }; if (n.kind === "unavailable") return n; if (n.kind === "plugin") return hasActivePluginClaimOwner(n.pluginId) ? { kind: "available" } : { kind: "available", agentId: normalizeAgentId(n.fallbackAgentId) }; return { kind: "available", agentId: normalizeAgentId(n.agentId) }; } catch (e) { if (e instanceof AgentSelectionRequiredError) return { kind: "available" }; throw e; } } function resolveConfiguredRouteOwner(e, t, n) { try { return resolveAgentRoute({ cfg: e, channel: t.channel, accountId: t.accountId, peer: { kind: t.kind, id: t.peerId }, ...n?.parentPeerId && t.kind !== "direct" ? { parentPeer: { kind: t.kind, id: n.parentPeerId } } : {}, ...n?.guildId ? { guildId: n.guildId } : {}, ...n?.teamId ? { teamId: n.teamId } : {}, ...n?.memberRoleIds ? { memberRoleIds: n.memberRoleIds } : {} }); } catch (e) { if (e instanceof AgentSelectionRequiredError) return; throw e; } } function prepareGenericRoute(e) { const t = { channel: e.conversation.channel, accountId: normalizeAccountId(e.conversation.accountId), conversationId: e.conversation.peerId, ...e.context?.parentPeerId ? { parentConversationId: e.context.parentPeerId } : {} }; return { conversation: t, route: resolveConfiguredBindingRoute({ cfg: e.config, route: e.route, conversation: t }).route }; } function resolveInspectedGenericRouteOwner(e, t) { const n = inspectRuntimeConversationBindingRoute({ route: e, inspection: t }); if (n.bindingOwnerAvailable === false) return { kind: "unavailable" }; if (n.pluginId && hasActivePluginClaimOwner(n.pluginId)) return { kind: "available" }; return { kind: "available", agentId: normalizeAgentId(n.route.agentId) }; } function bindingPeerCouldMatchConversation(e, t) { const n = e.match.peer; if (!n) return true; const r = normalizeChatType(n.kind); const i = normalizeRouteBindingId(n.id); if (!r || !i) return false; return peerKindMatches(r, t.kind) && (i === "*" || i === t.peerId); } function hasUnrecordedContextualBinding(e) { const t = normalizeLowercaseStringOrEmpty(e.conversation.channel); const n = normalizeAccountId(e.conversation.accountId); const r = Boolean(e.conversation.parentConversationRef || e.conversation.threadId); const i = e.conversation.kind === "channel"; return listRouteBindings(e.config).some((a) => { const o = a.match.accountId?.trim() ?? ""; return Boolean(i && normalizeRouteBindingId(a.match.guildId) || normalizeRouteBindingId(a.match.teamId) || i && a.match.roles?.length || r && a.match.peer?.kind !== "direct" && normalizeRouteBindingId(a.match.peer?.id)) && normalizeAgentId(a.agentId) !== e.resolvedAgentId && normalizeLowercaseStringOrEmpty(a.match.channel) === t && (o === "*" || normalizeAccountId(o) === n) && bindingPeerCouldMatchConversation(a, e.conversation); }); } function finishRouteEligibility(e, t) { if (t.kind === "unavailable") return "unavailable"; if (t.agentId !== normalizeAgentId(e.agentId)) return "denied"; return !e.conversation.routeContextObserved && !e.conversation.routeContext && hasUnrecordedContextualBinding({ config: e.config, conversation: e.conversation, resolvedAgentId: t.agentId }) ? "denied" : "eligible"; } /** Prepare native reads once; effect callbacks only consume owner-held facts and receipt invalidation. */ async function prepareConversationRouteEligibilitiesForAgent(e) { const t = e.conversations.map((t) => ({ config: e.config, agentId: e.agentId, conversation: t })); const n = []; const inspectBindings = async (e) => { const t = await prepareSessionBindingInspections(e); n.push(t.dispose); return () => t.inspect(); }; try { const r = /* @__PURE__ */ new Map(); const i = /* @__PURE__ */ new Map(); const a = t.map((e, t) => { const n = normalizeAnyChannelId(e.conversation.channel); const i = n ? getLoadedChannelPlugin(n) : void 0; const a = i?.messaging?.prepareConversationRouteOwnersAsync; if (a) { const e = r.get(a) ?? []; e.push(t); r.set(a, e); } return { channel: n, plugin: i }; }); for (const [n, a] of r) { let r = true; let o; try { o = await n(a.map((n) => pluginRouteOwnerInput(e.config, t[n].conversation)), (e) => { if (!r) throw new Error("Conversation route preparation is no longer active"); return inspectBindings(e); }); } finally { r = false; } if (o.length !== a.length) throw new Error("Plugin route owner returned an incomplete selection"); a.forEach((e, t) => i.set(e, o[t])); } const o = t.map((e, t) => { const n = i.get(t); if (resolvePluginRouteOwner(e.config, e.conversation, n)) return { kind: "plugin", resolver: n }; const r = resolveConfiguredRouteOwner(e.config, e.conversation, e.conversation.routeContext); return r ? { kind: "binding", ...prepareGenericRoute({ ...e, route: r, context: e.conversation.routeContext }) } : { kind: "denied" }; }); const s = await inspectBindings(o.flatMap((e) => e.kind === "binding" ? [e.conversation] : [])); return { read() { for (const { channel: e, plugin: t } of a) if (e && getLoadedChannelPlugin(e) !== t) throw new Error("Conversation route owner changed. Retry the request."); const e = s(); let n = 0; return o.map((r, i) => { if (r.kind === "denied") return "denied"; const a = t[i]; const o = r.kind === "plugin" ? resolvePluginRouteOwner(a.config, a.conversation, r.resolver) : resolveInspectedGenericRouteOwner(r.route, e[n++]); return o ? finishRouteEligibility(a, o) : "unavailable"; }); }, dispose() { for (const e of n) e(); } }; } catch (e) { for (const e of n) e(); throw e; } } async function resolveConversationRouteEligibilitiesForAgent(e) { const t = await prepareConversationRouteEligibilitiesForAgent(e); try { return t.read(); } finally { t.dispose(); } } function assertConversationDeliveryRouteAuthorized(e, t) { const n = e.conversation; try { assertConversationAuthority(n, e); } catch (t) { throw new PlatformMessageNotDispatchedError(`Conversation is no longer available to this agent: ${e.conversationRef}`, { cause: t, retryable: false }); } if (t === "eligible") return; throw new PlatformMessageNotDispatchedError(t === "unavailable" ? `Conversation ownership is temporarily unavailable: ${e.conversationRef}` : `Conversation is no longer available to this agent: ${e.conversationRef}`, { cause: void 0, retryable: t === "unavailable" }); } async function prepareConversationDeliveryRouteAuthorization(e) { const t = await prepareConversationRouteEligibilitiesForAgent({ ...e, conversations: [e.conversation] }); const assertConfigCurrent = () => { if ((e.readCurrentConfig?.() ?? e.config) !== e.config) throw new PlatformMessageNotDispatchedError("Conversation routing configuration changed. Retry the request.", { cause: void 0, retryable: true }); }; return { assertRequestEligible() { assertConfigCurrent(); const n = t.read()[0]; if (n === "denied") throw new ConversationInputError(`Conversation is not available to this agent: ${e.conversationRef}`); if (n === "unavailable") throw new Error(`Conversation ownership is temporarily unavailable: ${e.conversationRef}`); }, assertCurrent(n, r = e) { assertConfigCurrent(); assertConversationDeliveryRouteAuthorized({ ...e, ...r, conversation: n }, t.read()[0]); }, dispose: () => t.dispose() }; } async function withAuthorizedConversationDelivery(e, t) { const n = e.routeAuthority ? void 0 : await readConversation(e.scope, e.conversationRef); if (!e.routeAuthority && !n) throw new PlatformMessageNotDispatchedError("Conversation is no longer available", { cause: void 0, retryable: false }); const r = e.routeAuthority ?? await prepareConversationDeliveryRouteAuthorization({ ...e, conversation: n }); try { return await withConversationAuthority(e.scope, { conversationRef: e.conversationRef }, ({ conversation: n }) => { r.assertCurrent(n, e); return t; }); } finally { if (!e.routeAuthority) r.dispose(); } } async function withAuthorizedQueuedConversationDelivery(e, t, n) { const r = await getConversationDeliveryOperation(t, e.operationId); if (!r) throw new PlatformMessageNotDispatchedError(`Conversation delivery operation no longer exists: ${e.operationId}`, { cause: void 0, retryable: false }); const i = await readConversation(t, r.conversationRef); if (!i) throw new PlatformMessageNotDispatchedError("Conversation is no longer available", { cause: void 0, retryable: false }); const a = { conversationRef: r.conversationRef, expectedRouteFingerprint: e.routeFingerprint }; const o = await prepareConversationDeliveryRouteAuthorization({ ...a, config: e.readCurrentConfig(), readCurrentConfig: e.readCurrentConfig, agentId: t.agentId, conversation: i }); try { return await withConversationAuthority(t, { operationId: e.operationId }, ({ operation: t, conversation: r }) => { if (!t || t.conversationRef !== a.conversationRef) throw new PlatformMessageNotDispatchedError(`Conversation delivery operation no longer exists: ${e.operationId}`, { cause: void 0, retryable: false }); o.assertCurrent(r, a); return n; }); } finally { o.dispose(); } } //#endregion export { withAuthorizedQueuedConversationDelivery as a, withAuthorizedConversationDelivery as i, prepareConversationRouteEligibilitiesForAgent as n, ConversationInputError as o, resolveConversationRouteEligibilitiesForAgent as r, ConversationOperationConflictError as s, prepareConversationDeliveryRouteAuthorization as t };