Skip to content

code-mode: ctx.agentId undefined in before_tool_call for outer code-mode exec dispatch #83387

Closed

Description

@Kaspre

Scope: Bug directly in the Openclaw Code Mode dispatch path introduced by #80600 — every other dispatch path (Pi-direct, Codex Code Mode, nested calls from inside code-mode exec) propagates ctx.agentId correctly; only the outer code-mode exec dispatch falls through with undefined. Surfaced while testing #80600 on 2026.5.16-beta.4.

Problem

When Openclaw dispatches the outer code-mode exec tool call to the before_tool_call hook, ctx.agentId is undefined. The same hook receives a proper ctx.agentId for every other dispatch path I've checked:

  • Pi-direct tool calls (e.g., an agent calling exec({command: "..."}) outside code mode)
  • Codex Code Mode shell exec calls (exec({command: "..."}))
  • Nested tool calls from inside an Openclaw Code Mode exec (per docs: "Nested execution preserves... active agent id")

So agent context is plumbed through the rest of Openclaw — only the outer code-mode exec dispatch falls through with undefined.

Change and value

Populate ctx.agentId from the active run context when Openclaw dispatches the outer code-mode exec to before_tool_call. The same propagation logic used for nested tool calls (via the host bridge inside code mode) should apply to the outer dispatch.

Who's affected

Any plugin using before_tool_call to authorize or audit per-agent — firewall extensions, custom audit hooks, dashboards keyed on principal. All Openclaw Code Mode exec calls currently appear as agent:unknown in such logs and policy evaluation, so per-agent rules can't apply.

Reproduction

Tested on Openclaw 2026.5.16-beta.4.

  1. Install a minimal before_tool_call hook in a plugin/extension:

    api.on("before_tool_call", async (event, ctx) => {
      api.logger.info(
        `tool=${event.toolName} agentId=${ctx?.agentId} input_keys=${Object.keys(event.params).join(",")}`,
      );
    });
  2. Enable tools.codeMode.enabled: true at the root of openclaw.json.

  3. Have any agent invoke exec({code: "return 1;"}).

Expected

tool=exec agentId=test-agent input_keys=code,language

Actual

tool=exec agentId=undefined input_keys=code,language

For comparison, the same agent invoking a Pi-direct tool (read({path: "..."})) or a Codex Code Mode exec (exec({command: "..."})) logs with the agent id correctly populated.

Impact in practice

Discovered while debugging a separate authorization-plugin mis-classification (a per-agent allow rule keyed on tool name + extracted resource didn't match any code-mode dispatch). The compounded effect of agentId=undefined plus the unconventional code input field made every Openclaw Code Mode exec deny-by-default — neither the agent nor the resource could be matched. Fixing only one of the two would have left the other silently broken.

Hook-contract opacity (related)

The outer code-mode exec dispatch is doubly opaque to before_tool_call hook consumers:

  1. ctx.agentId is undefined (the bug above).
  2. The input field is code (with separate language) instead of the conventional command field used by every other exec dispatch in Openclaw (Pi-direct shell, Codex Code Mode).

This compounds for security-focused plugins — e.g. predicate-claw, which uses before_tool_call to apply per-principal authorization rules keyed on tool name + extracted resource. The dispatch arrives with no usable principal and no recognizable resource, so it falls into the plugin's deny-by-default path. The plugin author is then forced into a bad choice: widen rules to allow all outer code-mode exec (losing per-agent and per-resource enforcement), or deny all of them (losing code-mode for affected agents).

A maintainer fixing the agentId propagation is in the same code path that would let them align the input contract too — either by populating params.command alongside params.code, or by using a distinct tool name (e.g. code_exec) so before_tool_call consumers don't get a tool-name collision with an incompatible input contract. The agent-id fix alone is the minimum to make per-agent enforcement tractable; aligning the input contract on top would be a strictly better fix and would close the second opacity dimension in the same change.

Suggested fix

Minimum: when dispatching the outer code-mode exec to before_tool_call, set ctx.agentId from the active run context (the same value used when populating nested-call context inside the QuickJS host bridge).

Better: in the same change, align the input contract for the outer dispatch with the conventional exec shape — either by populating params.command alongside params.code, or by giving Openclaw Code Mode a distinct tool name. See the "Hook-contract opacity" section above.

Local workaround

In our firewall extension we widened the relevant allow rule's principals to ["*"] so it matches agent:unknown too. Nested tools.call() from inside exec re-enters the firewall with proper agent context, so per-agent rules on those nested calls still work — only the outer dispatch is affected.

A more robust workaround is to parse ctx.sessionKey (format agent:<id>:explicit:<session-id>) and recover the agent id manually when ctx.agentId is undefined. That information should not need recovering, though — populating it directly is the right fix.

Related

  • [codex] Add generic OpenClaw code mode #80600 (PR introducing Openclaw Code Mode)
  • Companion docs issue on the Codex Code Mode vs Openclaw Code Mode naming overlap — relevant because the overlap is what makes this bug subtle to discover.

Activity

  1. Kaspre commented on May 18, 2026

    @Kaspre
    ContributorAuthor

    Companion docs issue on the Codex Code Mode vs OC generic code mode naming overlap: #83390 — the overlap is part of why this propagation bug is subtle to discover.

  2. clawsweeper commented on May 18, 2026

    @clawsweeper
    Contributor

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve.

    Workflow note: Future ClawSweeper reviews update this same comment in place.

    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 maintainer comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
    • PR/issue authors can comment @clawsweeper re-review or @clawsweeper re-run on their own 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.

    Summary
    Keep open: current main still has a source-level path where the model-visible OpenClaw code-mode exec control reaches before_tool_call without a HookContext, while normal wrapped tools, client tools, and nested catalog tools have agent context available.

    Reproducibility: yes. source-reproducible on current main. The outer code-mode controls are visible unwrapped tools that enter toToolDefinitions, whose hook call omits ctx, while runBeforeToolCallHook only forwards agentId from args.ctx.agentId.

    Next step
    The fix shape is narrow, but the affected hook context is used for authorization/audit policy and should get maintainer/security review before a repair branch is promoted.

    Security
    Needs attention: The issue is security-sensitive because missing ctx.agentId can break per-agent authorization and audit decisions in before_tool_call hooks.

    Review details

    Best possible solution:

    Pass the existing per-run HookContext into visible code-mode control dispatch before Pi adapter execution, preserve the single-hook behavior for already wrapped tools, and add focused regression coverage for outer exec plus nested calls.

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

    Yes, source-reproducible on current main. The outer code-mode controls are visible unwrapped tools that enter toToolDefinitions, whose hook call omits ctx, while runBeforeToolCallHook only forwards agentId from args.ctx.agentId.

    Is this the best way to solve the issue?

    Yes for the minimum bug: carry the already-resolved run hook context into the outer exec/wait control dispatch rather than asking plugins to parse sessionKey or widen policies. The input-shape alignment suggestion should be handled as a separate API/contract decision if maintainers want it.

    Security concerns:

    • [medium] Restore agent context for code-mode hook authorization — src/agents/pi-tool-definition-adapter.ts:241
      The current outer code-mode control path can invoke before_tool_call without ctx.agentId, so security-focused plugins may classify code-mode executions as an unknown principal or require overly broad workarounds.
      Confidence: 0.88

    Acceptance criteria:

    • node scripts/run-vitest.mjs src/agents/code-mode.test.ts
    • node scripts/run-vitest.mjs src/agents/pi-tools.before-tool-call.integration.e2e.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.fires-once.test.ts

    What I checked:

    • Outer visible tool adapter lacks hook context: toToolDefinitions still calls runBeforeToolCallHook with toolName, params, and toolCallId only; there is no ctx argument on this path, so an unwrapped visible control tool cannot forward agentId. (src/agents/pi-tool-definition-adapter.ts:241, 1ab84b4327c1)
    • Hook contract only includes agentId when ctx is provided: runBeforeToolCallHook constructs the plugin hook context with agentId only from args.ctx.agentId, confirming that a missing ctx produces the reported undefined agent id. (src/agents/pi-tools.before-tool-call.ts:531, 1ab84b4327c1)
    • Code-mode controls carry run data but are not wrapped before adapter dispatch: The embedded runner builds catalogToolHookContext with agentId: sessionAgentId and also creates code-mode controls with that same agent id, but the controls are then exposed as visible tools and later converted through the contextless adapter path. (src/agents/pi-embedded-runner/run/attempt.ts:1680, 1ab84b4327c1)
    • Nested catalog path preserves hook context separately: Nested catalog entries wrap non-control tools with toolHookContext, and applyToolCatalogCompaction passes that context into catalog entries, matching the reporter's distinction between nested calls and the outer code-mode control call. (src/agents/tool-search.ts:482, 1ab84b4327c1)
    • Documented code-mode contract expects hook/context preservation for nested execution: The code-mode docs say nested execution preserves active agent id and plugin before_tool_call hooks, and plugin hook docs list ctx.agentId among hook context fields; that supports treating missing agent context as a contract bug, not a new feature request. Public docs: docs/reference/code-mode.md. (docs/reference/code-mode.md:523, 1ab84b4327c1)
    • Existing tests cover wrapped/client hook context but not outer code-mode control context: Current hook tests assert wrapped tools and client tools receive agent context, while code-mode tests exercise exec/wait behavior without a before_tool_call agent-context assertion for the outer control dispatch. (src/agents/pi-tools.before-tool-call.integration.e2e.test.ts:275, 1ab84b4327c1)

    Likely related people:

    • steipete: Related PR [codex] Add generic OpenClaw code mode #80600 introduced generic OpenClaw code mode, and local git show ties the code-mode hardening commit to Peter Steinberger touching src/agents/code-mode.ts and its tests. (role: introduced behavior / feature owner; confidence: high; commits: 0db097936568, bd4da03e68df; files: src/agents/code-mode.ts, src/agents/code-mode.test.ts, docs/reference/code-mode.md)
    • mjamiv: Current checkout blame for the central adapter, runner, tool-search, and docs lines resolves to commit c93d6d8daa37fadbbd98611f08c7489b3dc14097; because that commit is broad, this is a weaker routing signal than the code-mode feature PR. (role: recent current-main line provenance; confidence: low; commits: c93d6d8daa37; files: src/agents/pi-tool-definition-adapter.ts, src/agents/pi-embedded-runner/run/attempt.ts, src/agents/tool-search.ts)

    Remaining risk / open question:

    • No live code-mode session or Vitest run was executed in this read-only cleanup pass; the reproduction is source-level.
    • The issue also raises the exec input-shape collision (code versus command), which is broader than the minimum agent-id propagation fix and may need a separate contract decision.

    Codex review notes: model gpt-5.5, reasoning high; reviewed against 1ab84b4327c1.

  3. added
    P1
    impact:security
    impact:auth-provider
    clawsweeper:source-repro
    clawsweeper:no-new-fix-pr
    clawsweeper:queueable-fix
    clawsweeper:fix-shape-clear
    clawsweeper:needs-security-review
    issue-rating: 🦞 diamond lobster
    clawsweeper:needs-maintainer-review
    and removed
    clawsweeper:queueable-fix
    on May 18, 2026
  4. locked as resolved and limited conversation to collaborators on May 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1clawsweeper:fix-shape-clearclawsweeper:needs-maintainer-reviewclawsweeper:needs-security-reviewclawsweeper:no-new-fix-prclawsweeper:source-reproimpact:auth-providerimpact:securityissue-rating: 🦞 diamond lobster

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions