Skip to content

fix(agents): forward agent/session/run identity to tool-result middleware - #107000

Closed
SebTardif wants to merge 4 commits into
openclaw:mainfrom
SebTardif:fix/tool-result-middleware-context
Closed

SebTardif wants to merge 4 commits into
openclaw:mainfrom
SebTardif:fix/tool-result-middleware-context

Conversation

@SebTardif

@SebTardif SebTardif commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Closes #106910

What Problem This Solves

Fixes an issue where installed AgentToolResultMiddleware handlers on the
OpenClaw embedded runtime never received agentId, sessionId,
sessionKey, or runId, even though those fields are part of the public
middleware context and the Codex path already forwards them. Middleware
used for audit, telemetry, or session-scoped policy therefore could not
attribute OpenClaw tool-result events.

Why This Change Was Made

buildAgentToolResultMiddlewareFactory constructed
createAgentToolResultMiddlewareRunner({ runtime: "openclaw" }) only.
Pass agent/session/run identity from the embedded attempt (and compact)
call sites into that runner, matching the Codex toToolResultHookContext
shape. Fall back to SessionManager.getSessionId() when an explicit
session id is not provided.

User Impact

Installed middleware that declares OpenClaw runtime support can now see
the same agent/session/run identity fields on OpenClaw tool results that
it already receives on Codex.

Evidence

Installed middleware observed identity fields during an embedded OpenClaw
tool_result event (production buildEmbeddedExtensionFactories path):

$ node --import tsx scripts/proof-tool-result-middleware-identity.mjs
[state/db] state database schema migration pending; verifying integrity first
INSTALLED middleware observations:
[
  {
    "toolName": "read",
    "toolCallId": "call-proof-1",
    "runtime": "openclaw",
    "agentId": "main",
    "sessionId": "session-proof-107000",
    "sessionKey": "agent:main:chat",
    "runId": "run-proof-107000"
  }
]
handler result content: [{"type":"text","text":"middleware-ok"}]
RESULT: PASS — installed middleware received agent/session/run identity

Factory-level regression tests still cover explicit context construction and
SessionManager sessionId fallback.

Real behavior proof

Behavior addressed: Installed AgentToolResultMiddleware handlers on the OpenClaw embedded runtime never received agentId/sessionId/sessionKey/runId; they now receive the same identity fields as Codex.

Real environment tested: macOS darwin arm64, worktree /tmp/oc-proof-107000 on branch fix/tool-result-middleware-context rebased onto current upstream/main, Node via node --import tsx.

Exact steps or command run after this patch:

cd /tmp/oc-proof-107000
CI=true pnpm install --frozen-lockfile
node --import tsx scripts/proof-tool-result-middleware-identity.mjs

Evidence after fix: terminal output copied below.

[state/db] state database schema migration pending; verifying integrity first
INSTALLED middleware observations:
[
  {
    "toolName": "read",
    "toolCallId": "call-proof-1",
    "runtime": "openclaw",
    "agentId": "main",
    "sessionId": "session-proof-107000",
    "sessionKey": "agent:main:chat",
    "runId": "run-proof-107000"
  }
]
handler result content: [{"type":"text","text":"middleware-ok"}]
RESULT: PASS — installed middleware received agent/session/run identity

Observed result after fix: The installed plugin middleware handler received runtime=openclaw, agentId=main, sessionId=session-proof-107000, sessionKey=agent:main:chat, runId=run-proof-107000 for a real tool_result event dispatched through the embedded extension factory.

What was not tested: Full gateway Discord/WhatsApp turn with a published marketplace middleware package (plugin registry path was exercised via createEmptyPluginRegistry + setActivePluginRegistry).

Summary

  • Thread agentId/sessionId/sessionKey/runId into OpenClaw tool-result middleware context
  • Wire from prepareEmbeddedAttemptAgentSession and compact
  • Regression tests for explicit context and SessionManager fallback

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jul 14, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 14, 2026
@clawsweeper

clawsweeper Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 18, 2026, 6:52 PM ET / 22:52 UTC.

Summary
The PR forwards embedded OpenClaw agent, session, session-key, and run identity into tool-result middleware, adds focused factory tests, and registers a standalone runtime proof script with Knip.

PR surface: Source +32, Tests +60, Other +104. Total +196 across 6 files.

Reproducibility: yes. at source level: the linked report identifies the runner being created without identity fields, and the PR’s terminal proof observes those fields at a registered middleware handler after the change. I did not independently execute the reproduction in this read-only review.

Review metrics: none identified.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #106910
Summary: This PR directly implements the open canonical report’s missing middleware-identity propagation.

Members:

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

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

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

Rank-up moves:

  • [P2] Complete the direct ../codex tool-result contract inspection required by repository policy before approving the exact head.

