Skip to content

fix: reply hooks can claim ordinary agent turns - #108353

Merged
steipete merged 7 commits into
openclaw:mainfrom
MohandesD:agent/fix-before-agent-reply-user-turns
Jul 16, 2026
Merged

steipete merged 7 commits into
openclaw:mainfrom
MohandesD:agent/fix-before-agent-reply-user-turns

Conversation

@MohandesD

@MohandesD MohandesD commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Closes #108349

What Problem This Solves

Fixes an issue where users sending a prompt that a runtime plugin can answer deterministically would still wait for an embedded or CLI-backed model when the turn was triggered normally rather than by cron.

The runner call sites restricted before_agent_reply to cron turns. The earlier auto-reply call site could run before runtime plugins were available, so it did not reliably provide the documented pre-model interception point.

Why This Change Was Made

The embedded and CLI agent runners are now the canonical before_agent_reply interception point for supported user, heartbeat, and cron turns. The earlier auto-reply call site was removed so a hook that declines a turn cannot execute twice. Internal/manual runs remain excluded. Existing cron handling, handled/silent replies, fail-open behavior, execution-phase reporting, identity context, and pre-resource-allocation ordering are preserved.

This is a generic plugin-hook fix. It adds no plugin-specific policy, configuration, or provider dependency.

User Impact

Runtime plugins can claim ordinary user turns before model/backend execution. Deterministic workflows can therefore return immediately without unnecessary model latency, tokens, or provider cost; declining hooks continue into the selected runtime normally.

Evidence

  • TDD regression coverage proves trigger: "user" can be claimed before an embedded attempt and before CLI preparation/subprocess execution.
  • Regression coverage preserves native sender/chat/channel identity and proves internal/manual embedded and CLI runs are not exposed to reply hooks.
  • Existing cron claim, silent reply, decline/fall-through, phase reporting, and no-hook cases remain covered in the same focused suites.
  • pnpm vitest run src/agents/cli-runner.before-agent-reply-cron.test.ts src/agents/embedded-agent-runner/run.before-agent-reply-cron.test.ts src/auto-reply/reply/get-reply.before-agent-reply.test.ts — 50 tests passed across 4 Vitest project shards.
  • oxfmt --check, oxlint, and git diff --check on the touched surface — passed.
  • Live Raspberry Pi/Telegram proof using the equivalent installed-build patch: a deterministic lookup was claimed in 1.31 ms with zero provider calls; a non-matching query fell through to exactly one model call.
  • Built-in Codex commit review completed and identified two regressions; both were verified, fixed, and covered by tests.
  • OpenClaw structured autoreview (--mode branch --base origin/main, Codex gpt-5.6-sol, high reasoning) completed cleanly after fixes: no accepted/actionable findings; overall patch correct.
  • Crabbox and the Blacksmith CLI are installed and pass startup checks. The delegated Blacksmith test remains pending because browser authentication timed out; no Blacksmith result is claimed.

AI assistance

  • AI-assisted; the author reviewed the implementation and understands the canonical runner ownership and short-circuit behavior.
  • The issue and PR include the relevant prompt-derived design constraints and validation evidence. No private transcript or credentials are included.

@clawsweeper

clawsweeper Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed July 16, 2026, 5:32 AM ET / 09:32 UTC.

Summary
The PR moves before_agent_reply interception into embedded and CLI runners for user, heartbeat, and cron turns, deduplicates execution across fallbacks, and removes the earlier auto-reply call site.

PR surface: Source +9, Tests +10. Total +19 across 11 files.

Reproducibility: yes. at source level: current embedded and CLI runner branches dispatch before_agent_reply only for cron, while ordinary user turns can reach those runners without a reliable runtime-plugin interception point. The supplied focused tests and live run further support the report, although this review did not execute untrusted branch code locally.

Review metrics: 1 noteworthy metric.

  • Hook contract semantics: 1 public event field changed semantically. before_agent_reply.event.cleanedBody changes from normalized user input to the composed model prompt, which can break existing plugin matching behavior.

Stored data model
Persistent data-model change detected: persistent cache schema: src/auto-reply/reply/get-reply.before-agent-reply.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #108349
Summary: This PR is the explicit candidate fix for the linked ordinary-turn hook-dispatch bug.

Members:

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

Merge readiness
Overall: 🦪 silver shellfish
Proof: 🦞 diamond lobster
Patch quality: 🦪 silver shellfish
Result: blocked by patch quality or review findings.

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

