Skip to content

feat: add before_route_inbound_message plugin hook for channel bridging - #81198

Closed
DranboFieldston wants to merge 7 commits into
openclaw:mainfrom
DranboFieldston:feat/before-route-inbound-message-hook
Closed

DranboFieldston wants to merge 7 commits into
openclaw:mainfrom
DranboFieldston:feat/before-route-inbound-message-hook

Conversation

@DranboFieldston

Copy link
Copy Markdown

Summary

Implements the before_route_inbound_message plugin hook as proposed in #81061.

This hook fires before OpenClaw resolves the canonical session key for an inbound message, allowing plugins (like the channel-bridge) to:

  • Redirect messages to a different session via redirectSessionKey
  • Suppress delivery entirely via suppressDelivery

Hook Signature

type PluginHookBeforeRouteInboundMessageEvent = {
  channel: string;
  accountId?: string;
  conversationId?: string;   // NativeChannelId or OriginatingTo
  parentConversationId?: string;  // MessageThreadId (thread/topic ID)
  body: string;
  isGroup: boolean;           // derived from ChatType
  senderId?: string;          // From field
  originalSessionKey: string;
};

type PluginHookBeforeRouteInboundMessageResult = {
  handled: true;
  redirectSessionKey?: string;
  suppressDelivery?: boolean;
};

Integration Points

File Change
src/plugins/hook-types.ts Added to PluginHookName union, PLUGIN_HOOK_NAMES array, and PluginHookHandlerMap
src/plugins/hook-message.types.ts New event/context/result type definitions
src/plugins/hooks.ts runBeforeRouteInboundMessage() using runClaimingHook
src/channels/turn/kernel.ts Hook fired in runChannelTurn() after resolveTurn()

Pattern

Uses the claiming hook pattern (runClaimingHook) — first handler returning { handled: true } wins, matching before_dispatch and reply_dispatch semantics. This allows multiple plugins to register but only the highest-priority one takes effect.

Why Here?

Hook fires in runChannelTurn() right after resolveTurn(), which is the convergence point for all channel adapters (Discord, Telegram, etc.). At this point:

  • ctxPayload.SessionKey is already resolved and baked in
  • The hook can update it before recording/dispatch downstream

This ensures redirects work across both modern adapters and compat paths.

Unit Tests

Added 2 new tests in src/channels/turn/kernel.test.ts:

PASS   src/channels/turn/kernel.test.ts > channel turn kernel > redirects to a different session when before_route_inbound_message hook returns a redirect
PASS   src/channels/turn/kernel.test.ts > channel turn kernel > suppresses delivery when before_route_inbound_message hook returns suppressDelivery

Both tests verify:

  • Hook fires with correct event context
  • Redirect updates ctxPayload.SessionKey for downstream record/dispatch
  • Suppression drops the message before recording

Proof: supplied

This PR adds a new plugin hook infrastructure with unit test coverage. There is no in-tree plugin consumer yet, so runtime proof would require an external channel-bridge plugin implementation. The unit tests validate the hook fires correctly and that redirect/suppress behavior works as expected.

Fixes: #81061

@openclaw-barnacle openclaw-barnacle Bot added size: S triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 12, 2026
@clawsweeper

clawsweeper Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 3, 2026, 11:46 PM ET / 03:46 UTC.

Summary
Adds a before_route_inbound_message plugin hook with redirect/suppression types, hook-runner plumbing, channel-turn and compatibility-dispatch wiring, and kernel unit tests.

PR surface: Source +213, Tests +89. Total +302 across 6 files.

Reproducibility: yes. for source-level PR blockers: the PR head awaits the new claiming hook before record/dispatch, lacks a default timeout, and targets an old compatibility file. The linked capability gap itself is a feature/API request rather than a broken existing contract.

Review metrics: 1 noteworthy metric.

  • Public plugin hook surface: 1 added. The PR adds a new hook name and redirect/suppress result contract, so plugin API compatibility and trust boundaries need maintainer attention before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #81061
