Skip to content

feat(hooks): add config-driven message handlers for immediate agent triggering - #3559

Closed
stevengonsalvez wants to merge 5 commits into
openclaw:mainfrom
stevengonsalvez:feat/message-received-hook
Closed

stevengonsalvez wants to merge 5 commits into
openclaw:mainfrom
stevengonsalvez:feat/message-received-hook

Conversation

@stevengonsalvez

@stevengonsalvez stevengonsalvez commented Jan 28, 2026 •

Copy link
Copy Markdown

Problem Statement

The Flow Problem

When bug reports (or any important messages) arrive, they get lost in the queue:

  Bug report arrives (10:03)
          ↓
  Gateway routes to popashot session
          ↓
  Message sits in session queue
          ↓
  Cron fires at 10:10 (pipeline-dispatch)
          ↓
  Agent wakes up, sees ONLY the cron prompt
          ↓
  Agent processes pipeline work, replies HEARTBEAT_OK
          ↓
  Bug report message? Never saw it.

Why The Agent Doesn't See It

  1. Cron jobs inject their own prompt — When a cron fires, the system sends the cron's payload.text. That's what the agent responds to. The bug report from 7 minutes ago isn't in the immediate context.

  2. No automatic message aggregation — Clawdbot doesn't say "here's the cron prompt AND here are 3 WhatsApp messages that arrived since your last response." It's one-at-a-time.

  3. Session history exists but isn't surfaced — The messages ARE stored in ~/.clawdbot/agents/<id>/sessions/<id>.jsonl, but the agent doesn't automatically scan that on every wake.

  4. Race condition — If the agent is mid-response to one thing and a bug report arrives, it queues. But then the next wake might be a different cron.

The Solution (This PR)

Add hooks.internal.messageHandlers — config-driven handlers that trigger agent execution immediately when inbound messages match specified conditions, bypassing the queue entirely.

  Bug report arrives (10:03)
          ↓
  Gateway checks messageHandlers config
          ↓
  Match found: channelId=whatsapp, conversationId=bug-reports-group
          ↓
  Handler triggers agent IMMEDIATELY (priority: "immediate")
          ↓
  Agent processes bug report, creates GitHub issue
          ↓
  Response in seconds, not minutes

Summary

Add hooks.internal.messageHandlers config array for triggering agent execution when inbound messages match specified conditions.

Features

  • Match conditions: channelId, conversationId, from, contentPattern (regex), contentContains (keywords)
  • Priority modes: immediate (bypass queue) or queue (normal flow)
  • Execution modes: exclusive (handler only) or parallel (handler + normal)
  • Message transformation: prefix, suffix, or full template with placeholders
  • Configurable: model and thinking level per handler

Example Config

{
  "hooks": {
    "internal": {
      "messageHandlers": [
        {
          "id": "bug-reports",
          "match": {
            "channelId": "whatsapp",
            "conversationId": "[email protected]"
          },
          "action": "agent",
          "agentId": "popashot",
          "priority": "immediate",
          "mode": "exclusive",
          "messagePrefix": "[BUG REPORT] ",
          "thinking": "medium"
        }
      ]
    }
  }
}

Files Changed

  • src/config/types.hooks.ts: MessageHandlerConfig and MessageHandlerMatch types
  • src/config/zod-schema.hooks.ts: Zod validation schemas
  • src/hooks/message-handler-match.ts: Condition matching logic
  • src/hooks/message-handler-run.ts: Handler executor using runCronIsolatedAgentTurn
  • src/auto-reply/reply/dispatch-from-config.ts: Integration point
  • docs/hooks.md: Full documentation with examples

Test Plan

  • 28 unit tests for matcher logic (all passing)
  • Linter passes (0 warnings, 0 errors)
  • Manual testing: configured handler for WhatsApp bug reports group, verified immediate processing triggered GitHub issue creation within seconds of message arrival

AI-Assisted PR

This PR was developed with AI assistance (Claude). The implementation was fully tested locally and in production with a real bug report workflow.

@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Jan 28, 2026
Steven Gonsalvez and others added 3 commits January 28, 2026 20:46
- Add MessageReceivedHookContext type with full message metadata
- Add isMessageReceivedEvent() type guard for type-safe handling
- Trigger hook in dispatchReplyFromConfig() after plugin hooks
- Fire-and-forget execution to avoid blocking message processing
- Works across all 12 channels (whatsapp, telegram, discord, etc.)
- Add comprehensive tests for type guard and hook triggering
- Document message events, context fields, and filtering examples
…riggering

Add `hooks.internal.messageHandlers` config array for triggering agent
execution when inbound messages match specified conditions. This solves
the problem of important messages (like bug reports) being queued and
potentially missed when cron jobs wake the agent.