Rank-up moves:

  • [P2] Preserve the normalized cleanedBody separately from the model prompt and add full-pipeline embedded/CLI coverage.
  • [P2] Rebase the conflicted draft and obtain green exact-head required checks after the repair.

Risk before merge

  • [P1] Existing plugins that exact-match or parse event.cleanedBody may stop claiming user turns because they receive a metadata- and context-enriched model prompt instead.
  • [P1] The draft head is currently conflicted and several aggregate checks failed, so the eventual rebased merge result has not received exact-head validation.

Maintainer options:

  1. Preserve the hook payload contract (recommended)
    Thread the normalized cleanedBody through fallback and runner parameters, keep params.prompt model-facing, and add full-pipeline embedded and CLI regression coverage before merge.
  2. Pause the draft
    Leave the PR open as a draft until the compatibility repair is complete, then rebase and rerun exact-head checks.

Next step before merge

  • The external PR remains a conflicted draft with a blocking plugin-contract defect; the contributor should repair and rebase the branch before normal maintainer review resumes.

Security
Cleared: The diff adds no dependency, workflow, secret, permission, download, or new untrusted-code execution surface; registered runtime plugins already possess this claiming-hook authority.

Review findings

  • [P1] Preserve the cleaned user body in the hook event — src/agents/cli-runner.ts:490
Review details

Best possible solution:

Keep runner-level dispatch and once-per-turn fallback deduplication, but thread the normalized post-inline-action user body separately from the model prompt into both runners and cover the complete auto-reply-to-runner path for embedded and CLI execution.

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

Yes at source level: current embedded and CLI runner branches dispatch before_agent_reply only for cron, while ordinary user turns can reach those runners without a reliable runtime-plugin interception point. The supplied focused tests and live run further support the report, although this review did not execute untrusted branch code locally.

Is this the best way to solve the issue?

No, not as submitted. Moving ownership to the canonical runners and deduplicating fallbacks is the right shape, but the normalized hook input must remain separate from the model-facing prompt.

Full review comments:

  • [P1] Preserve the cleaned user body in the hook event — src/agents/cli-runner.ts:490
    The new runner seam fills event.cleanedBody with params.prompt, but the existing contract supplies the directive- and inline-action-normalized user body. The runner prompt can include inbound metadata, system events, active-goal text, and thread context, so existing plugins that exact-match or parse cleanedBody will stop claiming ordinary turns. Thread the normalized body separately through the fallback/run parameters and test a real getReplyFromConfig path for both embedded and CLI runners.
    Confidence: 0.96

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 57ae43a89c92.

Label changes

Label changes:

  • add P2: This fixes a real but bounded plugin workflow bug that adds latency and provider cost without making the core runtime unusable.
  • add merge-risk: 🚨 compatibility: Merging the current patch can break shipped plugins that rely on before_agent_reply.event.cleanedBody containing normalized user text.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body reports an after-fix live Raspberry Pi/Telegram run where a deterministic match returned in 1.31 ms with zero provider calls and a non-match fell through to exactly one model call; this proves the central interception behavior, though not the payload-compatibility concern.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The PR body reports an after-fix live Raspberry Pi/Telegram run where a deterministic match returned in 1.31 ms with zero provider calls and a non-match fell through to exactly one model call; this proves the central interception behavior, though not the payload-compatibility concern.

Label justifications:

  • P2: This fixes a real but bounded plugin workflow bug that adds latency and provider cost without making the core runtime unusable.
  • merge-risk: 🚨 compatibility: Merging the current patch can break shipped plugins that rely on before_agent_reply.event.cleanedBody containing normalized user text.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The PR body reports an after-fix live Raspberry Pi/Telegram run where a deterministic match returned in 1.31 ms with zero provider calls and a non-match fell through to exactly one model call; this proves the central interception behavior, though not the payload-compatibility concern.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body reports an after-fix live Raspberry Pi/Telegram run where a deterministic match returned in 1.31 ms with zero provider calls and a non-match fell through to exactly one model call; this proves the central interception behavior, though not the payload-compatibility concern.
Evidence reviewed

PR surface:

Source +9, Tests +10. Total +19 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 7 153 144 +9
Tests 4 178 168 +10
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 331 312 +19