Summary: This PR is the open candidate implementation for the exact pre-routing inbound hook issue; broader routing and passive-observation items overlap but do not replace it.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦪 silver shellfish
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Add redacted real channel-bridge or equivalent runtime proof showing redirect and suppression after this patch.
  • Rebase onto current main and move compatibility wiring to src/channels/message/inbound-reply-dispatch.ts.
  • [P2] Add fail-open timeout behavior plus public hook documentation and the linked reply/recency event fields.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body provides unit-test output only and explicitly says no in-tree consumer exists, so redirect/suppression has not been shown in a redacted real setup. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] A plugin-controlled hook can redirect or suppress inbound delivery before normal recording and dispatch, so target scope, account/session boundaries, audit expectations, and failure behavior need maintainer approval.
  • [P2] A slow or hung handler can stall inbound delivery because the PR awaits a claiming hook without adding a default fail-open timeout budget for the new hook.
  • [P1] The branch is dirty and wires compatibility behavior into a path that current main has turned into a deprecated facade, so rebase and owner-boundary repair are needed before review can rely on the merge result.
  • [P1] The contributor supplied unit-test output only; no redacted real channel-bridge or equivalent runtime proof shows redirect and suppression after this patch.

Maintainer options:

  1. Approve And Repair The Hook Contract (recommended)
    After maintainer API/security approval, rebase onto current main, move wiring to the active inbound owner, add default fail-open timeout behavior, complete docs/event fields, and require real behavior proof.
  2. Pause For Product Shape
    Hold the PR while maintainers decide whether broad redirect/suppression belongs in this public hook, a narrower binding feature, or a plugin-owned bridge seam.
  3. Accept Broad Trusted Routing Explicitly
    Maintainers can accept the broad plugin authority if the public contract documents scope, security expectations, timeout/error behavior, and audit consequences.

Next step before merge

  • [P1] Maintainer review is needed because the remaining blockers are API/security/trust-boundary direction and contributor-owned real behavior proof, not a safe automated repair.

Security
Needs attention: Needs attention because the diff gives plugins pre-record redirect/suppression authority and does not bound hook execution by default.

Review findings

  • [P1] Bound the pre-routing hook before awaiting it — src/plugins/hooks.ts:1001-1008
  • [P2] Move compatibility wiring to the active inbound owner — src/plugin-sdk/inbound-reply-dispatch.ts:159-207
  • [P2] Document the public routing hook contract — src/plugins/hook-types.ts:111
Review details

Best possible solution:

Land a maintainer-approved, documented, bounded pre-routing hook on the current inbound owner with fail-open timeout, a complete event contract, and redacted real bridge proof.

Do we have a high-confidence way to reproduce the issue?

Yes for source-level PR blockers: the PR head awaits the new claiming hook before record/dispatch, lacks a default timeout, and targets an old compatibility file. The linked capability gap itself is a feature/API request rather than a broken existing contract.

Is this the best way to solve the issue?

No as-is: a pre-routing hook is plausible, but this branch needs maintainer-approved API/security scope, current-main rebase, timeout/fail-open behavior, docs, a complete event contract, and real bridge proof before merge.