Features:
- Match conditions: channelId, conversationId, from, contentPattern (regex),
  contentContains (keywords)
- Priority modes: "immediate" (bypass queue) or "queue" (normal flow)
- Execution modes: "exclusive" (handler only) or "parallel" (handler + normal)
- Message transformation: prefix, suffix, or full template with placeholders
- Configurable model and thinking level per handler

Implementation:
- src/config/types.hooks.ts: MessageHandlerConfig and MessageHandlerMatch types
- src/config/zod-schema.hooks.ts: Zod validation schemas
- src/hooks/message-handler-match.ts: Condition matching logic
- src/hooks/message-handler-run.ts: Handler executor using runCronIsolatedAgentTurn
- src/auto-reply/reply/dispatch-from-config.ts: Integration point
- docs/hooks.md: Full documentation with examples
- 28 unit tests for matcher logic
@stevengonsalvez
stevengonsalvez force-pushed the feat/message-received-hook branch from be3736c to 42c647f Compare January 28, 2026 20:51
- Add ReDoS protection using safe-regex validation for contentPattern
- Add token bucket rate limiting (10/min per handler) to prevent cost explosions
- Require at least one match condition in Zod schema (reject empty match)
- Change error logging from logVerbose to logWarn for visibility

Includes tests for rate limiter and ReDoS protection.
@stevengonsalvez

Copy link
Copy Markdown
Author

Architectural Note: Why Message Handlers vs Hooks?

This PR introduces message handlers as a complement to the existing custom hooks system. They serve different purposes:

Custom Hooks (Observers)

  • Fire-and-forget event listeners
  • Cannot modify message flow - message always proceeds to queue
  • Great for: logging, analytics, external webhooks, side effects

Message Handlers (Routers)

  • Can intercept and take over message processing (mode: "exclusive")
  • Bypass the queue entirely for matched patterns
  • Great for: urgent patterns (!help, !stop), immediate responses, pattern-based routing

Why Not Use Hooks for Urgent Patterns?

Hooks cannot solve the queue-bypass problem:

With Hooks:
  Message → Hook fires → Message STILL enters queue → Waits behind other messages
                ↓
         Hook runs agent
         Response arrives... but user already waiting on queued response too
With Message Handlers (exclusive):
  Message → Handler matches → Takes over → Agent runs → Response sent
                                    ↓
                           Message NEVER enters queue
                           Clean, immediate response

For patterns like !help or !stop, you want:

  1. Immediate response (no queue wait)
  2. No duplicate responses (exclusive handling)
  3. Config-driven (no TypeScript code required)

Message handlers provide all three. Hooks provide none.

Security Hardening

This PR also adds protections that would be painful to re-implement in every custom hook:

  • ReDoS protection via safe-regex validation
  • Rate limiting (10 executions/min/handler) to prevent cost explosions
  • Match validation requiring at least one condition (no accidental catch-alls)

@sebslight

Copy link
Copy Markdown
Contributor

Closing: Large PRs (1000+ lines) require prior alignment with maintainers before submission. Please:

  1. Open an issue first to discuss the feature/change
  2. Get maintainer buy-in on the approach
  3. Consider breaking into smaller, reviewable PRs

We appreciate your interest in contributing, but reviewing massive unaligned PRs is not sustainable. Feel free to reopen after discussing the approach in an issue.

