Skip to content

feat(hooks): implement pre_route hook for dynamic routing before dispatch - #57510

Closed
zhkuang wants to merge 11 commits into
openclaw:mainfrom
zhkuang:feat/pre-route-hook
Closed

zhkuang wants to merge 11 commits into
openclaw:mainfrom
zhkuang:feat/pre-route-hook

Conversation

@zhkuang

@zhkuang zhkuang commented Mar 30, 2026

Copy link
Copy Markdown

Summary

  • Problem: inbound routing decisions that depend on plugin logic could not be applied in the same turn, because existing message hook handling was non-blocking and happened after key routing work had already started.
  • Why it matters: first-turn routing is required for dynamic route/session provisioning; otherwise users see one-turn lag or incorrect initial dispatch target.
  • What changed: added a blocking typed plugin hook named pre_route, executed before dispatch routing, with support for route/session override in the current inbound turn; added timeout fail-open behavior and duplicate-first guard to avoid side effects on replayed messages.
  • What did NOT change (scope boundary): no infra/bonjour changes, no channel-specific behavior changes, no outbound transport protocol changes.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #TBD
  • Related #TBD
  • This PR fixes a bug or regression

Root Cause / Regression History (if applicable)

  • Root cause: route-affecting plugin logic was not available as a blocking pre-dispatch decision point, so route/session overrides were not guaranteed to affect the first inbound turn.
  • Missing detection / guardrail: no dedicated pre-dispatch typed hook for route override; no explicit replay guard for hook side effects before routing.
  • Prior context (git blame, prior PR, issue, or refactor if known): existing typed hooks focused on inbound_claim and message_received semantics, but those are not equivalent to a pre-route blocking contract.
  • Why this regressed now: new dynamic routing/provisioning scenarios require immediate same-turn routing, which exposed the gap.
  • If unknown, what was ruled out: infra socket/bonjour paths were ruled out for this change set and intentionally not modified.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file:
    • dispatch-from-config.test.ts
    • wired-hooks-pre-route.test.ts
  • Scenario the test should lock in:
    • pre_route can override session/account for the current turn.
    • duplicate inbound messages are deduplicated before pre_route side effects.
    • if pre_route blocks past timeout, dispatch continues with current route.
    • hook runner uses first-handled-wins and continues after earlier handler failure.
  • Why this is the smallest reliable guardrail: these tests exercise the exact dispatch seam and typed-hook runner contract without unrelated channel/runtime variability.
  • Existing test that already covers this (if any): existing dispatch and hook-suite coverage now extended with pre_route-specific assertions.
  • If no new test is added, why not: N/A (new tests added).

User-visible / Behavior Changes

  • Plugins can now register pre_route to influence route/session selection before dispatch starts.
  • For handled pre_route with routeOverride, the selected route applies immediately in the same inbound turn.
  • Duplicate inbound replay no longer re-triggers pre_route side effects.
  • If pre_route stalls, dispatch fails open after timeout and continues with current route.

Diagram (if applicable)

Before:
[user inbound message] -> [dispatch starts] -> [non-blocking hook observes message] -> [override cannot reliably affect current turn]

After:
[user inbound message] -> [duplicate guard] -> [blocking pre_route hook] -> [optional route/session override] -> [dispatch continues in same turn]

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No
  • If any Yes, explain risk + mitigation: N/A

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: Node 22 + Vitest
  • Model/provider: N/A
  • Integration/channel (if any): dispatch core + plugin hook runner
  • Relevant config (redacted): default config with mocked hook runner and session store in tests

Steps

  1. Register a pre_route handler returning handled true with routeOverride.
  2. Send one inbound message with a known session/account baseline.
  3. Observe dispatch uses overridden route in the same turn; replay the same message id and verify pre_route is not re-run.

Expected

  • Same-turn route override applies.
  • Duplicate replay is skipped before pre_route.
  • Timeout in pre_route does not deadlock dispatch.

Actual

  • Matches expected in added test coverage and targeted runs.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Targeted verification run:

  • vitest run dispatch-from-config.test.ts wired-hooks-pre-route.test.ts
  • Result: 2 files, 69 tests passed