Full review comments:

  • [P1] Bound the pre-routing hook before awaiting it — src/plugins/hooks.ts:1001-1008
    runBeforeRouteInboundMessage delegates to the claiming-hook path, but the default modifying timeout map does not include the new hook. Since runChannelTurn awaits this before record/dispatch, a handler without its own timeout can stall inbound delivery instead of failing open as the linked contract requires.
    Confidence: 0.9
  • [P2] Move compatibility wiring to the active inbound owner — src/plugin-sdk/inbound-reply-dispatch.ts:159-207
    This branch adds redirect/suppress logic in src/plugin-sdk/inbound-reply-dispatch.ts, but current main has made that file a deprecated re-export facade and moved the implementation to src/channels/message/inbound-reply-dispatch.ts. Rebase the hook into the current owner so compatibility callers do not miss the behavior or drift from route/session synchronization.
    Confidence: 0.86
  • [P2] Document the public routing hook contract — src/plugins/hook-types.ts:111
    Adding this hook name exposes a public plugin API, but the plugin hook docs still list only the existing message hooks. The contract needs timing, redirect/suppress semantics, timeout/error behavior, trust boundaries, and event fields before external plugin authors depend on it.
    Confidence: 0.84
  • [P2] Complete the linked event contract before freezing it — src/plugins/hook-message.types.ts:115-142
    The linked issue discussion added reply linkage and recency context as requirements for this same hook, but this event type exposes only the basic conversation/body/session fields. Merging the narrower public API would not satisfy the stated reply-threading and topic-drift use cases and would create a compatibility burden when those fields are added later.
    Confidence: 0.78

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 9d68f877ac3e.

Label changes

Label justifications:

  • P2: This is a normal-priority plugin API feature with concrete channel-routing value but no urgent shipped regression.
  • merge-risk: 🚨 compatibility: The PR adds a new public plugin hook contract and touches a compatibility dispatch path that plugin/channel users may depend on.
  • merge-risk: 🚨 message-delivery: The proposed hook can suppress, stall, or redirect inbound delivery before the normal record/dispatch path.
  • merge-risk: 🚨 session-state: Redirecting before recording changes which session receives and persists an inbound message.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body provides unit-test output only and explicitly says no in-tree consumer exists, so redirect/suppression has not been shown in a redacted real setup. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +213, Tests +89. Total +302 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 5 214 1 +213
Tests 1 89 0 +89
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 303 1 +302

Security concerns:

  • [medium] Define redirect and suppression trust boundaries — src/plugins/hook-message.types.ts:135
    A registered plugin can select another session key or suppress inbound delivery before normal recording. That may be valid for trusted bridge plugins, but the public contract should define allowed target scope, account/channel boundaries, audit expectations, and failure behavior before exposing it.
    Confidence: 0.84
  • [medium] Bound pre-routing handler execution — src/plugins/hooks.ts:1001
    The new hook runs in the inbound delivery path and currently lacks a default timeout, so a slow or compromised plugin handler can stall routing before the message is recorded or dispatched.
    Confidence: 0.88

What I checked:

  • Repository policy applied: Root AGENTS.md requires full policy/scoped-guide review, treats plugin APIs and channel/session routing as compatibility-sensitive, and requires best-fix review beyond the diff; scoped channel, plugin, and Plugin SDK guides confirmed this touches public plugin/channel boundaries. (AGENTS.md:29, 9d68f877ac3e)
  • Live PR state and proof: Live GitHub shows the PR is open at head e938362, is conflicting/dirty, closes Hook: before_route_inbound_message — pre-routing interception for channel bridging/proxying #81061, and the body says no in-tree consumer exists so proof is unit-test only. (e93836272280)
  • Current main lacks requested hook: Current main's hook union and hook-name list include existing message hooks such as inbound_claim, before_dispatch, and reply_dispatch, but not before_route_inbound_message. (src/plugins/hook-types.ts:81, 9d68f877ac3e)
  • Current route resolution path: Current main resolves the channel turn before later dispatch/recording, which supports the linked capability gap but also makes any pre-routing hook delivery-sensitive. (src/channels/turn/kernel.ts:749, 9d68f877ac3e)
  • PR awaits the new hook in delivery path: The PR head awaits runBeforeRouteInboundMessage after resolveTurn and before assemble/dispatch, so a slow handler can stall inbound delivery before recording and dispatch continue. (src/channels/turn/kernel.ts:495, e93836272280)
  • No default timeout for new hook: At PR head, the default modifying-hook timeout map contains only before_agent_run and before_prompt_build, while the new runner delegates to runClaimingHook for before_route_inbound_message without adding a default budget. (src/plugins/hooks.ts:201, e93836272280)