Risk before merge

  • [P1] Repository policy requires a direct inspection of the sibling ../codex source for the exact tool-result contract before a final Codex-related merge verdict; that independent contract check is still required.

Maintainer options:

  1. Decide the mitigation before merge
    Retain the prepared-facts forwarding design, complete the direct Codex sibling-contract comparison, and then merge the focused fix so installed OpenClaw middleware receives the same available identity context as the Codex path.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Next step before merge

  • [P2] No mechanical repair is indicated; an agents-area reviewer should complete the required direct Codex sibling-contract comparison and make the normal merge decision on the exact head.

Security
Cleared: The diff forwards already-available runtime identity to an existing middleware runner and adds local tests/proof tooling; it introduces no new dependency, secret, permission, download, or execution boundary.

Review details

Best possible solution:

Retain the prepared-facts forwarding design, complete the direct Codex sibling-contract comparison, and then merge the focused fix so installed OpenClaw middleware receives the same available identity context as the Codex path.

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

Yes, at source level: the linked report identifies the runner being created without identity fields, and the PR’s terminal proof observes those fields at a registered middleware handler after the change. I did not independently execute the reproduction in this read-only review.

Is this the best way to solve the issue?

Yes, subject to the required sibling Codex contract check: forwarding already-prepared attempt and compaction facts into the existing middleware runner is the narrowest maintainable repair and avoids a new API or state path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 556a2ee276f0.

Label changes

Label justifications:

  • P2: This fixes session-scoped middleware attribution for installed plugins without evidence of message loss, runtime outage, or a release-blocking setup failure.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes after-fix terminal output from a registered middleware invoked through buildEmbeddedExtensionFactories, showing agentId, sessionId, sessionKey, and runId; the output contains no apparent private credentials.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes after-fix terminal output from a registered middleware invoked through buildEmbeddedExtensionFactories, showing agentId, sessionId, sessionKey, and runId; the output contains no apparent private credentials.
Evidence reviewed

PR surface:

Source +32, Tests +60, Other +104. Total +196 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 3 35 3 +32
Tests 1 60 0 +60
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 104 0 +104
Total 6 199 3 +196

What I checked:

  • Public middleware contract: The linked bug documents that AgentToolResultMiddlewareContext exposes optional agentId, sessionId, sessionKey, and runId, while the historical OpenClaw factory supplied only runtime. (src/plugins/agent-tool-result-middleware-types.ts:23, 345083a5ab95)
  • Narrow runtime boundary: The proposed factory creates the existing OpenClaw middleware runner with prepared identity facts and both embedded entry paths supply those facts; this keeps ownership at the embedded-runner boundary rather than introducing a parallel middleware API. (src/agents/embedded-agent-runner/extensions.ts:52, 013a2483fa38)
  • Sibling path coverage: The compact path now supplies the effective run, agent, session, and session-key facts, resolving the prior review-cycle concern that compaction would remain un-attributed. (src/agents/embedded-agent-runner/compact.ts:1449, 013a2483fa38)
  • Focused validation: The added tests assert explicit identity forwarding and SessionManager session-id fallback; the PR body also supplies after-fix terminal output from an installed registered middleware receiving all four fields. (src/agents/embedded-agent-runner/extensions.test.ts:156, 013a2483fa38)
  • Canonical bug remains open: The linked report is still open and describes the same OpenClaw-versus-Codex context parity defect, so this PR is a candidate fix rather than an obsolete branch.

Likely related people:

  • unknown: The available review material identifies the affected embedded-runner files but does not provide enough current-main blame or log provenance to name a reliable owner without guessing. (role: feature-history owner not established; confidence: low; files: src/agents/embedded-agent-runner/extensions.ts, src/agents/embedded-agent-runner/compact.ts, src/agents/embedded-agent-runner/run/attempt-session.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 (17 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-14T10:08:45.745Z sha 9183426f29fc9ad31925be493c15016206801f79 :: needs real behavior proof before merge. :: [P2] Forward the effective compaction identity
  • reviewed 2026-07-14T18:05:19.860Z sha d2b7a0fae6528911fb31c7f23b222a201a9203b6 :: needs real behavior proof before merge. :: [P2] Forward the effective compaction identity
  • reviewed 2026-07-14T18:35:44.670Z sha d2b7a0fae6528911fb31c7f23b222a201a9203b6 :: needs real behavior proof before merge. :: [P2] Forward the effective identity from compact runs | [P3] Remove the release-owned changelog entry
  • reviewed 2026-07-18T12:13:16.530Z sha d7e527656d9e710f04063bb922cab88778661873 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-18T12:55:37.081Z sha d7e527656d9e710f04063bb922cab88778661873 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-18T18:13:46.999Z sha 6fe3995254f036b6e644e183ff5a5b7cb541cfd4 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-18T21:27:49.100Z sha 159782a :: needs maintainer review before merge. :: none
  • reviewed 2026-07-18T22:09:46.575Z sha 013a248 :: needs maintainer review before merge. :: none

@SebTardif
SebTardif force-pushed the fix/tool-result-middleware-context branch from fd981e4 to 9183426 Compare July 14, 2026 03:00
@SebTardif

Copy link
Copy Markdown
Contributor Author

Note on check-lint (src/infra/push-apns-http2.ts:150 preserve-caught-error):

That file is not in this PR. The diff only touches middleware identity wiring under src/agents/embedded-agent-runner/ plus CHANGELOG. On current main, that throw already includes { cause: err }. Treating the failure as merge-base/main lint noise rather than a change introduced here.

checks-fast-loc-ratchet is green after keeping compact.ts un-grown (identity fields only on the attempt-session path).

@SebTardif
SebTardif force-pushed the fix/tool-result-middleware-context branch 2 times, most recently from 16b5b44 to d2b7a0f Compare July 14, 2026 17:48
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 14, 2026
@SebTardif
SebTardif force-pushed the fix/tool-result-middleware-context branch from d2b7a0f to d7e5276 Compare July 18, 2026 12:09
@SebTardif

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@SebTardif

Copy link
Copy Markdown
Contributor Author

Rebased onto current main and closed the compact sibling gap:

  1. buildEmbeddedExtensionFactories now accepts and forwards agentId / sessionId / sessionKey / runId into createAgentToolResultMiddlewareRunner.
  2. Attempt path (prepareEmbeddedAttemptAgentSession) and compact path (compactEmbeddedAgentSessionDirect) both pass those fields.
  3. Removed CHANGELOG.md edit.
  4. Added unit tests that assert the middleware factory receives identity context (and SessionManager fallback for sessionId).
$ pnpm exec vitest run src/agents/embedded-agent-runner/extensions.test.ts
Test Files  2 passed (2)
Tests  14 passed (14)

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 18, 2026
@SebTardif
SebTardif force-pushed the fix/tool-result-middleware-context branch from d7e5276 to 6fe3995 Compare July 18, 2026 18:10
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Jul 18, 2026
…ware

The OpenClaw embedded path constructed createAgentToolResultMiddlewareRunner
with only { runtime: "openclaw" }, so installed AgentToolResultMiddleware
handlers never saw agentId, sessionId, sessionKey, or runId. Pass those
fields from the attempt path and the compact sibling path. No CHANGELOG
edit (release-owned).

Closes openclaw#106910

Signed-off-by: Sebastien Tardif <[email protected]>
Exercise buildEmbeddedExtensionFactories with a registered plugin
middleware and a tool_result event so agent/session/run identity is
observed at the installed-handler boundary.

Signed-off-by: Sebastien Tardif <[email protected]>
@SebTardif
SebTardif force-pushed the fix/tool-result-middleware-context branch from 6fe3995 to ad8cfcf Compare July 18, 2026 21:23
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts and removed size: S labels Jul 18, 2026
Signed-off-by: Sebastien Tardif <[email protected]>
@SebTardif

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 18, 2026
Prevent deadcode:unused-files failure on scripts/proof-tool-result-middleware-identity.mjs.

Signed-off-by: Sebastien Tardif <[email protected]>
steipete added a commit that referenced this pull request Jul 29, 2026
Fixes #106910.

Preserve the contributor design from #107000 while updating both the normal and current compaction owner paths.

Co-authored-by: Sebastien Tardif <[email protected]>
@steipete

Copy link
Copy Markdown
Contributor

Thank you, @SebTardif. Your reviewed fix for #106910 has now landed in maintainer PR #115821 as bed7014, with your original Co-authored-by: Sebastien Tardif <[email protected]> credit preserved in the actual canonical merge commit.

The original branch was no longer mergeable against current main because compaction factory ownership moved to src/agents/embedded-agent-runner/compaction-session-execution.ts. The landed change carries your prepared-identity design through both current normal and compaction owners without shipping the standalone proof script or changing Knip configuration.

We independently reproduced both missing identities through a real installed plugin and actual extension tool-result event (red before, green after), verified all 588 owner/Codex/plugin regressions, full type and changed gates, all three official hard-zero dead-export scans, fresh xhigh autoreview, and the exact-head hosted openclaw/ci-gate.

Issue #106910 is now actually closed as completed. Closing this superseded original only after independently confirming the credited merge and issue closure. Thank you for the fix!

@steipete steipete closed this Jul 29, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 30, 2026
Fixes openclaw#106910.

Preserve the contributor design from openclaw#107000 while updating both the normal and current compaction owner paths.

Co-authored-by: Sebastien Tardif <[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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: OpenClaw AgentToolResultMiddleware omits agent/session/run context

2 participants