What I checked:

  • Current hook payload contract: Current main invokes before_agent_reply after directive and inline-action processing with the normalized cleanedBody, keeping it distinct from the prompt later assembled for model execution. (raw.githubusercontent.com) (src/auto-reply/reply/get-reply.ts:1023, 57ae43a89c92)
  • PR changes the payload meaning: The proposed runner call passes params.prompt as event.cleanedBody; this field therefore receives the model-facing command prompt rather than the normalized user body. (src/agents/cli-runner.ts:490, f336138fca51)
  • Model prompt contains additional context: The reply pipeline constructs prefixedCommandBody through buildReplyPromptEnvelope, which can add inbound metadata, active goals, system events, reply/thread context, and other prompt material before runner execution. (raw.githubusercontent.com) (src/auto-reply/reply/get-reply-run.ts, 57ae43a89c92)
  • Root cause is source-reproducible: Current embedded and CLI runners explicitly restrict their own hook dispatch to trigger === "cron", while the hook contract is a general pre-model claiming hook. (raw.githubusercontent.com) (src/agents/embedded-agent-runner/run-orchestrator.ts, 57ae43a89c92)
  • Linked canonical report: The linked issue documents the same embedded/CLI user-turn gap on v2026.7.1, and this PR uses closing syntax for that report.
  • Validation state: The focused runner and hook test shards are reported green and the PR body includes a live Raspberry Pi/Telegram run, but the current draft head is conflicted and aggregate required checks remain failed. (f336138fca51)

Likely related people:

  • steipete: Authored the PR commit that introduced once-per-admitted-turn hook ownership and directly refined this runner/lifecycle design. (role: recent area contributor; confidence: high; commits: d001d4a9a395, f336138fca51; files: src/plugins/before-agent-reply.ts, src/infra/agent-events.ts, src/agents/cli-runner.ts)
  • Takhoffman: Current-main history for src/plugins/hooks.ts identifies recent work on the shared hook runner, making this person relevant to preserving the claiming-hook contract. (role: recent hook-runner contributor; confidence: medium; files: src/plugins/hooks.ts)
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.
Review history (1 earlier review cycle)
  • reviewed 2026-07-16T08:54:33.006Z sha f336138 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 16, 2026
@steipete
steipete force-pushed the agent/fix-before-agent-reply-user-turns branch from f336138 to 0334da7 Compare July 16, 2026 17:58
@steipete
steipete marked this pull request as ready for review July 16, 2026 18:48
@steipete
steipete merged commit 63b0cac into openclaw:main Jul 16, 2026
301 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

@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: bfb4f39b6d

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +38 to +39
export function buildHandledBeforeAgentReplyPayloads(reply?: ReplyPayload): ReplyPayload[] {
return [reply ?? { text: SILENT_REPLY_TOKEN }];

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 Strip core-only media trust from hook replies

When a before_agent_reply handler returns a payload containing trustedLocalMedia: true (easy from JS or an as any cast), this helper now forwards that internal trust bit unchanged into dispatch. The plugin SDK explicitly omits trustedLocalMedia from plugin-facing replies (src/plugin-sdk/reply-payload.ts:12), and other hook reply payload paths strip it unless they can prove the media refs were already trusted (src/plugins/hooks.ts:284), because webchat media embedding gates local audio on that flag (src/gateway/server-methods/chat-webchat-media.ts:83). Preserve metadata and the public reply fields, but sanitize this core-only flag before returning plugin-owned hook replies.

Useful? React with 👍 / 👎.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 17, 2026
* fix: honor reply hooks for user agent turns

* fix: preserve reply hook turn context

* fix: gate CLI reply hooks by trigger

* fix(plugins): run reply hooks once per admitted turn

Co-authored-by: Clive (OpenClaw) <[email protected]>

* fix(plugins): reconcile reply hooks after rebase

* fix(auto-reply): dispatch hooks for active steers

* test: use valid channel context shape in steer hook test

---------

Co-authored-by: Clive (OpenClaw) <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
* fix: honor reply hooks for user agent turns

* fix: preserve reply hook turn context

* fix: gate CLI reply hooks by trigger

* fix(plugins): run reply hooks once per admitted turn

Co-authored-by: Clive (OpenClaw) <[email protected]>

* fix(plugins): reconcile reply hooks after rebase

* fix(auto-reply): dispatch hooks for active steers

* test: use valid channel context shape in steer hook test

---------

Co-authored-by: Clive (OpenClaw) <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: before_agent_reply skips ordinary embedded and CLI user turns

2 participants