Likely related people:

  • Peter Steinberger: Authored the reply-dispatch hook and channel seam work closest to this new claiming hook and inbound compatibility boundary. (role: adjacent hook and channel seam contributor; confidence: high; commits: 82ce30b7895a, 625fd5b3e3e2; files: src/plugins/hooks.ts, src/plugins/hook-types.ts, src/channels/message/inbound-reply-dispatch.ts)
  • Vincent Koc: Authored the hook contract split and recent current-main touches to the active hook/channel files involved in this PR. (role: recent plugin hook contract contributor; confidence: medium; commits: 7f5a5a34dbf8, e085fa1a3ffd; files: src/plugins/hook-types.ts, src/plugins/hooks.ts, src/channels/turn/kernel.ts)
  • ZhangXuan: Authored the adjacent before-dispatch delivery semantics change, which is the closest existing route/delivery hook invariant. (role: adjacent dispatch hook contributor; confidence: medium; commits: a10d587b4158; files: src/plugins/hooks.ts, src/plugins/hook-types.ts, docs/plugins/hooks.md)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

…ging

Implement a new plugin hook that fires before OpenClaw resolves the
canonical session key for an inbound message. This enables plugins
(like the channel-bridge) to:

- Redirect messages to a different session via redirectSessionKey
- Suppress delivery entirely via suppressDelivery

The hook follows the 'claiming' pattern (first handler returning
{ handled: true } wins), similar to before_dispatch and reply_dispatch.

Integration points:
- Hook types in src/plugins/hook-types.ts (PluginHookName union,
  PLUGIN_HOOK_NAMES array, PluginHookHandlerMap entry)
- Event/context/result types in src/plugins/hook-message.types.ts
- Handler in src/plugins/hooks.ts (runBeforeRouteInboundMessage)
- Dispatch pipeline wiring in src/plugin-sdk/inbound-reply-dispatch.ts
  (dispatchChannelMessageReplyWithBase — the main inbound routing path)

The hook extracts metadata from MsgContext (NativeChannelId,
OriginatingTo, MessageThreadId, ChatType, From) to populate the
event payload with conversation context.

Fixes: openclaw#81061
@DranboFieldston

Copy link
Copy Markdown
Author

Update: Added full hook infrastructure (types, handler, kernel integration). PR now contains all necessary changes. @clawsweeper re-review?

DranboFieldston added 3 commits May 12, 2026 22:01
- Remove unnecessary String() wrappers (oxlint no-unnecessary-type-conversion)
- Fix ctxPayload access: read from resolved.turn, not params (RunChannelTurnParams doesn't have ctxPayload)
- Update test assertion to call .toHaveBeenCalledOnce() instead of referencing without invocation
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label May 27, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels May 27, 2026
@clawsweeper

clawsweeper Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg: 🎁 locked until real behavior proof passes.

Details
  • No creature or rarity is rolled until proof passes.
  • Eggs are collectible flavor only; they do not affect labels, ratings, merge decisions, or automation.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label May 28, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 19, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added stale Marked as stale due to inactivity triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 19, 2026
@clawsweeper

clawsweeper Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: review started.

I am starting a fresh review of this pull request: feat: add before_route_inbound_message plugin hook for channel bridging This is item 1/1 in the current shard. Shard 6/20.

This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jul 20, 2026
@steipete

Copy link
Copy Markdown
Contributor

Closing per ClawSweeper review verdict stalled_unproven_pr (decision packet 2026-07-19T15:49:30.625Z). This item was part of the audited close backlog (openclaw/clawsweeper#920) stranded by an apply-lane defect, drained manually after re-verification. If this is wrong, reopen and ClawSweeper will re-review.

@steipete steipete closed this Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hook: before_route_inbound_message — pre-routing interception for channel bridging/proxying

2 participants