Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(plugins): conversation mappings capability + session-and-chat handover gate (#587)
Yudhi Armyndharisaaa3683e030f
diff --git a/src/core/plugins/handover-gate.spec.ts b/src/core/plugins/handover-gate.spec.tsindex aa48632d2..1c79c4645 100644--- a/src/core/plugins/handover-gate.spec.ts+++ b/src/core/plugins/handover-gate.spec.ts@@ -1,16 +1,21 @@-import { shouldDispatchInbound } from './handover-gate';+import { shouldDispatchToPlugin } from './handover-gate';-describe('shouldDispatchInbound', () => {- it('dispatches when there is no mapping (bot is default)', () => {- expect(shouldDispatchInbound(null)).toBe(true);+describe('shouldDispatchToPlugin', () => {+ it('dispatches when there is no handover row (bot is default)', () => {+ expect(shouldDispatchToPlugin(null, 'faq-bot')).toBe(true);});- it('dispatches for a bot conversation', () => {- expect(shouldDispatchInbound({ handoverState: 'bot' } as never)).toBe(true);+ it('dispatches while the conversation is bot-handled', () => {+ expect(shouldDispatchToPlugin({ pluginId: 'chatwoot-adapter', handoverState: 'bot' }, 'faq-bot')).toBe(true);});- it('does NOT dispatch to the bot for a human-handled conversation', () => {- expect(shouldDispatchInbound({ handoverState: 'human' } as never)).toBe(false);+ it('silences OTHER bots when the owner has taken over (human)', () => {+ expect(shouldDispatchToPlugin({ pluginId: 'chatwoot-adapter', handoverState: 'human' }, 'faq-bot')).toBe(false);});- it('does NOT dispatch for a closed conversation', () => {- expect(shouldDispatchInbound({ handoverState: 'closed' } as never)).toBe(false);+ it('silences OTHER bots when the conversation is closed', () => {+ expect(shouldDispatchToPlugin({ pluginId: 'chatwoot-adapter', handoverState: 'closed' }, 'faq-bot')).toBe(false);+ });+ it('exempts the owning plugin so the relay keeps mirroring', () => {+ expect(shouldDispatchToPlugin({ pluginId: 'chatwoot-adapter', handoverState: 'human' }, 'chatwoot-adapter')).toBe(+ true,+ );});});diff --git a/src/core/plugins/handover-gate.ts b/src/core/plugins/handover-gate.tsindex dc2182c1d..6809b5774 100644--- a/src/core/plugins/handover-gate.ts+++ b/src/core/plugins/handover-gate.ts@@ -1,7 +1,11 @@-import { ConversationMapping } from '../../modules/integration/entities/conversation-mapping.entity';--// The core deterministically stops the bot when a human has taken over (or the conversation is-// closed). Default (no mapping yet) = bot, so a brand-new conversation still reaches the adapter.-export function shouldDispatchInbound(mapping: Pick<ConversationMapping, 'handoverState'> | null): boolean {- return !mapping || mapping.handoverState === 'bot';+// The core deterministically silences OTHER bots once a plugin has taken a conversation over (human) or+// closed it, while exempting the owning plugin so it (e.g. the Chatwoot relay) keeps mirroring. Scoped by+// session+chat, NOT by pluginId: a handover set by one plugin governs every plugin on that chat.+export function shouldDispatchToPlugin(+ handover: { pluginId: string; handoverState: 'bot' | 'human' | 'closed' } | null,+ callerPluginId: string,+): boolean {+ if (!handover) return true; // no handover row => bot default => dispatch+ if (handover.handoverState === 'bot') return true;+ return handover.pluginId === callerPluginId; // owner exempt; every other plugin silenced}diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 705112f54..6c16a48e7 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -15,6 +15,7 @@ import {PluginNetCapability,PluginConversationsCapability,PluginHandoverCapability,+ PluginMappingsCapability,PluginInstance,PluginStatus,PluginContext,@@ -31,7 +32,7 @@ import { WorkerThreadChannel } from './sandbox/worker-thread-channel';import { dispatchCapabilityVerb } from './sandbox/capability-router';import { PluginLogLevel } from './sandbox/protocol';import { buildConversationSendFacade } from './conversation-send-facade';-import { shouldDispatchInbound } from './handover-gate';+import { shouldDispatchToPlugin } from './handover-gate';import { makeOnWebhookSubscribe } from './webhook-subscribe.util';import { INGRESS_DISPATCH_TIMEOUT_MS } from '../../modules/integration/integration.constants';import type { MessageService } from '../../modules/message/message.service';@@ -802,12 +803,11 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {try {const chatId = (hookCtx.data as { chatId?: string } | undefined)?.chatId;if (chatId && hookCtx.sessionId) {- const mapping = await this.getConversationMappingService().findForChat(+ const handover = await this.getConversationMappingService().findHandoverForChat(hookCtx.sessionId,chatId,- pluginId,);- if (!shouldDispatchInbound(mapping)) return { continue: true };+ if (!shouldDispatchToPlugin(handover, pluginId)) return { continue: true };}} catch (error) {this.logger.debug(`Handover gate lookup failed for plugin ${pluginId}; dispatching normally`, {@@ -1038,6 +1038,38 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {await this.getConversationMappingService().setHandover(mapping.id, state);},} satisfies PluginHandoverCapability,+ mappings: {+ upsert: async (key, providerConversationId) => {+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);+ this.assertSessionAllowed(plugin.manifest, key.sessionId);+ await this.getConversationMappingService().upsert(+ { sessionId: key.sessionId, chatId: key.chatId, pluginId: plugin.manifest.id, instanceId: key.instanceId },+ providerConversationId,+ );+ },+ get: async key => {+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);+ this.assertSessionAllowed(plugin.manifest, key.sessionId);+ const m = await this.getConversationMappingService().get({+ sessionId: key.sessionId,+ chatId: key.chatId,+ pluginId: plugin.manifest.id,+ instanceId: key.instanceId,+ });+ return m ? { providerConversationId: m.providerConversationId, handoverState: m.handoverState } : null;+ },+ getByProvider: async (instanceId, providerConversationId) => {+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);+ const m = await this.getConversationMappingService().getByProvider(+ plugin.manifest.id,+ instanceId,+ providerConversationId,+ );+ // Parity with get/upsert: a plugin may only read a mapping for a session it is scoped to.+ if (m) this.assertSessionAllowed(plugin.manifest, m.sessionId);+ return m ? { sessionId: m.sessionId, chatId: m.chatId, handoverState: m.handoverState } : null;+ },+ } satisfies PluginMappingsCapability,};}diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex c296544ba..ff3931331 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -298,6 +298,24 @@ export interface PluginHandoverCapability {set(key: { sessionId: string; chatId: string; instanceId: string }, state: HandoverState): Promise<unknown>;}+/**+ * Plugin-facing conversation mapping: create/read the WA-chat <-> provider-conversation link an adapter+ * needs so handover.set and conversation.send({source}) can resolve. Reuses the `conversation:send`+ * permission — owning the mapping is part of owning the conversation.+ */+export interface PluginMappingsCapability {+ upsert(key: { sessionId: string; chatId: string; instanceId: string }, providerConversationId: string): Promise<void>;+ get(key: {+ sessionId: string;+ chatId: string;+ instanceId: string;+ }): Promise<{ providerConversationId: string; handoverState: HandoverState } | null>;+ getByProvider(+ instanceId: string,+ providerConversationId: string,+ ): Promise<{ sessionId: string; chatId: string; handoverState: HandoverState } | null>;+}+// ============================================================================// Plugin Context (passed to plugin on initialization)// ============================================================================@@ -340,6 +358,9 @@ export interface PluginContext {// Flip a mapped conversation's bot/human/closed handover state. Requires `conversation:send`.handover: PluginHandoverCapability;++ // Create/read the WA-chat <-> provider-conversation mapping. Requires `conversation:send`.+ mappings: PluginMappingsCapability;}export interface PluginLogger {diff --git a/src/core/plugins/sandbox/capability-router.spec.ts b/src/core/plugins/sandbox/capability-router.spec.tsindex 7043a2784..77496ded3 100644--- a/src/core/plugins/sandbox/capability-router.spec.ts+++ b/src/core/plugins/sandbox/capability-router.spec.ts@@ -28,6 +28,11 @@ function makeContext() {handover: {set: jest.fn().mockResolvedValue(undefined),},+ mappings: {+ upsert: jest.fn().mockResolvedValue(undefined),+ get: jest.fn().mockResolvedValue(null),+ getByProvider: jest.fn().mockResolvedValue(null),+ },};}@@ -66,6 +71,33 @@ describe('dispatchCapabilityVerb', () => {expect(out).toMatchObject({ ok: true, status: 200, body: 'x' });});+ it('routes mappings verbs to the context', async () => {+ const calls: Array<[string, unknown[]]> = [];+ const ctx = {+ ...makeContext(),+ mappings: {+ upsert: (...a: unknown[]) => {+ calls.push(['upsert', a]);+ return Promise.resolve();+ },+ get: (...a: unknown[]) => {+ calls.push(['get', a]);+ return Promise.resolve(null);+ },+ getByProvider: (...a: unknown[]) => {+ calls.push(['getByProvider', a]);+ return Promise.resolve(null);+ },+ },+ } as unknown as CapabilityContext;+ await dispatchCapabilityVerb(ctx, 'mappings.upsert', [{ sessionId: 's', chatId: 'c', instanceId: 'i' }, 'conv1']);+ await dispatchCapabilityVerb(ctx, 'mappings.getByProvider', ['i', 'conv1']);+ expect(calls).toEqual([+ ['upsert', [{ sessionId: 's', chatId: 'c', instanceId: 'i' }, 'conv1']],+ ['getByProvider', ['i', 'conv1']],+ ]);+ });+it('rejects an unknown verb — only allowlisted capabilities are reachable', async () => {const ctx = makeContext();await expect(dispatchCapabilityVerb(ctx as unknown as CapabilityContext, 'process.exit', [0])).rejects.toThrow(diff --git a/src/core/plugins/sandbox/capability-router.ts b/src/core/plugins/sandbox/capability-router.tsindex 1bffaf3af..0789671b1 100644--- a/src/core/plugins/sandbox/capability-router.ts+++ b/src/core/plugins/sandbox/capability-router.ts@@ -9,6 +9,14 @@ export type CapabilityContext = Pick<PluginContext, 'messages' | 'engine' | 'stohandover: {set(key: { sessionId: string; chatId: string; instanceId: string }, state: HandoverState): Promise<unknown>;};+ mappings: {+ upsert(+ key: { sessionId: string; chatId: string; instanceId: string },+ providerConversationId: string,+ ): Promise<unknown>;+ get(key: { sessionId: string; chatId: string; instanceId: string }): Promise<unknown>;+ getByProvider(instanceId: string, providerConversationId: string): Promise<unknown>;+ };};/**@@ -58,6 +66,12 @@ export async function dispatchCapabilityVerb(args[0] as { sessionId: string; chatId: string; instanceId: string },args[1] as HandoverState,);+ case 'mappings.upsert':+ return context.mappings.upsert(args[0] as { sessionId: string; chatId: string; instanceId: string }, s(1));+ case 'mappings.get':+ return context.mappings.get(args[0] as { sessionId: string; chatId: string; instanceId: string });+ case 'mappings.getByProvider':+ return context.mappings.getByProvider(s(0), s(1));default:throw new Error(`Unknown capability verb: ${verb}`);}diff --git a/src/core/plugins/sandbox/worker-capability.ts b/src/core/plugins/sandbox/worker-capability.tsindex 2c7328143..0379f14ae 100644--- a/src/core/plugins/sandbox/worker-capability.ts+++ b/src/core/plugins/sandbox/worker-capability.ts@@ -57,6 +57,14 @@ export interface SandboxCapabilityContext {handover: {set(key: { sessionId: string; chatId: string; instanceId: string }, state: HandoverState): Promise<unknown>;};+ mappings: {+ upsert(+ key: { sessionId: string; chatId: string; instanceId: string },+ providerConversationId: string,+ ): Promise<unknown>;+ get(key: { sessionId: string; chatId: string; instanceId: string }): Promise<unknown>;+ getByProvider(instanceId: string, providerConversationId: string): Promise<unknown>;+ };}/** Build the proxy capability context handed to a sandboxed plugin in the worker. */@@ -89,5 +97,11 @@ export function buildSandboxContext(client: WorkerCapabilityClient): SandboxCapahandover: {set: (key, state) => client.call('handover.set', [key, state]),},+ mappings: {+ upsert: (key, providerConversationId) => client.call('mappings.upsert', [key, providerConversationId]),+ get: key => client.call('mappings.get', [key]),+ getByProvider: (instanceId, providerConversationId) =>+ client.call('mappings.getByProvider', [instanceId, providerConversationId]),+ },};}diff --git a/src/modules/integration/conversation-mapping.service.spec.ts b/src/modules/integration/conversation-mapping.service.spec.tsindex 3ae47fcd5..55b4c87c6 100644--- a/src/modules/integration/conversation-mapping.service.spec.ts+++ b/src/modules/integration/conversation-mapping.service.spec.ts@@ -50,4 +50,19 @@ describe('ConversationMappingService', () => {const stale = await service.getByProvider(key.pluginId, key.instanceId, 'conv-1');expect(stale).toBeNull();});++ it('findHandoverForChat returns any human/closed row for the chat, ignoring pluginId', async () => {+ // faq-bot keeps a bot mapping; chatwoot-adapter takes the same chat over (human).+ await service.upsert({ sessionId: 'sess-1', chatId: 'chat-1', pluginId: 'faq-bot', instanceId: 'i1' }, 'convA');+ await service.upsert(+ { sessionId: 'sess-1', chatId: 'chat-1', pluginId: 'chatwoot-adapter', instanceId: 'i2' },+ 'convB',+ { handoverState: 'human' },+ );+ expect(await service.findHandoverForChat('sess-1', 'chat-1')).toEqual({+ pluginId: 'chatwoot-adapter',+ handoverState: 'human',+ });+ expect(await service.findHandoverForChat('sess-1', 'other-chat')).toBeNull();+ });});diff --git a/src/modules/integration/conversation-mapping.service.ts b/src/modules/integration/conversation-mapping.service.tsindex ead7959d3..55fbf8990 100644--- a/src/modules/integration/conversation-mapping.service.ts+++ b/src/modules/integration/conversation-mapping.service.ts@@ -30,11 +30,21 @@ export class ConversationMappingService {return this.repo.findOne({ where: key });}- // Handover-gate lookup: any mapped instance for this plugin's chat, without resolving a specific- // instanceId at message time. The gate only needs "is THIS plugin's chat handed over?" — if a plugin- // has multiple instances mapped to the same chat, they share handover intent for this purpose.- findForChat(sessionId: string, chatId: string, pluginId: string): Promise<ConversationMapping | null> {- return this.repo.findOne({ where: { sessionId, chatId, pluginId } });+ // Session+chat-scoped handover lookup for the core gate: the most-recently-updated human/closed row for+ // this chat, IGNORING pluginId. A handover taken by one plugin (e.g. the Chatwoot relay) then governs+ // every plugin on that chat — the gate exempts the owner and silences the rest.+ async findHandoverForChat(+ sessionId: string,+ chatId: string,+ ): Promise<{ pluginId: string; handoverState: HandoverState } | null> {+ const row = await this.repo.findOne({+ where: [+ { sessionId, chatId, handoverState: 'human' },+ { sessionId, chatId, handoverState: 'closed' },+ ],+ order: { updatedAt: 'DESC' },+ });+ return row ? { pluginId: row.pluginId, handoverState: row.handoverState } : null;}getByProvider(