Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(automation): reply to inbound messages with per-session autoreply rules
Yudhi Armyndharis6b88b2842ec0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6dfbfff8c..783090f7c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Autoreply automation rules.** Per-session single-message rules under+ `POST|GET|PUT|DELETE /api/sessions/:sessionId/automation-rules`: when an inbound message matches a+ rule's conditions — the same filter format (and evaluator) webhook filters use — the gateway+ replies into the chat with the rule's text. Rules evaluate in creation order, first match wins,+ and the reply flows through the ordinary send path, so send pacing and plugin vetoes apply to it+ like any other outbound message. Three guards bound reply loops: rules never answer the+ account's own messages, messages older than five minutes get no automated answer (a reconnect+ never burst-replies the offline backlog), and a per-chat `cooldownSeconds` (default 60)+ rate-bounds a rule after it fires. Evaluation is fire-and-forget off the receive path and+ deduplicated per message. Two read-only+ agent tools (`AutomationRuleFindAll`, `AutomationRuleFindOne`) expose the rules to MCP callers;+ as operator-level configuration the module is not part of the SDK surface.+### Fixed- **Status posting on the whatsapp-web.js engine, which current WhatsApp Web had broken outright.**diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 5f45742be..3b14c64b0 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5706,6 +5706,77 @@ Request body and errors are identical to the voice endpoint.same `MEDIA_CONVERSION_MAX_OUTPUT_BYTES` cap (default 50 MiB) — and a client posting it onward isstill bound by `BODY_SIZE_LIMIT` (default 25 MiB) on that next request.+### 6.4.16 Automation rules (autoreply)++Single-message autoreply rules, managed under `/api/sessions/:sessionId/automation-rules`+(`AutomationRuleController`). Every route requires an API key with **OPERATOR** role or higher.++When an inbound message arrives, the session's enabled rules are evaluated in order — creation+time, `id` as the same-second tiebreak — and the **first** rule whose `conditions` match replies+into the chat with its `replyText`. The reply goes through the ordinary send path, so send pacing+and plugin vetoes apply to it like any other outbound message. Evaluation is fire-and-forget off+the receive path and runs at most once per message (engine re-fires are deduplicated).++`conditions` uses the **webhook filter format** (`message` family — see 6.4.8): a flat AND list of+conditions over `sender`, `recipient`, `body`, `type`, `isGroup`, `fromMe`, `hasMedia`, `mentions`.+Omitted or empty conditions match every inbound message.++Loop safety: a rule never answers the account's own (`fromMe`) messages, messages older than+5 minutes get no automated answer (so a reconnect never burst-replies the offline-queued backlog),+and `cooldownSeconds` (default 60, `0` disables, max 86400) keeps the rule quiet per chat after it+fires. Be clear about what this guarantees: the cooldown **rate-bounds** an+autoreply-vs-autoreply exchange with another bot, it does not terminate one — and+`cooldownSeconds: 0` removes that bound entirely, so disable it only for rules whose conditions+cannot match another bot's replies. The cooldown state is in-process: it resets on restart.++#### POST /api/sessions/:sessionId/automation-rules++Create a rule. **Auth:** API key (OPERATOR)++**Request body**++| Field | Type | Required | Description |+| --- | --- | --- | --- |+| name | string | yes | Display name, max 100 chars. |+| replyText | string | yes | Reply content, max 4096 chars (the send-text limit). |+| conditions | object | no | Webhook-filter conditions (`message` family). Omitted = match all. |+| cooldownSeconds | number | no | Per-chat quiet period, 0–86400. Default `60`. |+| enabled | boolean | no | Default `true`. |++**Response** `201`++```json+{+ "id": "f1e2d3c4-b5a6-7890-1234-567890abcdef",+ "sessionId": "0d7a2a4e-...",+ "name": "Greet new enquiries",+ "enabled": true,+ "conditions": { "conditions": [{ "field": "body", "operator": "contains", "value": "price" }] },+ "replyText": "Thanks for reaching out — we reply within the hour.",+ "cooldownSeconds": 60,+ "createdAt": "2026-08-04T10:00:00.000Z",+ "updatedAt": "2026-08-04T10:00:00.000Z"+}+```++`400` — invalid conditions (unknown field/operator, over-limit values) or over-limit text.++#### GET /api/sessions/:sessionId/automation-rules++List the session's rules in evaluation order. **Auth:** API key (OPERATOR) · **Response** `200` — array of the shape above.++#### GET /api/sessions/:sessionId/automation-rules/:ruleId++Get one rule. **Auth:** API key (OPERATOR) · `200` or `404` when the rule does not belong to the session.++#### PUT /api/sessions/:sessionId/automation-rules/:ruleId++Partial update (any subset of the create fields). **Auth:** API key (OPERATOR) · `200` or `404`.++#### DELETE /api/sessions/:sessionId/automation-rules/:ruleId++Delete a rule. **Auth:** API key (OPERATOR) · **Response** `204`.+## 6.5 Real-time API (WebSocket)Live events are delivered over a **Socket.IO** connection (not a raw WebSocket). The server mounts a single Socket.IO namespace, **`/events`**, on the same port as the REST API. There are no REST routes in this module.diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex 3225269e9..625f0b008 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -192,6 +192,7 @@ authoritative gate. Current policy:| `src/engine/identity/` | 85% | 95% | 94% | 93% || `src/modules/audit/` | 59% | 45% | 72% | 68% || `src/modules/auth/` | 75% | 85% | 86% | 85% |+| `src/modules/automation/` | 60% | 55% | 75% | 70% || `src/modules/chat-media/` | 78% | 81% | 92% | 90% || `src/modules/contact/` | 25% | 48% | 44% | 43% || `src/modules/docker/` | 26% | 52% | 37% | 38% |diff --git a/openapi.json b/openapi.jsonindex a95328a41..31964a878 100644--- a/openapi.json+++ b/openapi.json@@ -1504,6 +1504,205 @@]}},+ "/api/sessions/{sessionId}/automation-rules": {+ "post": {+ "operationId": "AutomationRuleController_create",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateAutomationRuleDto"+ }+ }+ }+ },+ "responses": {+ "201": {+ "description": "Rule created.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AutomationRuleResponseDto"+ }+ }+ }+ },+ "400": {+ "description": "Invalid rule (bad conditions, over-limit text)."+ }+ },+ "summary": "Create an autoreply rule",+ "tags": [+ "automation"+ ]+ },+ "get": {+ "operationId": "AutomationRuleController_findAll",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Rules in evaluation order: creation time, id as the same-second tiebreak."+ }+ },+ "summary": "List the session’s autoreply rules",+ "tags": [+ "automation"+ ]+ }+ },+ "/api/sessions/{sessionId}/automation-rules/{ruleId}": {+ "get": {+ "operationId": "AutomationRuleController_findOne",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "ruleId",+ "required": true,+ "in": "path",+ "description": "Rule ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "The rule.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AutomationRuleResponseDto"+ }+ }+ }+ },+ "404": {+ "description": "No such rule in this session."+ }+ },+ "summary": "Get one autoreply rule",+ "tags": [+ "automation"+ ]+ },+ "put": {+ "operationId": "AutomationRuleController_update",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "ruleId",+ "required": true,+ "in": "path",+ "description": "Rule ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateAutomationRuleDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Updated rule.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AutomationRuleResponseDto"+ }+ }+ }+ },+ "404": {+ "description": "No such rule in this session."+ }+ },+ "summary": "Update an autoreply rule",+ "tags": [+ "automation"+ ]+ },+ "delete": {+ "operationId": "AutomationRuleController_remove",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "ruleId",+ "required": true,+ "in": "path",+ "description": "Rule ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "204": {+ "description": "Rule deleted."+ },+ "404": {+ "description": "No such rule in this session."+ }+ },+ "summary": "Delete an autoreply rule",+ "tags": [+ "automation"+ ]+ }+ },"/api/sessions/{sessionId}/messages": {"get": {"operationId": "MessageController_getMessages",@@ -7882,6 +8081,118 @@}}},+ "CreateAutomationRuleDto": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "Display name for the rule",+ "example": "Greet new enquiries",+ "maxLength": 100+ },+ "replyText": {+ "type": "string",+ "description": "Text sent back into the chat when the rule matches",+ "example": "Thanks for reaching out — we reply within the hour.",+ "maxLength": 4096+ },+ "conditions": {+ "type": "object",+ "description": "Match conditions in the webhook filter format (message family: sender, recipient, body, type, isGroup, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or empty means the rule matches every inbound message."+ },+ "cooldownSeconds": {+ "type": "number",+ "description": "Quiet period per chat, in seconds: after the rule replies in a chat it stays silent there for this long (default 60, 0 disables). This is the guard against two auto-repliers answering each other forever, so disable it knowingly.",+ "default": 60,+ "minimum": 0,+ "maximum": 86400+ },+ "enabled": {+ "type": "boolean",+ "description": "Whether the rule is active",+ "default": true+ }+ },+ "required": [+ "name",+ "replyText"+ ]+ },+ "AutomationRuleResponseDto": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "sessionId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "enabled": {+ "type": "boolean"+ },+ "conditions": {+ "type": "object",+ "description": "Match conditions in the webhook filter format (message family: sender, recipient, body, type, isGroup, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or empty means the rule matches every inbound message.",+ "nullable": true+ },+ "replyText": {+ "type": "string"+ },+ "cooldownSeconds": {+ "type": "number"+ },+ "createdAt": {+ "format": "date-time",+ "type": "string"+ },+ "updatedAt": {+ "format": "date-time",+ "type": "string"+ }+ },+ "required": [+ "id",+ "sessionId",+ "name",+ "enabled",+ "replyText",+ "cooldownSeconds",+ "createdAt",+ "updatedAt"+ ]+ },+ "UpdateAutomationRuleDto": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "Display name for the rule",+ "maxLength": 100+ },+ "replyText": {+ "type": "string",+ "description": "Text sent back into the chat when the rule matches",+ "maxLength": 4096+ },+ "conditions": {+ "type": "object",+ "description": "Match conditions in the webhook filter format (message family: sender, recipient, body, type, isGroup, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or empty means the rule matches every inbound message."+ },+ "cooldownSeconds": {+ "type": "number",+ "description": "Quiet period per chat, in seconds: after the rule replies in a chat it stays silent there for this long (default 60, 0 disables). This is the guard against two auto-repliers answering each other forever, so disable it knowingly.",+ "minimum": 0,+ "maximum": 86400+ },+ "enabled": {+ "type": "boolean",+ "description": "Whether the rule is active"+ }+ }+ },"CustomLinkPreviewDto": {"type": "object","properties": {diff --git a/package.json b/package.jsonindex e9010bf06..5c75a970e 100644--- a/package.json+++ b/package.json@@ -251,6 +251,12 @@"lines": 86,"statements": 85},+ "./src/modules/automation/": {+ "branches": 60,+ "functions": 55,+ "lines": 75,+ "statements": 70+ },"./src/modules/chat-media/": {"branches": 78,"functions": 81,diff --git a/sdk/README.md b/sdk/README.mdindex 061509ec6..f70790afa 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -42,8 +42,9 @@ All five SDKs expose the same fluent resource surface:| `health` | check, live, ready |> ⚠️ Endpoints requiring an `OPERATOR`-level API key are noted in the inline-> docs. Operator-only modules (`docker`, `metrics`, `infra`, `plugins`, `mcp`)-> are intentionally **not** exposed in the SDK; all user-facing resources are.+> docs. Operator-only modules (`docker`, `metrics`, `infra`, `plugins`, `mcp`,+> `automation`) are intentionally **not** exposed in the SDK; all user-facing+> resources are.## JavaScript / TypeScriptdiff --git a/src/app.module.ts b/src/app.module.tsindex b5cc8621e..6ffea742f 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -35,6 +35,7 @@ import { StatusModule } from './modules/status/status.module';import { MediaModule } from './modules/media/media.module';import { StatusStoreModule } from './modules/status-store/status-store.module';import { ChatMediaModule } from './modules/chat-media/chat-media.module';+import { AutomationModule } from './modules/automation/automation.module';import { CatalogModule } from './modules/catalog/catalog.module';import { HooksModule } from './core/hooks';import { PluginsModule } from './core/plugins';@@ -164,6 +165,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {__dirname + '/engine/**/*.entity{.ts,.js}',__dirname + '/modules/integration/**/*.entity{.ts,.js}',__dirname + '/modules/status-store/**/*.entity{.ts,.js}',+ __dirname + '/modules/automation/**/*.entity{.ts,.js}',],migrations: [__dirname + '/database/migrations/*{.ts,.js}'],logging: configService.get<boolean>('dataDatabase.logging', false),@@ -297,6 +299,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {MediaModule, // Server-side media conversion (opt-in)StatusStoreModule, // Phase 3: inbound status/story TTL store (24h purge + media persistence)ChatMediaModule, // opt-in chat-media archive (retention purge + orphan sweep)+ AutomationModule, // single-message autoreply rules, evaluated on the inbound dispatchCatalogModule, // Phase 3: Catalog API (WhatsApp Business)PluginsApiModule, // Phase 5: Plugins APIAgentToolsModule, // Agent-invocable tool registry (protocol-neutral)diff --git a/src/core/agent-tools/agent-tools.module.ts b/src/core/agent-tools/agent-tools.module.tsindex 86f0e8967..1343b96aa 100644--- a/src/core/agent-tools/agent-tools.module.ts+++ b/src/core/agent-tools/agent-tools.module.ts@@ -6,21 +6,31 @@ import { ContactModule } from '../../modules/contact/contact.module';import { GroupModule } from '../../modules/group/group.module';import { WebhookModule } from '../../modules/webhook/webhook.module';import { LabelModule } from '../../modules/label/label.module';+import { AutomationModule } from '../../modules/automation/automation.module';import { SessionService } from '../../modules/session/session.service';import { MessageService } from '../../modules/message/message.service';import { ContactService } from '../../modules/contact/contact.service';import { GroupService } from '../../modules/group/group.service';import { WebhookService } from '../../modules/webhook/webhook.service';import { LabelService } from '../../modules/label/label.service';+import { AutomationRulesService } from '../../modules/automation/automation-rules.service';import { allAgentTools } from './tools';@Global()@Module({- imports: [SessionModule, MessageModule, ContactModule, GroupModule, WebhookModule, LabelModule],+ imports: [SessionModule, MessageModule, ContactModule, GroupModule, WebhookModule, LabelModule, AutomationModule],providers: [{provide: ToolRegistryService,- inject: [SessionService, MessageService, ContactService, GroupService, WebhookService, LabelService],+ inject: [+ SessionService,+ MessageService,+ ContactService,+ GroupService,+ WebhookService,+ LabelService,+ AutomationRulesService,+ ],useFactory: (session: SessionService,message: MessageService,@@ -28,7 +38,8 @@ import { allAgentTools } from './tools';group: GroupService,webhook: WebhookService,labels: LabelService,- ) => new ToolRegistryService(allAgentTools({ session, message, contact, group, webhook, labels })),+ automation: AutomationRulesService,+ ) => new ToolRegistryService(allAgentTools({ session, message, contact, group, webhook, labels, automation })),},],exports: [ToolRegistryService],diff --git a/src/core/agent-tools/tool-registry.spec.ts b/src/core/agent-tools/tool-registry.spec.tsindex 8e5d2ec99..c3851f827 100644--- a/src/core/agent-tools/tool-registry.spec.ts+++ b/src/core/agent-tools/tool-registry.spec.ts@@ -89,11 +89,13 @@ describe('v1 tool surface snapshot', () => {'LabelDelete','LabelAddToChat','LabelRemoveFromChat',+ 'AutomationRuleFindAll',+ 'AutomationRuleFindOne',].sort();const actualNames = [...allAgentTools({} as never)].map(t => t.name).sort();expect(actualNames).toEqual(expected);- expect(expected).toHaveLength(49);+ expect(expected).toHaveLength(51);});});diff --git a/src/core/agent-tools/tools/automation.tools.ts b/src/core/agent-tools/tools/automation.tools.tsnew file mode 100644index 000000000..057249b06--- /dev/null+++ b/src/core/agent-tools/tools/automation.tools.ts@@ -0,0 +1,37 @@+import { z } from 'zod';+import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';+import type { AutomationRulesService } from '../../../modules/automation/automation-rules.service';+import { AutomationRuleResponseDto } from '../../../modules/automation/dto/automation-rule.dto';+import { defineTool, type AnyToolDescriptor } from '../tool-descriptor';++const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');++export function automationTools(automation: AutomationRulesService): AnyToolDescriptor[] {+ return [+ defineTool({+ name: 'AutomationRuleFindAll',+ description: 'List a session’s autoreply rules in evaluation order (creation time, id as tiebreak).',+ tier: 'read',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({ sessionId }),+ handler: input =>+ automation+ .findAll(input.sessionId)+ .then(rules => rules.map(rule => AutomationRuleResponseDto.fromEntity(rule))),+ }),+ defineTool({+ name: 'AutomationRuleFindOne',+ description: 'Get one autoreply rule by ID within a session.',+ tier: 'read',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ ruleId: z.string().describe('Rule UUID'),+ }),+ handler: input =>+ automation.findOne(input.sessionId, input.ruleId).then(rule => AutomationRuleResponseDto.fromEntity(rule)),+ }),+ ];+}diff --git a/src/core/agent-tools/tools/index.ts b/src/core/agent-tools/tools/index.tsindex f2a1c85fa..66158e7d9 100644--- a/src/core/agent-tools/tools/index.ts+++ b/src/core/agent-tools/tools/index.ts@@ -4,6 +4,7 @@ import type { ContactService } from '../../../modules/contact/contact.service';import type { GroupService } from '../../../modules/group/group.service';import type { WebhookService } from '../../../modules/webhook/webhook.service';import type { LabelService } from '../../../modules/label/label.service';+import type { AutomationRulesService } from '../../../modules/automation/automation-rules.service';import type { AnyToolDescriptor } from '../tool-descriptor';import { sessionTools } from './session.tools';import { messageTools } from './message.tools';@@ -11,6 +12,7 @@ import { contactTools } from './contact.tools';import { groupTools } from './group.tools';import { webhookTools } from './webhook.tools';import { labelTools } from './label.tools';+import { automationTools } from './automation.tools';/** The services each tool family needs. Stubs suffice where a spec only inspects declarations. */export interface AgentToolDeps {@@ -20,6 +22,7 @@ export interface AgentToolDeps {group: GroupService;webhook: WebhookService;labels: LabelService;+ automation: AutomationRulesService;}/**@@ -38,5 +41,6 @@ export function allAgentTools(deps: AgentToolDeps): AnyToolDescriptor[] {...groupTools(deps.group),...webhookTools(deps.webhook),...labelTools(deps.labels),+ ...automationTools(deps.automation),];}diff --git a/src/database/data-source.ts b/src/database/data-source.tsindex a917e2cbd..c1d02e1de 100644--- a/src/database/data-source.ts+++ b/src/database/data-source.ts@@ -32,6 +32,7 @@ const dataEntities = [sourceGlob('..', 'engine', '**', '*.entity{.ts,.js}'),sourceGlob('..', 'modules', 'integration', '**', '*.entity{.ts,.js}'),sourceGlob('..', 'modules', 'status-store', '**', '*.entity{.ts,.js}'),+ sourceGlob('..', 'modules', 'automation', '**', '*.entity{.ts,.js}'),];const dataMigrations = [sourceGlob('migrations', '*{.ts,.js}')];diff --git a/src/database/migrations/1785900000000-AddAutomationRules.ts b/src/database/migrations/1785900000000-AddAutomationRules.tsnew file mode 100644index 000000000..c24700e0e--- /dev/null+++ b/src/database/migrations/1785900000000-AddAutomationRules.ts@@ -0,0 +1,43 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Creates `automation_rules` — per-session single-message autoreply rules. `conditions` is stored as+ * plain text (same reasoning as `webhooks.filters`: `simple-json` on both dialects, never jsonb).+ * CASCADE FK to sessions: a rule has no meaning after its session is gone. Hand-authored because+ * `synchronize` is off on the `data` connection for Postgres (and optional on SQLite).+ */+export class AddAutomationRules1785900000000 implements MigrationInterface {+ name = 'AddAutomationRules1785900000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (await queryRunner.hasTable('automation_rules')) return;+ const isPostgres = queryRunner.dataSource.options.type === 'postgres';++ if (isPostgres) {+ await queryRunner.query(+ `CREATE TABLE "automation_rules" ("id" varchar PRIMARY KEY NOT NULL DEFAULT gen_random_uuid()::varchar, ` ++ `"sessionId" varchar NOT NULL, "name" varchar(100) NOT NULL, "enabled" boolean NOT NULL DEFAULT true, ` ++ `"conditions" text, "replyText" text NOT NULL, "cooldownSeconds" integer NOT NULL DEFAULT 60, ` ++ `"createdAt" timestamp NOT NULL DEFAULT NOW(), "updatedAt" timestamp NOT NULL DEFAULT NOW(), ` ++ `CONSTRAINT "FK_automation_rules_sessionId" FOREIGN KEY ("sessionId") REFERENCES "sessions" ("id") ON DELETE CASCADE)`,+ );+ } else {+ await queryRunner.query(+ `CREATE TABLE "automation_rules" ("id" varchar PRIMARY KEY NOT NULL, ` ++ `"sessionId" varchar NOT NULL, "name" varchar(100) NOT NULL, "enabled" boolean NOT NULL DEFAULT (1), ` ++ `"conditions" text, "replyText" text NOT NULL, "cooldownSeconds" integer NOT NULL DEFAULT (60), ` ++ `"createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), ` ++ `CONSTRAINT "FK_automation_rules_sessionId" FOREIGN KEY ("sessionId") REFERENCES "sessions" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`,+ );+ }++ await queryRunner.query(`CREATE INDEX "IDX_automation_rules_sessionId" ON "automation_rules" ("sessionId")`);+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ // IF EXISTS so revert is idempotent on a synchronize-bootstrapped DB, where this migration was+ // recorded via the up() hasTable early-return and the named index was never created.+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_automation_rules_sessionId"`);+ await queryRunner.query(`DROP TABLE IF EXISTS "automation_rules"`);+ }+}diff --git a/src/modules/automation/automation-rule.controller.ts b/src/modules/automation/automation-rule.controller.tsnew file mode 100644index 000000000..00dad5a55--- /dev/null+++ b/src/modules/automation/automation-rule.controller.ts@@ -0,0 +1,78 @@+import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put } from '@nestjs/common';+import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';+import { RequireRole } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { AutomationRulesService } from './automation-rules.service';+import { AutomationRuleResponseDto, CreateAutomationRuleDto, UpdateAutomationRuleDto } from './dto/automation-rule.dto';++@ApiTags('automation')+@Controller('sessions/:sessionId/automation-rules')+export class AutomationRuleController {+ constructor(private readonly automationRules: AutomationRulesService) {}++ @Post()+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Create an autoreply rule' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({ status: 201, description: 'Rule created.', type: AutomationRuleResponseDto })+ @ApiResponse({ status: 400, description: 'Invalid rule (bad conditions, over-limit text).' })+ async create(+ @Param('sessionId') sessionId: string,+ @Body() dto: CreateAutomationRuleDto,+ ): Promise<AutomationRuleResponseDto> {+ return AutomationRuleResponseDto.fromEntity(await this.automationRules.create(sessionId, dto));+ }++ @Get()+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'List the session’s autoreply rules' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({+ status: 200,+ description: 'Rules in evaluation order: creation time, id as the same-second tiebreak.',+ })+ async findAll(@Param('sessionId') sessionId: string): Promise<AutomationRuleResponseDto[]> {+ return (await this.automationRules.findAll(sessionId)).map(rule => AutomationRuleResponseDto.fromEntity(rule));+ }++ @Get(':ruleId')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Get one autoreply rule' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'ruleId', description: 'Rule ID' })+ @ApiResponse({ status: 200, description: 'The rule.', type: AutomationRuleResponseDto })+ @ApiResponse({ status: 404, description: 'No such rule in this session.' })+ async findOne(+ @Param('sessionId') sessionId: string,+ @Param('ruleId') ruleId: string,+ ): Promise<AutomationRuleResponseDto> {+ return AutomationRuleResponseDto.fromEntity(await this.automationRules.findOne(sessionId, ruleId));+ }++ @Put(':ruleId')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({ summary: 'Update an autoreply rule' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'ruleId', description: 'Rule ID' })+ @ApiResponse({ status: 200, description: 'Updated rule.', type: AutomationRuleResponseDto })+ @ApiResponse({ status: 404, description: 'No such rule in this session.' })+ async update(+ @Param('sessionId') sessionId: string,+ @Param('ruleId') ruleId: string,+ @Body() dto: UpdateAutomationRuleDto,+ ): Promise<AutomationRuleResponseDto> {+ return AutomationRuleResponseDto.fromEntity(await this.automationRules.update(sessionId, ruleId, dto));+ }++ @Delete(':ruleId')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.NO_CONTENT)+ @ApiOperation({ summary: 'Delete an autoreply rule' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'ruleId', description: 'Rule ID' })+ @ApiResponse({ status: 204, description: 'Rule deleted.' })+ @ApiResponse({ status: 404, description: 'No such rule in this session.' })+ async remove(@Param('sessionId') sessionId: string, @Param('ruleId') ruleId: string): Promise<void> {+ await this.automationRules.remove(sessionId, ruleId);+ }+}diff --git a/src/modules/automation/automation-rules.service.spec.ts b/src/modules/automation/automation-rules.service.spec.tsnew file mode 100644index 000000000..e6b7cb504--- /dev/null+++ b/src/modules/automation/automation-rules.service.spec.ts@@ -0,0 +1,225 @@+// Rule CRUD must be scoped to the URL :sessionId (an OPERATOR key for one session must not read,+// edit or delete another session's rules), and the inbound evaluator carries the loop-safety+// contract: never reply to fromMe, one reply per message (first match), one reply per chat per+// cooldown window, and no failure may escape into the receive path. These run against a real+// in-memory DB so scoping and ordering are exercised end-to-end, not asserted on a mock's WHERE.+import { DataSource } from 'typeorm';+import { NotFoundException } from '@nestjs/common';+import { AutomationRulesService } from './automation-rules.service';+import { AutomationRule } from './entities/automation-rule.entity';+import { Session, SessionStatus } from '../session/entities/session.entity';+import type { MessageService } from '../message/message.service';+import type { ModuleRef } from '@nestjs/core';++describe('AutomationRulesService', () => {+ let ds: DataSource;+ let service: AutomationRulesService;+ let sends: Array<{ sessionId: string; chatId: string; text: string }>;+ let sendImpl: (sessionId: string, dto: { chatId: string; text: string }) => Promise<unknown>;++ const moduleRefStub = {+ get: () =>+ ({+ sendText: (sessionId: string, dto: { chatId: string; text: string }) => sendImpl(sessionId, dto),+ }) as unknown as MessageService,+ } as unknown as ModuleRef;++ beforeEach(async () => {+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [Session, AutomationRule],+ synchronize: true,+ });+ await ds.initialize();+ const sessions = ds.getRepository(Session);+ for (const id of ['sessA', 'sessB']) {+ await sessions.save(sessions.create({ id, name: id, status: SessionStatus.READY, config: {} }));+ }+ sends = [];+ sendImpl = (sessionId, dto) => {+ sends.push({ sessionId, chatId: dto.chatId, text: dto.text });+ return Promise.resolve({});+ };+ service = new AutomationRulesService(ds.getRepository(AutomationRule), moduleRefStub, undefined);+ });++ afterEach(async () => {+ await ds.destroy();+ });++ const inbound = (over: Record<string, unknown> = {}): Record<string, unknown> => ({+ id: 'wamid.1',+ from: '[email protected]',+ to: '[email protected]',+ chatId: '[email protected]',+ body: 'hello there',+ type: 'text',+ fromMe: false,+ isGroup: false,+ ...over,+ });++ describe('CRUD scoping', () => {+ it('create applies the defaults: enabled, 60s cooldown, no conditions', async () => {+ const rule = await service.create('sessA', { name: 'r', replyText: 'hi' });+ expect(rule.enabled).toBe(true);+ expect(rule.cooldownSeconds).toBe(60);+ expect(rule.conditions).toBeNull();+ });++ it('findOne returns a rule only for its owning session', async () => {+ const rule = await service.create('sessA', { name: 'r', replyText: 'hi' });+ expect((await service.findOne('sessA', rule.id)).id).toBe(rule.id);+ await expect(service.findOne('sessB', rule.id)).rejects.toThrow(NotFoundException);+ });++ it('update refuses (404) a rule owned by another session and does not mutate it', async () => {+ const rule = await service.create('sessA', { name: 'r', replyText: 'hi' });+ await expect(service.update('sessB', rule.id, { replyText: 'hijacked' })).rejects.toThrow(NotFoundException);+ expect((await ds.getRepository(AutomationRule).findOneByOrFail({ id: rule.id })).replyText).toBe('hi');+ });++ it('remove refuses (404) a rule owned by another session and does not delete it', async () => {+ const rule = await service.create('sessA', { name: 'r', replyText: 'hi' });+ await expect(service.remove('sessB', rule.id)).rejects.toThrow(NotFoundException);+ expect(await ds.getRepository(AutomationRule).countBy({ id: rule.id })).toBe(1);+ });++ it('findAll returns only the session’s rules', async () => {+ await service.create('sessA', { name: 'a', replyText: 'x' });+ await service.create('sessB', { name: 'b', replyText: 'y' });+ expect((await service.findAll('sessA')).map(r => r.name)).toEqual(['a']);+ });+ });++ describe('evaluateInbound', () => {+ it('replies through the send path when a condition matches', async () => {+ await service.create('sessA', {+ name: 'greet',+ replyText: 'welcome!',+ conditions: { conditions: [{ field: 'body', operator: 'contains', value: 'hello' }] },+ });++ await service.evaluateInbound('sessA', inbound());++ expect(sends).toEqual([{ sessionId: 'sessA', chatId: '[email protected]', text: 'welcome!' }]);+ });++ it('a rule without conditions matches every inbound message', async () => {+ await service.create('sessA', { name: 'all', replyText: 'ack' });++ await service.evaluateInbound('sessA', inbound({ body: 'anything at all' }));++ expect(sends).toHaveLength(1);+ });++ it('never replies to the account’s own messages (fromMe)', async () => {+ await service.create('sessA', { name: 'all', replyText: 'ack' });++ await service.evaluateInbound('sessA', inbound({ fromMe: true }));++ expect(sends).toHaveLength(0);+ });++ it('skips disabled rules and non-matching conditions', async () => {+ await service.create('sessA', { name: 'off', replyText: 'no', enabled: false });+ await service.create('sessA', {+ name: 'other',+ replyText: 'no',+ conditions: { conditions: [{ field: 'body', operator: 'contains', value: 'zzz-no-match' }] },+ });++ await service.evaluateInbound('sessA', inbound());++ expect(sends).toHaveLength(0);+ });++ it('first matching rule wins — one message never gets two replies', async () => {+ const first = await service.create('sessA', { name: 'first', replyText: 'first-reply' });+ await service.create('sessA', { name: 'second', replyText: 'second-reply' });+ // createdAt has 1s precision on SQLite; pin distinct timestamps so order is the one asserted.+ await ds.getRepository(AutomationRule).update(first.id, { createdAt: new Date('2026-01-01T00:00:00Z') });++ await service.evaluateInbound('sessA', inbound());++ expect(sends.map(s => s.text)).toEqual(['first-reply']);+ });++ it('cooldown: the same rule stays quiet in the same chat, other chats unaffected', async () => {+ await service.create('sessA', { name: 'all', replyText: 'ack', cooldownSeconds: 300 });++ await service.evaluateInbound('sessA', inbound());+ await service.evaluateInbound('sessA', inbound({ id: 'wamid.2' }));+ await service.evaluateInbound('sessA', inbound({ id: 'wamid.3', chatId: '[email protected]', from: '[email protected]' }));++ expect(sends.map(s => s.chatId)).toEqual(['[email protected]', '[email protected]']);+ });++ it('cooldownSeconds 0 disables the quiet period', async () => {+ await service.create('sessA', { name: 'all', replyText: 'ack', cooldownSeconds: 0 });++ await service.evaluateInbound('sessA', inbound());+ await service.evaluateInbound('sessA', inbound({ id: 'wamid.2' }));++ expect(sends).toHaveLength(2);+ });++ it('a rejected send is swallowed, and the cooldown still holds (no retry storm)', async () => {+ await service.create('sessA', { name: 'all', replyText: 'ack', cooldownSeconds: 300 });+ sendImpl = () => Promise.reject(new Error('engine down'));++ await expect(service.evaluateInbound('sessA', inbound())).resolves.toBeUndefined();+ sendImpl = (sessionId, dto) => {+ sends.push({ sessionId, chatId: dto.chatId, text: dto.text });+ return Promise.resolve({});+ };+ await service.evaluateInbound('sessA', inbound({ id: 'wamid.2' }));++ expect(sends).toHaveLength(0);+ });++ it('a failing rule lookup resolves without throwing (receive path stays safe)', async () => {+ const broken = new AutomationRulesService(+ { find: () => Promise.reject(new Error('db gone')) } as never,+ moduleRefStub,+ undefined,+ );++ await expect(broken.evaluateInbound('sessA', inbound())).resolves.toBeUndefined();+ });++ it('tolerates a missing ModuleRef (unit wiring) without throwing', async () => {+ const bare = new AutomationRulesService(ds.getRepository(AutomationRule), undefined, undefined);+ await service.create('sessA', { name: 'all', replyText: 'ack' });++ await expect(bare.evaluateInbound('sessA', inbound())).resolves.toBeUndefined();+ expect(sends).toHaveLength(0);+ });++ it('never answers a stale message — an offline-replayed backlog must not trigger a reply burst', async () => {+ await service.create('sessA', { name: 'all', replyText: 'ack' });++ await service.evaluateInbound('sessA', inbound({ timestamp: Math.floor(Date.now() / 1000) - 3600 }));++ expect(sends).toHaveLength(0);+ });++ it('a fresh timestamp (and a missing one) still get their reply', async () => {+ await service.create('sessA', { name: 'all', replyText: 'ack', cooldownSeconds: 0 });++ await service.evaluateInbound('sessA', inbound({ timestamp: Math.floor(Date.now() / 1000) - 5 }));+ await service.evaluateInbound('sessA', inbound({ id: 'wamid.2' }));++ expect(sends).toHaveLength(2);+ });++ it('ignores messages without a chatId', async () => {+ await service.create('sessA', { name: 'all', replyText: 'ack' });++ await service.evaluateInbound('sessA', inbound({ chatId: undefined }));++ expect(sends).toHaveLength(0);+ });+ });+});diff --git a/src/modules/automation/automation-rules.service.ts b/src/modules/automation/automation-rules.service.tsnew file mode 100644index 000000000..afc70db93--- /dev/null+++ b/src/modules/automation/automation-rules.service.ts@@ -0,0 +1,197 @@+import { Injectable, NotFoundException, Optional } from '@nestjs/common';+import { ModuleRef } from '@nestjs/core';+import { InjectRepository } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import { createLogger } from '../../common/services/logger.service';+import { userPart } from '../../engine/identity/wa-id';+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';+import { evaluateFilters } from '../webhook/filters/filter-evaluator';+import type { MessageService } from '../message/message.service';+import { AutomationRule } from './entities/automation-rule.entity';+import { CreateAutomationRuleDto, UpdateAutomationRuleDto } from './dto/automation-rule.dto';++/** Entries above this size trigger a sweep of expired cooldowns before inserting the next one. */+const COOLDOWN_SWEEP_THRESHOLD = 10_000;++/**+ * Messages older than this never get an automated answer. A reconnect replays the offline-queued+ * backlog through the same inbound path; answering it would burst-reply every stale message — and+ * it is the unbounded arm of an autoreply-vs-autoreply loop, where each side answers the other's+ * queued message only after its own cooldown has long expired.+ */+const MAX_MESSAGE_AGE_SECONDS = 300;++/**+ * Single-message autoreply rules: evaluated on every inbound message, first matching rule replies+ * into the chat through the ordinary send path.+ *+ * The reply is sent via `MessageService.sendText`, which the module graph cannot inject directly:+ * `MessageModule` imports `SessionModule`, and this module is imported BY `SessionModule` (the+ * projector calls `evaluateInbound`), so a constructor dependency here would close a module cycle.+ * `ModuleRef.get(..., { strict: false })` resolves it lazily at first use instead — the same escape+ * hatch `AuthService` uses. In unit contexts without a ModuleRef the evaluator logs and skips.+ */+@Injectable()+export class AutomationRulesService {+ private readonly logger = createLogger('AutomationRulesService');++ /** `${ruleId}:${chatId}` -> epoch ms until which the rule stays quiet in that chat. Per-process. */+ private readonly cooldowns = new Map<string, number>();++ private messageService?: MessageService;++ constructor(+ @InjectRepository(AutomationRule, 'data')+ private readonly ruleRepository: Repository<AutomationRule>,+ @Optional()+ private readonly moduleRef?: ModuleRef,+ @Optional()+ private readonly lidMappingStore?: LidMappingStoreService,+ ) {}++ async create(sessionId: string, dto: CreateAutomationRuleDto): Promise<AutomationRule> {+ const rule = this.ruleRepository.create({+ sessionId,+ name: dto.name,+ replyText: dto.replyText,+ conditions: dto.conditions ?? null,+ cooldownSeconds: dto.cooldownSeconds ?? 60,+ enabled: dto.enabled ?? true,+ });+ return this.ruleRepository.save(rule);+ }++ async findAll(sessionId: string): Promise<AutomationRule[]> {+ // id is the tiebreak: createdAt has 1-second precision on SQLite, so rules created together+ // would otherwise have an unstable order — and order here IS the evaluation order.+ return this.ruleRepository.find({ where: { sessionId }, order: { createdAt: 'ASC', id: 'ASC' } });+ }++ async findOne(sessionId: string, id: string): Promise<AutomationRule> {+ const rule = await this.ruleRepository.findOne({ where: { id, sessionId } });+ if (!rule) {+ throw new NotFoundException(`Automation rule ${id} not found`);+ }+ return rule;+ }++ async update(sessionId: string, id: string, dto: UpdateAutomationRuleDto): Promise<AutomationRule> {+ const rule = await this.findOne(sessionId, id);+ if (dto.name !== undefined) rule.name = dto.name;+ if (dto.replyText !== undefined) rule.replyText = dto.replyText;+ if (dto.conditions !== undefined) rule.conditions = dto.conditions;+ if (dto.cooldownSeconds !== undefined) rule.cooldownSeconds = dto.cooldownSeconds;+ if (dto.enabled !== undefined) rule.enabled = dto.enabled;+ return this.ruleRepository.save(rule);+ }++ async remove(sessionId: string, id: string): Promise<void> {+ const rule = await this.findOne(sessionId, id);+ await this.ruleRepository.remove(rule);+ }++ /**+ * Evaluate one inbound message against the session's rules; first match replies.+ *+ * Called fire-and-forget from the projector's dispatch stage, which runs at most once per inbound+ * message (the UNIQUE(sessionId, waMessageId) insert oracle) — so a rule sees no engine re-fires.+ * Everything here must swallow its own failures: a broken rule, a dead DB or a refused send must+ * never surface into the receive path.+ *+ * `fromMe` is guarded HERE because the inbound path does not filter it — some engine deliveries+ * carry the account's own messages, and answering yourself is the shortest possible reply loop.+ */+ async evaluateInbound(sessionId: string, message: Record<string, unknown>): Promise<void> {+ if (message.fromMe === true) return;+ const chatId = typeof message.chatId === 'string' ? message.chatId : null;+ if (!chatId) return;+ // Freshness gate (see MAX_MESSAGE_AGE_SECONDS). A missing timestamp counts as fresh — losing+ // one legitimate reply to a mapper quirk is worse than answering a possibly old message once.+ const timestamp = typeof message.timestamp === 'number' ? message.timestamp : null;+ if (timestamp !== null && Date.now() / 1000 - timestamp > MAX_MESSAGE_AGE_SECONDS) return;++ let rules: AutomationRule[];+ try {+ rules = await this.ruleRepository.find({+ where: { sessionId, enabled: true },+ order: { createdAt: 'ASC', id: 'ASC' },+ });+ } catch (error) {+ this.logger.warn('Automation rule lookup failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ return;+ }+ if (rules.length === 0) return;++ // Same lid->phone resolution the webhook filter match uses, so a phone-valued sender condition+ // matches a lid-addressed sender identically in both places.+ const resolveLid = (jid: string): string | null => this.lidMappingStore?.getCached(userPart(jid)) ?? null;++ // First match wins: one inbound message never produces more than one automated reply, and rule+ // order (creation order) is the tiebreak the operator can reason about.+ const rule = rules.find(candidate =>+ evaluateFilters(candidate.conditions, 'message.received', message, resolveLid),+ );+ if (!rule) return;+ if (this.inCooldown(rule, chatId)) return;+ // Enter the cooldown BEFORE the send: a burst of matching messages must collapse to one reply+ // even while the first send is still in flight.+ this.enterCooldown(rule, chatId);++ try {+ const messageService = this.resolveMessageService();+ if (!messageService) return;+ await messageService.sendText(sessionId, { chatId, text: rule.replyText });+ this.logger.log('Automation rule replied', { sessionId, ruleId: rule.id, chatId });+ } catch (error) {+ // The send path already persisted/audited its own failure; here it only must not propagate.+ this.logger.warn('Automation rule reply failed', {+ sessionId,+ ruleId: rule.id,+ chatId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }++ private resolveMessageService(): MessageService | undefined {+ if (!this.messageService) {+ try {+ // Deferred require, not a static import: a value-import of MessageService here closes the+ // file cycle session (projector) -> automation -> message -> session, and whichever class+ // evaluates last in that cycle is `undefined` while Nest builds the graph. By reply time+ // every module is loaded, so requiring the token lazily sidesteps the cycle entirely.+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { MessageService: token } = require('../message/message.service') as {+ MessageService: new (...args: never[]) => MessageService;+ };+ this.messageService = this.moduleRef?.get(token, { strict: false });+ } catch (error) {+ this.logger.warn('MessageService is not resolvable; automation replies are disabled', {+ error: error instanceof Error ? error.message : String(error),+ });+ return undefined;+ }+ }+ return this.messageService;+ }++ private inCooldown(rule: AutomationRule, chatId: string): boolean {+ if (!rule.cooldownSeconds) return false;+ const until = this.cooldowns.get(`${rule.id}:${chatId}`);+ return until !== undefined && until > Date.now();+ }++ private enterCooldown(rule: AutomationRule, chatId: string): void {+ if (!rule.cooldownSeconds) return;+ if (this.cooldowns.size >= COOLDOWN_SWEEP_THRESHOLD) {+ const now = Date.now();+ for (const [key, until] of this.cooldowns) {+ if (until <= now) this.cooldowns.delete(key);+ }+ }+ this.cooldowns.set(`${rule.id}:${chatId}`, Date.now() + rule.cooldownSeconds * 1000);+ }+}diff --git a/src/modules/automation/automation.module.ts b/src/modules/automation/automation.module.tsnew file mode 100644index 000000000..a99f4f851--- /dev/null+++ b/src/modules/automation/automation.module.ts@@ -0,0 +1,18 @@+import { Module } from '@nestjs/common';+import { TypeOrmModule } from '@nestjs/typeorm';+import { AutomationRule } from './entities/automation-rule.entity';+import { AutomationRulesService } from './automation-rules.service';+import { AutomationRuleController } from './automation-rule.controller';++/**+ * Deliberately imports no feature module: SessionModule imports this one (the projector fires rule+ * evaluation), so anything imported here must not lead back to SessionModule. The reply dependency+ * (MessageService) is resolved lazily via ModuleRef inside the service for exactly that reason.+ */+@Module({+ imports: [TypeOrmModule.forFeature([AutomationRule], 'data')],+ controllers: [AutomationRuleController],+ providers: [AutomationRulesService],+ exports: [AutomationRulesService],+})+export class AutomationModule {}diff --git a/src/modules/automation/dto/automation-rule.dto.ts b/src/modules/automation/dto/automation-rule.dto.tsnew file mode 100644index 000000000..b5a9d2fd8--- /dev/null+++ b/src/modules/automation/dto/automation-rule.dto.ts@@ -0,0 +1,143 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { Expose, plainToInstance } from 'class-transformer';+import { IsBoolean, IsInt, IsNotEmpty, IsOptional, IsString, Max, MaxLength, Min } from 'class-validator';+import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';+import { MESSAGE_TEXT_MAX_LENGTH } from '../../message/dto/send-message.dto';+import { WebhookFilters } from '../../webhook/filters/filter-types';+import { IsValidWebhookFilters } from '../../webhook/filters/filter-validation';+import { AutomationRule } from '../entities/automation-rule.entity';++/** Longest quiet period a rule may ask for: one day. */+export const AUTOMATION_COOLDOWN_MAX_SECONDS = 86_400;++const CONDITIONS_DESCRIPTION =+ 'Match conditions in the webhook filter format (message family: sender, recipient, body, type, ' ++ 'isGroup, fromMe, hasMedia, mentions). All conditions must match (AND). Omitted or empty means ' ++ 'the rule matches every inbound message.';++const COOLDOWN_DESCRIPTION =+ 'Quiet period per chat, in seconds: after the rule replies in a chat it stays silent there for ' ++ 'this long (default 60, 0 disables). This is the guard against two auto-repliers answering each ' ++ 'other forever, so disable it knowingly.';++export class CreateAutomationRuleDto {+ @ApiProperty({ description: 'Display name for the rule', example: 'Greet new enquiries', maxLength: 100 })+ @IsString()+ @IsNotEmpty()+ @MaxLength(100)+ name!: string;++ @ApiProperty({+ description: 'Text sent back into the chat when the rule matches',+ example: 'Thanks for reaching out — we reply within the hour.',+ maxLength: MESSAGE_TEXT_MAX_LENGTH,+ })+ @IsString()+ @IsNotEmpty()+ @MaxLength(MESSAGE_TEXT_MAX_LENGTH)+ replyText!: string;++ @ApiPropertyOptional({ description: CONDITIONS_DESCRIPTION })+ @IsOptional()+ @IsValidWebhookFilters()+ conditions?: WebhookFilters | null;++ @ApiPropertyOptional({+ description: COOLDOWN_DESCRIPTION,+ default: 60,+ minimum: 0,+ maximum: AUTOMATION_COOLDOWN_MAX_SECONDS,+ })+ @IsOptional()+ @ToStrictNumber()+ @IsInt()+ @Min(0)+ @Max(AUTOMATION_COOLDOWN_MAX_SECONDS)+ cooldownSeconds?: number;++ @ApiPropertyOptional({ description: 'Whether the rule is active', default: true })+ @IsOptional()+ @ToStrictBoolean()+ @IsBoolean()+ enabled?: boolean;+}++export class UpdateAutomationRuleDto {+ @ApiPropertyOptional({ description: 'Display name for the rule', maxLength: 100 })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ @MaxLength(100)+ name?: string;++ @ApiPropertyOptional({+ description: 'Text sent back into the chat when the rule matches',+ maxLength: MESSAGE_TEXT_MAX_LENGTH,+ })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ @MaxLength(MESSAGE_TEXT_MAX_LENGTH)+ replyText?: string;++ @ApiPropertyOptional({ description: CONDITIONS_DESCRIPTION })+ @IsOptional()+ @IsValidWebhookFilters()+ conditions?: WebhookFilters | null;++ @ApiPropertyOptional({ description: COOLDOWN_DESCRIPTION, minimum: 0, maximum: AUTOMATION_COOLDOWN_MAX_SECONDS })+ @IsOptional()+ @ToStrictNumber()+ @IsInt()+ @Min(0)+ @Max(AUTOMATION_COOLDOWN_MAX_SECONDS)+ cooldownSeconds?: number;++ @ApiPropertyOptional({ description: 'Whether the rule is active' })+ @IsOptional()+ @ToStrictBoolean()+ @IsBoolean()+ enabled?: boolean;+}++export class AutomationRuleResponseDto {+ @ApiProperty()+ @Expose()+ id!: string;++ @ApiProperty()+ @Expose()+ sessionId!: string;++ @ApiProperty()+ @Expose()+ name!: string;++ @ApiProperty()+ @Expose()+ enabled!: boolean;++ @ApiPropertyOptional({ description: CONDITIONS_DESCRIPTION, nullable: true })+ @Expose()+ conditions!: WebhookFilters | null;++ @ApiProperty()+ @Expose()+ replyText!: string;++ @ApiProperty()+ @Expose()+ cooldownSeconds!: number;++ @ApiProperty()+ @Expose()+ createdAt!: Date;++ @ApiProperty()+ @Expose()+ updatedAt!: Date;++ static fromEntity(rule: AutomationRule): AutomationRuleResponseDto {+ return plainToInstance(AutomationRuleResponseDto, rule, { excludeExtraneousValues: true });+ }+}diff --git a/src/modules/automation/entities/automation-rule.entity.ts b/src/modules/automation/entities/automation-rule.entity.tsnew file mode 100644index 000000000..f5b17f75a--- /dev/null+++ b/src/modules/automation/entities/automation-rule.entity.ts@@ -0,0 +1,62 @@+import {+ Entity,+ Column,+ Index,+ PrimaryGeneratedColumn,+ CreateDateColumn,+ UpdateDateColumn,+ ManyToOne,+ JoinColumn,+} from 'typeorm';+import { Session } from '../../session/entities/session.entity';+import { jsonColumnType } from '../../../common/utils/column-types';+import { WebhookFilters } from '../../webhook/filters/filter-types';++/**+ * A single-message autoreply rule: when an inbound message matches `conditions`, the gateway answers+ * the chat with `replyText` through the ordinary send path (send pacing and plugin vetoes included).+ *+ * `conditions` reuses the webhook filter shape (`message` family) verbatim — same JSON, same+ * validator, same evaluator — so a rule matches exactly what a filtered `message.received` webhook+ * would have fired for. Null/empty conditions match every inbound message.+ */+@Entity('automation_rules')+export class AutomationRule {+ @PrimaryGeneratedColumn('uuid')+ id!: string;++ // varchar (not uuid) to match sessions.id, same reasoning as webhooks.sessionId; indexed because+ // the evaluation path loads a session's rules on every inbound message.+ @Index('IDX_automation_rules_sessionId')+ @Column({ type: 'varchar' })+ sessionId!: string;++ @ManyToOne(() => Session, { onDelete: 'CASCADE' })+ @JoinColumn({ name: 'sessionId' })+ session!: Session;++ @Column({ type: 'varchar', length: 100 })+ name!: string;++ @Column({ type: 'boolean', default: true })+ enabled!: boolean;++ // Null/absent means "match every inbound message" — mirrors webhook filters' additive default.+ @Column({ type: jsonColumnType(), nullable: true })+ conditions!: WebhookFilters | null;++ @Column({ type: 'text' })+ replyText!: string;++ // Per-(rule, chat) quiet period: the same rule will not fire twice into the same chat within the+ // window. Together with the evaluator's freshness gate this rate-bounds (not: terminates) an+ // autoreply-vs-autoreply exchange. 0 disables it — knowingly.+ @Column({ type: 'int', default: 60 })+ cooldownSeconds!: number;++ @CreateDateColumn()+ createdAt!: Date;++ @UpdateDateColumn()+ updatedAt!: Date;+}diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.tsindex 37f143480..649eb4ca5 100644--- a/src/modules/session/message-projector.service.spec.ts+++ b/src/modules/session/message-projector.service.spec.ts@@ -11,6 +11,7 @@ import { WebhookService } from '../webhook/webhook.service';import { HookManager } from '../../core/hooks';import { StatusStoreService } from '../status-store/status-store.service';import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';+import { AutomationRulesService } from '../automation/automation-rules.service';import { SessionLidResolver } from './session-lid-resolver.service';import type { IncomingMessage, IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';@@ -213,6 +214,7 @@ describe('MessageProjector (inbound projection)', () => {let statusStore: { ingest: jest.Mock };let lidResolver: { resolveSenderPhone: jest.Mock };let chatMediaArchive: { archive: jest.Mock };+ let automationRules: { evaluateInbound: jest.Mock };const SESSION_ID = 'session-1';@@ -253,6 +255,7 @@ describe('MessageProjector (inbound projection)', () => {statusStore = { ingest: jest.fn().mockResolvedValue({ row: {}, created: false }) };lidResolver = { resolveSenderPhone: jest.fn().mockResolvedValue(null) };chatMediaArchive = { archive: jest.fn().mockResolvedValue(null) };+ automationRules = { evaluateInbound: jest.fn().mockResolvedValue(undefined) };const module: TestingModule = await Test.createTestingModule({providers: [@@ -269,6 +272,7 @@ describe('MessageProjector (inbound projection)', () => {{ provide: SessionLidResolver, useValue: lidResolver },{ provide: ConfigService, useValue: { get: jest.fn() } },{ provide: ChatMediaArchiveService, useValue: chatMediaArchive },+ { provide: AutomationRulesService, useValue: automationRules },],}).compile();@@ -395,5 +399,34 @@ describe('MessageProjector (inbound projection)', () => {expect(eventsGateway.emitMessage).toHaveBeenCalledWith(SESSION_ID, expect.anything());});});++ describe('automation rules', () => {+ it('hands the dispatched message to the rule evaluator', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);++ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming());+ await new Promise(resolve => setImmediate(resolve));++ // The hook-final message, same object the webhook dispatch gets — rule conditions must see+ // exactly what a filtered message.received webhook would have seen.+ expect(automationRules.evaluateInbound).toHaveBeenCalledWith(+ SESSION_ID,+ expect.objectContaining({ chatId: '[email protected]' }),+ );+ });++ it('keeps delivering when rule evaluation rejects — a broken rule must never break the receive path', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ automationRules.evaluateInbound.mockRejectedValueOnce(new Error('rules table gone'));++ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming());+ await new Promise(resolve => setImmediate(resolve));++ expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.received', expect.anything());+ expect(eventsGateway.emitMessage).toHaveBeenCalledWith(SESSION_ID, expect.anything());+ });+ });});});diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.tsindex cf84b92b8..ab78f9245 100644--- a/src/modules/session/message-projector.service.ts+++ b/src/modules/session/message-projector.service.ts@@ -15,6 +15,7 @@ import { isUniqueConstraintError } from '../../common/utils/unique-constraint.utimport { resolveFeatureFlags } from '../../config/feature-flags';import { StatusStoreService } from '../status-store/status-store.service';import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';+import { AutomationRulesService } from '../automation/automation-rules.service';import { buildIncomingStatus } from '../status-store/incoming-status';import type { StatusUpdate } from '../status-store/entities/status-update.entity';import {@@ -105,6 +106,9 @@ export class MessageProjector {// predates the archive). Absent simply means inbound media is not archived.@Optional()private readonly chatMediaArchive?: ChatMediaArchiveService,+ // Optional for the same reason. Absent simply means no autoreply rules are evaluated.+ @Optional()+ private readonly automationRules?: AutomationRulesService,) {this.mutationProjector = new MessageMutationProjector(this.messageRepository,@@ -329,6 +333,9 @@ export class MessageProjector {// Dispatch to webhooks with potentially modified messagevoid this.webhookService.dispatch(id, 'message.received', finalMessage);+ // Autoreply rules ride the same at-most-once dispatch (the insert oracle above dedupes engine+ // re-fires) and stay fail-open like the webhook: a broken rule must never break the receive path.+ void this.automationRules?.evaluateInbound(id, finalMessage).catch(() => undefined);// Emit real-time event to WebSocket clientsthis.eventsGateway.emitMessage(id, finalMessage);}diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.tsindex 48a2d890b..7aa72c30c 100644--- a/src/modules/session/session.module.ts+++ b/src/modules/session/session.module.ts@@ -15,11 +15,18 @@ import { SessionController } from './session.controller';import { WebhookModule } from '../webhook/webhook.module';import { StatusStoreModule } from '../status-store/status-store.module';import { ChatMediaModule } from '../chat-media/chat-media.module';+import { AutomationModule } from '../automation/automation.module';@Module({- // WebhookModule/StatusStoreModule/ChatMediaModule do not import SessionModule back, so the- // dependency is one-directional — no forwardRef() needed.- imports: [TypeOrmModule.forFeature([Session, Message], 'data'), WebhookModule, StatusStoreModule, ChatMediaModule],+ // WebhookModule/StatusStoreModule/ChatMediaModule/AutomationModule do not import SessionModule+ // back, so the dependency is one-directional — no forwardRef() needed.+ imports: [+ TypeOrmModule.forFeature([Session, Message], 'data'),+ WebhookModule,+ StatusStoreModule,+ ChatMediaModule,+ AutomationModule,+ ],controllers: [SessionController],providers: [SessionService,diff --git a/test/automation-rules.e2e-spec.ts b/test/automation-rules.e2e-spec.tsnew file mode 100644index 000000000..23c014d41--- /dev/null+++ b/test/automation-rules.e2e-spec.ts@@ -0,0 +1,170 @@+// archiver v8 is ESM-only (pulled in transitively via @Global StorageModule); stub for ts-jest CJS.+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));++import { Test, TestingModule } from '@nestjs/testing';+import { INestApplication } from '@nestjs/common';+import { getRepositoryToken } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import request from 'supertest';+import { App } from 'supertest/types';+import { AppModule } from './../src/app.module';+import { applyGlobalValidation } from './../src/config/app-validation';+import { AuthService } from './../src/modules/auth/auth.service';+import { ApiKeyRole } from './../src/modules/auth/entities/api-key.entity';+import { Session } from './../src/modules/session/entities/session.entity';+import { AutomationRule } from './../src/modules/automation/entities/automation-rule.entity';++/**+ * REST-surface coverage for autoreply rules: CRUD with the global ValidationPipe, role+ * enforcement, and the cross-session ownership fence. Evaluation itself (matching, cooldown,+ * loop-safety) is unit-covered in automation-rules.service.spec.ts — no engine runs here.+ */+describe('Automation rules (e2e)', () => {+ let app: INestApplication<App>;+ let sessionRepo: Repository<Session>;+ let apiKey: string;+ let viewerKey: string;++ let sessionSeq = 0;+ const nextSession = async (): Promise<string> => {+ const session = await sessionRepo.save(+ sessionRepo.create({ name: `e2e-automation-${Date.now()}-${sessionSeq++}` }),+ );+ return session.id;+ };++ const createRule = async (+ session: string,+ overrides: Record<string, unknown> = {},+ ): Promise<Record<string, unknown>> => {+ const res = await request(app.getHttpServer())+ .post(`/api/sessions/${session}/automation-rules`)+ .set('X-API-Key', apiKey)+ .send({ name: 'greet', replyText: 'welcome!', ...overrides })+ .expect(201);+ return res.body as Record<string, unknown>;+ };++ beforeAll(async () => {+ const moduleFixture: TestingModule = await Test.createTestingModule({+ imports: [AppModule],+ }).compile();++ app = moduleFixture.createNestApplication();+ applyGlobalValidation(app);+ await app.init();++ sessionRepo = app.get(getRepositoryToken(Session, 'data'));+ const authService = app.get(AuthService);+ apiKey = (await authService.createApiKey({ name: 'e2e-automation-admin', role: ApiKeyRole.ADMIN })).rawKey;+ viewerKey = (await authService.createApiKey({ name: 'e2e-automation-viewer', role: ApiKeyRole.VIEWER })).rawKey;+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ it('creates a rule with defaults and reads it back', async () => {+ const session = await nextSession();+ const rule = await createRule(session);++ expect(rule.enabled).toBe(true);+ expect(rule.cooldownSeconds).toBe(60);+ expect(rule.conditions).toBeNull();+ expect(rule.replyText).toBe('welcome!');++ const fetched = await request(app.getHttpServer())+ .get(`/api/sessions/${session}/automation-rules/${rule.id as string}`)+ .set('X-API-Key', apiKey)+ .expect(200);+ expect((fetched.body as { id: string }).id).toBe(rule.id);+ });++ it('lists rules in evaluation order and updates in place', async () => {+ const session = await nextSession();+ const first = await createRule(session, { name: 'first' });+ await createRule(session, { name: 'second' });+ // createdAt has 1-second precision on SQLite; same-second rules tie and fall back to the id+ // tiebreak. Pin distinct timestamps so the asserted order is the chronological one.+ await app+ .get<Repository<AutomationRule>>(getRepositoryToken(AutomationRule, 'data'))+ .update(first.id as string, { createdAt: new Date('2026-01-01T00:00:00Z') });++ const list = await request(app.getHttpServer())+ .get(`/api/sessions/${session}/automation-rules`)+ .set('X-API-Key', apiKey)+ .expect(200);+ expect((list.body as Array<{ name: string }>).map(r => r.name)).toEqual(['first', 'second']);++ const updated = await request(app.getHttpServer())+ .put(`/api/sessions/${session}/automation-rules/${first.id as string}`)+ .set('X-API-Key', apiKey)+ .send({ enabled: false, cooldownSeconds: 0 })+ .expect(200);+ const updatedBody = updated.body as { enabled: boolean; cooldownSeconds: number };+ expect(updatedBody.enabled).toBe(false);+ expect(updatedBody.cooldownSeconds).toBe(0);+ });++ it('deletes a rule (204) and answers 404 afterwards', async () => {+ const session = await nextSession();+ const rule = await createRule(session);++ await request(app.getHttpServer())+ .delete(`/api/sessions/${session}/automation-rules/${rule.id as string}`)+ .set('X-API-Key', apiKey)+ .expect(204);+ await request(app.getHttpServer())+ .get(`/api/sessions/${session}/automation-rules/${rule.id as string}`)+ .set('X-API-Key', apiKey)+ .expect(404);+ });++ it('fences rules to their owning session (cross-session read/update/delete answer 404)', async () => {+ const sessionA = await nextSession();+ const sessionB = await nextSession();+ const rule = await createRule(sessionA);++ const base = `/api/sessions/${sessionB}/automation-rules/${rule.id as string}`;+ await request(app.getHttpServer()).get(base).set('X-API-Key', apiKey).expect(404);+ await request(app.getHttpServer()).put(base).set('X-API-Key', apiKey).send({ name: 'x' }).expect(404);+ await request(app.getHttpServer()).delete(base).set('X-API-Key', apiKey).expect(404);+ });++ it('requires an API key (401) and the OPERATOR role (403 for a viewer)', async () => {+ const session = await nextSession();+ await request(app.getHttpServer()).get(`/api/sessions/${session}/automation-rules`).expect(401);+ await request(app.getHttpServer())+ .post(`/api/sessions/${session}/automation-rules`)+ .set('X-API-Key', viewerKey)+ .send({ name: 'x', replyText: 'y' })+ .expect(403);+ });++ it('rejects invalid rules: missing reply, unknown condition field, out-of-range cooldown', async () => {+ const session = await nextSession();+ await request(app.getHttpServer())+ .post(`/api/sessions/${session}/automation-rules`)+ .set('X-API-Key', apiKey)+ .send({ name: 'x' })+ .expect(400);+ await request(app.getHttpServer())+ .post(`/api/sessions/${session}/automation-rules`)+ .set('X-API-Key', apiKey)+ .send({+ name: 'x',+ replyText: 'y',+ conditions: { conditions: [{ field: 'no-such-field', operator: 'is', value: ['1'] }] },+ })+ .expect(400);+ await request(app.getHttpServer())+ .post(`/api/sessions/${session}/automation-rules`)+ .set('X-API-Key', apiKey)+ .send({ name: 'x', replyText: 'y', cooldownSeconds: 999_999 })+ .expect(400);+ });+});