@sebslight sebslight closed this Jan 29, 2026
supmo668 added a commit to Syntropy-Health/openclaw that referenced this pull request Jul 15, 2026
…ig, signed webhook, TCPA STOP/HELP rail) (#68)

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 1 — SMS config contract (scoped API keys / per-env subaccount, fail-closed)

First slice of B-Twilio-1 (Twilio SMS ChannelTransport adapter, greenfield). The auth + number config contract per AD-onboarding-channels §4.2/4.3.

- Scoped Standard API Keys (SID+Secret) on per-env SUBACCOUNTS, NEVER the master Auth Token (test/prod isolation by construction); subaccount Auth Token retained ONLY as the X-Twilio-Signature HMAC key (§4.3).
- E.164 sender + allowFrom validation; inbound policy defaults to 'pairing' (deny-by-default, mirrors SYNTROPY_GATE).
- resolveTwilioSmsConfig: FAIL-CLOSED on credential completeness — returns null (channel INERT, registers nothing) unless EVERY credential + the sender number is present; no partial Twilio wiring. authToken REQUIRED (an SMS channel with no way to validate inbound signatures must not run).
- Infisical channels/twilio/{env} → runtime env fallback; config wins per-field.

Red-first: 11 tests (E.164 valid/invalid, strict-schema typo-safety, inbound default, credential-completeness incl. each-single-missing → null, authToken-required, env fallback, config precedence). tsgo clean, oxfmt clean. Standalone module — no plugin wiring yet (slice 5). Slices 2-6 (send / webhook+sig / TCPA STOP-HELP hard rail / plugin wiring / rails tests) per B-TWILIO-1-PLAN.md.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 2 — outbound SMS send (scoped API-key auth, injectable fetch, fail-closed secret hygiene)

send.ts: sendSms() → Twilio REST POST /2010-04-01/Accounts/{accountSid}/Messages.json. Basic-auth apiKeySid:apiKeySecret (scoped API key §4.2), NOT the authToken (webhook-HMAC only). Form-encoded From/To/Body. Injectable fetch seam (default global fetch). Discriminated {ok:true,sid}|{ok:false,status,error} — never throws, never leaks the api-key secret in error/return. No media v1. Does NOT import voice-call's twilioApiRequest (keeps the vendor-agnostic single-extension rail; that helper is account-auth + non-injectable). 6 red-first tests: URL/path, scoped-key auth (asserts NOT account:authToken), form fields, success sid, HTTP-error no-leak, network-throw no-leak. Full twilio suite 17/17; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 3 — inbound SMS webhook + X-Twilio-Signature gate (validate BEFORE routing)

webhook.ts: decideInboundSms() pure security gate — non-POST 405; X-Twilio-Signature validated (HMAC-SHA1, subaccount authToken §4.3) BEFORE any parse/route, mismatch/absent => 403 and inbound NEVER surfaced; authenticated-but-no-From => 400; authenticated+routable => 200 with {from,body}. Validator REUSED from voice-call (validateTwilioSignature, pure timing-safe) — single source of truth for the crypto (precedent: syntropy-mcp reuses syntropy/src). createSmsWebhookHandler: thin IncomingMessage/ServerResponse adapter (body read, header/url extraction, empty-TwiML 200); resolveUrl seam for proxy URL reconstruction. 9 red-first tests incl. genuine-HMAC accept + tamper-detection (good sig + altered body => 403) proving reject-on-mismatch end-to-end. Full twilio suite 26/26; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 4 — TCPA STOP/HELP hard rail (QG-blocking behavioral pin, CTO openclaw#3559)

compliance.ts: the non-negotiable opt-out rail. classifyCompliance() EXACT-match (trim/upper/strip-punct) STOP/STOPALL/UNSUBSCRIBE/CANCEL/END/QUIT->stop, START/YES/UNSTOP->start, HELP/INFO->help — conversational text containing a keyword as substring does NOT opt-out (no false positives). handleInboundCompliance(): STOP persists durable opt-out + confirmation, START clears, HELP replies (no state change), else passthrough to agent; replies are generic (no PHI/clerk-id/pairing). guardedSendSms(): enforcement half — checks opt-out FAIL-CLOSED (store throws => suppress, never send) before delegating to sendSms. ★ BEHAVIORAL PIN GREEN: a STOP'd number receives ZERO subsequent sends (fetch never called) + fail-closed. OptOutStore is an injectable seam; durable DB impl wired at slice 5. 12 red-first tests. Full twilio suite 38/38; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 5b — SMS outbound adapter (send→OutboundDeliveryResult, opt-out=terminal sentinel)

outbound.ts buildSmsOutboundAdapter(): maps guardedSendSms → ChannelOutboundAdapter.sendText per the delivery-queue semantics (returned result=ack/terminal, throw=fail/retry). Opt-out suppression returns a TERMINAL sentinel {messageId:'suppressed:optout',meta.suppressed} so a STOP'd recipient never re-enters the retry queue; genuine send failure THROWS (retryable); resolveConfig→null throws not-configured. deliveryMode 'direct'. Config/store/fetch injected — pure testable mapping. Secret never in thrown error. 6 red-first tests. Full twilio suite 44/44; tsgo+lint+fmt clean. Remaining slice-5 parts: 5a config-adapter bridge, 5c durable pg OptOutStore, 5d plugin object + register()/registerHttpRoute wiring, 5e manifest.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 5c — durable pg OptOutStore (ADR 0001: OpenClaw's own DB, user-independent key)

optout-store.ts: ensureOptOutSchema (idempotent CREATE TABLE IF NOT EXISTS lp_sms_optouts) + createPgOptOutStore backing the slice-4 OptOutStore seam. Per ADR 0001: lives in OpenClaw's OWN persist-user-identity Postgres, NEVER the Journal PHI DB; keyed by bare E.164 (user-independent) so a pre-pairing STOP is honored. Injected-sql convention (mirrors persist-user-identity/db.ts) via a minimal structural SqlTag type — zero new deps, decoupled from the postgres driver (real postgres.Sql satisfies it structurally at the wiring site). 4 tests via fake-sql round-trip (optOut->isOptedOut true, optIn clears, unknown=false, DDL issued). Full twilio suite 48/48; tsgo+lint+fmt clean. Remaining: 5d plugin object + register() (create pg client from DATABASE_URL, ensureSchema, wire channel + /twilio/sms route + compliance-before-gateway), 5e manifest.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 5a — SMS config-adapter bridge (OpenClawConfig.channels.sms → resolveTwilioSmsConfig)

accounts.ts: resolveSmsAccount reads cfg.channels.sms (ChannelsConfig index signature — no core config-type change) → TwilioSmsConfigSchema.safeParse → resolveTwilioSmsConfig (+ TWILIO_* env fallback). Inert until credential-complete (configured=false, config=null); malformed config object is ignored (falls back to env) rather than throwing. v1 single-account (listSmsAccountIds → [DEFAULT_ACCOUNT_ID]). Exports smsConfigAdapter (ChannelConfigAdapter) for the plugin object (5d). 7 red-first tests (full/inert/env-fallback/partial-fail-closed/bad-schema/default-account). Full twilio suite 55/55; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 5d — SMS plugin assembled + registered (channel + inbound webhook → compliance → agent)

Wires the tested blocks into a live channel. package.json (@openclaw/twilio, postgres dep, openclaw.extensions entry — the extension now LOADS). db.ts: own pg pool to DATABASE_URL (ADR 0001, OpenClaw's DB). channel.ts: createSmsPlugin factory (id 'sms', direct-only, no media, config adapter + opt-out-guarded outbound; 5 tests). index.ts register(): build durable pg opt-out store (fail-closed if no DATABASE_URL), api.registerChannel, api.registerHttpRoute('/twilio/sms') → createSmsWebhookHandler; onInbound runs handleInboundCompliance FIRST (STOP/START/HELP reply via guardedSendSms, no agent) else routeInboundToAgent (buildAgentPeerSessionKey agent:main:sms:direct:<e164> + minimal MsgContext → dispatchInboundMessageWithDispatcher, agent reply delivered via opt-out-guarded send); gateway_stop closes the pool. webhook.ts: handler now resolves config lazily (503 when inert) — honors unprovisioned/changed config. Deep core imports (dispatch/session-key/MsgContext) per established twitch/syntropy-mcp precedent. Full twilio suite 60/60; tsgo+lint+fmt clean. Remaining: 5e manifest (uiHints) + slice 6 integration/rails tests.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slices 5e+6 — manifest uiHints + rails/integration tests (PHI-deny, register wiring)

5e: openclaw.plugin.json uiHints — apiKeySecret+authToken marked sensitive (masked in config UI), field labels/help/placeholders. 6: rails.test.ts — (a) PHI boundary: isThirdPartyChannel('sms')===true (sms can never be phiApproved via plain config; B5 deny-unknown), (b) register() wiring integration: fake api confirms registerChannel(id 'sms') + registerHttpRoute('/twilio/sms') + gateway_stop cleanup, forcing the no-DB branch for determinism. Signature-negative + opt-out-suppression rails already covered in webhook/compliance suites. Full twilio suite 62/62; tsgo+lint+fmt clean. B-Twilio-1 feature-complete.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: fix(twilio): B-Twilio-1 QG remediation — STOP-ack suppression (CRITICAL), webhook DoS cap, inbound-policy enforcement + coverage

Addresses all confirmed 4-reviewer QG findings.
CRITICAL (code+test+security): STOP/HELP compliance acks were suppressed by guardedSendSms (which re-checks isOptedOut after optOut persists) → the CTIA/TCPA-mandated confirmation never sent. Fix: extract testable inbound.ts (handleInboundSms) from index.ts's inline closures; compliance acks now go via UNGUARDED sendSms (mandated replies exempt from the opt-out gate); agent-generated replies stay opt-out-guarded (createSmsReplyDeliver).
MEDIUM (security): readBody had no size cap on the unauthenticated webhook (CWE-770 OOM DoS) → MAX_INBOUND_BODY_BYTES=64KB, 413 on Content-Length over cap AND on streamed overflow.
MEDIUM (design): inbound policy (disabled/allowlist/pairing) was declared but never enforced → inboundAllowed() gates passthrough (STOP always honored first regardless).
LOW: send.ts success-path JSON.parse guarded (never-throws contract); outbound.ts uses SMS_CHANNEL_ID not literal.
Coverage (test): +18 tests → inbound.test.ts (STOP-ack-sends-despite-optout ★, HELP-to-opted-out, compliance-first ordering, policy enforcement, pin-#1 at the agent-reply deliver), webhook-handler.test.ts (503 inert / 200→onInbound / forged→no-onInbound / 413), send missing-sid + non-JSON, classify blank-body, strengthened outbound secret-leak assertion. Full twilio suite 80/80; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: cto <[email protected]>
Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants