Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(plugins)!: remove bundled auto-reply/translation reference extensions (#442)
Yudhi Armyndharis0ea6d3e4e6e3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 67d6ca43d..ca0395b5b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,11 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+> **v0.7 — plugin-contract expansion.** Richer plugin config (declarative + sandboxed-iframe editors),+> per-session activation and config, SSRF-guarded outbound HTTP, and the removal of the bundled+> reference extensions in favour of the marketplace. ⚠️ See the **Removed** note before upgrading.+### Added+- Plugins: richer **config schema** vocabulary — a `textarea` type, `min`/`max`/`pattern` validation hints, and composite kinds (`items` for arrays, including **array-of-rows** when `items` is an object; `properties` for nested objects; `enum` renders a select). The dashboard config form renders them recursively, and secret redaction/restore now recurses so a `secret` field at any depth is masked on read and preserved on an unchanged write. (#439)+- Plugins: a plugin may ship a **sandboxed-iframe config editor** via manifest `configUi { entry, height? }`. The host serves the entry over an authenticated `GET /plugins/:id/config-ui` (ADMIN, path/realpath escape-guarded, CSP-sandboxed) and the dashboard injects it as an `srcdoc` into a `sandbox="allow-scripts"` iframe (opaque origin). The editor exchanges config over a `postMessage` bridge — the API key never enters the iframe, and it only ever receives schema-declared, secret-redacted config. (#440)+- Plugins: **per-session config overrides**. A session-scoped plugin can carry per-session config on top of its base (`'*'`) config via `PUT /plugins/:id/config/:sessionId`; `ctx.config` (read inside a hook) is the override shallow-merged over the base for the firing session, resolved race-safely via `AsyncLocalStorage` for both in-process and sandboxed plugins. Overrides are secret-redacted per slice on the API and survive a restart. (#441)- Plugins: per-session activation. A session-scoped plugin can now be activated for all numbers (`*`) or an explicit set of sessions via `PUT /plugins/:id/sessions`, and only receives hook events for the sessions it is active for (enforced at delivery). A plugin declares `sessionScoped` in its manifest (default `true`); a global plugin (`false`, e.g. a metrics logger) always runs. The active set is surfaced on the plugin API and survives a restart. (#438)- Plugins: a new `ctx.net.fetch` capability lets a sandboxed plugin make outbound HTTP through the host's SSRF guard (resolve-once-pin, redirects refused), gated by a `net:fetch` permission plus a manifest `net.allow` host allowlist (`host:port`, bare `host`, or `*` for any public host; internal IPs are always blocked). Responses are bounded by a timeout and a streamed size cap. (#437)+### Removed++- ⚠️ **Breaking:** the bundled reference extensions `auto-reply` and `translation` have been removed from core. They are superseded by the marketplace plugins **`chat-flow`** (interactive auto-reply) and **`group-translate`** (LibreTranslate group translation), which target the v0.7 contract. **Upgrade:** if you had either enabled, install the replacement from the dashboard (Plugins → Catalog, or `POST /plugins/install-url`) and re-enter its config. The ids `auto-reply` / `translation` remain reserved (an uploaded package can't claim them). Built-in **engines** (whatsapp-web.js, Baileys) are unaffected.++### Fixed++- Plugins: an operator's per-session activation (and now per-session config) was silently dropped from the on-disk registry on the second restart, because the registry entry was rebuilt on each load without carrying those fields. Both are now preserved across restarts. (#441)+## [0.6.2] - 2026-06-23Plugin platform follow-ups (sandbox hardening, install-from-URL + catalog), a mark-chat-unreaddiff --git a/src/app.module.ts b/src/app.module.tsindex 0138fc400..3aaa9ed26 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -32,7 +32,6 @@ import { CatalogModule } from './modules/catalog/catalog.module';import { HooksModule } from './core/hooks';import { PluginsModule } from './core/plugins';import { PluginsApiModule } from './modules/plugins/plugins.module';-import { ExtensionsModule } from './plugins/extensions/extensions.module';// Only import QueueModule if explicitly enabled to avoid Redis connection errorsconst queueModules: Array<Type | DynamicModule> = [];@@ -217,7 +216,6 @@ if (dashboardServingEnabled && dashboardBuildPresent) {StatusModule, // Phase 3: Status/Stories APICatalogModule, // Phase 3: Catalog API (WhatsApp Business)PluginsApiModule, // Phase 5: Plugins API- ExtensionsModule, // First-party extension plugins (registered disabled)...serveStaticModules, // Bundled dashboard SPA (production single-port setup)],})diff --git a/src/modules/plugins/plugin-installer.ts b/src/modules/plugins/plugin-installer.tsindex 55746d26f..84b30f388 100644--- a/src/modules/plugins/plugin-installer.ts+++ b/src/modules/plugins/plugin-installer.ts@@ -12,7 +12,11 @@ export interface PackageLimits {export const DEFAULT_PACKAGE_LIMITS: PackageLimits = { maxEntries: 200, maxTotalBytes: 20 * 1024 * 1024 };-/** Plugin ids that ship built-in and must never be shadowed by an uploaded package. */+/**+ * Plugin ids an uploaded package must never use. `whatsapp-web.js` / `baileys` are built-in engines;+ * `auto-reply` / `translation` are the legacy bundled-extension ids (removed in v0.7 — superseded by+ * the marketplace `chat-flow` / `group-translate`) kept reserved so a re-upload can't shadow them.+ */export const RESERVED_PLUGIN_IDS = new Set(['whatsapp-web.js', 'baileys', 'auto-reply', 'translation']);/** Only extensions are user-installable; engines (and other tiers) are built-in by design. */diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 01e090665..1949277ac 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -541,7 +541,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}).then(async ({ continue: shouldContinue, data: finalMessage }) => {if (!shouldContinue) {- // Plugin stopped processing (e.g., auto-reply handled it)+ // A plugin handled the event and asked to stop the chain (continue: false).return;}diff --git a/src/plugins/extensions/auto-reply/auto-reply.plugin.spec.ts b/src/plugins/extensions/auto-reply/auto-reply.plugin.spec.tsdeleted file mode 100644index 2cdc605ca..000000000--- a/src/plugins/extensions/auto-reply/auto-reply.plugin.spec.ts+++ /dev/null@@ -1,82 +0,0 @@-import { AutoReplyPlugin } from './index';-import { PluginContext } from '../../../core/plugins';-import { HookContext, HookEvent, HookHandler } from '../../../core/hooks';-import { IncomingMessage } from '../../../engine/interfaces/whatsapp-engine.interface';--function makeContext(reply: jest.Mock): { context: PluginContext; getHandler: () => HookHandler } {- let captured: HookHandler | undefined;- const context = {- pluginId: 'auto-reply',- registerHook: (_event: HookEvent, handler: HookHandler) => {- captured = handler;- },- messages: { reply, sendText: jest.fn() },- logger: { log: jest.fn(), debug: jest.fn(), warn: jest.fn(), error: jest.fn() },- } as unknown as PluginContext;- return { context, getHandler: () => captured as HookHandler };-}--function inbound(overrides: Partial<IncomingMessage> = {}): IncomingMessage {- return {- id: 'msg-1',- from: '[email protected]',- to: 'me',- chatId: '[email protected]',- body: 'ping',- type: 'text',- timestamp: 1,- fromMe: false,- isGroup: false,- ...overrides,- };-}--function ctxFor(data: IncomingMessage): HookContext<IncomingMessage> {- return { event: 'message:received', data, sessionId: 'sess-1', timestamp: new Date(), source: 'Engine' };-}--describe('AutoReplyPlugin', () => {- it('replies to an inbound direct message and keeps it in history', async () => {- const reply = jest.fn().mockResolvedValue({ messageId: 'x', timestamp: 1 });- const { context, getHandler } = makeContext(reply);- await new AutoReplyPlugin().onEnable(context);-- const result = await getHandler()(ctxFor(inbound()));-- expect(reply).toHaveBeenCalledWith('sess-1', '[email protected]', 'msg-1', 'Auto-reply: ping');- expect(result).toEqual({ continue: true });- });-- it('does NOT reply to its own outgoing messages (fromMe)', async () => {- const reply = jest.fn();- const { context, getHandler } = makeContext(reply);- await new AutoReplyPlugin().onEnable(context);-- const result = await getHandler()(ctxFor(inbound({ fromMe: true })));-- expect(reply).not.toHaveBeenCalled();- expect(result).toEqual({ continue: true });- });-- it('does NOT reply to group messages', async () => {- const reply = jest.fn();- const { context, getHandler } = makeContext(reply);- await new AutoReplyPlugin().onEnable(context);-- const result = await getHandler()(ctxFor(inbound({ isGroup: true })));-- expect(reply).not.toHaveBeenCalled();- expect(result).toEqual({ continue: true });- });-- it('does NOT reply when the message did not originate from the engine', async () => {- const reply = jest.fn();- const { context, getHandler } = makeContext(reply);- await new AutoReplyPlugin().onEnable(context);-- const result = await getHandler()({ ...ctxFor(inbound()), source: 'API' });-- expect(reply).not.toHaveBeenCalled();- expect(result).toEqual({ continue: true });- });-});diff --git a/src/plugins/extensions/auto-reply/index.ts b/src/plugins/extensions/auto-reply/index.tsdeleted file mode 100644index 58cfe97f3..000000000--- a/src/plugins/extensions/auto-reply/index.ts+++ /dev/null@@ -1,38 +0,0 @@-/**- * Auto-reply reference extension plugin.- *- * Demonstrates the Tier-2 capability layer end-to-end: it hooks inbound messages and replies- * via ctx.messages.reply. Registered DISABLED by default — enable it from the dashboard to try- * the capability layer live. Replies only to inbound, non-group, engine-originated messages.- */-import { PluginContext, IPlugin } from '../../../core/plugins';-import { HookContext, HookResult } from '../../../core/hooks';-import { IncomingMessage } from '../../../engine/interfaces/whatsapp-engine.interface';--export class AutoReplyPlugin implements IPlugin {- onEnable(context: PluginContext): Promise<void> {- context.registerHook('message:received', ctx => this.onMessage(context, ctx as HookContext<IncomingMessage>));- context.logger.log('Auto-reply reference plugin enabled');- return Promise.resolve();- }-- private async onMessage(context: PluginContext, ctx: HookContext<IncomingMessage>): Promise<HookResult> {- const message = ctx.data;-- // Reply only to inbound, non-group, engine-originated messages; never to our own sends.- if (ctx.source !== 'Engine' || !ctx.sessionId || message.fromMe || message.isGroup) {- return { continue: true };- }-- try {- await context.messages.reply(ctx.sessionId, message.chatId, message.id, `Auto-reply: ${message.body}`);- } catch (error) {- context.logger.error('Auto-reply failed', error);- }-- // Keep the inbound message in history + webhooks + ws (do not swallow).- return { continue: true };- }-}--export default AutoReplyPlugin;diff --git a/src/plugins/extensions/auto-reply/manifest.json b/src/plugins/extensions/auto-reply/manifest.jsondeleted file mode 100644index 11cefd317..000000000--- a/src/plugins/extensions/auto-reply/manifest.json+++ /dev/null@@ -1,10 +0,0 @@-{- "id": "auto-reply",- "name": "Auto Reply (reference)",- "version": "1.0.0",- "type": "extension",- "description": "Reference extension plugin: replies to inbound direct messages. Disabled by default.",- "main": "index.ts",- "permissions": ["messages:send"],- "sessions": ["*"]-}diff --git a/src/plugins/extensions/extensions.module.ts b/src/plugins/extensions/extensions.module.tsdeleted file mode 100644index b3eddb95e..000000000--- a/src/plugins/extensions/extensions.module.ts+++ /dev/null@@ -1,85 +0,0 @@-import { Injectable, Module, OnModuleInit } from '@nestjs/common';-import { PluginLoaderService, PluginManifest, PluginType } from '../../core/plugins';-import { AutoReplyPlugin } from './auto-reply';-import { TranslationPlugin } from './translation';-import { createLogger } from '../../common/services/logger.service';--/**- * Registers first-party built-in EXTENSION plugins with the (global) PluginLoaderService.- * Mirrors EngineFactory's registration pattern so src/core never imports a concrete plugin.- * Built-in extensions are registered DISABLED; operators enable them via POST /plugins/:id/enable.- */-@Injectable()-export class ExtensionsRegistrar implements OnModuleInit {- private readonly logger = createLogger('ExtensionsRegistrar');-- constructor(private readonly pluginLoader: PluginLoaderService) {}-- onModuleInit(): void {- const autoReplyManifest: PluginManifest = {- id: 'auto-reply',- name: 'Auto Reply (reference)',- version: '1.0.0',- type: PluginType.EXTENSION,- description: 'Reference extension plugin: replies to inbound direct messages. Disabled by default.',- main: 'index.ts',- permissions: ['messages:send'],- sessions: ['*'],- };-- this.pluginLoader.registerBuiltInPlugin(autoReplyManifest, new AutoReplyPlugin());- this.logger.log('Auto-reply reference plugin registered (disabled)');-- const translationManifest: PluginManifest = {- id: 'translation',- name: 'Group Auto-Translation',- version: '1.0.0',- type: PluginType.EXTENSION,- description:- "Auto-translates group messages between participants' languages via LibreTranslate. Configure in-group with /tr commands. Disabled by default.",- main: 'index.ts',- // Sends translations (messages:send) and reads group admins via ctx.engine.getGroupInfo (engine:read).- permissions: ['messages:send', 'engine:read'],- sessions: ['*'],- // Exposed via GET /plugins so the dashboard renders an editable config form (URL + API key, etc.).- configSchema: {- type: 'object',- properties: {- libretranslateUrl: {- type: 'string',- title: 'LibreTranslate URL',- description:- 'Base URL of the LibreTranslate instance (e.g. http://libretranslate:7001 or https://libretranslate.com).',- default: 'http://localhost:7001',- required: true,- },- libretranslateApiKey: {- type: 'string',- title: 'LibreTranslate API key',- description:- 'Optional API key, if your LibreTranslate instance requires one (e.g. hosted libretranslate.com).',- secret: true,- },- timeoutMs: { type: 'number', title: 'Translate timeout (ms)', default: 5000 },- commandPrefix: { type: 'string', title: 'Command prefix', default: '/tr' },- minLength: { type: 'number', title: 'Min message length to translate', default: 2 },- maxLength: { type: 'number', title: 'Max message length to translate', default: 2000 },- denyReply: {- type: 'boolean',- title: 'Reply on denied commands',- description: "Reply with an 'admins only' message when a non-admin runs a restricted command.",- default: false,- },- },- },- };-- this.pluginLoader.registerBuiltInPlugin(translationManifest, new TranslationPlugin());- this.logger.log('Translation plugin registered (disabled)');- }-}--@Module({- providers: [ExtensionsRegistrar],-})-export class ExtensionsModule {}diff --git a/src/plugins/extensions/translation/core/command.parser.spec.ts b/src/plugins/extensions/translation/core/command.parser.spec.tsdeleted file mode 100644index 138a125ae..000000000--- a/src/plugins/extensions/translation/core/command.parser.spec.ts+++ /dev/null@@ -1,43 +0,0 @@-// src/modules/translation/core/command.parser.spec.ts-import { parseCommand } from './command.parser';--describe('parseCommand', () => {- it('returns null for non-prefixed text', () => {- expect(parseCommand('hello world', '/tr')).toBeNull();- });-- it('parses bare commands', () => {- expect(parseCommand('/tr on', '/tr')).toEqual({ name: 'on' });- expect(parseCommand('/tr help', '/tr')).toEqual({ name: 'help' });- });-- it('accepts the /translate alias and is case-insensitive on the verb', () => {- expect(parseCommand('/translate OFF', '/tr')).toEqual({ name: 'off' });- });-- it('parses setlang with default me target', () => {- expect(parseCommand('/tr setlang es', '/tr')).toEqual({- name: 'setlang',- lang: 'es',- target: { kind: 'me' },- });- });-- it('parses a number target', () => {- expect(parseCommand('/tr grant 14155551212', '/tr')).toEqual({- name: 'grant',- target: { kind: 'number', number: '14155551212' },- });- });-- it('parses a mention target', () => {- expect(parseCommand('/tr ignore @someone', '/tr')).toEqual({- name: 'ignore',- target: { kind: 'mention' },- });- });-- it('returns null for an unknown verb', () => {- expect(parseCommand('/tr frobnicate', '/tr')).toBeNull();- });-});diff --git a/src/plugins/extensions/translation/core/command.parser.ts b/src/plugins/extensions/translation/core/command.parser.tsdeleted file mode 100644index 69f944966..000000000--- a/src/plugins/extensions/translation/core/command.parser.ts+++ /dev/null@@ -1,64 +0,0 @@-// src/modules/translation/core/command.parser.ts-import { ParsedCommand, CommandName, CommandTarget } from './ports';--const COMMANDS: ReadonlySet<string> = new Set<CommandName>([- 'help',- 'status',- 'on',- 'off',- 'setlang',- 'auto',- 'ignore',- 'unignore',- 'grant',- 'revoke',-]);--const NEEDS_TARGET: ReadonlySet<string> = new Set(['setlang', 'auto', 'ignore', 'unignore', 'grant', 'revoke']);--/**- * Parse a chat message into a control command, or null if it isn't one.- * Accepts the configured prefix and the `/translate` alias.- */-export function parseCommand(body: string, prefix: string): ParsedCommand | null {- const trimmed = body.trim();- const lower = trimmed.toLowerCase();- // Check the '/translate' alias BEFORE the configured prefix: a short prefix like- // '/tr' is a leading substring of '/translate', so testing the prefix first would- // match '/translate' against '/tr' and strip only two chars. Alias-first avoids that.- const matched = lower.startsWith('/translate')- ? '/translate'- : lower.startsWith(prefix.toLowerCase())- ? prefix- : null;- if (!matched) return null;-- const rest = trimmed.slice(matched.length).trim();- if (!rest) return null;-- const tokens = rest.split(/\s+/);- const verb = tokens[0].toLowerCase();- if (!COMMANDS.has(verb)) return null;-- const name = verb as CommandName;- const args = tokens.slice(1);-- if (name === 'setlang') {- const lang = args[0]?.toLowerCase();- if (!lang) return null;- return { name, lang, target: parseTarget(args.slice(1)) };- }-- if (NEEDS_TARGET.has(name)) {- return { name, target: parseTarget(args) };- }-- return { name };-}--function parseTarget(args: string[]): CommandTarget {- const raw = args[0];- if (!raw || raw.toLowerCase() === 'me') return { kind: 'me' };- if (raw.startsWith('@')) return { kind: 'mention' };- return { kind: 'number', number: raw.replace(/[^0-9]/g, '') };-}diff --git a/src/plugins/extensions/translation/core/ports.ts b/src/plugins/extensions/translation/core/ports.tsdeleted file mode 100644index 2c6e24889..000000000--- a/src/plugins/extensions/translation/core/ports.ts+++ /dev/null@@ -1,95 +0,0 @@-// src/modules/translation/core/ports.ts-// Framework-agnostic contracts for the translation core. NO NestJS/TypeORM/engine imports.--export interface DetectResult {- lang: string; // ISO 639-1- confidence: number; // 0..1-}--export interface Translation {- lang: string;- text: string;-}--export interface ParticipantState {- lang: string | null; // null = not learned yet- source: 'learned' | 'pinned';- enabled: boolean;- samples: number;- /** Candidate language awaiting a 2nd consecutive detection before a learned switch. */- pendingLang?: string;- updatedAt: string;- /** Last-seen WhatsApp pushName; a secondary identity anchor used to reconcile a misrouted- * @lid author back to the real sender. */- pushName?: string;-}--export type ParticipantMap = Record<string, ParticipantState>; // key = author WID--export interface GroupState {- sessionId: string;- chatId: string;- active: boolean;- participants: ParticipantMap;- delegatedControllers: string[];- announced: boolean;-}--export interface InboundMessage {- id: string;- chatId: string;- body: string;- author: string; // sender WID (group participant)- isGroup: boolean;- fromMe: boolean;- mentionedIds: string[];- pushName?: string;-}--export type CommandName =- | 'help'- | 'status'- | 'on'- | 'off'- | 'setlang'- | 'auto'- | 'ignore'- | 'unignore'- | 'grant'- | 'revoke';--export type CommandTarget = { kind: 'me' } | { kind: 'mention' } | { kind: 'number'; number: string };--export interface ParsedCommand {- name: CommandName;- lang?: string; // setlang only- target?: CommandTarget; // setlang/auto/ignore/unignore/grant/revoke-}--export interface Translator {- detect(text: string): Promise<DetectResult>;- translate(text: string, source: string, target: string): Promise<string>;- languages(): Promise<string[]>;- isHealthy(): boolean;-}--export interface ConfigStore {- load(sessionId: string, chatId: string): Promise<GroupState>;- save(state: GroupState): Promise<void>;-}--export interface ChatGateway {- sendText(sessionId: string, chatId: string, text: string): Promise<void>;- sendCombinedReply(sessionId: string, chatId: string, quotedMessageId: string, text: string): Promise<void>;- getGroupAdmins(sessionId: string, chatId: string): Promise<string[]>;-}--/**- * Structured logging port for the translation core. Implemented at the plugin boundary over the- * host's PluginLogger; declared here so `core/` stays framework-agnostic.- */-export interface TranslationLogger {- debug(message: string, meta?: Record<string, unknown>): void;- info(message: string, meta?: Record<string, unknown>): void;- warn(message: string, meta?: Record<string, unknown>): void;-}diff --git a/src/plugins/extensions/translation/core/reply.formatter.spec.ts b/src/plugins/extensions/translation/core/reply.formatter.spec.tsdeleted file mode 100644index beb3ffc1c..000000000--- a/src/plugins/extensions/translation/core/reply.formatter.spec.ts+++ /dev/null@@ -1,36 +0,0 @@-// src/modules/translation/core/reply.formatter.spec.ts-import { formatCombinedReply, buildHelpText, formatStatus } from './reply.formatter';-import { GroupState } from './ports';--describe('reply.formatter', () => {- it('formats one line per translation with an uppercased code label', () => {- const out = formatCombinedReply([- { lang: 'es', text: 'Hola' },- { lang: 'fr', text: 'Bonjour' },- ]);- expect(out).toContain('Hola');- expect(out).toContain('Bonjour');- expect(out.split('\n')).toHaveLength(2);- expect(out).toMatch(/ES/);- });-- it('buildHelpText lists key commands with the active prefix', () => {- const help = buildHelpText('/tr');- expect(help).toContain('/tr on');- expect(help).toContain('/tr setlang');- });-- it('formatStatus reports active state and participants', () => {- const state: GroupState = {- sessionId: 's',- chatId: '[email protected]',- active: true,- participants: { '[email protected]': { lang: 'en', source: 'pinned', enabled: true, samples: 3, updatedAt: 'x' } },- delegatedControllers: [],- announced: true,- };- const out = formatStatus(state, true);- expect(out).toMatch(/active/i);- expect(out).toContain('en');- });-});diff --git a/src/plugins/extensions/translation/core/reply.formatter.ts b/src/plugins/extensions/translation/core/reply.formatter.tsdeleted file mode 100644index 4fcac07ee..000000000--- a/src/plugins/extensions/translation/core/reply.formatter.ts+++ /dev/null@@ -1,60 +0,0 @@-// src/modules/translation/core/reply.formatter.ts-import { Translation, GroupState } from './ports';--const FLAGS: Record<string, string> = {- en: '🇬🇧',- es: '🇪🇸',- fr: '🇫🇷',- de: '🇩🇪',- pt: '🇵🇹',- it: '🇮🇹',- nl: '🇳🇱',- ru: '🇷🇺',- ar: '🇸🇦',- zh: '🇨🇳',- ja: '🇯🇵',-};--function label(lang: string): string {- const flag = FLAGS[lang];- return flag ? `${flag} ${lang.toUpperCase()}` : lang.toUpperCase();-}--export function formatCombinedReply(translations: Translation[]): string {- return translations.map(t => `${label(t.lang)}: ${t.text}`).join('\n');-}--export function buildHelpText(prefix: string): string {- return [- '👋 Translation bot. I am OFF in this group until an admin runs `' + prefix + ' on`.',- 'Commands:',- `${prefix} on / ${prefix} off — enable/disable translation here`,- `${prefix} setlang <code> [me|@user|number] — pin a language (default: you)`,- `${prefix} auto [me|@user|number] — go back to auto-detect`,- `${prefix} ignore <@user|number> / ${prefix} unignore <@user|number>`,- `${prefix} grant <@user|number> / ${prefix} revoke <@user|number> — delegate control (admins)`,- `${prefix} status — show settings`,- `${prefix} help — this message`,- ].join('\n');-}--export function formatStatus(state: GroupState, translatorHealthy: boolean): string {- const lines: string[] = [];- lines.push(`Translation: ${state.active ? 'ACTIVE' : 'inactive'}`);- lines.push(`Translator: ${translatorHealthy ? 'ok' : 'unreachable'}`);- const entries = Object.entries(state.participants);- if (entries.length === 0) {- lines.push('No participants learned yet.');- } else {- lines.push('Participants:');- for (const [wid, p] of entries) {- const lang = p.lang ?? 'unknown';- const flags = `${p.source}${p.enabled ? '' : ', ignored'}`;- lines.push(`• ${wid}: ${lang} (${flags})`);- }- }- if (state.delegatedControllers.length > 0) {- lines.push(`Delegated controllers: ${state.delegatedControllers.join(', ')}`);- }- return lines.join('\n');-}diff --git a/src/plugins/extensions/translation/core/translation.coordinator.spec.ts b/src/plugins/extensions/translation/core/translation.coordinator.spec.tsdeleted file mode 100644index 3f0802a70..000000000--- a/src/plugins/extensions/translation/core/translation.coordinator.spec.ts+++ /dev/null@@ -1,373 +0,0 @@-// src/modules/translation/core/translation.coordinator.spec.ts-import { TranslationCoordinator, CoordinatorOptions } from './translation.coordinator';-import { ChatGateway, ConfigStore, GroupState, InboundMessage, Translator, TranslationLogger } from './ports';--const OPTS: CoordinatorOptions = { prefix: '/tr', minLength: 2, maxLength: 2000, denyReply: false };--function freshState(over: Partial<GroupState> = {}): GroupState {- return {- sessionId: 's',- chatId: '[email protected]',- active: false,- participants: {},- delegatedControllers: [],- announced: false,- ...over,- };-}--function makeDeps(state: GroupState) {- const saved: GroupState[] = [];- const load = jest.fn().mockResolvedValue(state);- const save = jest.fn().mockImplementation((s: GroupState) => {- saved.push(JSON.parse(JSON.stringify(s)) as GroupState);- return Promise.resolve();- });- const sendText = jest.fn().mockResolvedValue(undefined);- const sendCombinedReply = jest.fn().mockResolvedValue(undefined);- const getGroupAdmins = jest.fn().mockResolvedValue([]);- const detect = jest.fn();- const translate = jest.fn();- const languages = jest.fn().mockResolvedValue(['en', 'es', 'fr']);- const isHealthy = jest.fn().mockReturnValue(true);- const debug = jest.fn();- const info = jest.fn();- const warn = jest.fn();-- const store: ConfigStore = { load, save };- const gateway: ChatGateway = { sendText, sendCombinedReply, getGroupAdmins };- const translator: Translator = { detect, translate, languages, isHealthy };- const logger: TranslationLogger = { debug, info, warn };-- return {- store,- gateway,- translator,- logger,- saved,- mocks: {- load,- save,- sendText,- sendCombinedReply,- getGroupAdmins,- detect,- translate,- languages,- isHealthy,- debug,- info,- warn,- },- };-}--function msg(over: Partial<InboundMessage> = {}): InboundMessage {- return {- id: 'M1',- chatId: '[email protected]',- body: 'hello',- author: '[email protected]',- isGroup: true,- fromMe: false,- mentionedIds: [],- ...over,- };-}--describe('TranslationCoordinator', () => {- it('ignores non-group and fromMe messages', async () => {- const { store, gateway, translator, mocks } = makeDeps(freshState());- const c = new TranslationCoordinator(translator, store, gateway, OPTS);- expect(await c.handleMessage('s', msg({ isGroup: false }))).toEqual({ swallow: false });- expect(await c.handleMessage('s', msg({ fromMe: true }))).toEqual({ swallow: false });- expect(mocks.sendText).not.toHaveBeenCalled();- });-- it('announces once on first contact then stays dormant', async () => {- const { store, gateway, translator, mocks } = makeDeps(freshState());- const c = new TranslationCoordinator(translator, store, gateway, OPTS);- await c.handleMessage('s', msg());- expect(mocks.sendText).toHaveBeenCalledTimes(1);- expect(mocks.save).toHaveBeenCalled();- });-- it('activates only for an admin', async () => {- const state = freshState({ announced: true });- const { store, gateway, translator, saved, mocks } = makeDeps(state);- mocks.getGroupAdmins.mockResolvedValue(['[email protected]']);- const c = new TranslationCoordinator(translator, store, gateway, OPTS);- const res = await c.handleMessage('s', msg({ body: '/tr on' }));- expect(res).toEqual({ swallow: true });- expect(saved.at(-1)?.active).toBe(true);- });-- it('recognizes a resolved-lid admin once group ids share the @c.us dialect', async () => {- // In a lid-addressed group the author is canonicalized to <phone>@c.us; the admin list must be- // canonicalized through the same path so widEquals (which does NOT bridge lid<->phone) can match.- const state = freshState({ announced: true });- const { store, gateway, translator, saved, mocks } = makeDeps(state);- mocks.getGroupAdmins.mockResolvedValue(['[email protected]']); // resolved-lid admin, neutral dialect- const c = new TranslationCoordinator(translator, store, gateway, OPTS);- const res = await c.handleMessage('s', msg({ author: '[email protected]', body: '/tr on' }));- expect(res).toEqual({ swallow: true });- expect(saved.at(-1)?.active).toBe(true);- });-- it('regression guard: a raw @lid admin list does NOT match a resolved @c.us author', async () => {- // The pre-fix one-sided state: author canonicalized but the admin list left raw. widEquals compares- // user-parts (111 vs 628111) and deliberately won't bridge the namespaces, so the admin is denied.- const state = freshState({ announced: true });- const { store, gateway, translator, saved, mocks } = makeDeps(state);- mocks.getGroupAdmins.mockResolvedValue(['111@lid']); // un-canonicalized- const c = new TranslationCoordinator(translator, store, gateway, OPTS);- const res = await c.handleMessage('s', msg({ author: '[email protected]', body: '/tr on' }));- expect(res).toEqual({ swallow: true });- expect(saved.at(-1)?.active ?? false).toBe(false);- });-- it('rejects activation from a non-admin (silent by default)', async () => {- const state = freshState({ announced: true });- const { store, gateway, translator, saved, mocks } = makeDeps(state);- mocks.getGroupAdmins.mockResolvedValue(['[email protected]']);- const c = new TranslationCoordinator(translator, store, gateway, OPTS);- const res = await c.handleMessage('s', msg({ body: '/tr on' }));- expect(res).toEqual({ swallow: true });- expect(saved.at(-1)?.active ?? false).toBe(false);- });-- it('translates an active-group message into other participants languages (skipping the source)', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- '[email protected]': { lang: 'en', source: 'learned', enabled: true, samples: 2, updatedAt: 'x' },- '[email protected]': { lang: 'es', source: 'learned', enabled: true, samples: 2, updatedAt: 'x' },- },- });- const { store, gateway, translator, mocks } = makeDeps(state);- mocks.detect.mockResolvedValue({ lang: 'en', confidence: 0.99 });- mocks.translate.mockResolvedValue('Hola');- const c = new TranslationCoordinator(translator, store, gateway, OPTS);- const res = await c.handleMessage('s', msg({ author: '[email protected]', body: 'Hello' }));- expect(res).toEqual({ swallow: false });- expect(mocks.translate).toHaveBeenCalledWith('Hello', 'en', 'es');- expect(mocks.sendCombinedReply).toHaveBeenCalledWith('s', '[email protected]', 'M1', expect.stringContaining('Hola'));- });-- it('falls back to the sender language and never translates into the source when detection misfires', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- '[email protected]': { lang: 'en', source: 'learned', enabled: true, samples: 3, updatedAt: 'x' },- '[email protected]': { lang: 'es', source: 'pinned', enabled: true, samples: 3, updatedAt: 'x' },- },- });- const { store, gateway, translator, mocks } = makeDeps(state);- // Detection misfires on colloquial Spanish, returning 'gl' — a language the group does not use.- mocks.detect.mockResolvedValue({ lang: 'gl', confidence: 0.5 });- mocks.translate.mockResolvedValue('Let me know');- const c = new TranslationCoordinator(translator, store, gateway, OPTS);- await c.handleMessage('s', msg({ author: '[email protected]', body: 'Haber dime que debo darte' }));- // Effective source falls back to the sender's known 'es'; 'en' is the only target.- expect(mocks.translate).toHaveBeenCalledTimes(1);- expect(mocks.translate).toHaveBeenCalledWith('Haber dime que debo darte', 'es', 'en');- // Must never translate a message into the sender's own language.- expect(mocks.translate).not.toHaveBeenCalledWith(expect.anything(), expect.anything(), 'es');- });-- it('learns a sender language only after a 2-message debounce', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- '[email protected]': { lang: 'en', source: 'learned', enabled: true, samples: 5, updatedAt: 'x' },- '[email protected]': { lang: 'es', source: 'learned', enabled: true, samples: 2, updatedAt: 'x' },- },- });- const { store, gateway, translator, saved, mocks } = makeDeps(state);- mocks.detect.mockResolvedValue({ lang: 'fr', confidence: 0.99 });- mocks.translate.mockResolvedValue('x');- const c = new TranslationCoordinator(translator, store, gateway, OPTS);- // First foreign detection: lang stays 'en'- await c.handleMessage('s', msg({ author: '[email protected]', body: 'Bonjour' }));- expect(saved.at(-1)?.participants['[email protected]'].lang).toBe('en');- // Second consecutive foreign detection: switches to 'fr'- await c.handleMessage('s', msg({ author: '[email protected]', body: 'Salut' }));- expect(saved.at(-1)?.participants['[email protected]'].lang).toBe('fr');- });-- it('skips trivial messages below minLength', async () => {- const state = freshState({ announced: true, active: true });- const { store, gateway, translator, mocks } = makeDeps(state);- const c = new TranslationCoordinator(translator, store, gateway, OPTS);- await c.handleMessage('s', msg({ body: '.' }));- expect(mocks.detect).not.toHaveBeenCalled();- expect(mocks.sendCombinedReply).not.toHaveBeenCalled();- });-- it('records the sender pushName on a translated message', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- '[email protected]': { lang: 'en', source: 'pinned', enabled: true, samples: 2, updatedAt: 'x' },- '[email protected]': { lang: 'es', source: 'pinned', enabled: true, samples: 2, updatedAt: 'x' },- },- });- const { store, gateway, translator, logger, saved, mocks } = makeDeps(state);- mocks.detect.mockResolvedValue({ lang: 'en', confidence: 0.99 });- mocks.translate.mockResolvedValue('Hola');- const c = new TranslationCoordinator(translator, store, gateway, OPTS, logger);- await c.handleMessage('s', msg({ author: '[email protected]', body: 'Hello', pushName: 'Doug' }));- expect(saved.at(-1)?.participants['[email protected]'].pushName).toBe('Doug');- });-- it('reconciles a misrouted @lid author via a uniquely-matching pushName', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- 'liz@lid': { lang: 'es', source: 'pinned', enabled: true, samples: 5, updatedAt: 'x', pushName: 'Lizeth' },- 'doug@lid': { lang: 'en', source: 'pinned', enabled: true, samples: 5, updatedAt: 'x', pushName: 'Doug' },- },- });- const { store, gateway, translator, logger, mocks } = makeDeps(state);- mocks.detect.mockResolvedValue({ lang: 'es', confidence: 0.99 });- mocks.translate.mockResolvedValue('I feel sick');- const c = new TranslationCoordinator(translator, store, gateway, OPTS, logger);- // Liz's Spanish message is misrouted to Doug's @lid, but the pushName is still Liz's.- await c.handleMessage('s', msg({ author: 'doug@lid', pushName: 'Lizeth', body: 'Me siento mal' }));- expect(mocks.translate).toHaveBeenCalledWith('Me siento mal', 'es', 'en');- expect(mocks.sendCombinedReply).toHaveBeenCalled();- expect(mocks.info).toHaveBeenCalledWith(- 'sender reconciled by pushName',- expect.objectContaining({ resolvedKey: 'liz@lid' }),- );- });-- it('does not reconcile when the author already owns the pushName', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- 'a@lid': { lang: 'es', source: 'pinned', enabled: true, samples: 1, updatedAt: 'x', pushName: 'Sam' },- 'b@lid': { lang: 'en', source: 'pinned', enabled: true, samples: 1, updatedAt: 'x', pushName: 'Sam' },- },- });- const { store, gateway, translator, logger, mocks } = makeDeps(state);- mocks.detect.mockResolvedValue({ lang: 'es', confidence: 0.99 });- mocks.translate.mockResolvedValue('hi');- const c = new TranslationCoordinator(translator, store, gateway, OPTS, logger);- await c.handleMessage('s', msg({ author: 'a@lid', pushName: 'Sam', body: 'Hola amigo' }));- expect(mocks.info).not.toHaveBeenCalledWith('sender reconciled by pushName', expect.anything());- // a@lid (es) wrote es -> target en (attributed to the author, not reconciled to b).- expect(mocks.translate).toHaveBeenCalledWith('Hola amigo', 'es', 'en');- });-- it('does not reconcile when the pushName is ambiguous across participants', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- 'x@lid': { lang: 'fr', source: 'pinned', enabled: true, samples: 1, updatedAt: 'x', pushName: 'Xavier' },- 'a@lid': { lang: 'es', source: 'pinned', enabled: true, samples: 1, updatedAt: 'x', pushName: 'Sam' },- 'b@lid': { lang: 'en', source: 'pinned', enabled: true, samples: 1, updatedAt: 'x', pushName: 'Sam' },- },- });- const { store, gateway, translator, logger, mocks } = makeDeps(state);- mocks.detect.mockResolvedValue({ lang: 'fr', confidence: 0.99 });- mocks.translate.mockResolvedValue('x');- const c = new TranslationCoordinator(translator, store, gateway, OPTS, logger);- // Author x@lid (Xavier); message pushName 'Sam' matches TWO other participants -> ambiguous.- await c.handleMessage('s', msg({ author: 'x@lid', pushName: 'Sam', body: 'Bonjour tout le monde' }));- expect(mocks.info).not.toHaveBeenCalledWith('sender reconciled by pushName', expect.anything());- expect(mocks.debug).toHaveBeenCalledWith(- 'ambiguous pushName; not reconciling',- expect.objectContaining({ author: 'x@lid' }),- );- });-- it('engages the backstop instead of dropping when source != senderLang', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- 'liz@lid': { lang: 'es', source: 'pinned', enabled: true, samples: 5, updatedAt: 'x', pushName: 'Lizeth' },- 'doug@lid': { lang: 'en', source: 'pinned', enabled: true, samples: 5, updatedAt: 'x', pushName: 'Doug' },- },- });- const { store, gateway, translator, logger, mocks } = makeDeps(state);- // Worst case: misrouted to Doug AND pushName also corrupted -> reconciliation can't help.- mocks.detect.mockResolvedValue({ lang: 'es', confidence: 0.99 });- mocks.translate.mockResolvedValue('I feel sick');- const c = new TranslationCoordinator(translator, store, gateway, OPTS, logger);- await c.handleMessage('s', msg({ author: 'doug@lid', pushName: 'Doug', body: 'Me siento mal' }));- expect(mocks.warn).toHaveBeenCalledWith(- 'target backstop engaged (possible misroute or cross-language write)',- expect.objectContaining({ source: 'es' }),- );- expect(mocks.translate).toHaveBeenCalledWith('Me siento mal', 'es', 'en');- expect(mocks.sendCombinedReply).toHaveBeenCalled();- });-- it('does not warn or translate when the group speaks only the source language', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- 'a@lid': { lang: 'en', source: 'pinned', enabled: true, samples: 5, updatedAt: 'x', pushName: 'A' },- 'b@lid': { lang: 'en', source: 'pinned', enabled: true, samples: 5, updatedAt: 'x', pushName: 'B' },- },- });- const { store, gateway, translator, logger, mocks } = makeDeps(state);- mocks.detect.mockResolvedValue({ lang: 'en', confidence: 0.99 });- const c = new TranslationCoordinator(translator, store, gateway, OPTS, logger);- await c.handleMessage('s', msg({ author: 'a@lid', pushName: 'A', body: 'Hello there' }));- expect(mocks.translate).not.toHaveBeenCalled();- expect(mocks.warn).not.toHaveBeenCalled();- expect(mocks.sendCombinedReply).not.toHaveBeenCalled();- });-- it('warns on a failed translate call and still delivers the successful targets', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- 's1@lid': { lang: 'en', source: 'pinned', enabled: true, samples: 5, updatedAt: 'x', pushName: 'S1' },- 's2@lid': { lang: 'es', source: 'pinned', enabled: true, samples: 5, updatedAt: 'x', pushName: 'S2' },- 's3@lid': { lang: 'fr', source: 'pinned', enabled: true, samples: 5, updatedAt: 'x', pushName: 'S3' },- },- });- const { store, gateway, translator, logger, mocks } = makeDeps(state);- mocks.detect.mockResolvedValue({ lang: 'en', confidence: 0.99 });- mocks.translate.mockImplementation((_t: string, _s: string, target: string) =>- target === 'fr' ? Promise.reject(new Error('boom')) : Promise.resolve('Hola'),- );- const c = new TranslationCoordinator(translator, store, gateway, OPTS, logger);- await c.handleMessage('s', msg({ author: 's1@lid', pushName: 'S1', body: 'Hello everyone' }));- expect(mocks.warn).toHaveBeenCalledWith('translate call failed', expect.objectContaining({ target: 'fr' }));- expect(mocks.sendCombinedReply).toHaveBeenCalledWith('s', '[email protected]', 'M1', expect.stringContaining('Hola'));- });-- it('emits a decision debug log for each translated message', async () => {- const state = freshState({- announced: true,- active: true,- participants: {- '[email protected]': { lang: 'en', source: 'pinned', enabled: true, samples: 2, updatedAt: 'x', pushName: 'D' },- '[email protected]': { lang: 'es', source: 'pinned', enabled: true, samples: 2, updatedAt: 'x', pushName: 'L' },- },- });- const { store, gateway, translator, logger, mocks } = makeDeps(state);- mocks.detect.mockResolvedValue({ lang: 'en', confidence: 0.99 });- mocks.translate.mockResolvedValue('Hola');- const c = new TranslationCoordinator(translator, store, gateway, OPTS, logger);- await c.handleMessage('s', msg({ author: '[email protected]', pushName: 'D', body: 'Hello' }));- expect(mocks.debug).toHaveBeenCalledWith(- 'translate decision',- expect.objectContaining({ detected: 'en', source: 'en', sent: 1 }),- );- });-});diff --git a/src/plugins/extensions/translation/core/translation.coordinator.ts b/src/plugins/extensions/translation/core/translation.coordinator.tsdeleted file mode 100644index 82f695b61..000000000--- a/src/plugins/extensions/translation/core/translation.coordinator.ts+++ /dev/null@@ -1,372 +0,0 @@-// src/modules/translation/core/translation.coordinator.ts-import {- ChatGateway,- ConfigStore,- GroupState,- InboundMessage,- ParsedCommand,- ParticipantState,- Translation,- Translator,- TranslationLogger,- CommandTarget,-} from './ports';-import { parseCommand } from './command.parser';-import { buildHelpText, formatCombinedReply, formatStatus } from './reply.formatter';--export interface CoordinatorOptions {- prefix: string;- minLength: number;- maxLength: number;- denyReply: boolean;-}--const URL_OR_EMOJI_ONLY = /^(?:\s|\p{Emoji}|https?:\/\/\S+)+$/u;--const NOOP_LOGGER: TranslationLogger = { debug: () => {}, info: () => {}, warn: () => {} };--/**- * Compare two WhatsApp IDs tolerantly: exact match, or same user part ignoring- * an `@domain` and any `:device` suffix (e.g. `[email protected]` === `123:[email protected]`).- * Note: this does NOT bridge the LID (`@lid`) and phone (`@c.us`) namespaces —- * those have different user numbers (see spec §16).- */-function widEquals(a: string, b: string): boolean {- if (a === b) return true;- const userPart = (w: string): string => w.split('@')[0].split(':')[0];- return userPart(a) === userPart(b);-}--export class TranslationCoordinator {- constructor(- private readonly translator: Translator,- private readonly store: ConfigStore,- private readonly gateway: ChatGateway,- private readonly opts: CoordinatorOptions,- private readonly logger: TranslationLogger = NOOP_LOGGER,- ) {}-- async handleMessage(sessionId: string, msg: InboundMessage): Promise<{ swallow: boolean }> {- if (!msg.isGroup || msg.fromMe || !msg.author) return { swallow: false };-- const state = await this.store.load(sessionId, msg.chatId);-- if (!state.announced) {- await this.gateway.sendText(sessionId, msg.chatId, buildHelpText(this.opts.prefix));- state.announced = true;- await this.store.save(state);- }-- const command = parseCommand(msg.body, this.opts.prefix);- if (command) {- await this.handleCommand(sessionId, msg, state, command);- return { swallow: true };- }-- if (!state.active) return { swallow: false };- await this.translateMessage(sessionId, msg, state);- return { swallow: false };- }-- private async translateMessage(sessionId: string, msg: InboundMessage, state: GroupState): Promise<void> {- const text = msg.body.trim();- if (text.length < this.opts.minLength || text.length > this.opts.maxLength || URL_OR_EMOJI_ONLY.test(text)) {- return;- }-- const senderKey = this.resolveSenderKey(state, msg);- const sender = this.ensureParticipant(state, senderKey);- // Record the pushName, but never overwrite a different existing value (a misrouted message- // could otherwise poison the identity anchor).- if (msg.pushName && (sender.pushName === undefined || sender.pushName === msg.pushName)) {- sender.pushName = msg.pushName;- }- if (!sender.enabled) return;-- let detected: string;- try {- detected = (await this.translator.detect(text)).lang;- } catch {- return; // translator down — silent skip- }- this.applyLearning(sender, detected);-- // Pick the effective source language. Detection misfires on short/colloquial text — it often- // returns a near-neighbour language (e.g. es misread as gl/ca) — so trust the detected code only- // when it names a language the group actually uses; otherwise fall back to the sender's known- // language. Combined with excluding the sender's own language from the targets below, this stops- // a message ever being "translated" into its own language (the duplicate/echo bug).- const knownLangs = this.knownLanguages(state);- const source = knownLangs.includes(detected) ? detected : (sender.lang ?? detected);-- let targets = this.targetLanguages(state, source, sender.lang);- if (targets.length === 0) {- // Backstop: a real message detected in a known language must never be silently dropped due- // to a sender/source mismatch (e.g. a misrouted @lid author keyed to the wrong participant).- // Translate into every known language except the source — guarantees delivery.- const backstop = knownLangs.filter(l => l !== source);- if (backstop.length === 0) {- this.logger.debug('no targets; group speaks only the source language', {- action: 'translation_no_targets',- source,- });- await this.store.save(state);- return;- }- this.logger.warn('target backstop engaged (possible misroute or cross-language write)', {- action: 'translation_backstop',- author: msg.author,- pushName: msg.pushName,- source,- senderLang: sender.lang,- targets: backstop,- });- targets = backstop;- }-- const settled = await Promise.allSettled(targets.map(t => this.translator.translate(text, source, t)));- const translations: Translation[] = [];- settled.forEach((r, i) => {- if (r.status === 'fulfilled') {- translations.push({ lang: targets[i], text: r.value });- } else {- this.logger.warn('translate call failed', {- action: 'translation_translate_failed',- source,- target: targets[i],- error: String(r.reason),- });- }- });-- this.logger.debug('translate decision', {- action: 'translation_decision',- author: msg.author,- resolvedKey: senderKey,- pushName: msg.pushName,- detected,- source,- senderLang: sender.lang,- knownLangs,- targets,- sent: translations.length,- });-- if (translations.length > 0) {- await this.gateway.sendCombinedReply(sessionId, msg.chatId, msg.id, formatCombinedReply(translations));- }- await this.store.save(state);- }-- /** Distinct languages currently spoken by enabled participants. */- private knownLanguages(state: GroupState): string[] {- const langs = new Set<string>();- for (const p of Object.values(state.participants)) {- if (p.enabled && p.lang) langs.add(p.lang);- }- return [...langs];- }-- /**- * Distinct languages of enabled participants, excluding the message source language AND the- * sender's own language — a sender never needs their own message translated back to themselves- * (this also guards against a detection misfire leaving the source language in the target set).- */- private targetLanguages(state: GroupState, source: string, senderLang: string | null): string[] {- const langs = new Set<string>();- for (const p of Object.values(state.participants)) {- if (p.enabled && p.lang && p.lang !== source && p.lang !== senderLang) langs.add(p.lang);- }- return [...langs];- }-- /** 2-message debounce: a learned language only switches after a new language is seen twice in a row. */- private applyLearning(p: ParticipantState, detected: string): void {- p.samples++;- if (p.source === 'pinned') return;- if (p.lang === detected) {- p.pendingLang = undefined;- return;- }- if (p.pendingLang === detected) {- p.lang = detected;- p.pendingLang = undefined;- } else {- p.pendingLang = detected;- if (p.lang === null) p.lang = detected; // cold start: adopt immediately- }- p.updatedAt = new Date().toISOString();- }-- /**- * Resolve which participant a message belongs to. whatsapp-web.js can misroute a group message's- * `@lid` author after a reconnect; when the message's pushName uniquely identifies a DIFFERENT- * known participant (and the author doesn't already own that pushName), trust the pushName.- * Ambiguous (shared pushName) or no-match cases fall back to the raw author.- */- private resolveSenderKey(state: GroupState, msg: InboundMessage): string {- const { author, pushName } = msg;- if (!pushName) return author;- // No conflict if the author already owns this pushName.- if (state.participants[author]?.pushName === pushName) return author;- const matches = Object.keys(state.participants).filter(- key => key !== author && state.participants[key].pushName === pushName,- );- if (matches.length === 1) {- this.logger.info('sender reconciled by pushName', {- action: 'translation_sender_reconciled',- author,- resolvedKey: matches[0],- pushName,- });- return matches[0];- }- if (matches.length > 1) {- this.logger.debug('ambiguous pushName; not reconciling', {- action: 'translation_pushname_ambiguous',- author,- pushName,- matches,- });- }- return author;- }-- private ensureParticipant(state: GroupState, wid: string): ParticipantState {- if (!state.participants[wid]) {- state.participants[wid] = { lang: null, source: 'learned', enabled: true, samples: 0, updatedAt: '' };- }- return state.participants[wid];- }-- private async handleCommand(- sessionId: string,- msg: InboundMessage,- state: GroupState,- cmd: ParsedCommand,- ): Promise<void> {- if (cmd.name === 'help') {- await this.gateway.sendText(sessionId, msg.chatId, buildHelpText(this.opts.prefix));- return;- }- if (cmd.name === 'status') {- await this.gateway.sendText(sessionId, msg.chatId, formatStatus(state, this.translator.isHealthy()));- return;- }-- const targetsSelf = cmd.target?.kind === 'me';- const isSelfServe = (cmd.name === 'setlang' || cmd.name === 'auto') && targetsSelf;- if (!isSelfServe) {- const admins = await this.gateway.getGroupAdmins(sessionId, msg.chatId);- const isAdmin = admins.some(a => widEquals(a, msg.author));- const isController = isAdmin || state.delegatedControllers.some(c => widEquals(c, msg.author));- const adminOnly = cmd.name === 'grant' || cmd.name === 'revoke';- if ((adminOnly && !isAdmin) || (!adminOnly && !isController)) {- // Always reply on denial — a command must never fail silently.- await this.gateway.sendText(- sessionId,- msg.chatId,- adminOnly- ? '⛔ Only group admins can use that command.'- : '⛔ Only group admins or delegated users can use that command.',- );- return;- }- }-- const targetWid = this.resolveTarget(msg, cmd.target);-- switch (cmd.name) {- case 'on':- state.active = true;- await this.confirm(sessionId, msg, '✅ Translation activated.', state);- return;- case 'off':- state.active = false;- await this.confirm(sessionId, msg, '✅ Translation deactivated.', state);- return;- case 'setlang': {- if (!targetWid || !cmd.lang)- return this.replyError(sessionId, msg, 'Usage: ' + this.opts.prefix + ' setlang <code> [me|@user|number]');- const langs = await this.safeLanguages();- if (langs && !langs.includes(cmd.lang)) {- return this.replyError(sessionId, msg, `Unsupported language "${cmd.lang}". Supported: ${langs.join(', ')}`);- }- const p = this.ensureParticipant(state, targetWid);- p.lang = cmd.lang;- p.source = 'pinned';- p.pendingLang = undefined;- p.updatedAt = new Date().toISOString();- await this.confirm(sessionId, msg, `✅ Set ${targetWid} to ${cmd.lang}.`, state);- return;- }- case 'auto': {- if (!targetWid) return this.replyError(sessionId, msg, this.targetHelp());- const p = this.ensureParticipant(state, targetWid);- p.source = 'learned';- p.pendingLang = undefined;- await this.confirm(sessionId, msg, `✅ ${targetWid} set to auto-detect.`, state);- return;- }- case 'ignore':- case 'unignore': {- if (!targetWid) return this.replyError(sessionId, msg, this.targetHelp());- const p = this.ensureParticipant(state, targetWid);- p.enabled = cmd.name === 'unignore';- await this.confirm(- sessionId,- msg,- `✅ ${cmd.name === 'ignore' ? 'Ignoring' : 'Including'} ${targetWid}.`,- state,- );- return;- }- case 'grant':- case 'revoke': {- if (!targetWid) return this.replyError(sessionId, msg, this.targetHelp());- const set = new Set(state.delegatedControllers);- if (cmd.name === 'grant') set.add(targetWid);- else set.delete(targetWid);- state.delegatedControllers = [...set];- await this.confirm(- sessionId,- msg,- `✅ ${cmd.name === 'grant' ? 'Granted' : 'Revoked'} control for ${targetWid}.`,- state,- );- return;- }- }- }-- private resolveTarget(msg: InboundMessage, target?: CommandTarget): string | null {- if (!target || target.kind === 'me') return msg.author;- if (target.kind === 'mention') return msg.mentionedIds[0] ?? null;- // NOTE: a `<number>` target assumes phone-number JID keying (`<number>@c.us`). Under- // WhatsApp's newer LID scheme participants may be keyed by an opaque `@lid` id instead,- // so this constructed wid can fail to match the stored participant. The `@mention` and- // `me` forms resolve to the actual wid and are robust to LID; prefer them. See spec §16.- return `${target.number}@c.us`;- }-- private async safeLanguages(): Promise<string[] | null> {- try {- return await this.translator.languages();- } catch {- return null; // can't validate — allow- }- }-- private async confirm(sessionId: string, msg: InboundMessage, text: string, state: GroupState): Promise<void> {- await this.store.save(state);- await this.gateway.sendText(sessionId, msg.chatId, text);- }-- private replyError(sessionId: string, msg: InboundMessage, text: string): Promise<void> {- return this.gateway.sendText(sessionId, msg.chatId, text);- }-- private targetHelp(): string {- return "⚠️ Couldn't identify that user. Target them by @mention, by phone number, or use 'me' for yourself.";- }-}diff --git a/src/plugins/extensions/translation/index.ts b/src/plugins/extensions/translation/index.tsdeleted file mode 100644index 56fbca056..000000000--- a/src/plugins/extensions/translation/index.ts+++ /dev/null@@ -1,113 +0,0 @@-/**- * Group auto-translation extension plugin.- *- * Ports the former core `translation` module onto the Tier-2 capability layer (#294): the- * framework-agnostic `core/` (coordinator, parser, formatter, ports) is reused unchanged, with- * `ChatGateway`/`ConfigStore` implemented over `ctx.messages`/`ctx.engine`/`ctx.storage`.- * Registered DISABLED by default — enable via `POST /plugins/translation/enable`.- */-import { PluginContext, IPlugin } from '../../../core/plugins';-import { HookContext, HookResult } from '../../../core/hooks';-import { IncomingMessage } from '../../../engine/interfaces/whatsapp-engine.interface';-import { TranslationCoordinator, CoordinatorOptions } from './core/translation.coordinator';-import { InboundMessage, TranslationLogger } from './core/ports';-import { LibreTranslateClient } from './libretranslate.client';-import { PluginChatGateway } from './plugin-chat.gateway';-import { PluginConfigStore } from './plugin-config.store';--function readString(cfg: Record<string, unknown>, key: string, fallback: string): string {- const v = cfg[key];- return typeof v === 'string' && v.length > 0 ? v : fallback;-}-function readOptionalString(cfg: Record<string, unknown>, key: string): string | undefined {- const v = cfg[key];- return typeof v === 'string' && v.length > 0 ? v : undefined;-}-function readNumber(cfg: Record<string, unknown>, key: string, fallback: number): number {- const v = cfg[key];- return typeof v === 'number' && Number.isFinite(v) ? v : fallback;-}-function readBool(cfg: Record<string, unknown>, key: string, fallback: boolean): boolean {- const v = cfg[key];- return typeof v === 'boolean' ? v : fallback;-}--export class TranslationPlugin implements IPlugin {- private coordinator: TranslationCoordinator | null = null;-- onEnable(context: PluginContext): Promise<void> {- this.coordinator = this.buildCoordinator(context);- context.registerHook('message:received', ctx => this.onMessage(context, ctx as HookContext<IncomingMessage>));- context.logger.log('Translation plugin enabled', { action: 'translation_enabled' });- return Promise.resolve();- }-- onConfigChange(context: PluginContext): Promise<void> {- // Rebuild the coordinator so a config edit (e.g. a new LibreTranslate URL/key saved from the- // dashboard) takes effect immediately, without a disable/enable cycle.- this.coordinator = this.buildCoordinator(context);- context.logger.log('Translation plugin config updated', { action: 'translation_config_changed' });- return Promise.resolve();- }-- private buildCoordinator(context: PluginContext): TranslationCoordinator {- const cfg = context.config;- const translator = new LibreTranslateClient({- url: readString(cfg, 'libretranslateUrl', 'http://localhost:7001'),- apiKey: readOptionalString(cfg, 'libretranslateApiKey'),- timeoutMs: readNumber(cfg, 'timeoutMs', 5000),- });- const store = new PluginConfigStore(context.storage);- const gateway = new PluginChatGateway(context.messages, context.engine);- const opts: CoordinatorOptions = {- prefix: readString(cfg, 'commandPrefix', '/tr'),- minLength: readNumber(cfg, 'minLength', 2),- maxLength: readNumber(cfg, 'maxLength', 2000),- denyReply: readBool(cfg, 'denyReply', false),- };- const logger: TranslationLogger = {- debug: (m, meta) => context.logger.debug(m, meta),- info: (m, meta) => context.logger.log(m, meta),- warn: (m, meta) => context.logger.warn(m, meta),- };- return new TranslationCoordinator(translator, store, gateway, opts, logger);- }-- onDisable(context: PluginContext): Promise<void> {- // The loader unregisters this plugin's hooks on disable; drop the coordinator too.- this.coordinator = null;- context.logger.log('Translation plugin disabled', { action: 'translation_disabled' });- return Promise.resolve();- }-- private async onMessage(context: PluginContext, ctx: HookContext<IncomingMessage>): Promise<HookResult> {- const msg = ctx.data;- // Only act on engine-originated inbound messages for a known session. The bot's own sends are- // `fromMe` and route through `message:sent`, so they never reach here (no translation loop).- if (!this.coordinator || ctx.source !== 'Engine' || !ctx.sessionId) {- return { continue: true };- }- try {- const inbound: InboundMessage = {- id: msg.id,- chatId: msg.chatId,- body: msg.body,- author: msg.author ?? '',- isGroup: msg.isGroup,- fromMe: msg.fromMe,- mentionedIds: msg.mentionedIds ?? [],- pushName: msg.contact?.pushName,- };- const { swallow } = await this.coordinator.handleMessage(ctx.sessionId, inbound);- return { continue: !swallow };- } catch (error) {- context.logger.error('Translation hook failed', error, {- sessionId: ctx.sessionId,- action: 'translation_hook_error',- });- return { continue: true };- }- }-}--export default TranslationPlugin;diff --git a/src/plugins/extensions/translation/libretranslate.client.spec.ts b/src/plugins/extensions/translation/libretranslate.client.spec.tsdeleted file mode 100644index f537a8302..000000000--- a/src/plugins/extensions/translation/libretranslate.client.spec.ts+++ /dev/null@@ -1,106 +0,0 @@-import { LibreTranslateClient } from './libretranslate.client';-import { SsrfBlockedError, withSafeFetch } from '../../../common/security/ssrf-guard';--// The client delegates the actual request to withSafeFetch (the IP-pinned, redirect-refusing primitive-// that the SSRF guard owns and ssrf-guard.spec.ts covers). Stub only that helper; keep SsrfBlockedError-// and isSsrfProtectionEnabled real so the client's circuit-exemption and guard-flag logic run for real.-jest.mock('../../../common/security/ssrf-guard', () => {- const actual = jest.requireActual<typeof import('../../../common/security/ssrf-guard')>(- '../../../common/security/ssrf-guard',- );- return { ...actual, withSafeFetch: jest.fn() };-});--const mockedWithSafeFetch = withSafeFetch as unknown as jest.Mock;--type CannedResponse = { ok: boolean; status?: number; json?: () => Promise<unknown> };-type WsfCall = [string, { method?: string; body?: string }, (r: unknown) => unknown, { guard: boolean }];--// Feed the client a canned response into its `use` callback, mirroring withSafeFetch's real contract-// (`return await use(response)`), so success/non-ok handling exercises the real client code.-const respondWith = (res: CannedResponse): void => {- mockedWithSafeFetch.mockImplementation((_url: string, _init: unknown, use: (r: unknown) => unknown) =>- Promise.resolve(use(res)),- );-};--describe('LibreTranslateClient', () => {- const ORIG_PROTECT = process.env.WEBHOOK_SSRF_PROTECT;- beforeEach(() => mockedWithSafeFetch.mockReset());- afterEach(() => {- if (ORIG_PROTECT === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;- else process.env.WEBHOOK_SSRF_PROTECT = ORIG_PROTECT;- });-- it('routes the request through the IP-pinned withSafeFetch helper (guard on by default)', async () => {- respondWith({ ok: true, json: () => Promise.resolve({ translatedText: 'Hola' }) });- const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000 });- await client.translate('Hello', 'en', 'es');- expect(mockedWithSafeFetch).toHaveBeenCalledTimes(1);- const [url, , , opts] = mockedWithSafeFetch.mock.calls[0] as WsfCall;- expect(url).toBe('http://lt:7001/translate');- expect(opts).toEqual({ guard: true });- });-- it('translate() sends q/source/target plus the api_key in the POST body and returns translatedText', async () => {- respondWith({ ok: true, json: () => Promise.resolve({ translatedText: 'Hola' }) });- const client = new LibreTranslateClient({ url: 'http://lt:7001', apiKey: 'secret', timeoutMs: 1000 });- const out = await client.translate('Hello', 'en', 'es');- expect(out).toBe('Hola');- const [, init] = mockedWithSafeFetch.mock.calls[0] as WsfCall;- expect(init.method).toBe('POST');- expect(JSON.parse(init.body as string) as Record<string, unknown>).toMatchObject({- q: 'Hello',- source: 'en',- target: 'es',- api_key: 'secret',- });- });-- it('detect() returns the top language', async () => {- respondWith({ ok: true, json: () => Promise.resolve([{ language: 'fr', confidence: 0.97 }]) });- const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000 });- expect(await client.detect('Bonjour')).toEqual({ lang: 'fr', confidence: 0.97 });- });-- it('languages() uses GET with no body', async () => {- respondWith({ ok: true, json: () => Promise.resolve([{ code: 'en' }, { code: 'es' }]) });- const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000 });- expect(await client.languages()).toEqual(['en', 'es']);- const [, init] = mockedWithSafeFetch.mock.calls[0] as WsfCall;- expect(init.method).toBe('GET');- expect(init.body).toBeUndefined();- });-- it('passes guard:false to withSafeFetch when SSRF protection is disabled', async () => {- process.env.WEBHOOK_SSRF_PROTECT = 'false';- respondWith({ ok: true, json: () => Promise.resolve({ translatedText: 'x' }) });- const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000 });- await client.translate('a', 'en', 'es');- const [, , , opts] = mockedWithSafeFetch.mock.calls[0] as WsfCall;- expect(opts).toEqual({ guard: false });- });-- it('propagates an SsrfBlockedError without tripping the circuit breaker', async () => {- mockedWithSafeFetch.mockRejectedValue(new SsrfBlockedError('blocked internal address'));- const client = new LibreTranslateClient({ url: 'http://lt:7001', timeoutMs: 1000, failureThreshold: 2 });- await expect(client.translate('a', 'en', 'es')).rejects.toThrow(SsrfBlockedError);- await expect(client.translate('a', 'en', 'es')).rejects.toThrow(SsrfBlockedError);- await expect(client.translate('a', 'en', 'es')).rejects.toThrow(SsrfBlockedError);- expect(client.isHealthy()).toBe(true);- });-- it('a non-ok response rejects and counts toward the circuit breaker', async () => {- respondWith({ ok: false, status: 500 });- const client = new LibreTranslateClient({- url: 'http://lt:7001',- timeoutMs: 1000,- failureThreshold: 2,- cooldownMs: 60000,- });- await expect(client.translate('a', 'en', 'es')).rejects.toThrow(/HTTP 500/);- await expect(client.translate('a', 'en', 'es')).rejects.toThrow(/HTTP 500/);- expect(client.isHealthy()).toBe(false);- await expect(client.translate('a', 'en', 'es')).rejects.toThrow(/circuit open/i);- });-});diff --git a/src/plugins/extensions/translation/libretranslate.client.ts b/src/plugins/extensions/translation/libretranslate.client.tsdeleted file mode 100644index 126704ebb..000000000--- a/src/plugins/extensions/translation/libretranslate.client.ts+++ /dev/null@@ -1,100 +0,0 @@-// src/modules/translation/adapters/libretranslate.client.ts-import { Translator, DetectResult } from './core/ports';-import { createLogger } from '../../../common/services/logger.service';-import { isSsrfProtectionEnabled, SsrfBlockedError, withSafeFetch } from '../../../common/security/ssrf-guard';--export interface LibreTranslateOptions {- url: string;- apiKey?: string;- timeoutMs: number;- failureThreshold?: number;- cooldownMs?: number;-}--export class LibreTranslateClient implements Translator {- private readonly logger = createLogger('LibreTranslateClient');- private readonly base: string;- private readonly failureThreshold: number;- private readonly cooldownMs: number;- private consecutiveFailures = 0;- private openUntil = 0;-- constructor(private readonly opts: LibreTranslateOptions) {- this.base = opts.url.replace(/\/+$/, '');- this.failureThreshold = opts.failureThreshold ?? 5;- this.cooldownMs = opts.cooldownMs ?? 30000;- }-- isHealthy(): boolean {- return this.consecutiveFailures < this.failureThreshold;- }-- async detect(text: string): Promise<DetectResult> {- const data = (await this.post('/detect', { q: text })) as Array<{ language: string; confidence: number }>;- const top = data[0];- if (!top) throw new Error('LibreTranslate /detect returned no result');- return { lang: top.language, confidence: top.confidence };- }-- async translate(text: string, source: string, target: string): Promise<string> {- const data = (await this.post('/translate', { q: text, source, target, format: 'text' })) as {- translatedText: string;- };- return data.translatedText;- }-- async languages(): Promise<string[]> {- const data = (await this.post('/languages', {}, 'GET')) as Array<{ code: string }>;- return data.map(l => l.code);- }-- private async post(- path: string,- payload: Record<string, unknown>,- method: 'GET' | 'POST' = 'POST',- ): Promise<unknown> {- const now = Date.now();- if (now < this.openUntil) {- throw new Error('LibreTranslate circuit open');- }-- const url = `${this.base}${path}`;- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), this.opts.timeoutMs);- try {- const body = method === 'POST' ? JSON.stringify({ ...payload, api_key: this.opts.apiKey }) : undefined;- // Route through the IP-pinned fetch: the host is validated once and the connection is pinned to the- // vetted address(es), closing the DNS-rebinding window between check and connect (the api_key- // travels in the body, so a rebind to an internal listener would otherwise exfiltrate it). Honors- // SSRF_ALLOWED_HOSTS for the documented localhost sidecar, and refuses redirects. When SSRF- // protection is disabled this degrades to a plain redirect-following fetch.- const data = await withSafeFetch(- url,- { method, headers: { 'Content-Type': 'application/json' }, body, signal: controller.signal },- async res => {- if (!res.ok) {- throw new Error(`LibreTranslate ${path} -> HTTP ${res.status}`);- }- return res.json();- },- { guard: isSsrfProtectionEnabled() },- );- this.consecutiveFailures = 0;- return data;- } catch (err) {- // A blocked-host SSRF error is a deterministic configuration problem, not a transient upstream- // failure — don't let it trip the circuit breaker (which exists to back off a flaky server).- if (err instanceof SsrfBlockedError) {- throw err;- }- this.consecutiveFailures++;- if (this.consecutiveFailures >= this.failureThreshold) {- this.openUntil = Date.now() + this.cooldownMs;- this.logger.warn(`LibreTranslate circuit opened for ${this.cooldownMs}ms`, { action: 'lt_circuit_open' });- }- throw err;- } finally {- clearTimeout(timer);- }- }-}diff --git a/src/plugins/extensions/translation/manifest.json b/src/plugins/extensions/translation/manifest.jsondeleted file mode 100644index f070a3d34..000000000--- a/src/plugins/extensions/translation/manifest.json+++ /dev/null@@ -1,54 +0,0 @@-{- "id": "translation",- "name": "Group Auto-Translation",- "version": "1.0.0",- "type": "extension",- "description": "Auto-translates group messages between participants' languages via LibreTranslate. Configure in-group with /tr commands. Disabled by default.",- "main": "index.ts",- "permissions": ["messages:send", "engine:read"],- "sessions": ["*"],- "configSchema": {- "type": "object",- "properties": {- "libretranslateUrl": {- "type": "string",- "title": "LibreTranslate URL",- "description": "Base URL of the LibreTranslate instance (e.g. http://libretranslate:7001). With SSRF protection on (the default), a loopback/internal URL such as http://localhost:7001 must be added to SSRF_ALLOWED_HOSTS.",- "default": "http://localhost:7001",- "required": true- },- "libretranslateApiKey": {- "type": "string",- "title": "LibreTranslate API key",- "description": "Optional API key, if your LibreTranslate instance requires one.",- "secret": true- },- "timeoutMs": {- "type": "number",- "title": "Translate timeout (ms)",- "default": 5000- },- "commandPrefix": {- "type": "string",- "title": "Command prefix",- "default": "/tr"- },- "minLength": {- "type": "number",- "title": "Min message length to translate",- "default": 2- },- "maxLength": {- "type": "number",- "title": "Max message length to translate",- "default": 2000- },- "denyReply": {- "type": "boolean",- "title": "Reply on denied commands",- "description": "If true, reply with an 'admins only' message when a non-admin runs a restricted command.",- "default": false- }- }- }-}diff --git a/src/plugins/extensions/translation/plugin-chat.gateway.spec.ts b/src/plugins/extensions/translation/plugin-chat.gateway.spec.tsdeleted file mode 100644index aadeb8cae..000000000--- a/src/plugins/extensions/translation/plugin-chat.gateway.spec.ts+++ /dev/null@@ -1,45 +0,0 @@-import { PluginChatGateway } from './plugin-chat.gateway';--describe('PluginChatGateway', () => {- it('sendText routes through ctx.messages.sendText', async () => {- const messages = { sendText: jest.fn(() => Promise.resolve({})), reply: jest.fn(() => Promise.resolve({})) };- const engine = { getGroupInfo: jest.fn() };- const gw = new PluginChatGateway(messages as never, engine as never);- await gw.sendText('s', '[email protected]', 'hi');- expect(messages.sendText).toHaveBeenCalledWith('s', '[email protected]', 'hi');- });-- it('sendCombinedReply routes through ctx.messages.reply', async () => {- const messages = { sendText: jest.fn(() => Promise.resolve({})), reply: jest.fn(() => Promise.resolve({})) };- const engine = { getGroupInfo: jest.fn() };- const gw = new PluginChatGateway(messages as never, engine as never);- await gw.sendCombinedReply('s', '[email protected]', 'M1', 'Hola');- expect(messages.reply).toHaveBeenCalledWith('s', '[email protected]', 'M1', 'Hola');- });-- it('getGroupAdmins includes phone-scheme admins + the LID owner, deduped', async () => {- const messages = { sendText: jest.fn(), reply: jest.fn() };- const engine = {- getGroupInfo: jest.fn(() =>- Promise.resolve({- owner: '149207180681386@lid',- participants: [- { id: '[email protected]', isAdmin: true, isSuperAdmin: true },- { id: '[email protected]', isAdmin: false, isSuperAdmin: false },- ],- }),- ),- };- const gw = new PluginChatGateway(messages, engine as never);- const admins = await gw.getGroupAdmins('s', '[email protected]');- expect(admins).toContain('[email protected]');- expect(admins).toContain('149207180681386@lid');- });-- it('getGroupAdmins returns [] when there is no group info', async () => {- const messages = { sendText: jest.fn(), reply: jest.fn() };- const engine = { getGroupInfo: jest.fn(() => Promise.resolve(null)) };- const gw = new PluginChatGateway(messages, engine as never);- expect(await gw.getGroupAdmins('s', '[email protected]')).toEqual([]);- });-});diff --git a/src/plugins/extensions/translation/plugin-chat.gateway.ts b/src/plugins/extensions/translation/plugin-chat.gateway.tsdeleted file mode 100644index 1a226e21d..000000000--- a/src/plugins/extensions/translation/plugin-chat.gateway.ts+++ /dev/null@@ -1,35 +0,0 @@-import { ChatGateway } from './core/ports';-import { PluginMessagingCapability, PluginEngineReadCapability } from '../../../core/plugins';--/**- * ChatGateway backed by the Tier-2 plugin capability surface: writes go through- * `ctx.messages` (routed via MessageService, so persistence is preserved), and group-admin- * reads through `ctx.engine`. It implements the same port the translation core already- * depends on, so the coordinator/parser/formatter are reused unchanged.- */-export class PluginChatGateway implements ChatGateway {- constructor(- private readonly messages: PluginMessagingCapability,- private readonly engine: PluginEngineReadCapability,- ) {}-- async sendText(sessionId: string, chatId: string, text: string): Promise<void> {- await this.messages.sendText(sessionId, chatId, text);- }-- async sendCombinedReply(sessionId: string, chatId: string, quotedMessageId: string, text: string): Promise<void> {- await this.messages.reply(sessionId, chatId, quotedMessageId, text);- }-- async getGroupAdmins(sessionId: string, chatId: string): Promise<string[]> {- const info = await this.engine.getGroupInfo(sessionId, chatId);- if (!info) return [];- const admins = info.participants.filter(p => p.isAdmin || p.isSuperAdmin).map(p => p.id);- // Participant ids can be in the phone (@c.us) scheme while message authors arrive as LID- // (@lid). The group `owner` is reported in the author's scheme, so include it to recognize- // the group creator across that split. Non-owner admins on a differing scheme can be granted- // control via `/tr grant`.- if (info.owner) admins.push(info.owner);- return [...new Set(admins)];- }-}diff --git a/src/plugins/extensions/translation/plugin-config.store.spec.ts b/src/plugins/extensions/translation/plugin-config.store.spec.tsdeleted file mode 100644index 34abb2487..000000000--- a/src/plugins/extensions/translation/plugin-config.store.spec.ts+++ /dev/null@@ -1,44 +0,0 @@-import { PluginConfigStore } from './plugin-config.store';-import { GroupState } from './core/ports';--function makeStorage() {- const data = new Map<string, unknown>();- return {- get: jest.fn((k: string) => Promise.resolve(data.has(k) ? data.get(k) : null)),- set: jest.fn((k: string, v: unknown) => {- data.set(k, v);- return Promise.resolve();- }),- delete: jest.fn((k: string) => {- data.delete(k);- return Promise.resolve();- }),- list: jest.fn(() => Promise.resolve([...data.keys()])),- };-}--describe('PluginConfigStore', () => {- it('returns a default inactive state for an unknown group', async () => {- const store = new PluginConfigStore(makeStorage() as never);- const state = await store.load('s', '[email protected]');- expect(state).toMatchObject({ sessionId: 's', chatId: '[email protected]', active: false, announced: false });- expect(state.participants).toEqual({});- expect(state.delegatedControllers).toEqual([]);- });-- it('round-trips a saved state under a per-group key', async () => {- const storage = makeStorage();- const store = new PluginConfigStore(storage as never);- const state: GroupState = {- sessionId: 's',- chatId: '[email protected]',- active: true,- participants: { '111@lid': { lang: 'en', source: 'pinned', enabled: true, samples: 1, updatedAt: 'x' } },- delegatedControllers: ['222@lid'],- announced: true,- };- await store.save(state);- expect(storage.set).toHaveBeenCalledWith('group:s:[email protected]', state);- expect(await store.load('s', '[email protected]')).toEqual(state);- });-});diff --git a/src/plugins/extensions/translation/plugin-config.store.ts b/src/plugins/extensions/translation/plugin-config.store.tsdeleted file mode 100644index 4a081e891..000000000--- a/src/plugins/extensions/translation/plugin-config.store.ts+++ /dev/null@@ -1,34 +0,0 @@-import { ConfigStore, GroupState } from './core/ports';-import { PluginStorage } from '../../../core/plugins';--/**- * ConfigStore backed by the plugin's KV storage (`ctx.storage`). Persists one GroupState- * JSON document per (sessionId, chatId) and returns a default inactive state for groups the- * bot hasn't met yet. Replaces the TypeORM entity/migration the core-module version used —- * a plugin owns its own state via the capability surface.- */-export class PluginConfigStore implements ConfigStore {- constructor(private readonly storage: PluginStorage) {}-- private key(sessionId: string, chatId: string): string {- return `group:${sessionId}:${chatId}`;- }-- async load(sessionId: string, chatId: string): Promise<GroupState> {- const stored = await this.storage.get<GroupState>(this.key(sessionId, chatId));- return (- stored ?? {- sessionId,- chatId,- active: false,- participants: {},- delegatedControllers: [],- announced: false,- }- );- }-- async save(state: GroupState): Promise<void> {- await this.storage.set(this.key(state.sessionId, state.chatId), state);- }-}