Human Verification (required)

  • Verified scenarios:
    • pre_route route/session override applies in current turn.
    • duplicate inbound is deduped before pre_route.
    • pre_route timeout path fails open and continues dispatch.
  • Edge cases checked:
    • override with session-only route resolves account fallback from session store.
    • pre_route handler failure in one plugin does not prevent later handler claim.
  • What you did not verify:
    • full end-to-end behavior across all channel adapters with live plugins.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No required changes
  • Migration needed? No
  • If yes, exact upgrade steps: N/A

Risks and Mitigations

  • Risk: plugin pre_route logic may block dispatch.
    • Mitigation: bounded timeout with fail-open continuation in dispatch.
  • Risk: inconsistent account resolution when only sessionKey is overridden.
    • Mitigation: account fallback from target session store when available.
  • Risk: behavioral ambiguity for plugin authors around blocking semantics.
    • Mitigation: docs updated with explicit pre_route decision semantics in SDK docs.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: L labels Mar 30, 2026
@greptile-apps

greptile-apps Bot commented Mar 30, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces a new blocking pre_route typed plugin hook that runs before dispatch routing, allowing plugins to override the session key and account ID for an inbound turn. The duplicate-inbound guard is moved earlier (before any hook side effects), a timeout with fail-open semantics is applied to prevent dispatch stalls, and effectiveCtx is threaded through all downstream call sites to carry any route overrides. The hook runner plumbing follows the established runClaimingHook pattern and is well-covered by new unit tests.

Two issues need attention before merging:

  • CHANGELOG.md has unresolved git merge conflict markers (<<<<<<< HEAD / ======= / >>>>>>> main on lines 19–27). These raw markers will be committed as-is unless the conflict is resolved.
  • routeOverride.agentId is declared in PluginHookPreRouteResult but never consumed in dispatch-from-config.ts. The dispatch logic reads only sessionKey and accountId from the result; agentId is silently dropped. Plugin authors who set this field expecting routing effects will get incorrect behavior with no error signal. Either the field should be wired up or removed from the exported type.

Confidence Score: 4/5

Not safe to merge until the CHANGELOG merge conflict is resolved and the routeOverride.agentId gap is addressed.

Two P0/P1 issues block clean merge: an unresolved merge conflict in CHANGELOG.md that will ship raw conflict markers, and a public API type field (routeOverride.agentId) that is declared but silently ignored in dispatch, creating a misleading contract for plugin authors. The core hook logic, timeout handling, and test coverage are otherwise solid.

CHANGELOG.md (merge conflict) and src/plugins/types.ts together with dispatch-from-config.ts (agentId contract gap)

Important Files Changed

Filename Overview
CHANGELOG.md Contains unresolved git merge conflict markers from a merge with main; must be resolved before this file is correct.
src/auto-reply/reply/dispatch-from-config.ts Core logic for the pre_route feature: duplicate guard moved before hooks, timeout-wrapped runPreRoute call added, effectiveCtx plumbed through all downstream call sites. Logic is sound, but routeOverride.agentId from the result type is never consumed here.
src/plugins/types.ts Adds pre_route hook types; PluginHookPreRouteResult.routeOverride.agentId is declared but never applied in dispatch logic, creating a misleading public API contract.
src/plugins/hooks.ts Adds runPreRoute to the hook runner via the existing runClaimingHook pattern; consistent with other typed hook implementations.
src/auto-reply/reply/dispatch-from-config.test.ts Adds well-structured tests for duplicate deduplication, session/account override, account fallback from session store, and timeout fail-open behavior.
src/plugins/wired-hooks-pre-route.test.ts New test file covering first-handled-wins semantics and handler failure continuation for the pre_route hook runner.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: CHANGELOG.md
Line: 19-27

Comment:
**Unresolved merge conflict markers**

`CHANGELOG.md` contains raw git conflict markers (`<<<<<<< HEAD`, `=======`, `>>>>>>> main`) that were never resolved. This will ship these markers as literal content in the changelog.

The conflict needs to be manually resolved by combining the entries from both sides. Based on the diff, the intended content from this branch is the `pre_route` hook entry and the two Docs/zh-CN entries, while `main` added the LLM idle-stream timeout, OpenAI/Responses verbosity, and Android notification entries. All of these should appear in the final merged list.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/plugins/types.ts
Line: 2083-2090

Comment:
**`routeOverride.agentId` declared but never consumed**

