Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(plugins): host→plugin search RPC (let a plugin be a SearchProvider)

Yudhi Armyndharise5f100d17d3c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 317a0c908..e96cde616 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- **Plugin search providers (host→plugin search RPC).** A sandboxed plugin can now register as a `SearchProvider` by calling `ctx.registerSearchProvider(handler)` (e.g. `ctx.registerSearchProvider(async (query) => …)`) from its worker. The host routes `GET /api/search` queries to the plugin over a new correlated `search` / `search-result` wire protocol (mirroring the existing hook/webhook/health-check bridges), so a plugin owns all of its vendor-specific query logic (Meilisearch, Elasticsearch, Typesense, …) while the core stays backend-agnostic — adding a new backend is a plugin, with no core changes. When `SEARCH_PROVIDER=auto` (the default), an enabled plugin provider supersedes the built-in database full-text provider; `SEARCH_PROVIDER=builtin-fts` keeps the built-in active; `SEARCH_PROVIDER=none` disables search. Searches are bounded by a 10s timeout and fail fast rather than hanging, and a provider is dropped from the registry when its plugin is disabled. This is Part 1 of the plugin-search work (the query RPC + selection policy); the indexing side uses the existing `message:persisted` hook.
+
### Fixed
- **`base64` media now takes precedence over `url` when both are provided on a media send.** A `send-image`/`send-video`/etc. request carrying both fields previously sent the URL — and because `@ValidateIf` skipped `@IsUrl` validation on `url` whenever `base64` was present, a stale `url` (e.g. an example default left in the body, or a client such as the n8n community node that sends both) was fetched unvalidated and could 404, silently shadowing the supplied base64 image. `buildMediaInput` now prefers `base64`, aligning the send path with the already-base64-first persisted message metadata. Both engine adapters (whatsapp-web.js and Baileys) already guard the remote fetch behind an `isHttpUrl` check, so the change covers both. [#670]
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index a7e04ab84..f1cdf5019 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -121,6 +121,10 @@ import { ModuleRef } from '@nestjs/core';
import { HookManager } from '../hooks';
import { PluginStorageService } from './plugin-storage.service';
import { IPlugin, PluginContext, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';
+import { SearchProviderRegistry } from '../../modules/search/search-provider.registry';
+import { WorkerThreadChannel } from './sandbox/worker-thread-channel';
+import { PluginWorkerHost } from './sandbox/plugin-worker-host';
+import { PluginLogLevel } from './sandbox/protocol';
describe('PluginLoaderService.registerBuiltInPlugin config', () => {
function makeLoader(): PluginLoaderService {
@@ -572,3 +576,216 @@ describe('PluginLoaderService.dispatchWebhookForInstance config delivery', () =>
);
});
});
+
+describe('PluginLoaderService — search-provider wiring', () => {
+ function makeLoader(moduleRefGet: jest.Mock): PluginLoaderService {
+ const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
+ const pluginStorage = {
+ getPluginEntry: jest.fn().mockReturnValue(undefined),
+ setPluginEntry: jest.fn(),
+ setPluginStatus: jest.fn(),
+ getPluginConfig: jest.fn().mockReturnValue(null),
+ getPluginSessions: jest.fn().mockReturnValue(undefined),
+ getPluginSessionConfig: jest.fn().mockReturnValue(undefined),
+ createPluginStorage: jest
+ .fn()
+ .mockReturnValue({ get: jest.fn(), set: jest.fn(), delete: jest.fn(), list: jest.fn() }),
+ } as unknown as PluginStorageService;
+ return new PluginLoaderService(configService, new HookManager(), pluginStorage, {
+ get: moduleRefGet,
+ } as unknown as ModuleRef);
+ }
+
+ it('getSearchRegistry returns the registry when ModuleRef has it', () => {
+ const registry = new SearchProviderRegistry();
+ const loader = makeLoader(jest.fn().mockReturnValue(registry));
+ expect((loader as unknown as { getSearchRegistry: () => unknown }).getSearchRegistry()).toBe(registry);
+ });
+
+ it('getSearchRegistry returns undefined when ModuleRef has no registry (search disabled)', () => {
+ const loader = makeLoader(
+ jest.fn().mockImplementation(() => {
+ throw new Error('not found');
+ }),
+ );
+ expect((loader as unknown as { getSearchRegistry: () => unknown }).getSearchRegistry()).toBeUndefined();
+ });
+
+ it('disablePlugin unregisters the plugin’s search-provider entry', async () => {
+ const registry = new SearchProviderRegistry();
+ registry.register({ id: 'plugin:disable-test', label: 'p', search: jest.fn(), health: jest.fn() });
+ const loader = makeLoader(jest.fn().mockReturnValue(registry));
+ const manifest: PluginManifest = {
+ id: 'disable-test',
+ name: 'Disable Test',
+ version: '1.0.0',
+ type: PluginType.EXTENSION,
+ main: 'index.js',
+ };
+ loader.registerBuiltInPlugin(manifest, {});
+ await loader.enablePlugin('disable-test'); // builtIn → enableInProcess, status→ENABLED
+ expect(registry.list().map(p => p.id)).toContain('plugin:disable-test');
+
+ await loader.disablePlugin('disable-test');
+
+ expect(registry.list().map(p => p.id)).not.toContain('plugin:disable-test');
+ });
+});
+
+describe('PluginLoaderService — search-provider enable-failure cleanup', () => {
+ jest.setTimeout(30000);
+ let tmpDir: string;
+ const BOOTSTRAP = path.resolve(__dirname, 'sandbox/worker-bootstrap.ts');
+ const TS_NODE_OPTS = JSON.stringify({
+ module: 'commonjs',
+ moduleResolution: 'node',
+ resolvePackageJsonExports: false,
+ });
+
+ // Runs the REAL worker (ts-node) instead of the compiled dist bootstrap, so enableSandboxed
+ // exercises its true load/lifecycle/catch path with a live worker thread.
+ class RealWorkerLoader extends PluginLoaderService {
+ protected createSandboxHost(
+ capDispatcher?: (verb: string, args: unknown[]) => Promise<unknown>,
+ onHookSubscribe?: (event: string, priority?: number) => void,
+ onWebhookSubscribe?: (route: string) => void,
+ onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,
+ runWithHookGuard?: (inFlightEvents: string[], run: () => Promise<unknown>) => Promise<unknown>,
+ onSearchProviderRegister?: () => void,
+ ): PluginWorkerHost {
+ return new PluginWorkerHost(
+ new WorkerThreadChannel({
+ workerEntry: BOOTSTRAP,
+ execArgv: ['-r', 'ts-node/register/transpile-only'],
+ env: { ...process.env, TS_NODE_COMPILER_OPTIONS: TS_NODE_OPTS },
+ }),
+ capDispatcher,
+ onHookSubscribe,
+ onWebhookSubscribe,
+ onLog,
+ runWithHookGuard,
+ undefined,
+ onSearchProviderRegister,
+ );
+ }
+ }
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-search-ef-'));
+ fs.mkdirSync(path.join(tmpDir, 'rt'), { recursive: true });
+ fs.writeFileSync(
+ path.join(tmpDir, 'rt', 'manifest.json'),
+ JSON.stringify({ id: 'rt', name: 'RT', version: '1.0.0', type: 'EXTENSION', main: 'index.cjs' }),
+ );
+ // Fixture: register a search provider, THEN throw in onEnable — so the host has received
+ // search-provider-register (and activated the provider in auto mode) before enable fails.
+ fs.writeFileSync(
+ path.join(tmpDir, 'rt', 'index.cjs'),
+ "module.exports = class { async onEnable(ctx) { ctx.registerSearchProvider(async () => ({ hits: [], total: 0, tookMs: 1, provider: 'plugin:rt' })); throw new Error('onEnable failed'); } };",
+ );
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ it('unregisters the search provider when enable fails after registration (no dead active provider)', async () => {
+ const registry = new SearchProviderRegistry();
+ registry.register({ id: 'builtin-fts', label: 'b', search: jest.fn(), health: jest.fn() });
+ const config = {
+ get: (k: string) =>
+ k === 'search.provider' ? 'auto' : k === 'plugins.dir' || k === 'dataDir' ? tmpDir : undefined,
+ } as unknown as ConfigService;
+ const storage = new PluginStorageService(config);
+ const loader = new RealWorkerLoader(config, new HookManager(), storage, {
+ get: () => registry,
+ } as unknown as ModuleRef);
+
+ loader.loadPlugin(path.join(tmpDir, 'rt'));
+ await expect(loader.enablePlugin('rt')).rejects.toThrow('onEnable failed');
+
+ // Registered mid-onEnable, then onEnable threw → the catch must unregister the dead provider.
+ expect(registry.list().map(p => p.id)).not.toContain('plugin:rt');
+ expect(registry.active()?.id).toBe('builtin-fts');
+ });
+});
+
+describe('PluginLoaderService — search-provider worker-crash fallback', () => {
+ jest.setTimeout(30000);
+ let tmpDir: string;
+ const BOOTSTRAP = path.resolve(__dirname, 'sandbox/worker-bootstrap.ts');
+ const TS_NODE_OPTS = JSON.stringify({
+ module: 'commonjs',
+ moduleResolution: 'node',
+ resolvePackageJsonExports: false,
+ });
+
+ // Real ts-node worker (so enableSandboxed runs its true path) that captures the host so the test can
+ // crash it.
+ class CapturingLoader extends PluginLoaderService {
+ lastHost?: PluginWorkerHost;
+ protected createSandboxHost(
+ capDispatcher?: (verb: string, args: unknown[]) => Promise<unknown>,
+ onHookSubscribe?: (event: string, priority?: number) => void,
+ onWebhookSubscribe?: (route: string) => void,
+ onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,
+ runWithHookGuard?: (inFlightEvents: string[], run: () => Promise<unknown>) => Promise<unknown>,
+ onSearchProviderRegister?: () => void,
+ onWorkerExit?: (code: number) => void,
+ ): PluginWorkerHost {
+ const host = new PluginWorkerHost(
+ new WorkerThreadChannel({
+ workerEntry: BOOTSTRAP,
+ execArgv: ['-r', 'ts-node/register/transpile-only'],
+ env: { ...process.env, TS_NODE_COMPILER_OPTIONS: TS_NODE_OPTS },
+ }),
+ capDispatcher,
+ onHookSubscribe,
+ onWebhookSubscribe,
+ onLog,
+ runWithHookGuard,
+ undefined,
+ onSearchProviderRegister,
+ onWorkerExit,
+ );
+ this.lastHost = host;
+ return host;
+ }
+ }
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-search-crash-'));
+ fs.mkdirSync(path.join(tmpDir, 'ok'), { recursive: true });
+ fs.writeFileSync(
+ path.join(tmpDir, 'ok', 'manifest.json'),
+ JSON.stringify({ id: 'ok', name: 'OK', version: '1.0.0', type: 'EXTENSION', main: 'index.cjs' }),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'ok', 'index.cjs'),
+ "module.exports = class { async onEnable(ctx) { ctx.registerSearchProvider(async () => ({ hits: [], total: 0, tookMs: 1, provider: 'plugin:ok' })); } };",
+ );
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ it('falls back to builtin-fts when the plugin worker crashes after a successful enable', async () => {
+ const registry = new SearchProviderRegistry();
+ registry.register({ id: 'builtin-fts', label: 'b', search: jest.fn(), health: jest.fn() });
+ const config = {
+ get: (k: string) =>
+ k === 'search.provider' ? 'auto' : k === 'plugins.dir' || k === 'dataDir' ? tmpDir : undefined,
+ } as unknown as ConfigService;
+ const storage = new PluginStorageService(config);
+ const loader = new CapturingLoader(config, new HookManager(), storage, {
+ get: () => registry,
+ } as unknown as ModuleRef);
+
+ loader.loadPlugin(path.join(tmpDir, 'ok'));
+ await loader.enablePlugin('ok'); // registers + setActive -> active = plugin:ok
+ expect(registry.active()?.id).toBe('plugin:ok');
+
+ // Worker crashes (unexpected exit) — terminate() emits the worker 'exit' event -> handleExit -> onWorkerExit.
+ await loader.lastHost!.terminate();
+ await new Promise(resolve => setImmediate(resolve));
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(registry.list().map(p => p.id)).not.toContain('plugin:ok');
+ expect(registry.active()?.id).toBe('builtin-fts'); // fell back, not pinned to the dead plugin
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 86f3710e6..8a90db1c7 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -36,6 +36,7 @@ import { PluginLogLevel } from './sandbox/protocol';
import { buildConversationSendFacade, ConversationMediaType } from './conversation-send-facade';
import { shouldDispatchToPlugin } from './handover-gate';
import { makeOnWebhookSubscribe } from './webhook-subscribe.util';
+import { registerPluginSearchProvider, unregisterPluginSearchProvider } from './search-provider-registration.util';
import { INGRESS_DISPATCH_TIMEOUT_MS } from '../../modules/integration/integration.constants';
import type { MessageService } from '../../modules/message/message.service';
import type { SessionService } from '../../modules/session/session.service';
@@ -43,6 +44,7 @@ import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.in
import type { ConversationMappingService } from '../../modules/integration/conversation-mapping.service';
import type { PluginInstanceService } from '../../modules/integration/plugin-instance.service';
import type { IngressJobData } from '../../modules/queue/processors/ingress.processor';
+import type { SearchProviderRegistry } from '../../modules/search/search-provider.registry';
/** Default per-plugin heap cap for the sandbox worker; an OOM terminates the worker, not the host. */
const SANDBOX_MAX_OLD_GEN_MB = 256;
@@ -50,6 +52,8 @@ const SANDBOX_MAX_OLD_GEN_MB = 256;
const SANDBOX_HOOK_TIMEOUT_MS = 5000;
/** A sandboxed plugin's healthCheck must answer within this, else it's reported unhealthy (not hung). */
const SANDBOX_HEALTH_TIMEOUT_MS = 5000;
+/** A sandboxed plugin's search handler must answer within this, else /search fails fast (not hung). */
+const SANDBOX_SEARCH_TIMEOUT_MS = 10000;
/**
* A sandboxed plugin's load()/onLoad/onEnable/onDisable must complete within this, else the worker is
* torn down and the operation fails — a wedged lifecycle can't hang the enable/disable request (and
@@ -417,6 +421,8 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
// 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.getSearchRegistry(), pluginId);
plugin.status = PluginStatus.DISABLED;
@@ -678,6 +684,23 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
return this.moduleRef.get(mod.PluginInstanceService, { strict: false });
}
+ /**
+ * Resolve the SearchProviderRegistry lazily — search is conditionally loaded (SEARCH_ENABLED=false omits
+ * SearchModule), so the registry may not be registered. Mirrors the lazy-require pattern for
+ * MessageService/SessionService to avoid a static module edge and a DI cycle. Returns undefined when
+ * search is disabled, so the loader can no-op search-provider registration without throwing.
+ */
+ private getSearchRegistry(): SearchProviderRegistry | 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 });
+ } catch {
+ return undefined;
+ }
+ }
+
/**
* Enforce a plugin's declared manifest permissions at the capability boundary. A plugin may only
* use a capability whose permission string it declares in `manifest.permissions`; anything else
@@ -753,6 +776,8 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
onWebhookSubscribe?: (route: string) => void,
onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,
runWithHookGuard?: (inFlightEvents: string[], run: () => Promise<unknown>) => Promise<unknown>,
+ onSearchProviderRegister?: () => void,
+ onWorkerExit?: (code: number, intentional: boolean) => void,
): PluginWorkerHost {
const workerEntry = path.join(__dirname, 'sandbox', 'worker-bootstrap.js');
return new PluginWorkerHost(
@@ -768,6 +793,8 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
onLog,
runWithHookGuard,
SANDBOX_MAX_INFLIGHT_CAPS,
+ onSearchProviderRegister,
+ onWorkerExit,
);
}
@@ -918,6 +945,41 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
else context.logger[level](message, meta);
};
+ // When the worker declares itself a search provider (ctx.registerSearchProvider →
+ // search-provider-register), register a PluginSearchProvider in the SearchProviderRegistry. The host
+ // is in sandboxHosts by the time registration fires (during onLoad/onEnable), so look it up lazily
+ // like onHookSubscribe. Search disabled (no registry, or SEARCH_PROVIDER=none) → the util skips.
+ const onSearchProviderRegister = (): void => {
+ const liveHost = this.sandboxHosts.get(pluginId);
+ if (!liveHost) return;
+ registerPluginSearchProvider({
+ pluginId,
+ label: `${plugin.manifest.name} (plugin)`,
+ transport: liveHost,
+ timeoutMs: SANDBOX_SEARCH_TIMEOUT_MS,
+ registry: this.getSearchRegistry(),
+ mode: this.configService.get<string>('search.provider', 'auto'),
+ });
+ };
+
+ // A worker that crashes AFTER a successful enable is otherwise invisible to the loader (handleExit only
+ // drains in-flight calls). Drop the plugin's search-provider entry so the registry falls back to
+ // builtin-fts instead of routing every /search to a dead worker (auto mode would otherwise pin the dead
+ // provider ACTIVE). Mirrors the enable-failure cleanup. Broader crash-lifecycle cleanup (status, hooks)
+ // is a pre-existing gap for all bridges and out of scope here.
+ const onWorkerExit = (code: number, intentional: boolean): void => {
+ // 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.getSearchRegistry(), pluginId);
+ if (intentional) return; // routine disable/enable-failure already logged and expected
+ this.logger.warn(`Sandboxed plugin ${pluginId} worker exited unexpectedly (code ${code})`, {
+ pluginId,
+ code,
+ action: 'sandbox_worker_exit',
+ });
+ };
+
const host = this.createSandboxHost(
(verb, args) => dispatchCapabilityVerb(context, verb, args),
onHookSubscribe,
@@ -926,6 +988,8 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
// Re-establish the in-flight hook context for worker-initiated capability calls, so a sandboxed
// plugin that sends from within a send hook can't loop the event back into itself unboundedly.
(events, run) => this.hookManager.runInFlight(events as HookEvent[], run),
+ onSearchProviderRegister,
+ onWorkerExit,
);
this.sandboxHosts.set(pluginId, host);
try {
@@ -934,6 +998,10 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
await host.runLifecycle('onEnable', SANDBOX_LIFECYCLE_TIMEOUT_MS);
} catch (error) {
this.sandboxHosts.delete(pluginId);
+ // 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.getSearchRegistry(), pluginId);
await host.terminate().catch(() => undefined);
throw error;
}
diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
index 8dfa39f0b..bea5b0325 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.spec.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
@@ -339,6 +339,84 @@ describe('PluginWorkerHost', () => {
});
});
+ describe('search bridge', () => {
+ const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));
+
+ it('calls onSearchProviderRegister when the worker declares itself a search provider', async () => {
+ const ch = new FakeChannel();
+ const onSearchProviderRegister = jest.fn();
+ // 8th positional arg (after maxInFlightCaps) is onSearchProviderRegister.
+ new PluginWorkerHost(
+ ch,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ onSearchProviderRegister,
+ );
+
+ ch.reply({ kind: 'search-provider-register' });
+ await flush();
+
+ expect(onSearchProviderRegister).toHaveBeenCalledTimes(1);
+ });
+
+ it('dispatchSearch posts a search and resolves ok:true on the matching search-result', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const pending = host.dispatchSearch({ query: { q: 'hello' }, timeoutMs: 1000 });
+ const sent = ch.sent.find(m => m.kind === 'search') as Extract<HostToWorkerMessage, { kind: 'search' }>;
+ expect(sent).toMatchObject({ kind: 'search', query: { q: 'hello' } });
+
+ ch.reply({
+ kind: 'search-result',
+ id: sent.id,
+ ok: true,
+ results: { hits: [], total: 0, tookMs: 1, provider: 'plugin:p' },
+ });
+ await expect(pending).resolves.toMatchObject({ ok: true, results: { provider: 'plugin:p' } });
+ });
+
+ it('dispatchSearch resolves ok:false with the error on a failed search-result', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const pending = host.dispatchSearch({ query: { q: 'x' }, timeoutMs: 1000 });
+ const sent = ch.sent.find(m => m.kind === 'search') as Extract<HostToWorkerMessage, { kind: 'search' }>;
+
+ ch.reply({ kind: 'search-result', id: sent.id, ok: false, error: 'backend down' });
+ await expect(pending).resolves.toEqual({ ok: false, error: 'backend down' });
+ });
+
+ it('dispatchSearch resolves ok:false on timeout so /search is not hung', async () => {
+ jest.useFakeTimers();
+ try {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const pending = host.dispatchSearch({ query: { q: 'x' }, timeoutMs: 100 });
+ jest.advanceTimersByTime(100);
+
+ await expect(pending).resolves.toMatchObject({ ok: false, error: /timed out/i });
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('drains an in-flight search to ok:false on worker exit (no stall for the full timeout)', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const pending = host.dispatchSearch({ query: { q: 'x' }, timeoutMs: 5000 });
+ ch.crash(1);
+
+ await expect(pending).resolves.toMatchObject({ ok: false, error: /exit/i });
+ });
+ });
+
describe('lifecycle timeouts', () => {
it('rejects load() when the worker never reports ready within the timeout', async () => {
jest.useFakeTimers();
diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.ts
index 6cb5a8772..c413b89cd 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.ts
@@ -5,6 +5,7 @@ import {
SandboxStaticContext,
PluginLogLevel,
} from './protocol';
+import type { SearchQuery, SearchResults } from '../../../modules/search/search.types';
/**
* Host-side driver for a single untrusted plugin running in a worker. Owns the request/response
@@ -48,6 +49,13 @@ export class PluginWorkerHost {
number,
{ resolve: (result: { healthy: boolean; message?: string }) => void; timer: ReturnType<typeof setTimeout> }
>();
+ private readonly searchPending = new Map<
+ number,
+ {
+ resolve: (result: { ok: true; results: SearchResults } | { ok: false; error: string }) => void;
+ timer: ReturnType<typeof setTimeout>;
+ }
+ >();
// Hook events currently dispatched to the worker and not yet settled, as a multiset. While the
// worker handles a hook it may issue capability calls that round-trip to the host; those run inside
// this in-flight set so a capability that re-fires the same event is short-circuited (HookManager's
@@ -56,6 +64,9 @@ export class PluginWorkerHost {
// Worker-initiated capability calls currently running host-side, bounded by maxInFlightCaps.
private inFlightCaps = 0;
+ // True once terminate() is called, so onExit can tell a deliberate kill (disable/enable-failure) from an
+ // unexpected worker crash — only the latter is logged as a warning.
+ private terminated = false;
constructor(
private readonly channel: PluginWorkerChannel,
@@ -79,6 +90,13 @@ export class PluginWorkerHost {
// sees a thrown Error) instead of queuing host-side work — bounding the aggregate sendText/net.fetch/
// storage load a single sandboxed plugin can trigger. Absent/undefined => no cap (legacy behavior).
private readonly maxInFlightCaps?: number,
+ // Called when the worker sends `search-provider-register` (the plugin called ctx.registerSearchProvider),
+ // so the host can create a PluginSearchProvider and register it. Mirrors onHookSubscribe /
+ // onWebhookSubscribe for the search bridge. Absent => the host ignores the declaration (e.g. tests).
+ private readonly onSearchProviderRegister?: () => void,
+ // Called once after the worker exits (crash or terminate), after in-flight calls are drained, so the
+ // loader can release plugin-owned host resources (e.g. unregister a search provider the worker declared).
+ private readonly onExit?: (code: number, intentional: boolean) => void,
) {
this.channel.onMessage(message => this.handleMessage(message));
this.channel.onExit(code => this.handleExit(code));
@@ -183,6 +201,27 @@ export class PluginWorkerHost {
});
}
+ /**
+ * Dispatch a search query to a plugin that registered as a SearchProvider and await its result.
+ * Bounded by `timeoutMs`: a slow/wedged worker resolves ok:false (the caller throws) rather than
+ * hanging the /search request. A mid-search worker crash is drained to ok:false in handleExit.
+ */
+ dispatchSearch(options: {
+ query: SearchQuery;
+ timeoutMs: number;
+ }): Promise<{ ok: true; results: SearchResults } | { ok: false; error: string }> {
+ if (this.dead) return Promise.resolve({ ok: false, error: 'plugin worker is no longer running' });
+ const id = this.nextId++;
+ return new Promise(resolve => {
+ const timer = setTimeout(() => {
+ this.searchPending.delete(id);
+ resolve({ ok: false, error: 'search timed out' });
+ }, options.timeoutMs);
+ this.searchPending.set(id, { resolve, timer });
+ this.channel.postMessage({ kind: 'search', id, query: options.query });
+ });
+ }
+
/**
* Load the plugin module in the worker; resolves once it reports `ready`, rejects if it errors.
* When `timeoutMs` is given, a worker that never reports ready rejects the call (the caller then
@@ -257,6 +296,7 @@ export class PluginWorkerHost {
/** Tear the worker down. */
terminate(): Promise<void> {
+ this.terminated = true;
return this.channel.terminate();
}
@@ -330,6 +370,18 @@ export class PluginWorkerHost {
waiter.resolve({ healthy: message.healthy, message: message.message });
break;
}
+ case 'search-provider-register':
+ this.onSearchProviderRegister?.();
+ break;
+ case 'search-result': {
+ const waiter = this.searchPending.get(message.id);
+ if (!waiter) return;
+ this.searchPending.delete(message.id);
+ clearTimeout(waiter.timer);
+ if (message.ok) waiter.resolve({ ok: true, results: message.results });
+ else waiter.resolve({ ok: false, error: message.error });
+ break;
+ }
}
}
@@ -403,6 +455,14 @@ export class PluginWorkerHost {
resolve({ ok: false, status: 502 });
});
this.webhookPending.clear();
+ // Drain in-flight searches: a mid-query worker crash must reject (ok:false) so the /search caller
+ // gets an error instead of waiting the full timeout for a worker that is already dead.
+ this.searchPending.forEach(({ resolve, timer }) => {
+ clearTimeout(timer);
+ resolve({ ok: false, error: 'plugin worker exited' });
+ });
+ this.searchPending.clear();
+ this.onExit?.(code, this.terminated);
}
private drain<T>(waiters: T[], fn: (w: T) => void): void {
diff --git a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
index e86cae076..e3d16b66f 100644
--- a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
+++ b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
@@ -13,6 +13,7 @@ const RUNAWAY_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/runaway-plugin
const CTX_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/ctx-aware-plugin.cjs');
const HOOK_CONFIG_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-config-plugin.cjs');
const CTX_LIFECYCLE_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/ctx-lifecycle-plugin.cjs');
+const SEARCH_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/search-plugin.cjs');
const flushAsync = (): Promise<void> => new Promise(resolve => setImmediate(resolve));
// Run the TS bootstrap inside the worker via ts-node. The base tsconfig is nodenext; we pin the
@@ -219,4 +220,41 @@ describe('plugin worker — real worker_threads round-trip (B1)', () => {
await host.terminate();
});
+
+ it('round-trips a search: the worker registers a provider and the host dispatches a query', async () => {
+ let registered = false;
+ const host = new PluginWorkerHost(
+ makeChannel(),
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ () => {
+ registered = true;
+ },
+ );
+
+ await host.load(SEARCH_FIXTURE, { pluginId: 'search-fixture', config: {} });
+ await host.runLifecycle('onEnable'); // the plugin calls ctx.registerSearchProvider here
+ await flushAsync(); // let search-provider-register land
+ expect(registered).toBe(true);
+
+ const reply = await host.dispatchSearch({ query: { q: 'hello' }, timeoutMs: 5000 });
+ expect(reply.ok).toBe(true);
+ if (reply.ok) {
+ expect(reply.results.provider).toBe('plugin:search-fixture');
+ expect(reply.results.hits).toHaveLength(1);
+ expect(reply.results.hits[0].body).toBe('match for hello');
+ expect(reply.results.hits[0].snippet).toBe('<mark>hello</mark>');
+ }
+
+ // Empty query → empty hits (structured-clone-safe SearchResults round-trip).
+ const empty = await host.dispatchSearch({ query: { q: '' }, timeoutMs: 5000 });
+ expect(empty.ok).toBe(true);
+ if (empty.ok) expect(empty.results.hits).toEqual([]);
+
+ await host.terminate();
+ });
});
diff --git a/src/core/plugins/sandbox/protocol.ts b/src/core/plugins/sandbox/protocol.ts
index 0327ad023..9b3d0ab9c 100644
--- a/src/core/plugins/sandbox/protocol.ts
+++ b/src/core/plugins/sandbox/protocol.ts
@@ -9,6 +9,8 @@
* (B2) and hook bridge (B3) add more message kinds later.
*/
+import type { SearchQuery, SearchResults } from '../../../modules/search/search.types';
+
export type PluginLifecycleMethod = 'onLoad' | 'onEnable' | 'onDisable' | 'onUnload';
/** Static context fields handed to a sandboxed plugin at load (serializable; no live references). */
@@ -61,7 +63,12 @@ export type HostToWorkerMessage =
// Per-instance-resolved config for this delivery (like the `hook` message's config). The worker
// exposes it as ctx.config for the duration of the handler via hookConfigStore.
config?: Record<string, unknown>;
- };
+ }
+ // Host→Worker: dispatch a search query to a plugin that registered as a SearchProvider. The worker
+ // runs the plugin's search handler and replies with `search-result` (same `id` correlation as
+ // hook/health-check/webhook). No per-session config: search is a global query; session scoping travels
+ // inside SearchQuery.sessionIds (scoped by SearchService from the caller's API-key).
+ | { kind: 'search'; id: number; query: SearchQuery };
export type WorkerToHostMessage =
| { kind: 'ready' }
@@ -90,6 +97,13 @@ export type WorkerToHostMessage =
body?: string;
error?: string;
}
+ // The plugin called ctx.registerSearchProvider → the worker tells the host "I provide search." The host
+ // then creates a PluginSearchProvider wrapping this worker and registers it in SearchProviderRegistry.
+ | { kind: 'search-provider-register' }
+ // The worker's search-handler result for a host `search` request. ok:true carries SearchResults; ok:false
+ // carries the handler's error (handler threw / no handler / etc.).
+ | { kind: 'search-result'; id: number; ok: true; results: SearchResults }
+ | { kind: 'search-result'; id: number; ok: false; error: string }
| { kind: 'error'; error: string };
/**
diff --git a/src/core/plugins/sandbox/worker-bootstrap.ts b/src/core/plugins/sandbox/worker-bootstrap.ts
index bb8e93ff9..30f22cd28 100644
--- a/src/core/plugins/sandbox/worker-bootstrap.ts
+++ b/src/core/plugins/sandbox/worker-bootstrap.ts
@@ -3,6 +3,7 @@ import { HostToWorkerMessage, WorkerToHostMessage } from './protocol';
import { WorkerCapabilityClient, buildSandboxContext } from './worker-capability';
import { WorkerHookRegistry, WorkerHookHandler, hookConfigStore } from './worker-hooks';
import { WebhookRegistry, WebhookHandler } from './worker-webhooks';
+import { WorkerSearchRegistry, WorkerSearchHandler } from './worker-search-registry';
/**
* Worker entry for a plugin. Loads the plugin module and drives its lifecycle in response to host
@@ -37,6 +38,7 @@ const errorMessage = (error: unknown): string => (error instanceof Error ? error
const capClient = new WorkerCapabilityClient(send);
const hookRegistry = new WorkerHookRegistry(send);
const webhookRegistry = new WebhookRegistry(send);
+const searchRegistry = new WorkerSearchRegistry(send);
// ctx.logger proxy: forwards to the host's per-plugin logger (the same one in-process plugins use).
const logger = {
@@ -69,6 +71,10 @@ port.on('message', (message: HostToWorkerMessage) => {
void webhookRegistry.handleWebhook(message);
return;
}
+ if (message.kind === 'search') {
+ void searchRegistry.handleSearch(message);
+ return;
+ }
void handle(message);
});
@@ -93,6 +99,7 @@ async function handle(message: HostToWorkerMessage): Promise<void> {
registerHook: (event: string, handler: WorkerHookHandler, priority?: number) =>
hookRegistry.register(event, handler, priority),
registerWebhook: (route: string, handler: WebhookHandler) => webhookRegistry.register(route, handler),
+ registerSearchProvider: (handler: WorkerSearchHandler) => searchRegistry.register(handler),
};
send({ kind: 'ready' });
} catch (error) {
diff --git a/src/core/plugins/sandbox/worker-search-registry.spec.ts b/src/core/plugins/sandbox/worker-search-registry.spec.ts
new file mode 100644
index 000000000..42ec08e35
--- /dev/null
+++ b/src/core/plugins/sandbox/worker-search-registry.spec.ts
@@ -0,0 +1,68 @@
+import { WorkerSearchRegistry } from './worker-search-registry';
+import { WorkerToHostMessage } from './protocol';
+
+const collect = () => {
+ const sent: WorkerToHostMessage[] = [];
+ return { sent, post: (m: WorkerToHostMessage) => sent.push(m) };
+};
+
+const okResults = { hits: [], total: 0, tookMs: 2, provider: 'plugin:x' };
+
+describe('WorkerSearchRegistry', () => {
+ it('posts search-provider-register on the first register', () => {
+ const { sent, post } = collect();
+ const reg = new WorkerSearchRegistry(post);
+
+ reg.register(() => Promise.resolve(okResults));
+
+ expect(sent).toContainEqual({ kind: 'search-provider-register' });
+ });
+
+ it('does not re-post search-provider-register on a second register (replace handler only)', () => {
+ const { sent, post } = collect();
+ const reg = new WorkerSearchRegistry(post);
+ reg.register(() => Promise.resolve(okResults));
+ reg.register(() => Promise.resolve(okResults));
+
+ expect(sent.filter(m => m.kind === 'search-provider-register')).toHaveLength(1);
+ });
+
+ it('runs the handler on a search and replies ok:true with the results', async () => {
+ const { sent, post } = collect();
+ const reg = new WorkerSearchRegistry(post);
+ reg.register(() => Promise.resolve(okResults));
+
+ await reg.handleSearch({ kind: 'search', id: 7, query: { q: 'hello' } });
+
+ expect(sent).toContainEqual({ kind: 'search-result', id: 7, ok: true, results: okResults });
+ });
+
+ it('threads the query into the handler', async () => {
+ const { sent, post } = collect();
+ const reg = new WorkerSearchRegistry(post);
+ reg.register(q => Promise.resolve({ hits: [], total: 0, tookMs: 1, provider: String(q.q) }));
+
+ await reg.handleSearch({ kind: 'search', id: 1, query: { q: 'term' } });
+
+ expect(sent.find(m => m.kind === 'search-result')).toMatchObject({ ok: true, results: { provider: 'term' } });
+ });
+
+ it('replies ok:false with the error message when the handler throws', async () => {
+ const { sent, post } = collect();
+ const reg = new WorkerSearchRegistry(post);
+ reg.register(() => Promise.reject(new Error('backend down')));
+
+ await reg.handleSearch({ kind: 'search', id: 3, query: { q: 'x' } });
+
+ expect(sent.find(m => m.kind === 'search-result')).toMatchObject({ id: 3, ok: false, error: 'backend down' });
+ });
+
+ it('replies ok:false when no handler is registered', async () => {
+ const { sent, post } = collect();
+ const reg = new WorkerSearchRegistry(post);
+
+ await reg.handleSearch({ kind: 'search', id: 1, query: { q: 'x' } });
+
+ expect(sent.find(m => m.kind === 'search-result')).toMatchObject({ id: 1, ok: false });
+ });
+});
diff --git a/src/core/plugins/sandbox/worker-search-registry.ts b/src/core/plugins/sandbox/worker-search-registry.ts
new file mode 100644
index 000000000..f4714a390
--- /dev/null
+++ b/src/core/plugins/sandbox/worker-search-registry.ts
@@ -0,0 +1,48 @@
+import { HostToWorkerMessage, WorkerToHostMessage } from './protocol';
+import type { SearchQuery, SearchResults } from '../../../modules/search/search.types';
+
+/** A sandboxed plugin's search handler — runs the plugin's query logic (e.g. Meilisearch) and returns
+ * SearchResults. Registered via ctx.registerSearchProvider; invoked when the host sends `search`. */
+export type WorkerSearchHandler = (query: SearchQuery) => Promise<SearchResults> | SearchResults;
+
+/**
+ * Worker-side search-provider handling, mirroring {@link WebhookRegistry}. A sandboxed plugin registers
+ * ONE search handler (via ctx.registerSearchProvider); the registry tells the host once (so the host
+ * creates a PluginSearchProvider), and on a `search` message runs the handler and replies with
+ * `search-result` — a thrown handler becomes ok:false, a missing handler ok:false too.
+ *
+ * Unlike hooks (per-event) / webhooks (per-route), a plugin provides exactly one search handler, so
+ * `register` replaces any prior handler and posts `search-provider-register` only on the first call
+ * (the host dedups by `plugin:<id>` anyway, but this avoids re-registration churn).
+ */
+export class WorkerSearchRegistry {
+ private handler?: WorkerSearchHandler;
+ private registered = false;
+
+ constructor(private readonly post: (message: WorkerToHostMessage) => void) {}
+
+ register(handler: WorkerSearchHandler): void {
+ this.handler = handler;
+ if (this.registered) return;
+ this.registered = true;
+ this.post({ kind: 'search-provider-register' });
+ }
+
+ async handleSearch(message: Extract<HostToWorkerMessage, { kind: 'search' }>): Promise<void> {
+ if (!this.handler) {
+ this.post({ kind: 'search-result', id: message.id, ok: false, error: 'no search handler registered' });
+ return;
+ }
+ try {
+ const results = await this.handler(message.query);
+ this.post({ kind: 'search-result', id: message.id, ok: true, results });
+ } catch (err) {
+ this.post({
+ kind: 'search-result',
+ id: message.id,
+ ok: false,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+}
diff --git a/src/core/plugins/search-provider-registration.spec.ts b/src/core/plugins/search-provider-registration.spec.ts
new file mode 100644
index 000000000..1ed3f31ff
--- /dev/null
+++ b/src/core/plugins/search-provider-registration.spec.ts
@@ -0,0 +1,70 @@
+import { registerPluginSearchProvider, unregisterPluginSearchProvider } from './search-provider-registration.util';
+import { SearchProviderRegistry } from '../../modules/search/search-provider.registry';
+import type { PluginSearchTransport } from '../../modules/search/providers/plugin-search-provider';
+
+const mkTransport = (): PluginSearchTransport => ({ dispatchSearch: jest.fn(), healthCheck: jest.fn() });
+
+const deps = (overrides: Partial<Parameters<typeof registerPluginSearchProvider>[0]> = {}) => ({
+ pluginId: 'meili',
+ label: 'Meilisearch (plugin)',
+ transport: mkTransport(),
+ timeoutMs: 10000,
+ registry: new SearchProviderRegistry(),
+ mode: 'auto',
+ ...overrides,
+});
+
+const builtin = () => ({ id: 'builtin-fts', label: 'b', search: jest.fn(), health: jest.fn() });
+
+describe('registerPluginSearchProvider', () => {
+ it('auto mode registers and activates the plugin, superseding builtin-fts', () => {
+ const registry = new SearchProviderRegistry();
+ registry.register(builtin());
+ expect(registry.active()?.id).toBe('builtin-fts');
+
+ registerPluginSearchProvider(deps({ registry }));
+
+ expect(registry.list().map(p => p.id)).toContain('plugin:meili');
+ expect(registry.active()?.id).toBe('plugin:meili');
+ });
+
+ it('builtin-fts mode registers the plugin but leaves builtin active', () => {
+ const registry = new SearchProviderRegistry();
+ registry.register(builtin());
+
+ registerPluginSearchProvider(deps({ registry, mode: 'builtin-fts' }));
+
+ expect(registry.list().map(p => p.id)).toContain('plugin:meili');
+ expect(registry.active()?.id).toBe('builtin-fts');
+ });
+
+ it('none mode skips registration entirely', () => {
+ const registry = new SearchProviderRegistry();
+
+ registerPluginSearchProvider(deps({ registry, mode: 'none' }));
+
+ expect(registry.list().map(p => p.id)).not.toContain('plugin:meili');
+ expect(registry.active()).toBeNull();
+ });
+
+ it('undefined registry (search module not loaded) skips without throwing', () => {
+ expect(() => registerPluginSearchProvider(deps({ registry: undefined }))).not.toThrow();
+ });
+});
+
+describe('unregisterPluginSearchProvider', () => {
+ it('removes the plugin:<id> provider and falls back', () => {
+ const registry = new SearchProviderRegistry();
+ registry.register(builtin());
+ registerPluginSearchProvider(deps({ registry })); // active = plugin:meili
+
+ unregisterPluginSearchProvider(registry, 'meili');
+
+ expect(registry.list().map(p => p.id)).not.toContain('plugin:meili');
+ expect(registry.active()?.id).toBe('builtin-fts');
+ });
+
+ it('is a no-op when the registry is absent', () => {
+ expect(() => unregisterPluginSearchProvider(undefined, 'meili')).not.toThrow();
+ });
+});
diff --git a/src/core/plugins/search-provider-registration.util.ts b/src/core/plugins/search-provider-registration.util.ts
new file mode 100644
index 000000000..a3e4ac2b1
--- /dev/null
+++ b/src/core/plugins/search-provider-registration.util.ts
@@ -0,0 +1,38 @@
+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';
+
+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;
+ /** Resolved SEARCH_PROVIDER mode: 'auto' | 'builtin-fts' | 'none'. */
+ mode: string;
+}
+
+/**
+ * Register a sandboxed plugin as a SearchProvider when it declares itself one (search-provider-register).
+ * Pure policy, extracted from the loader so it is unit-testable without constructing PluginLoaderService:
+ *
+ * - registry undefined → search module not loaded (SEARCH_ENABLED=false); skip silently.
+ * - mode 'none' → operator disabled search; skip.
+ * - mode 'auto' → register AND setActive, superseding builtin-fts (the documented auto behavior).
+ * - mode 'builtin-fts' → register but leave inactive (operator pinned the built-in).
+ *
+ * Last-registered plugin wins in 'auto' if multiple register (Part 1 limitation).
+ */
+export function registerPluginSearchProvider(deps: RegisterPluginSearchProviderDeps): void {
+ if (!deps.registry) return;
+ if (deps.mode === 'none') return;
+ const provider = new PluginSearchProvider(deps.pluginId, deps.label, deps.transport, deps.timeoutMs);
+ deps.registry.register(provider);
+ if (deps.mode === 'auto') deps.registry.setActive(provider.id);
+}
+
+/** 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 {
+ registry?.unregister(`plugin:${pluginId}`);
+}
diff --git a/src/modules/search/providers/plugin-search-provider.spec.ts b/src/modules/search/providers/plugin-search-provider.spec.ts
new file mode 100644
index 000000000..2860b31f0
--- /dev/null
+++ b/src/modules/search/providers/plugin-search-provider.spec.ts
@@ -0,0 +1,56 @@
+import { ServiceUnavailableException } from '@nestjs/common';
+import { PluginSearchProvider } from './plugin-search-provider';
+import type { PluginSearchTransport } from './plugin-search-provider';
+import type { SearchResults } from '../search.types';
+
+const fakeTransport = (overrides: Partial<PluginSearchTransport> = {}): PluginSearchTransport => ({
+ dispatchSearch: jest
+ .fn()
+ .mockResolvedValue({ ok: true, results: { hits: [], total: 0, tookMs: 1, provider: 'plugin:p' } }),
+ healthCheck: jest.fn().mockResolvedValue({ healthy: true, message: undefined }),
+ ...overrides,
+});
+
+describe('PluginSearchProvider', () => {
+ it('id is plugin:<pluginId> and the label passes through', () => {
+ const p = new PluginSearchProvider('meili', 'Meilisearch (plugin)', fakeTransport(), 1000);
+ expect(p.id).toBe('plugin:meili');
+ expect(p.label).toBe('Meilisearch (plugin)');
+ });
+
+ it('search returns the results from the transport, forwarding the query + timeout', async () => {
+ const results: SearchResults = { hits: [], total: 0, tookMs: 5, provider: 'plugin:p' };
+ const dispatchSearch = jest.fn().mockResolvedValue({ ok: true, results });
+ const transport = fakeTransport({ dispatchSearch });
+ const p = new PluginSearchProvider('p', 'P', transport, 7000);
+
+ await expect(p.search({ q: 'hi' })).resolves.toBe(results);
+ expect(dispatchSearch).toHaveBeenCalledWith({ query: { q: 'hi' }, timeoutMs: 7000 });
+ });
+
+ it('search throws a 503 ServiceUnavailableException carrying the cause on ok:false', async () => {
+ const transport = fakeTransport({
+ dispatchSearch: jest.fn().mockResolvedValue({ ok: false, error: 'backend down' }),
+ });
+ const p = new PluginSearchProvider('p', 'P', transport, 1000);
+
+ await expect(p.search({ q: 'hi' })).rejects.toMatchObject({ status: 503, message: 'backend down' });
+ await expect(p.search({ q: 'hi' })).rejects.toBeInstanceOf(ServiceUnavailableException);
+ });
+
+ it('health maps healthy→ok and message→detail', async () => {
+ const transport = fakeTransport({
+ healthCheck: jest.fn().mockResolvedValue({ healthy: false, message: 'no index' }),
+ });
+ const p = new PluginSearchProvider('p', 'P', transport, 1000);
+
+ await expect(p.health()).resolves.toEqual({ ok: false, detail: 'no index' });
+ });
+
+ it('health omits detail when the worker reports no message', async () => {
+ const transport = fakeTransport({ healthCheck: jest.fn().mockResolvedValue({ healthy: true }) });
+ const p = new PluginSearchProvider('p', 'P', transport, 1000);
+
+ await expect(p.health()).resolves.toEqual({ ok: true });
+ });
+});
diff --git a/src/modules/search/providers/plugin-search-provider.ts b/src/modules/search/providers/plugin-search-provider.ts
new file mode 100644
index 000000000..e0234f9e0
--- /dev/null
+++ b/src/modules/search/providers/plugin-search-provider.ts
@@ -0,0 +1,45 @@
+import { ServiceUnavailableException } from '@nestjs/common';
+import type { SearchProvider, SearchQuery, SearchResults, SearchHealth } from '../search.types';
+
+/**
+ * The host-side transport a PluginSearchProvider uses to reach its worker: dispatch a search query and
+ * run the plugin's general healthCheck. Satisfied structurally by PluginWorkerHost, so the search module
+ * has no static dependency on the plugin sandbox — the loader (which knows both) passes the host in.
+ */
+export interface PluginSearchTransport {
+ dispatchSearch(options: {
+ query: SearchQuery;
+ timeoutMs: number;
+ }): Promise<{ ok: true; results: SearchResults } | { ok: false; error: string }>;
+ healthCheck(timeoutMs: number): Promise<{ healthy: boolean; message?: string }>;
+}
+
+/**
+ * A SearchProvider backed by a sandboxed plugin's worker. The host routes a query to the worker via the
+ * search RPC (dispatchSearch); the plugin runs its own backend logic (Meilisearch, Elasticsearch, etc.)
+ * and returns SearchResults. health() reuses the worker's general healthCheck (healthy→ok, message→detail)
+ * — no search-specific health message (Part 1 decision). All vendor-specific logic lives in the plugin.
+ */
+export class PluginSearchProvider implements SearchProvider {
+ readonly id: string;
+
+ constructor(
+ pluginId: string,
+ readonly label: string,
+ private readonly transport: PluginSearchTransport,
+ private readonly timeoutMs: number,
+ ) {
+ this.id = `plugin:${pluginId}`;
+ }
+
+ async search(query: SearchQuery): Promise<SearchResults> {
+ const reply = await this.transport.dispatchSearch({ query, timeoutMs: this.timeoutMs });
+ if (!reply.ok) throw new ServiceUnavailableException(reply.error);
+ return reply.results;
+ }
+
+ async health(): Promise<SearchHealth> {
+ const result = await this.transport.healthCheck(this.timeoutMs);
+ return { ok: result.healthy, detail: result.message };
+ }
+}
diff --git a/test/fixtures/sandbox/search-plugin.cjs b/test/fixtures/sandbox/search-plugin.cjs
new file mode 100644
index 000000000..7687308d6
--- /dev/null
+++ b/test/fixtures/sandbox/search-plugin.cjs
@@ -0,0 +1,31 @@
+// Sandbox fixture: registers a search provider whose handler returns canned SearchResults derived from
+// the query, so the integration test can assert the full search RPC round-trip
+// (host dispatch -> worker handler -> search-result). The handler echoes the query term into the hit.
+module.exports = class SearchPlugin {
+ async onEnable(ctx) {
+ ctx.registerSearchProvider(async (query) => {
+ const term = String(query.q || '');
+ return {
+ hits: term
+ ? [
+ {
+ messageId: 'm1',
+ waMessageId: 'wamid1',
+ sessionId: 's1',
+ chatId: '[email protected]',
+ body: `match for ${term}`,
+ snippet: `<mark>${term}</mark>`,
+ timestamp: 1700000000,
+ type: 'text',
+ direction: 'outgoing',
+ },
+ ]
+ : [],
+ total: term ? 1 : 0,
+ tookMs: 2,
+ provider: 'plugin:search-fixture',
+ };
+ });
+ }
+};