Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(plugins): resolve host services through core-owned port tokens

Yudhi Armyndharisbacf0866b28a
diff --git a/src/core/plugins/ingress-instance-config.spec.ts b/src/core/plugins/ingress-instance-config.spec.ts
index 811e0ee32..7f4e418e4 100644
--- a/src/core/plugins/ingress-instance-config.spec.ts
+++ b/src/core/plugins/ingress-instance-config.spec.ts
@@ -87,7 +87,7 @@ function makeBridge(opts: {
]);
const hostServices = {
- getPluginInstanceService: () => ({
+ getPluginInstancePort: () => ({
resolve: (pluginId: string, instanceId: string) =>
Promise.resolve(opts.rows.find(r => r.pluginId === pluginId && r.instanceId === instanceId) ?? null),
list: (pluginId: string) => Promise.resolve(opts.rows.filter(r => r.pluginId === pluginId)),
diff --git a/src/core/plugins/plugin-capability-context.ts b/src/core/plugins/plugin-capability-context.ts
index 343b94296..da441d7f4 100644
--- a/src/core/plugins/plugin-capability-context.ts
+++ b/src/core/plugins/plugin-capability-context.ts
@@ -6,11 +6,11 @@ import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.in
import { toNeutralJid } from '../../engine/identity/wa-id';
import { ConversationMappingConflict } from '../../modules/integration/conversation-mapping.service';
import { createLogger } from '../../common/services/logger.service';
-import type { MessageService } from '../../modules/message/message.service';
import { isPluginActiveForSession, resolvePluginConfig } from './plugin-activation';
import { effectiveNetAllow, isNetHostAllowed, performPluginFetch } from './plugin-net';
import { buildConversationSendFacade, type ConversationMediaType } from './conversation-send-facade';
import { PluginHostServices } from './plugin-host-services';
+import type { PluginMessagePort } from './plugin-host-ports';
import { PluginStorageService } from './plugin-storage.service';
import {
PluginCapabilityError,
@@ -35,7 +35,7 @@ import {
* compile error here rather than a silent runtime fall-through.
*/
export function dispatchConversationMedia(
- svc: Pick<MessageService, 'sendImage' | 'sendVideo' | 'sendAudio' | 'sendDocument'>,
+ svc: Pick<PluginMessagePort, 'sendImage' | 'sendVideo' | 'sendAudio' | 'sendDocument'>,
sessionId: string,
opts: { chatId: string; url: string; type: ConversationMediaType; caption?: string },
): Promise<unknown> {
@@ -143,7 +143,7 @@ export class PluginCapabilityContext {
*/
private resolveEngine(plugin: PluginInstance, sessionId: string): IWhatsAppEngine {
this.assertSessionActive(plugin, sessionId);
- const engine = this.hostServices.getSessionService().getEngine(sessionId);
+ const engine = this.hostServices.getSessionPort().getEngine(sessionId);
if (!engine) {
throw new PluginCapabilityError(`Session ${sessionId} has no active engine (unknown or not started)`);
}
@@ -165,7 +165,7 @@ export class PluginCapabilityContext {
*/
private async isSessionGone(sessionId: string): Promise<boolean> {
try {
- await this.hostServices.getSessionService().findOne(sessionId);
+ await this.hostServices.getSessionPort().findOne(sessionId);
return false;
} catch (error) {
return error instanceof NotFoundException;
@@ -246,12 +246,12 @@ export class PluginCapabilityContext {
// assertSessionActive.
this.assertPermission(plugin.manifest, PluginCapabilityPermission.MESSAGES_SEND);
this.resolveEngine(plugin, sessionId);
- return this.hostServices.getMessageService().sendText(sessionId, { chatId, text });
+ return this.hostServices.getMessagePort().sendText(sessionId, { chatId, text });
},
reply: async (sessionId, chatId, quotedMessageId, text) => {
this.assertPermission(plugin.manifest, PluginCapabilityPermission.MESSAGES_SEND);
this.resolveEngine(plugin, sessionId);
- return this.hostServices.getMessageService().reply(sessionId, { chatId, quotedMessageId, text });
+ return this.hostServices.getMessagePort().reply(sessionId, { chatId, quotedMessageId, text });
},
} satisfies PluginMessagingCapability;
}
@@ -328,7 +328,7 @@ export class PluginCapabilityContext {
*/
private async enabledInstanceConfigs(pluginId: string): Promise<Record<string, unknown>[]> {
try {
- const rows = await this.hostServices.getPluginInstanceService().list(pluginId);
+ const rows = await this.hostServices.getPluginInstancePort().list(pluginId);
return rows.filter(row => row.enabled).map(row => row.config ?? {});
} catch {
return [];
@@ -384,7 +384,7 @@ export class PluginCapabilityContext {
);
}
const mapping = await this.hostServices
- .getConversationMappingService()
+ .getConversationMappingPort()
.getByProvider(plugin.manifest.id, env.instanceId, env.source.externalConversationId);
if (!mapping) {
throw new PluginCapabilityError(
@@ -404,7 +404,7 @@ export class PluginCapabilityContext {
// dead session's rows bricked conversation.send permanently. A mapping owned by another
// EXISTING session is a genuine cross-session violation and still throws.
if (await this.isSessionGone(mapping.sessionId)) {
- await this.hostServices.getConversationMappingService().rebindSession(mapping.id, env.sessionId);
+ await this.hostServices.getConversationMappingPort().rebindSession(mapping.id, env.sessionId);
this.logger.warn(
`Rebound conversation mapping for instance ${env.instanceId} / ${env.source.externalConversationId} ` +
`from deleted session ${mapping.sessionId} to ${env.sessionId}`,
@@ -427,10 +427,10 @@ export class PluginCapabilityContext {
(events as HookEvent[]).some(e => this.hookManager.isInFlight(e))
? this.hookManager.runInFlight(events as HookEvent[], run)
: run(),
- sendText: (sessionId, opts) => this.hostServices.getMessageService().sendText(sessionId, opts),
- reply: (sessionId, opts) => this.hostServices.getMessageService().reply(sessionId, opts),
- sendMedia: (sessionId, opts) => dispatchConversationMedia(this.hostServices.getMessageService(), sessionId, opts),
- sendLocation: (sessionId, opts) => this.hostServices.getMessageService().sendLocation(sessionId, opts),
+ sendText: (sessionId, opts) => this.hostServices.getMessagePort().sendText(sessionId, opts),
+ reply: (sessionId, opts) => this.hostServices.getMessagePort().reply(sessionId, opts),
+ sendMedia: (sessionId, opts) => dispatchConversationMedia(this.hostServices.getMessagePort(), sessionId, opts),
+ sendLocation: (sessionId, opts) => this.hostServices.getMessagePort().sendLocation(sessionId, opts),
} satisfies Parameters<typeof buildConversationSendFacade>[0]) satisfies PluginConversationsCapability;
}
@@ -441,7 +441,7 @@ export class PluginCapabilityContext {
// it reuses CONVERSATION_SEND rather than adding a new permission.
this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);
this.assertSessionActive(plugin, key.sessionId);
- const mapping = await this.hostServices.getConversationMappingService().get({
+ const mapping = await this.hostServices.getConversationMappingPort().get({
sessionId: key.sessionId,
chatId: key.chatId,
pluginId: plugin.manifest.id,
@@ -452,7 +452,7 @@ export class PluginCapabilityContext {
`Plugin ${plugin.manifest.id}: no conversation mapping for session ${key.sessionId} / chat ${key.chatId} / instance ${key.instanceId}`,
);
}
- await this.hostServices.getConversationMappingService().setHandover(mapping.id, state);
+ await this.hostServices.getConversationMappingPort().setHandover(mapping.id, state);
},
} satisfies PluginHandoverCapability;
}
@@ -469,7 +469,7 @@ export class PluginCapabilityContext {
instanceId: key.instanceId,
};
try {
- await this.hostServices.getConversationMappingService().upsert(mappingKey, providerConversationId);
+ await this.hostServices.getConversationMappingPort().upsert(mappingKey, providerConversationId);
} catch (error) {
if (!(error instanceof ConversationMappingConflict)) throw error;
// The reverse unique key is held by another row. If that row's session was DELETED
@@ -478,17 +478,17 @@ export class PluginCapabilityContext {
// the stale row and retry once. A row owned by an EXISTING session is a genuine conflict
// and rethrows.
const stale = await this.hostServices
- .getConversationMappingService()
+ .getConversationMappingPort()
.getByProvider(plugin.manifest.id, key.instanceId, providerConversationId);
if (!stale || !(await this.isSessionGone(stale.sessionId))) throw error;
- await this.hostServices.getConversationMappingService().delete(stale.id);
- await this.hostServices.getConversationMappingService().upsert(mappingKey, providerConversationId);
+ await this.hostServices.getConversationMappingPort().delete(stale.id);
+ await this.hostServices.getConversationMappingPort().upsert(mappingKey, providerConversationId);
}
},
get: async key => {
this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);
this.assertSessionActive(plugin, key.sessionId);
- const m = await this.hostServices.getConversationMappingService().get({
+ const m = await this.hostServices.getConversationMappingPort().get({
sessionId: key.sessionId,
chatId: key.chatId,
pluginId: plugin.manifest.id,
@@ -499,7 +499,7 @@ export class PluginCapabilityContext {
getByProvider: async (instanceId, providerConversationId) => {
this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);
const m = await this.hostServices
- .getConversationMappingService()
+ .getConversationMappingPort()
.getByProvider(plugin.manifest.id, instanceId, providerConversationId);
// Parity with get/upsert: a plugin may only read a mapping for a session it is activated for.
if (m) this.assertSessionActive(plugin, m.sessionId);
diff --git a/src/core/plugins/plugin-capability.spec.ts b/src/core/plugins/plugin-capability.spec.ts
index afe372047..981b4225f 100644
--- a/src/core/plugins/plugin-capability.spec.ts
+++ b/src/core/plugins/plugin-capability.spec.ts
@@ -13,9 +13,7 @@ import {
PluginStatus,
PluginType,
} from './plugin.interfaces';
-import { MessageService } from '../../modules/message/message.service';
-import { SessionService } from '../../modules/session/session.service';
-import { ConversationMappingService } from '../../modules/integration/conversation-mapping.service';
+import { PLUGIN_CONVERSATION_MAPPING_PORT, PLUGIN_MESSAGE_PORT, PLUGIN_SESSION_PORT } from './plugin-host-ports';
function makePlugin(
sessions?: string[],
@@ -51,7 +49,7 @@ describe('PluginLoaderService capability facade — ctx.messages', () => {
moduleRef = {
get: jest
.fn()
- .mockImplementation((token: unknown) => (token === SessionService ? sessionService : messageService)),
+ .mockImplementation((token: unknown) => (token === PLUGIN_SESSION_PORT ? sessionService : messageService)),
};
const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
const pluginStorage = {
@@ -76,14 +74,14 @@ describe('PluginLoaderService capability facade — ctx.messages', () => {
it('messages.sendText delegates to MessageService.sendText with a wrapped dto', async () => {
const ctx = contextFor(makePlugin(['*']));
await ctx.messages.sendText('sess-1', '[email protected]', 'hi');
- expect(moduleRef.get).toHaveBeenCalledWith(MessageService, { strict: false });
+ expect(moduleRef.get).toHaveBeenCalledWith(PLUGIN_MESSAGE_PORT, { strict: false });
expect(messageService.sendText).toHaveBeenCalledWith('sess-1', { chatId: '[email protected]', text: 'hi' });
});
it('messages.reply delegates to MessageService.reply', async () => {
const ctx = contextFor(makePlugin(['*']));
await ctx.messages.reply('sess-1', '[email protected]', 'quoted-id', 'pong');
- expect(moduleRef.get).toHaveBeenCalledWith(MessageService, { strict: false });
+ expect(moduleRef.get).toHaveBeenCalledWith(PLUGIN_MESSAGE_PORT, { strict: false });
expect(messageService.reply).toHaveBeenCalledWith('sess-1', {
chatId: '[email protected]',
quotedMessageId: 'quoted-id',
@@ -232,7 +230,7 @@ describe('PluginLoaderService capability facade — ctx.engine', () => {
const { sessionService } = build(engine);
const ctx = contextFor(makePlugin(['*']));
await ctx.engine.getGroupInfo('sess-1', '[email protected]');
- expect(moduleRef.get).toHaveBeenCalledWith(SessionService, { strict: false });
+ expect(moduleRef.get).toHaveBeenCalledWith(PLUGIN_SESSION_PORT, { strict: false });
expect(sessionService.getEngine).toHaveBeenCalledWith('sess-1');
expect(engine.getGroupInfo).toHaveBeenCalledWith('[email protected]');
});
@@ -352,7 +350,7 @@ describe('PluginLoaderService capability facade — ctx.conversations', () => {
get: jest
.fn()
.mockImplementation((token: unknown) =>
- token === ConversationMappingService ? mappingService : messageService,
+ token === PLUGIN_CONVERSATION_MAPPING_PORT ? mappingService : messageService,
),
};
const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
diff --git a/src/core/plugins/plugin-host-ports.ts b/src/core/plugins/plugin-host-ports.ts
new file mode 100644
index 000000000..c46e19549
--- /dev/null
+++ b/src/core/plugins/plugin-host-ports.ts
@@ -0,0 +1,121 @@
+import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+// Type-only, on purpose: they keep the port signatures aligned with the real services without
+// creating any runtime module edge from core back into a feature module.
+import type { MessageResponseDto } from '../../modules/message/dto';
+import type { HandoverState } from '../../modules/integration/entities/conversation-mapping.entity';
+
+/**
+ * The narrow slices of host feature services that plugin capability code invokes — one port per
+ * service, each holding ONLY the members `PluginCapabilityContext` and `PluginSandboxBridge` actually
+ * call, plus one for the automation reply path. Deliberately not whole-service mirrors: a reviewer
+ * reads here what the plugin runtime can reach, nothing more.
+ *
+ * The module that owns each service binds it to the port's token with an adapter provider
+ * (a `useFactory` closing over the real service). Core resolves the TOKEN at call time via
+ * `ModuleRef.get(..., { strict: false })` — never the service class — so the deferral that breaks
+ * the plugin provider cycle stays, while core/plugins itself imports no feature-module value and
+ * the old lazy `require(...)` of feature-module paths is gone entirely.
+ */
+export interface PluginMessagePort {
+ sendText(
+ sessionId: string,
+ dto: { chatId: string; text: string; linkPreview?: boolean },
+ ): Promise<MessageResponseDto>;
+ reply(sessionId: string, dto: { chatId: string; quotedMessageId: string; text: string }): Promise<MessageResponseDto>;
+ sendImage(sessionId: string, dto: { chatId: string; url?: string; caption?: string }): Promise<MessageResponseDto>;
+ sendVideo(sessionId: string, dto: { chatId: string; url?: string; caption?: string }): Promise<MessageResponseDto>;
+ sendDocument(sessionId: string, dto: { chatId: string; url?: string; caption?: string }): Promise<MessageResponseDto>;
+ sendAudio(
+ sessionId: string,
+ dto: { chatId: string; url?: string; caption?: string; ptt?: boolean },
+ ): Promise<MessageResponseDto>;
+ sendLocation(
+ sessionId: string,
+ dto: { chatId: string; latitude: number; longitude: number; description?: string },
+ ): Promise<MessageResponseDto>;
+ getChatHistory(
+ sessionId: string,
+ chatId: string,
+ limit?: number,
+ includeMedia?: boolean,
+ ): ReturnType<IWhatsAppEngine['getChatHistory']>;
+}
+
+/** Live-engine resolution + the deleted-session probe the capability gates rely on. */
+export interface PluginSessionPort {
+ getEngine(sessionId: string): IWhatsAppEngine | undefined;
+ /** Rejects with NotFoundException when the session row no longer exists. */
+ findOne(sessionId: string): Promise<unknown>;
+}
+
+/** Forward key of a conversation mapping — (session, chat, plugin, provisioned instance). */
+export interface PluginMappingKey {
+ sessionId: string;
+ chatId: string;
+ pluginId: string;
+ instanceId: string;
+}
+
+/** The mapping columns plugin capability code reads. */
+export interface PluginConversationMappingRow {
+ id: string;
+ sessionId: string;
+ chatId: string;
+ pluginId: string;
+ instanceId: string;
+ providerConversationId: string;
+ handoverState: HandoverState;
+}
+
+/** Conversation-mapping verbs: the conversation/handover/mappings capabilities and the hook handover gate. */
+export interface PluginConversationMappingPort {
+ get(key: PluginMappingKey): Promise<PluginConversationMappingRow | null>;
+ getByProvider(
+ pluginId: string,
+ instanceId: string,
+ providerConversationId: string,
+ ): Promise<PluginConversationMappingRow | null>;
+ upsert(key: PluginMappingKey, providerConversationId: string): Promise<void>;
+ delete(id: string): Promise<void>;
+ setHandover(id: string, state: HandoverState): Promise<void>;
+ rebindSession(id: string, sessionId: string): Promise<void>;
+ findHandoverForChat(
+ sessionId: string,
+ chatId: string,
+ ): Promise<{ pluginId: string; handoverState: HandoverState } | null>;
+}
+
+/** A provisioned instance of an adapter plugin, as the instance-allowlist and ingress dispatch read it. */
+export interface PluginInstanceRecord {
+ enabled: boolean;
+ config?: Record<string, unknown> | null;
+ sessionScope?: string | null;
+}
+
+/** Instance lookup verbs: the net-allowlist widening and the ingress per-instance config resolution. */
+export interface PluginInstancePort {
+ list(pluginId: string): Promise<PluginInstanceRecord[]>;
+ resolve(pluginId: string, instanceId: string): Promise<PluginInstanceRecord | null>;
+}
+
+/**
+ * Search-registry mutations a sandboxed plugin's registration reaches. `register` takes the provider
+ * shape the registration util constructs; the registry port is intentionally wider than nothing but
+ * narrower than the whole registry (`active`/`list` belong to the search feature's own callers).
+ */
+export interface PluginSearchRegistryPort {
+ register(provider: { id: string }): void;
+ unregister(id: string): void;
+ setActive(id: string): void;
+}
+
+/** Message send/history surface, bound to MessageService by MessageModule. */
+export const PLUGIN_MESSAGE_PORT = Symbol('PLUGIN_MESSAGE_PORT');
+/** Session engine resolution, bound to SessionService by SessionModule. */
+export const PLUGIN_SESSION_PORT = Symbol('PLUGIN_SESSION_PORT');
+/** Conversation mapping verbs, bound to ConversationMappingService by PluginsModule (its provider home). */
+export const PLUGIN_CONVERSATION_MAPPING_PORT = Symbol('PLUGIN_CONVERSATION_MAPPING_PORT');
+/** Provisioned-instance lookup, bound to PluginInstanceService by IntegrationModule. */
+export const PLUGIN_INSTANCE_PORT = Symbol('PLUGIN_INSTANCE_PORT');
+/** Search-registry mutations, bound to SearchProviderRegistry by SearchModule. */
+export const PLUGIN_SEARCH_REGISTRY_PORT = Symbol('PLUGIN_SEARCH_REGISTRY_PORT');
diff --git a/src/core/plugins/plugin-host-services.spec.ts b/src/core/plugins/plugin-host-services.spec.ts
index bd8483d92..91e23db1b 100644
--- a/src/core/plugins/plugin-host-services.spec.ts
+++ b/src/core/plugins/plugin-host-services.spec.ts
@@ -5,11 +5,11 @@ import type { ModuleRef } from '@nestjs/core';
const hostServices = (get: jest.Mock): PluginHostServices => new PluginHostServices({ get } as unknown as ModuleRef);
describe('PluginHostServices', () => {
- describe('getSearchRegistry', () => {
+ describe('getSearchRegistryPort', () => {
it('returns the registry when ModuleRef has it', () => {
const registry = new SearchProviderRegistry();
- expect(hostServices(jest.fn().mockReturnValue(registry)).getSearchRegistry()).toBe(registry);
+ expect(hostServices(jest.fn().mockReturnValue(registry)).getSearchRegistryPort()).toBe(registry);
});
it('returns undefined when ModuleRef has no registry (search disabled)', () => {
@@ -19,7 +19,7 @@ describe('PluginHostServices', () => {
throw new Error('not found');
});
- expect(hostServices(get).getSearchRegistry()).toBeUndefined();
+ expect(hostServices(get).getSearchRegistryPort()).toBeUndefined();
});
});
});
diff --git a/src/core/plugins/plugin-host-services.ts b/src/core/plugins/plugin-host-services.ts
index f526b7264..55de08bb8 100644
--- a/src/core/plugins/plugin-host-services.ts
+++ b/src/core/plugins/plugin-host-services.ts
@@ -1,69 +1,66 @@
import type { ModuleRef } from '@nestjs/core';
-import type { MessageService } from '../../modules/message/message.service';
-import type { SessionService } from '../../modules/session/session.service';
-import type { ConversationMappingService } from '../../modules/integration/conversation-mapping.service';
-import type { PluginInstanceService } from '../../modules/integration/plugin-instance.service';
-import type { SearchProviderRegistry } from '../../modules/search/search-provider.registry';
+import {
+ PLUGIN_CONVERSATION_MAPPING_PORT,
+ PLUGIN_INSTANCE_PORT,
+ PLUGIN_MESSAGE_PORT,
+ PLUGIN_SEARCH_REGISTRY_PORT,
+ PLUGIN_SESSION_PORT,
+ type PluginConversationMappingPort,
+ type PluginInstancePort,
+ type PluginMessagePort,
+ type PluginSearchRegistryPort,
+ type PluginSessionPort,
+} from './plugin-host-ports';
/**
* Resolves the host services a plugin capability reaches, at call time rather than at module load.
*
- * Every lookup here is a lazy `require` plus a non-strict `ModuleRef.get`, and both halves are
- * load-bearing:
+ * Every lookup is a non-strict `ModuleRef.get` against a core-owned port token from
+ * plugin-host-ports.ts, and the deferral is load-bearing: constructor injection would close the
+ * provider cycle
+ * `PluginLoaderService -> SessionService -> SessionEngineLifecycle -> EngineFactory -> PluginLoaderService`.
+ * Resolving the PORT tokens rather than the feature-module service classes also means this file
+ * names no feature module at all — no static import edge, and no lazy `require` either. The module
+ * that owns each service registers the token adapter, so the binding lives with the service while
+ * core/plugins depends only on its own tokens.
*
- * - The lazy require exists so this file creates NO top-level module edge to the services. A static
- * import of MessageService closes the cycle
- * `plugin-loader -> message -> session -> engine.factory -> core/plugins barrel -> plugin-loader`,
- * which corrupts MessageService's constructor paramtype metadata (`SessionService -> undefined`)
- * at boot. The same reasoning covers the two integration services.
- * - `ModuleRef` rather than constructor injection avoids the provider cycle
- * `PluginLoaderService -> SessionService -> SessionEngineLifecycle -> EngineFactory -> PluginLoaderService`.
- *
- * Keeping the pair in one place means the loader no longer has to carry that reasoning, nor name the
- * five services it was resolving. Everything below is a resolution detail; nothing here decides
- * policy.
+ * Keeping the lookups in one place means the loader never has to carry that reasoning, nor name the
+ * five ports it was resolving. Everything below is a resolution detail; nothing here decides policy.
*/
export class PluginHostServices {
constructor(private readonly moduleRef: ModuleRef) {}
- getMessageService(): MessageService {
- const mod =
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- require('../../modules/message/message.service') as typeof import('../../modules/message/message.service');
- return this.moduleRef.get(mod.MessageService, { strict: false });
+ getMessagePort(): PluginMessagePort {
+ return this.moduleRef.get<typeof PLUGIN_MESSAGE_PORT, PluginMessagePort>(PLUGIN_MESSAGE_PORT, { strict: false });
}
- getSessionService(): SessionService {
- const mod =
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- require('../../modules/session/session.service') as typeof import('../../modules/session/session.service');
- return this.moduleRef.get(mod.SessionService, { strict: false });
+ getSessionPort(): PluginSessionPort {
+ return this.moduleRef.get<typeof PLUGIN_SESSION_PORT, PluginSessionPort>(PLUGIN_SESSION_PORT, { strict: false });
}
- getConversationMappingService(): ConversationMappingService {
- const mod =
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- require('../../modules/integration/conversation-mapping.service') as typeof import('../../modules/integration/conversation-mapping.service');
- return this.moduleRef.get(mod.ConversationMappingService, { strict: false });
+ getConversationMappingPort(): PluginConversationMappingPort {
+ return this.moduleRef.get<typeof PLUGIN_CONVERSATION_MAPPING_PORT, PluginConversationMappingPort>(
+ PLUGIN_CONVERSATION_MAPPING_PORT,
+ { strict: false },
+ );
}
- getPluginInstanceService(): PluginInstanceService {
- const mod =
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- require('../../modules/integration/plugin-instance.service') as typeof import('../../modules/integration/plugin-instance.service');
- return this.moduleRef.get(mod.PluginInstanceService, { strict: false });
+ getPluginInstancePort(): PluginInstancePort {
+ return this.moduleRef.get<typeof PLUGIN_INSTANCE_PORT, PluginInstancePort>(PLUGIN_INSTANCE_PORT, {
+ strict: false,
+ });
}
/**
- * Search is conditionally loaded (`SEARCH_ENABLED=false` omits SearchModule), so the registry may
- * not be registered at all. Returns undefined in that case so callers can no-op rather than throw.
+ * Search is conditionally loaded (`SEARCH_ENABLED=false` omits SearchModule), so the port adapter
+ * may not be registered at all. Returns undefined in that case so callers can no-op rather than throw.
*/
- getSearchRegistry(): SearchProviderRegistry | undefined {
+ getSearchRegistryPort(): PluginSearchRegistryPort | undefined {
try {
- const mod =
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- require('../../modules/search/search-provider.registry') as typeof import('../../modules/search/search-provider.registry');
- return this.moduleRef.get(mod.SearchProviderRegistry, { strict: false });
+ return this.moduleRef.get<typeof PLUGIN_SEARCH_REGISTRY_PORT, PluginSearchRegistryPort>(
+ PLUGIN_SEARCH_REGISTRY_PORT,
+ { strict: false },
+ );
} catch {
return undefined;
}
diff --git a/src/core/plugins/plugin-loader-conversation-repair.spec.ts b/src/core/plugins/plugin-loader-conversation-repair.spec.ts
index 88cf6aee1..e46d74d73 100644
--- a/src/core/plugins/plugin-loader-conversation-repair.spec.ts
+++ b/src/core/plugins/plugin-loader-conversation-repair.spec.ts
@@ -5,11 +5,8 @@ import { PluginLoaderService } from './plugin-loader.service';
import { PluginStorageService } from './plugin-storage.service';
import { HookManager } from '../hooks';
import { PluginContext, PluginInstance, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';
-import { SessionService } from '../../modules/session/session.service';
-import {
- ConversationMappingConflict,
- ConversationMappingService,
-} from '../../modules/integration/conversation-mapping.service';
+import { ConversationMappingConflict } from '../../modules/integration/conversation-mapping.service';
+import { PLUGIN_CONVERSATION_MAPPING_PORT, PLUGIN_MESSAGE_PORT, PLUGIN_SESSION_PORT } from './plugin-host-ports';
/**
* Stale-mapping repair after a session is deleted and re-paired under a new id. The cross-session
@@ -37,8 +34,8 @@ describe('PluginLoaderService — stale conversation-mapping repair', () => {
sessionService = { findOne: jest.fn() };
const moduleRef = {
get: jest.fn().mockImplementation((token: unknown) => {
- if (token === ConversationMappingService) return mappingService;
- if (token === SessionService) return sessionService;
+ if (token === PLUGIN_CONVERSATION_MAPPING_PORT) return mappingService;
+ if (token === PLUGIN_SESSION_PORT) return sessionService;
return messageService;
}),
};
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index 7377fbd00..0d3f46ae4 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -783,7 +783,7 @@ describe('PluginLoaderService — search-provider wiring', () => {
} as unknown as ModuleRef);
}
- // getSearchRegistry's own behaviour now lives in plugin-host-services.spec.ts, tested on the class
+ // getSearchRegistryPort's own behaviour now lives in plugin-host-services.spec.ts, tested on the class
// that owns it instead of through a private reach-in on the loader.
it('disablePlugin unregisters the plugin’s search-provider entry', async () => {
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index c340fd924..ec8eea2aa 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -733,7 +733,7 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
// Unregister all hooks for this plugin
this.hookManager.unregisterPlugin(pluginId);
// Drop the plugin's search-provider entry (if any) so queries don't route to a terminated worker.
- unregisterPluginSearchProvider(this.hostServices.getSearchRegistry(), pluginId);
+ unregisterPluginSearchProvider(this.hostServices.getSearchRegistryPort(), pluginId);
plugin.status = PluginStatus.DISABLED;
diff --git a/src/core/plugins/plugin-net-instance-allowlist.spec.ts b/src/core/plugins/plugin-net-instance-allowlist.spec.ts
index 1e4733617..fb448ca53 100644
--- a/src/core/plugins/plugin-net-instance-allowlist.spec.ts
+++ b/src/core/plugins/plugin-net-instance-allowlist.spec.ts
@@ -57,7 +57,7 @@ describe('the net allowlist admits every provisioned instance host', () => {
const netCapability = (instances: InstanceRow[]) => {
const hostServices = {
- getPluginInstanceService: () => ({ list: () => Promise.resolve(instances) }),
+ getPluginInstancePort: () => ({ list: () => Promise.resolve(instances) }),
} as unknown as PluginHostServices;
const ctx = new PluginCapabilityContext(createLogger('net-allowlist.spec'), hostServices, new HookManager(), {
createPluginStorage: () => ({}),
@@ -110,7 +110,7 @@ describe('the net allowlist admits every provisioned instance host', () => {
*/
it('falls back to the config-derived allowlist when the instance lookup is unavailable', async () => {
const hostServices = {
- getPluginInstanceService: () => {
+ getPluginInstancePort: () => {
throw new Error('no instance service in this host');
},
} as unknown as PluginHostServices;
diff --git a/src/core/plugins/plugin-sandbox-bridge.ts b/src/core/plugins/plugin-sandbox-bridge.ts
index 25694f431..b7f065604 100644
--- a/src/core/plugins/plugin-sandbox-bridge.ts
+++ b/src/core/plugins/plugin-sandbox-bridge.ts
@@ -184,7 +184,7 @@ export class PluginSandboxBridge {
// explicitly configured with scheme:none is unauthenticated and must never be labelled verified.
// Missing/hot-swapped route metadata fails closed.
const verified = route ? route.signature.scheme !== 'none' : false;
- const instance = await this.hostServices.getPluginInstanceService().resolve(d.pluginId, d.instanceId);
+ const instance = await this.hostServices.getPluginInstancePort().resolve(d.pluginId, d.instanceId);
// Three layers, most specific last: the base ('*') config, then the operator's per-session
// override from PUT /plugins/:id/sessions/:sessionId/config, then THIS instance's own config.
// The instance layer is what keeps two instances sharing one session scope apart — provisioning
@@ -256,7 +256,7 @@ export class PluginSandboxBridge {
private async scopeHasAtMostOneInstance(pluginId: string, scope: string | undefined): Promise<boolean> {
if (!scope) return false;
try {
- const rows = await this.hostServices.getPluginInstanceService().list(pluginId);
+ const rows = await this.hostServices.getPluginInstancePort().list(pluginId);
return rows.filter(row => row.enabled && row.sessionScope === scope).length <= 1;
} catch (error) {
// Logged rather than swallowed: this drops the operator's per-session override for the
@@ -344,7 +344,7 @@ export class PluginSandboxBridge {
// Drop a search provider registered mid-onEnable before the failure: without this, a plugin that
// registers then throws leaves a dead provider as the ACTIVE registry entry in auto mode, so every
// /search routes to a terminated worker → outage. Mirrors disablePlugin's cleanup.
- unregisterPluginSearchProvider(this.hostServices.getSearchRegistry(), pluginId);
+ unregisterPluginSearchProvider(this.hostServices.getSearchRegistryPort(), pluginId);
await host.terminate().catch(() => undefined);
throw error;
}
@@ -448,7 +448,7 @@ export class PluginSandboxBridge {
const chatId = (hookCtx.data as { chatId?: string } | undefined)?.chatId;
if (chatId && hookCtx.sessionId) {
const handover = await this.hostServices
- .getConversationMappingService()
+ .getConversationMappingPort()
.findHandoverForChat(hookCtx.sessionId, chatId);
if (!shouldDispatchToPlugin(handover, pluginId)) return { continue: true };
}
@@ -549,7 +549,7 @@ export class PluginSandboxBridge {
label: `${plugin.manifest.name} (plugin)`,
transport: liveHost,
timeoutMs: SANDBOX_SEARCH_TIMEOUT_MS,
- registry: this.hostServices.getSearchRegistry(),
+ registry: this.hostServices.getSearchRegistryPort(),
mode: this.configService.get<string>('search.provider', 'auto'),
hasPermission: (plugin.manifest.permissions ?? []).includes(PluginCapabilityPermission.SEARCH_PROVIDE),
warn: (message, meta) => this.logger.warn(message, meta),
@@ -580,7 +580,7 @@ export class PluginSandboxBridge {
// Always release the search-provider slot so the registry can fall back to builtin-fts. On a crash
// this is the only cleanup; on a deliberate disable/enable-failure the explicit unregister already
// ran, making this a harmless no-op.
- unregisterPluginSearchProvider(this.hostServices.getSearchRegistry(), pluginId);
+ unregisterPluginSearchProvider(this.hostServices.getSearchRegistryPort(), pluginId);
if (intentional) return; // routine disable/enable-failure already logged and expected
// Unexpected crash after a successful enable: the worker is gone. Drop the dead host +
// unregister the hook shims (so they don't keep dispatching into the dead worker) + mark the
diff --git a/src/core/plugins/plugins.module.ts b/src/core/plugins/plugins.module.ts
index 1cdc1324e..a47bad5e4 100644
--- a/src/core/plugins/plugins.module.ts
+++ b/src/core/plugins/plugins.module.ts
@@ -4,14 +4,24 @@ import { PluginLoaderService } from './plugin-loader.service';
import { PluginStorageService } from './plugin-storage.service';
import { ConversationMapping } from '../../modules/integration/entities/conversation-mapping.entity';
import { ConversationMappingService } from '../../modules/integration/conversation-mapping.service';
+import { PLUGIN_CONVERSATION_MAPPING_PORT, type PluginConversationMappingPort } from './plugin-host-ports';
@Global() // Make plugin services available everywhere
@Module({
imports: [TypeOrmModule.forFeature([ConversationMapping], 'data')],
- // ConversationMappingService is resolved lazily (ModuleRef) by PluginLoaderService, the same
- // pattern used for MessageService/SessionService, to avoid a static import edge back into this
- // module's graph — so it only needs to be a provider here, not re-exported.
- providers: [PluginStorageService, PluginLoaderService, ConversationMappingService],
+ // ConversationMappingService lives here (its own module never provides it) and is reached by the
+ // plugin runtime only through the core-owned port token, resolved lazily via ModuleRef by
+ // PluginHostServices — so neither the service nor the port needs re-exporting.
+ providers: [
+ PluginStorageService,
+ PluginLoaderService,
+ ConversationMappingService,
+ {
+ provide: PLUGIN_CONVERSATION_MAPPING_PORT,
+ useFactory: (mappings: ConversationMappingService): PluginConversationMappingPort => mappings,
+ inject: [ConversationMappingService],
+ },
+ ],
exports: [PluginLoaderService, PluginStorageService],
})
export class PluginsModule {}
diff --git a/src/core/plugins/search-provider-registration.util.ts b/src/core/plugins/search-provider-registration.util.ts
index c3718a674..834bf7784 100644
--- a/src/core/plugins/search-provider-registration.util.ts
+++ b/src/core/plugins/search-provider-registration.util.ts
@@ -1,14 +1,14 @@
import { PluginSearchProvider } from '../../modules/search/providers/plugin-search-provider';
import type { PluginSearchTransport } from '../../modules/search/providers/plugin-search-provider';
-import type { SearchProviderRegistry } from '../../modules/search/search-provider.registry';
+import type { PluginSearchRegistryPort } from './plugin-host-ports';
export interface RegisterPluginSearchProviderDeps {
pluginId: string;
label: string;
transport: PluginSearchTransport;
timeoutMs: number;
- /** The live SearchProviderRegistry, or undefined when the search module isn't loaded (SEARCH_ENABLED=false). */
- registry: SearchProviderRegistry | undefined;
+ /** The live search registry port, or undefined when the search module isn't loaded (SEARCH_ENABLED=false). */
+ registry: PluginSearchRegistryPort | undefined;
/** Resolved SEARCH_PROVIDER mode: 'auto' | 'builtin-fts' | 'none'. */
mode: string;
/** manifest declares search:provide */
@@ -51,6 +51,6 @@ export function registerPluginSearchProvider(deps: RegisterPluginSearchProviderD
}
/** Drop a plugin's SearchProvider entry on disable/uninstall so queries don't route to a dead worker. */
-export function unregisterPluginSearchProvider(registry: SearchProviderRegistry | undefined, pluginId: string): void {
+export function unregisterPluginSearchProvider(registry: PluginSearchRegistryPort | undefined, pluginId: string): void {
registry?.unregister(`plugin:${pluginId}`);
}
diff --git a/src/modules/automation/automation-rules.service.ts b/src/modules/automation/automation-rules.service.ts
index 383eb7860..95fd0ecaf 100644
--- a/src/modules/automation/automation-rules.service.ts
+++ b/src/modules/automation/automation-rules.service.ts
@@ -6,7 +6,7 @@ import { Repository } from 'typeorm';
import { createLogger } from '../../common/services/logger.service';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { evaluateFilters } from '../webhook/filters/filter-evaluator';
-import type { MessageService } from '../message/message.service';
+import { PLUGIN_MESSAGE_PORT, type PluginMessagePort } from '../../core/plugins/plugin-host-ports';
import { AutomationRule } from './entities/automation-rule.entity';
import { CreateAutomationRuleDto, UpdateAutomationRuleDto } from './dto/automation-rule.dto';
@@ -25,11 +25,12 @@ const MAX_MESSAGE_AGE_SECONDS = 300;
* Single-message autoreply rules: evaluated on every inbound message, first matching rule replies
* into the chat through the ordinary send path.
*
- * The reply is sent via `MessageService.sendText`, which the module graph cannot inject directly:
- * `MessageModule` imports `SessionModule`, and this module is imported BY `SessionModule` (the
- * projector calls `evaluateInbound`), so a constructor dependency here would close a module cycle.
- * `ModuleRef.get(..., { strict: false })` resolves it lazily at first use instead — the same escape
- * hatch `AuthService` uses. In unit contexts without a ModuleRef the evaluator logs and skips.
+ * The reply is sent via the plugin message port (bound to `MessageService.sendText` by
+ * MessageModule), which the module graph cannot inject directly: `MessageModule` imports
+ * `SessionModule`, and this module is imported BY `SessionModule` (the projector calls
+ * `evaluateInbound`), so a constructor dependency here would close a module cycle.
+ * `ModuleRef.get(..., { strict: false })` resolves the core-owned token lazily at first use
+ * instead. In unit contexts without a ModuleRef the evaluator logs and skips.
*/
@Injectable()
export class AutomationRulesService {
@@ -38,7 +39,7 @@ export class AutomationRulesService {
/** `${ruleId}:${chatId}` -> epoch ms until which the rule stays quiet in that chat. Per-process. */
private readonly cooldowns = new Map<string, number>();
- private messageService?: MessageService;
+ private messagePort?: PluginMessagePort;
constructor(
@InjectRepository(AutomationRule, 'data')
@@ -156,9 +157,9 @@ export class AutomationRulesService {
this.enterCooldown(rule, chatId);
try {
- const messageService = this.resolveMessageService();
- if (!messageService) return;
- await messageService.sendText(sessionId, { chatId, text: rule.replyText });
+ const messagePort = this.resolveMessagePort();
+ if (!messagePort) return;
+ await messagePort.sendText(sessionId, { chatId, text: rule.replyText });
this.logger.log('Automation rule replied', { sessionId, ruleId: rule.id, chatId });
} catch (error) {
// The send path already persisted/audited its own failure; here it only must not propagate.
@@ -171,18 +172,17 @@ export class AutomationRulesService {
}
}
- private resolveMessageService(): MessageService | undefined {
- if (!this.messageService) {
+ private resolveMessagePort(): PluginMessagePort | undefined {
+ if (!this.messagePort) {
try {
- // Deferred require, not a static import: a value-import of MessageService here closes the
- // file cycle session (projector) -> automation -> message -> session, and whichever class
- // evaluates last in that cycle is `undefined` while Nest builds the graph. By reply time
- // every module is loaded, so requiring the token lazily sidesteps the cycle entirely.
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { MessageService: token } = require('../message/message.service') as {
- MessageService: new (...args: never[]) => MessageService;
- };
- this.messageService = this.moduleRef?.get(token, { strict: false });
+ // The core-owned port token, resolved lazily — never a static import of MessageService: a
+ // value-import here closes the file cycle session (projector) -> automation -> message ->
+ // session, and whichever class evaluates last in that cycle is `undefined` while Nest builds
+ // the graph. By reply time every module is loaded, so resolving the token lazily sidesteps
+ // the cycle entirely.
+ this.messagePort = this.moduleRef?.get<typeof PLUGIN_MESSAGE_PORT, PluginMessagePort>(PLUGIN_MESSAGE_PORT, {
+ strict: false,
+ });
} catch (error) {
this.logger.warn('MessageService is not resolvable; automation replies are disabled', {
error: error instanceof Error ? error.message : String(error),
@@ -190,7 +190,7 @@ export class AutomationRulesService {
return undefined;
}
}
- return this.messageService;
+ return this.messagePort;
}
private inCooldown(rule: AutomationRule, chatId: string): boolean {
diff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.ts
index a3bf59a34..e8e94cd55 100644
--- a/src/modules/integration/integration.module.ts
+++ b/src/modules/integration/integration.module.ts
@@ -16,6 +16,7 @@ import { IntegrationRetentionService } from './integration-retention.service';
import { IntegrationInstanceController } from './integration-instance.controller';
import { ScopeBindingService } from './scope-binding.service';
import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
+import { PLUGIN_INSTANCE_PORT, type PluginInstancePort } from '../../core/plugins/plugin-host-ports';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { Session } from '../session/entities/session.entity';
import { createLogger } from '../../common/services/logger.service';
@@ -55,6 +56,13 @@ if (process.env.QUEUE_ENABLED === 'true') {
RedriveService,
ScopeBindingService,
IntegrationRetentionService,
+ // Binds the core-owned plugin capability port to this module's service; resolved lazily by the
+ // plugin runtime (PluginHostServices) so its provider cycle stays broken.
+ {
+ provide: PLUGIN_INSTANCE_PORT,
+ useFactory: (instances: PluginInstanceService): PluginInstancePort => instances,
+ inject: [PluginInstanceService],
+ },
{
provide: IngressService,
inject: [
diff --git a/src/modules/message/message.module.ts b/src/modules/message/message.module.ts
index a1603fb4f..ea25671f6 100644
--- a/src/modules/message/message.module.ts
+++ b/src/modules/message/message.module.ts
@@ -13,6 +13,7 @@ import { Message } from './entities/message.entity';
import { Session } from '../session/entities/session.entity';
import { SendPacingService } from './send-pacing.service';
import { MessageBatch } from './entities/message-batch.entity';
+import { PLUGIN_MESSAGE_PORT, type PluginMessagePort } from '../../core/plugins/plugin-host-ports';
@Module({
imports: [
@@ -29,6 +30,14 @@ import { MessageBatch } from './entities/message-batch.entity';
MessageTypeBackfillService,
PendingMessageReaperService,
SendPacingService,
+ // Binds the core-owned plugin capability port to this module's service. The plugin runtime
+ // resolves the token lazily via ModuleRef (PluginHostServices), which keeps its provider cycle
+ // broken; this adapter is how core reaches the service without importing it.
+ {
+ provide: PLUGIN_MESSAGE_PORT,
+ useFactory: (message: MessageService): PluginMessagePort => message,
+ inject: [MessageService],
+ },
],
exports: [MessageService, BulkMessageService, SendPacingService],
})
diff --git a/src/modules/search/search.module.ts b/src/modules/search/search.module.ts
index a448ed887..aceacb907 100644
--- a/src/modules/search/search.module.ts
+++ b/src/modules/search/search.module.ts
@@ -4,6 +4,7 @@ import { SearchController } from './search.controller';
import { SearchService } from './search.service';
import { SearchProviderRegistry } from './search-provider.registry';
import { BuiltInFtsProvider } from './providers/builtin-fts.provider';
+import { PLUGIN_SEARCH_REGISTRY_PORT, type PluginSearchRegistryPort } from '../../core/plugins/plugin-host-ports';
/**
* Wires the global search feature: the route (SearchController), the service layer (SearchService),
@@ -47,6 +48,14 @@ export function bootstrapSearchProviders(
inject: [SearchProviderRegistry, BuiltInFtsProvider, ConfigService],
useFactory: bootstrapSearchProviders,
},
+ // Binds the core-owned plugin capability port to this module's registry; resolved lazily by the
+ // plugin runtime (PluginHostServices), which no-ops when this whole module is omitted
+ // (SEARCH_ENABLED=false).
+ {
+ provide: PLUGIN_SEARCH_REGISTRY_PORT,
+ useFactory: (registry: SearchProviderRegistry): PluginSearchRegistryPort => registry,
+ inject: [SearchProviderRegistry],
+ },
],
})
export class SearchModule {}
diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.ts
index fef175c48..2d1d4cc8c 100644
--- a/src/modules/session/session.module.ts
+++ b/src/modules/session/session.module.ts
@@ -18,6 +18,7 @@ import { WebhookModule } from '../webhook/webhook.module';
import { StatusStoreModule } from '../status-store/status-store.module';
import { ChatMediaModule } from '../chat-media/chat-media.module';
import { AutomationModule } from '../automation/automation.module';
+import { PLUGIN_SESSION_PORT, type PluginSessionPort } from '../../core/plugins/plugin-host-ports';
@Module({
// WebhookModule/StatusStoreModule/ChatMediaModule/AutomationModule do not import SessionModule
@@ -42,6 +43,13 @@ import { AutomationModule } from '../automation/automation.module';
SessionLivenessWatchdog,
SessionOwnershipService,
MessageProjector,
+ // Binds the core-owned plugin capability port to this module's service; resolved lazily by the
+ // plugin runtime (PluginHostServices) so its provider cycle stays broken.
+ {
+ provide: PLUGIN_SESSION_PORT,
+ useFactory: (session: SessionService): PluginSessionPort => session,
+ inject: [SessionService],
+ },
],
exports: [SessionService, MessageProjector, SessionOwnershipService],
})