`PluginHookPreRouteResult` exposes `routeOverride.agentId` as a valid override field in the public type contract, but `dispatch-from-config.ts` never reads or applies it when processing the result. In the override-application block (around line 267 of the updated dispatch file), only `sessionKey` and `accountId` are extracted from `routeOverride` — `agentId` is completely ignored.

Plugin authors who follow this type and return a `routeOverride` containing an `agentId` will have their override silently dropped, with no routing effect and no error. Either the field needs to be wired into the dispatch logic, or it should be removed from the exported type until a future version implements it.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix: merge upstream changes and resolve ..." | Re-trigger Greptile

Comment thread CHANGELOG.md Outdated
Comment on lines +19 to +27
<<<<<<< HEAD
- Docs/zh-CN: add a Chinese Diffs tool page so Chinese readers can access the full Diffs viewer, file-rendering, security, and troubleshooting docs. (#40773) Thanks @elliotllliu.
- Docs/zh-CN: align the Chinese Diffs tool page with the current English source and generated translation metadata. Thanks @gumadeiras.
- Plugins/hooks: add a blocking `pre_route` typed hook that can override route/session for the current inbound turn, enabling dynamic route provisioning to apply on the first inbound message instead of waiting for a follow-up turn.
=======
- Agents/LLM: add a configurable idle-stream timeout for embedded runner requests so stalled model streams abort cleanly instead of hanging until the broader run timeout fires. (#55072) Thanks @liuy.
- OpenAI/Responses: forward configured `text.verbosity` across Responses HTTP and WebSocket transports, surface it in `/status`, and keep per-agent verbosity precedence aligned with runtime behavior. (#47106) Thanks @merc1305 and @vincentkoc.
- Android/notifications: add notification-forwarding controls with package filtering, quiet hours, rate limiting, and safer picker behavior for forwarded notification events. (#40175) Thanks @nimbleenigma.
>>>>>>> main

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P0 Unresolved merge conflict markers

CHANGELOG.md contains raw git conflict markers (<<<<<<< HEAD, =======, >>>>>>> main) that were never resolved. This will ship these markers as literal content in the changelog.

The conflict needs to be manually resolved by combining the entries from both sides. Based on the diff, the intended content from this branch is the pre_route hook entry and the two Docs/zh-CN entries, while main added the LLM idle-stream timeout, OpenAI/Responses verbosity, and Android notification entries. All of these should appear in the final merged list.

Prompt To Fix With AI
This is a comment left during a code review.
Path: CHANGELOG.md
Line: 19-27

Comment:
**Unresolved merge conflict markers**

`CHANGELOG.md` contains raw git conflict markers (`<<<<<<< HEAD`, `=======`, `>>>>>>> main`) that were never resolved. This will ship these markers as literal content in the changelog.

The conflict needs to be manually resolved by combining the entries from both sides. Based on the diff, the intended content from this branch is the `pre_route` hook entry and the two Docs/zh-CN entries, while `main` added the LLM idle-stream timeout, OpenAI/Responses verbosity, and Android notification entries. All of these should appear in the final merged list.

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the oversight. I've cleaned up the merge markers in CHANGELOG.md and pushed the fix. It should be clear now. Thanks for catching that!

Comment thread src/plugins/types.ts
Comment on lines +2083 to +2090
export type PluginHookPreRouteResult = {
handled: boolean;
routeOverride?: {
sessionKey: string;
agentId?: string;
accountId?: string;
};
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 routeOverride.agentId declared but never consumed

PluginHookPreRouteResult exposes routeOverride.agentId as a valid override field in the public type contract, but dispatch-from-config.ts never reads or applies it when processing the result. In the override-application block (around line 267 of the updated dispatch file), only sessionKey and accountId are extracted from routeOverride — agentId is completely ignored.

Plugin authors who follow this type and return a routeOverride containing an agentId will have their override silently dropped, with no routing effect and no error. Either the field needs to be wired into the dispatch logic, or it should be removed from the exported type until a future version implements it.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/plugins/types.ts
Line: 2083-2090

Comment:
**`routeOverride.agentId` declared but never consumed**

`PluginHookPreRouteResult` exposes `routeOverride.agentId` as a valid override field in the public type contract, but `dispatch-from-config.ts` never reads or applies it when processing the result. In the override-application block (around line 267 of the updated dispatch file), only `sessionKey` and `accountId` are extracted from `routeOverride` — `agentId` is completely ignored.

Plugin authors who follow this type and return a `routeOverride` containing an `agentId` will have their override silently dropped, with no routing effect and no error. Either the field needs to be wired into the dispatch logic, or it should be removed from the exported type until a future version implements it.

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implemented.
routeOverride.agentId is now consumed in dispatch-from-config by threading it into session-store lookup resolution.
Specifically, pre-route now captures agentId and uses it for both override-account fallback lookup and the main session-store lookup path, so plugin-provided agent overrides have routing effect.
Added a regression test to verify the override reaches resolveStorePath with the expected agentId.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 014642b114

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +294 to +297
...ctx,
SessionKey: resolvedSessionKey,
AccountId: resolvedAccountId,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Apply pre_route override to native command target session

The pre-route override only rewrites SessionKey/AccountId in effectiveCtx, but native-command flows still prioritize CommandTargetSessionKey in resolveSessionStoreLookup, so ACP/send-policy routing can continue on the old session while outbound routing uses the new one. This makes pre_route overrides inconsistent or ineffective for native command turns (for example slash-command resets targeting a specific session). When applying a pre_route override, update the native command target session as well (or change lookup precedence) so all downstream dispatch logic uses the same routed session.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implemented.
When pre_route returns a routeOverride.sessionKey, we now also sync native command targeting so downstream lookup/dispatch uses a single routed session consistently.

  • Updated effectiveCtx to rewrite CommandTargetSessionKey for native turns when the route is overridden.
  • Updated the session-store fallback lookup path (when only sessionKey is overridden) to use the overridden native command target as well.
  • Added a regression test covering native command + pre_route override to verify session store lookup resolves against the overridden session.

Comment thread CHANGELOG.md Outdated
- Agents/MCP: materialize bundle MCP tools with provider-safe names (`serverName__toolName`), support optional `streamable-http` transport selection plus per-server connection timeouts, and preserve real tool results from aborted/error turns unless truncation explicitly drops them. (#49505) Thanks @ziomancer.
- Plugins/hooks: add a `before_install` hook with structured request provenance, built-in scan status, and install-target metadata so external security scanners and policy engines can review and block skill, plugin package, plugin bundle, and single-file plugin installs. (#56050) thanks @odysseus0.
- ACP/plugins: add an explicit default-off ACPX plugin-tools MCP bridge config, document the trust boundary, and harden the built-in bridge packaging/logging path so global installs and stdio MCP sessions work reliably. (#56867) Thanks @joe2643.
<<<<<<< HEAD

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove unresolved merge markers from changelog

This commit leaves Git conflict markers in CHANGELOG.md, which means the unreleased section now contains unresolved branch state instead of valid release notes. That can break changelog parsing/release-note generation and will publish visibly corrupted notes until the conflict is resolved.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the oversight. I've cleaned up the merge markers in CHANGELOG.md and pushed the fix. It should be clear now. Thanks for catching that!

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2fc20c3163

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +295 to +297
const shouldSyncNativeCommandTargetSession =
ctx.CommandSource === "native" &&
resolvedSessionKey !== (ctx.CommandTargetSessionKey?.trim() || undefined);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve native command target when no pre_route override

Gate the CommandTargetSessionKey rewrite on an actual pre-route session override. As written, resolvedSessionKey starts from ctx.SessionKey, so any native turn that already has a different CommandTargetSessionKey satisfies this condition even when pre_route did nothing; the code then overwrites the original target with the source session. That reroutes targeted native commands (e.g., ACP/slash actions aimed at another session) back to the caller session and breaks existing targeting behavior.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implemented: CommandTargetSessionKey sync is now gated by an actual pre_route session override. Native command targets are preserved when no override is returned, and a regression test was added to lock this behavior.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e1a024439c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +269 to +271
...inboundClaimContext,
sessionKey: resolvedSessionKey,
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use native target session in pre_route hook context

For native-command turns, the effective dispatch target is CommandTargetSessionKey (when present), but the pre-route hook context is currently populated from resolvedSessionKey, which starts as ctx.SessionKey. This means plugins evaluating pre_route see the caller session instead of the actual native command target, so routing decisions can be made against the wrong session (for example ACP/slash actions aimed at a different session). Build the pre-route context session key with the same native-target precedence used for dispatch/session lookup.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implemented: pre_route hook context now uses native target precedence (CommandTargetSessionKey when present) for sessionKey, and a regression test was added to verify plugin hooks see the actual native command target session.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 35e0dfc689

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +68 to +70
return await Promise.race([
params.run(),
new Promise<undefined>((resolve) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Cancel timed-out pre_route executions

runPreRouteWithTimeout uses Promise.race to fail open after 8s, but the original params.run() continues running in the background with no cancellation or concurrency cap. If a plugin pre_route handler hangs (for example on a stuck network call), each inbound message creates another long-lived in-flight hook; dispatch keeps progressing, so these pile up and can exhaust memory/sockets or apply delayed side effects out of order. The timeout path should actively cancel or otherwise bound outstanding pre_route executions.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. runPreRouteWithTimeout now creates an AbortController internally and calls controller.abort() when the timeout fires. runPreRoute in hooks.ts accepts an optional signal?: AbortSignal and checks signal.aborted between handler iterations, so timed-out executions stop at the next handler boundary rather than continuing to run in the background.

@yttsws

yttsws commented Mar 31, 2026

Copy link
Copy Markdown

Great, I really need it

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ecd148527c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +379 to +381
const sessionStoreEntry = resolveSessionStoreLookup(effectiveCtx, cfg, {
agentId: resolvedRouteAgentId,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate pre_route agentId override to reply execution

The routeOverride.agentId from pre_route is only used in this resolveSessionStoreLookup call and is never threaded into the actual turn execution path. Downstream logic still resolves the active agent from ctx.CommandTargetSessionKey || ctx.SessionKey (see src/auto-reply/reply/get-reply.ts), so an override like { sessionKey: "session:override:...", agentId: "codex" } can still execute on the default agent. This makes agent-targeted pre-routing inconsistent and can send turns to the wrong workspace/model unless the plugin also encodes the agent in the session key.

Useful? React with 👍 / 👎.

@xyzphp

xyzphp commented Mar 31, 2026

Copy link
Copy Markdown

Great work on this PR! The pre_route hook addresses a critical gap in the routing architecture. The design is solid

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: aea8134e57

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +382 to +384
const sessionStoreEntry = resolveSessionStoreLookup(effectiveCtx, cfg, {
agentId: resolvedRouteAgentId,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate pre_route agent override into dispatch context

routeOverride.agentId is stored in resolvedRouteAgentId but only used for session-store path lookups, so reply execution can still run under the wrong agent when the override session key does not embed an agent id. In this path, replyResolver receives only effectiveCtx, and getReplyFromConfig later resolves agent selection from ctx.CommandTargetSessionKey || ctx.SessionKey (src/auto-reply/reply/get-reply.ts), which ignores the pre-route agent override. Fresh evidence in this commit is that resolvedRouteAgentId is introduced and consumed for resolveSessionStoreLookup(...) only, without being threaded into the downstream agent-selection path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Added agentIdOverride?: string to GetReplyOptions. get-reply.ts now checks opts?.agentIdOverride before falling back to session-key derivation, so the override controls which agent workspace, model config, and tools are used for the entire turn. dispatch-from-config.ts forwards resolvedRouteAgentId (from the pre_route routeOverride) as agentIdOverride when calling the reply resolver.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a6d3e3d176

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/plugins/hooks.ts
Comment on lines +624 to +628
const handlerResult = await (
hook.handler as (
event: unknown,
ctx: unknown,
) => Promise<PluginHookPreRouteResult | void>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Pass AbortSignal into pre_route handlers

The timeout path still cannot cancel a stuck pre_route handler: runPreRouteWithTimeout aborts a signal after 8s, but runPreRoute awaits hook.handler(event, ctx) directly, so a hanging first handler keeps running in the background and each inbound message can add another long-lived in-flight promise. Fresh evidence in this commit is that runPreRoute now accepts signal but does not propagate it to handlers (or enforce a per-handler timeout), so the abort only prevents later iterations and does not stop the active one.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated the pre_route hook contract and runner to pass an AbortSignal into handlers, and the runner now forwards the timeout signal to each handler invocation. I also added regression tests to verify both signal propagation and the already-aborted behavior. This keeps timeout behavior bounded and prevents silent drift in future changes.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5f1486df76

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

...params.replyOptions,
typingPolicy: typing.typingPolicy,
suppressTyping: typing.suppressTyping,
agentIdOverride: resolvedRouteAgentId ?? params.replyOptions?.agentIdOverride,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Apply pre_route agent override before ACP dispatch

When pre_route returns { routeOverride: { sessionKey, agentId } } for a session key that does not embed the agent, this change only forwards agentIdOverride into getReplyFromConfig here, but ACP dispatch is attempted earlier via tryDispatchAcpReply using only sessionKey. In ACP-enabled turns that means ACP resolution still derives the agent from the session key/store path and can miss the intended agent session, causing the turn to bypass ACP and execute on the wrong path. Please thread the pre-route agentId override into ACP resolution/dispatch as well so routing is consistent across both ACP and non-ACP execution.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have fixed this by threading routeOverride.agentId from pre_route into the actual reply execution path, so it now affects turn-time agent resolution instead of being used only for session-store lookup. I also added a regression test to ensure this override is preserved end-to-end.

@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 Apr 30, 2026
@clawsweeper

clawsweeper Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close: the same pre-routing hook problem is now tracked by #81061 with active implementation PR #81198, while this branch is stale against current hook contracts and still has correctness, proof, and trust-boundary blockers.

Canonical path: Consolidate pre-routing hook review on #81061 and #81198, while leaving binding-level content routing decisions on #13304.

So I’m closing this here and keeping the remaining discussion on #81061, #81198, and #13304.

Review details

Best possible solution:

Consolidate pre-routing hook review on #81061 and #81198, while leaving binding-level content routing decisions on #13304.

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

Not applicable: this PR proposes a new public plugin routing hook rather than fixing broken behavior under an existing documented contract. Source inspection of current main shows no pre_route API to reproduce against, and the missing capability is now tracked by the linked canonical issue and PR.

Is this the best way to solve the issue?

No as-is: the branch targets old hook/reply option surfaces and misses current dedupe and ACP routing contracts. The safer solution is to continue the current-design review in #81198 and move any unique semantics there.

Security review:

Security review needs attention: The diff adds a trusted-plugin route override authority and would need explicit scope, boundary, and audit semantics before merge.

  • [medium] Review route override trust boundaries — src/plugins/types.ts:2085
    routeOverride lets a plugin select session key, account id, and agent id before dispatch. That may be appropriate for trusted plugins, but the public SDK contract should define allowed target scope, account/channel boundaries, and audit behavior before exposing it.
    Confidence: 0.83

What I checked:

Likely related people:

  • steipete: Recent history ties @steipete to gateway hook refresh behavior, ACP/reply-dispatch adjacent work, and the public review context for the newer canonical pre-routing issue. (role: recent area contributor and reviewer; confidence: high; commits: 9ca1f1a64e7a, 3d3ef6f65f39; files: src/plugins/hooks.ts, src/auto-reply/reply/dispatch-from-config.ts, src/channels/turn/kernel.ts)
  • gfzhx: Introduced the structurally adjacent before_dispatch plugin hook and dispatch integration in merged PR Plugins: add a before-dispatch hook to the reply pipeline #50444. (role: adjacent hook feature contributor; confidence: high; commits: e9259c5ae0a8, 8bc5f78882a4, af96e3de5c02; files: src/plugins/types.ts, src/plugins/hooks.ts, src/auto-reply/reply/dispatch-from-config.ts)
  • giodl73-repo: Current-main blame for the dedupe/dispatch and reply option surfaces points to PR fix(gateway): fire session:patch hooks for model changes #82257, which recently touched adjacent gateway hook/session behavior. (role: recent area contributor; confidence: medium; commits: dccf5f684211, ebe994317e62, 928cea2e8ef8; files: src/auto-reply/reply/dispatch-from-config.ts, src/auto-reply/get-reply-options.types.ts, src/gateway/session-patch-hooks.ts)
  • vincentkoc: Recent current-main commits updated the active src/plugins/hook-types.ts registry and plugin hook alias behavior, which any revived pre-route design must use. (role: recent plugin hook registry contributor; confidence: medium; commits: a85cd65775fc, 33be0fbea7e1; files: src/plugins/hook-types.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against 225e48f63291.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label May 1, 2026
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 size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants