Repository navigation
feat(hooks): add config-driven message handlers for immediate agent triggering - #3559
Closed
stevengonsalvez wants to merge 5 commits into
Closed
stevengonsalvez wants to merge 5 commits into
stevengonsalvez wants to merge 5 commits into
Conversation
- 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
force-pushed
the
feat/message-received-hook
branch
from
January 28, 2026 20:51
be3736c to
42c647f
Compare
- 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.
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)
Message Handlers (Routers)
Why Not Use Hooks for Urgent Patterns?Hooks cannot solve the queue-bypass problem: For patterns like
Message handlers provide all three. Hooks provide none. Security HardeningThis PR also adds protections that would be painful to re-implement in every custom hook:
|
Contributor
|
Closing: Large PRs (1000+ lines) require prior alignment with maintainers before submission. Please:
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. |
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem Statement
The Flow Problem
When bug reports (or any important messages) arrive, they get lost in the queue:
Why The Agent Doesn't See It
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.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.
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.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.Summary
Add
hooks.internal.messageHandlersconfig array for triggering agent execution when inbound messages match specified conditions.Features
immediate(bypass queue) orqueue(normal flow)exclusive(handler only) orparallel(handler + normal)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 typessrc/config/zod-schema.hooks.ts: Zod validation schemassrc/hooks/message-handler-match.ts: Condition matching logicsrc/hooks/message-handler-run.ts: Handler executor using runCronIsolatedAgentTurnsrc/auto-reply/reply/dispatch-from-config.ts: Integration pointdocs/hooks.md: Full documentation with examplesTest Plan
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.