Skip to content

fix(code-mode): align outer exec hook params - #83483

Merged
steipete merged 2 commits into
openclaw:mainfrom
Kaspre:fix/code-mode-hook-agent-context
May 22, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
Kaspre:fix/code-mode-hook-agent-context

Conversation

@Kaspre

@Kaspre Kaspre commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #83387 after #83481 landed the active hook-context plumbing.

Problem

Code-mode exposes its outer exec control tool through the Pi custom-tool adapter. On current main, the active hook context is already threaded into that outer dispatch via toolHookContext, which gives before_tool_call handlers the active agent/session/run identity.

The remaining gap is that the outer code-mode exec input is model-facing code, while conventional exec-shaped hook policies inspect command. That makes it harder for one policy to reason consistently about outer code-mode exec and normal exec-shaped dispatches.

Why this matters

Several code execution surfaces can reach hook policy with similar intent but different names and payload shapes:

Surface Hook-facing tool name Source field Runtime
OpenClaw code-mode exec exec code today, code + command after this PR QuickJS-WASI code mode
Pi shell exec exec command host shell
Codex shell relay shell_command / unified_exec command Codex shell tools
Proposed Codex code-mode hook coverage code_mode_exec with exec alias command Codex code mode

The important OpenClaw-specific problem is that code-mode exec and Pi shell exec share the same hook-facing tool name, but historically only shell-style exec exposed params.command. That makes broad exec / command policies easy to write but incomplete for code-mode cells.

This PR keeps the model-facing code-mode tool named exec, mirrors code-mode source into params.command, and adds toolKind: "code_mode_exec" so policy authors can choose either broad execution coverage or code-mode-specific handling.

Compatibility note: existing policies that match event.toolName === "exec" and inspect event.params.command may now also evaluate outer code-mode cells. Policies intended to apply only to shell-style exec should exclude event.toolKind === "code_mode_exec".

Change and value

This PR preserves the current active hook-context path and aligns the outer code-mode exec input contract with exec-shaped policy expectations:

  • keeps code accepted as the documented model-facing field
  • accepts command as an alias for code-mode exec
  • mirrors code and command in before_tool_call hook payloads for marked code-mode control tools only
  • adds hook-visible toolKind: "code_mode_exec" and toolInputKind metadata so policies can distinguish code-mode cells from shell-style exec
  • normalizes code-mode aliases and recomputes input metadata after trusted-policy param rewrites, including between trusted policies in the same policy chain
  • reconciles single-alias hook rewrites before execution
  • records reconciled adapter params so after_tool_call observes the payload that actually executed
  • rejects divergent code and command values before execution
  • treats non-string counterpart values as absent so hooks still see executable source under both expected names

Scope

Affected:

  • code-mode users with before_tool_call, after_tool_call, or trusted policies that inspect outer code-mode exec
  • policy authors who want outer code-mode exec to expose an exec-compatible command field while still being distinguishable from shell exec

Not affected:

  • normal shell exec behavior, which remains unmarked by the code-mode discriminator
  • non-code-mode tools named exec
  • the existing code-mode code field, which remains accepted
  • nested tool calls made from inside code mode; the discriminator applies only to the outer code-mode exec control tool

Maintainer decision needed

This PR intentionally makes outer code-mode exec visible to policies that match event.toolName === "exec" and inspect event.params.command. The opt-out / audit shape is the additive host-authored discriminator pair: toolKind: "code_mode_exec" and toolInputKind: "javascript" | "typescript" when the language is known.

Please confirm whether command plus toolKind / toolInputKind is the intended outer code-mode exec hook contract. If maintainers would rather require policy authors to handle code directly, or rename the hook-facing tool instead of adding discriminators, this PR should change shape before merge.

Verification

Current head: 3b40c538ccdcaff62f9a463e689e096285dab9f2.

  • Local: git diff --check origin/main...HEAD
  • Local: timeout 120s node_modules/.bin/oxfmt --check docs/plugins/hooks.md docs/reference/code-mode.md src/plugins/trusted-tool-policy.ts src/agents/code-mode-control-tools.ts src/agents/code-mode.ts src/agents/code-mode.test.ts src/agents/pi-tools.before-tool-call.ts src/agents/pi-tool-definition-adapter.ts src/agents/pi-tools.before-tool-call.integration.e2e.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.fires-once.test.ts src/plugins/hook-types.ts
  • Local: timeout 120s node_modules/.bin/oxlint docs/plugins/hooks.md docs/reference/code-mode.md src/plugins/trusted-tool-policy.ts src/agents/code-mode-control-tools.ts src/agents/code-mode.ts src/agents/code-mode.test.ts src/agents/pi-tools.before-tool-call.ts src/agents/pi-tool-definition-adapter.ts src/agents/pi-tools.before-tool-call.integration.e2e.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.fires-once.test.ts src/plugins/hook-types.ts
  • Local: timeout 180s node_modules/vitest/vitest.mjs run --config test/vitest/vitest.e2e.config.ts src/agents/pi-tools.before-tool-call.integration.e2e.test.ts -t "agent context to outer code-mode exec|trusted policy rewrites|single-alias" --reporter verbose passed: 3 tests passed, 16 skipped by filter
  • Local: timeout 220s node_modules/vitest/vitest.mjs run --config test/vitest/vitest.e2e.config.ts src/agents/pi-tools.before-tool-call.integration.e2e.test.ts --reporter verbose passed: 19 tests passed
  • Local: timeout 120s node_modules/vitest/vitest.mjs run --config test/vitest/vitest.contracts-plugin.config.ts src/plugins/contracts/host-hooks.contract.test.ts -t "trusted policy|derived paths" --reporter verbose passed: 8 tests passed, 42 skipped by filter
  • Local: timeout 120s node_modules/vitest/vitest.mjs run --config test/vitest/vitest.agents-core.config.ts src/agents/pi-tool-definition-adapter.after-tool-call.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.fires-once.test.ts --reporter verbose passed: 7 tests passed
  • Local runtime hook proof: timeout 60s node --import tsx /tmp/openclaw-code-mode-hook-proof.mjs

Real behavior proof

Behavior or issue addressed: Outer code-mode exec now exposes executable source under both the model-facing code field and the exec-shaped command alias when hooks inspect the dispatch. The same outer dispatch keeps the active agent/session/run/tool-call context from the #83481 hook-context path and includes toolKind: "code_mode_exec" plus toolInputKind when the input language is known, so shell-style exec policies can deliberately distinguish code-mode cells. Trusted-policy rewrites are normalized before later trusted policies and normal hooks observe params, including command-only rewrites and language changes. Reconciled adapter params are recorded so after_tool_call observes the payload that actually executed.

Real environment tested: Local OpenClaw source worktree at head 3b40c538ccdcaff62f9a463e689e096285dab9f2, Node v26.1.0, pnpm 11.1.0, Linux x86_64. The runtime proof registered a real global before_tool_call hook runner, sent the code-mode exec control tool through the production Pi custom-tool adapter, and compared it with an unmarked plain exec tool.

Exact steps or command run after this patch: From /tmp/openclaw-pr-83387, ran:

$ git diff --check origin/main...HEAD
$ timeout 120s node_modules/.bin/oxfmt --check docs/plugins/hooks.md docs/reference/code-mode.md src/plugins/trusted-tool-policy.ts src/agents/code-mode-control-tools.ts src/agents/code-mode.ts src/agents/code-mode.test.ts src/agents/pi-tools.before-tool-call.ts src/agents/pi-tool-definition-adapter.ts src/agents/pi-tools.before-tool-call.integration.e2e.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.fires-once.test.ts src/plugins/hook-types.ts
$ timeout 120s node_modules/.bin/oxlint docs/plugins/hooks.md docs/reference/code-mode.md src/plugins/trusted-tool-policy.ts src/agents/code-mode-control-tools.ts src/agents/code-mode.ts src/agents/code-mode.test.ts src/agents/pi-tools.before-tool-call.ts src/agents/pi-tool-definition-adapter.ts src/agents/pi-tools.before-tool-call.integration.e2e.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.fires-once.test.ts src/plugins/hook-types.ts
$ timeout 180s node_modules/vitest/vitest.mjs run --config test/vitest/vitest.e2e.config.ts src/agents/pi-tools.before-tool-call.integration.e2e.test.ts -t "agent context to outer code-mode exec|trusted policy rewrites|single-alias" --reporter verbose
$ timeout 220s node_modules/vitest/vitest.mjs run --config test/vitest/vitest.e2e.config.ts src/agents/pi-tools.before-tool-call.integration.e2e.test.ts --reporter verbose
$ timeout 120s node_modules/vitest/vitest.mjs run --config test/vitest/vitest.contracts-plugin.config.ts src/plugins/contracts/host-hooks.contract.test.ts -t "trusted policy|derived paths" --reporter verbose
$ timeout 120s node_modules/vitest/vitest.mjs run --config test/vitest/vitest.agents-core.config.ts src/agents/pi-tool-definition-adapter.after-tool-call.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.fires-once.test.ts --reporter verbose
$ timeout 60s node --import tsx /tmp/openclaw-code-mode-hook-proof.mjs

Evidence after fix: Formatting and lint passed on the touched docs, source, and test files:

All matched files use the correct format.
Found 0 warnings and 0 errors.

The affected integration file completed successfully:

Test Files  1 passed (1)
Tests  19 passed (19)

The focused post-review regression check completed successfully and covers direct TypeScript input, trusted-policy command-only rewrites, trusted-policy language rewrites, and hook single-alias rewrites:

Test Files  1 passed (1)
Tests  3 passed | 16 skipped (19)

The focused contracts check for trusted-policy and derived-path behavior completed successfully:

Test Files  1 passed (1)
Tests  8 passed | 42 skipped (50)

The adapter after-hook focused tests completed successfully:

Test Files  2 passed (2)
Tests  7 passed (7)

The runtime hook proof produced this redacted live hook observation:

{
  "proof": "OpenClaw runtime before_tool_call hook observation",
  "head": "3b40c538ccdcaff62f9a463e689e096285dab9f2",
  "codeModeResult": {
    "status": "blocked",
    "deniedReason": "plugin-before-tool-call",
    "reason": "runtime proof captured code_mode_exec"
  },
  "plainExecResult": {
    "status": "blocked",
    "deniedReason": "plugin-before-tool-call",
    "reason": "runtime proof captured plain_exec"
  },
  "observations": [
    {
      "event": {
        "toolName": "exec",
        "toolKind": "code_mode_exec",
        "toolInputKind": "javascript",
        "runId": "run-runtime-proof",
        "toolCallId": "proof-code-mode-exec",
        "params": {
          "hasCode": true,
          "hasCommand": true,
          "codeEqualsCommand": true,
          "code": "console.log('runtime proof');",
          "command": "console.log('runtime proof');",
          "language": "javascript"
        }
      },
      "context": {
        "toolName": "exec",
        "toolKind": "code_mode_exec",
        "toolInputKind": "javascript",
        "agentId": "main",
        "sessionKey": "agent:main:runtime-proof",
        "sessionId": "session-runtime-proof",
        "runId": "run-runtime-proof",
        "toolCallId": "proof-code-mode-exec"
      }
    },
    {
      "event": {
        "toolName": "exec",
        "toolKind": null,
        "toolInputKind": null,
        "runId": "run-runtime-proof",
        "toolCallId": "proof-plain-exec",
        "params": {
          "hasCode": false,
          "hasCommand": true,
          "codeEqualsCommand": false,
          "command": "echo runtime-proof"
        }
      },
      "context": {
        "toolName": "exec",
        "toolKind": null,
        "toolInputKind": null,
        "agentId": "main",
        "sessionKey": "agent:main:runtime-proof",
        "sessionId": "session-runtime-proof",
        "runId": "run-runtime-proof",
        "toolCallId": "proof-plain-exec"
      }
    }
  ]
}

Observed result after fix: Hooks inspecting outer code-mode exec see code and command mirrored for code-only, command-only, malformed-counterpart, trusted-policy command-only rewrite, and hook single-alias rewrite inputs. Trusted-policy chains see normalized params and recomputed input kind between policies. after_tool_call sees reconciled adapter params for rewritten code-mode exec payloads. A plain unmarked tool named exec still reaches hooks without toolKind, so existing shell-style policies can distinguish the two paths instead of relying on tool name alone.

What was not tested: I did not run a live model/gateway conversation. The runtime hook proof intentionally blocked before executing source so the evidence isolates the hook contract and does not depend on model output. Two earlier attempts to run these same affected standard-config tests through the top-level Vitest project config timed out during project startup, so I reran the affected files with their scoped configs instead.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: M triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. labels May 18, 2026
@clawsweeper

clawsweeper Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

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 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.

Summary
The PR changes code-mode exec to accept and mirror command alongside code, adds hook toolKind/toolInputKind discriminators, normalizes trusted-policy rewrites, updates docs, and adds focused regression tests.

Reproducibility: yes. at source level. Current main's code-mode exec only accepts code and exposes no code-mode hook discriminator, while the PR diff and tests add the alias and metadata path.

PR rating
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Summary: The PR has strong current-head runtime proof and focused tests, with merge readiness mainly gated by maintainer acceptance of the hook contract.

Rank-up moves:

  • Get explicit maintainer security/compatibility signoff on the command plus toolKind/toolInputKind contract before merge.
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.

Real behavior proof
Sufficient (terminal): The PR body now includes current-head terminal/runtime proof showing the production adapter emits mirrored code-mode exec params and discriminators while plain exec remains unmarked.

Risk before merge

  • Existing plugin policies that match toolName === "exec" and inspect params.command may newly allow, deny, or audit outer code-mode cells after merge.
  • toolKind and toolInputKind become public hook-contract fields for policy and audit plugins, so maintainers need to explicitly accept that discriminator shape as the security boundary.
  • The contributor proof covers the runtime hook contract and scoped tests, but it does not exercise a live model or gateway conversation.

Maintainer options:

  1. Confirm the Hook Contract Before Merge (recommended)
    A maintainer should explicitly approve command plus toolKind/toolInputKind as the code-mode exec policy contract, then merge with the documented compatibility note.
  2. Keep Per-Mechanism Policy Semantics
    If maintainers do not want existing exec/command policies to match code-mode cells by default, pause this PR and keep the current code contract or choose a distinct hook-facing tool identity.

Next step before merge
This needs human maintainer security/compatibility contract approval rather than an automated repair.

Security
Needs attention: No supply-chain issue is visible, but the PR changes code-execution hook authorization semantics and needs maintainer security-boundary signoff.

Review details

Best possible solution:

Land the additive alias/discriminator contract only if maintainers explicitly accept that broad exec/command policies should cover outer code-mode cells; otherwise keep per-mechanism policy semantics or use a distinct code-mode tool identity.

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

Yes at source level. Current main's code-mode exec only accepts code and exposes no code-mode hook discriminator, while the PR diff and tests add the alias and metadata path.

Is this the best way to solve the issue?

Unclear until maintainer contract review. If maintainers want broad exec/command policy coverage with an explicit discriminator, this is a cohesive implementation; if not, a distinct tool identity or per-mechanism policy shape is safer.

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body now includes current-head terminal/runtime proof showing the production adapter emits mirrored code-mode exec params and discriminators while plain exec remains unmarked.
  • add rating: 🐚 platinum hermit: Current PR rating is 🐚 platinum hermit because proof is 🦞 diamond lobster, patch quality is 🐚 platinum hermit, and The PR has strong current-head runtime proof and focused tests, with merge readiness mainly gated by maintainer acceptance of the hook contract.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body now includes current-head terminal/runtime proof showing the production adapter emits mirrored code-mode exec params and discriminators while plain exec remains unmarked.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P2: This is a focused agent hook-contract improvement with meaningful but limited blast radius around code-mode policy handling.
  • merge-risk: 🚨 compatibility: Existing exec/command policies can start applying to outer code-mode cells after this PR.
  • merge-risk: 🚨 security-boundary: The diff intentionally changes the authorization and audit payload seen by plugin hooks for code execution.
  • rating: 🐚 platinum hermit: Current PR rating is 🐚 platinum hermit because proof is 🦞 diamond lobster, patch quality is 🐚 platinum hermit, and The PR has strong current-head runtime proof and focused tests, with merge readiness mainly gated by maintainer acceptance of the hook contract.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body now includes current-head terminal/runtime proof showing the production adapter emits mirrored code-mode exec params and discriminators while plain exec remains unmarked.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body now includes current-head terminal/runtime proof showing the production adapter emits mirrored code-mode exec params and discriminators while plain exec remains unmarked.

Security concerns:

  • [medium] Hook authorization contract changes — src/plugins/hook-types.ts:431
    Adding command to code-mode exec and exposing toolKind/toolInputKind changes what policy plugins authorize or audit for executable code, so maintainers should explicitly approve this boundary before merge.
    Confidence: 0.9

What I checked:

  • Current main code-mode input contract: Current main still reads only params.code for code-mode exec and rejects calls without a non-empty code string, so the requested command alias is not already implemented. (src/agents/code-mode.ts:299, 504f0dfa36be)
  • Current main hook type contract: Current main's plugin hook event/context types expose toolName, params, run/tool ids, and context fields, but not the proposed toolKind or toolInputKind discriminators. (src/plugins/hook-types.ts:431, 504f0dfa36be)
  • PR alias and discriminator implementation: The PR adds marked code-mode control-tool helpers that mirror code and command, identify outer code-mode exec as code_mode_exec, derive the input kind, and reconcile single-alias hook rewrites. (src/agents/code-mode-control-tools.ts:45, 3b40c538ccdc)
  • PR hook dispatch path: The Pi tool adapter passes normalized hook params and code-mode metadata into runBeforeToolCallHook, reconciles returned params before execution, and records executed params for after-hook observation. (src/agents/pi-tool-definition-adapter.ts:247, 3b40c538ccdc)
  • PR trusted-policy and normal-hook propagation: The PR threads toolKind and toolInputKind through trusted policies and normal hooks, and recomputes the metadata after trusted-policy param rewrites before later hooks observe the event. (src/agents/pi-tools.before-tool-call.ts:457, 3b40c538ccdc)
  • Current-head real behavior proof: The PR body now includes current-head proof for 3b40c538ccdcaff62f9a463e689e096285dab9f2: a runtime before_tool_call hook observed code-mode exec with mirrored code/command and toolKind: code_mode_exec, while a plain unmarked exec remained undiscriminated. (3b40c538ccdc)

Likely related people:

  • steipete: Related history shows Peter Steinberger authored the code-mode runtime hardening and merged the immediate top-level code-mode hook-context fix that this PR follows. (role: feature owner and recent area contributor; confidence: high; commits: 0db097936568, 69aec1085234; files: src/agents/code-mode.ts, src/agents/pi-tool-definition-adapter.ts, src/agents/pi-tools.before-tool-call.integration.e2e.test.ts)
  • vincentkoc: Vincent Koc authored recent hook context, run/tool id propagation, and after_tool_call consolidation commits on the same hook pipeline files. (role: adjacent hook-context contributor; confidence: medium; commits: 747902a26a63, 0954b6bf5f48, 44183c6eb19e; files: src/agents/pi-tools.before-tool-call.ts, src/agents/pi-tool-definition-adapter.ts, src/plugins/types.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against 504f0dfa36be.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels May 18, 2026
@Kaspre
Kaspre force-pushed the fix/code-mode-hook-agent-context branch from 5c7c872 to 3b1bc5c Compare May 18, 2026 07:39
@Kaspre
Kaspre marked this pull request as ready for review May 18, 2026 07:39
@Kaspre Kaspre changed the title fix(code-mode): pass hook context to outer exec fix(code-mode): align outer exec hook params May 18, 2026
@openclaw-barnacle openclaw-barnacle Bot added triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 18, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels May 18, 2026
@Kaspre

Kaspre commented May 18, 2026 •

Copy link
Copy Markdown
Contributor Author

How to Keep Code-Mode Exec Distinct from Shell Exec Policies

Four distinct tools that all involve "running code" reach the before_tool_call hook with overlapping but inconsistent shapes:

Tool Tool name Payload to before_tool_call Runtime
Codex Code Mode (via Codex harness) exec freeform JS source as ToolPayload::Custom { input } codex code mode runtime
Codex shell tools shell_command / unified_exec { command: "..." } codex harness shell
Openclaw Code Mode (#80600) exec { code: "...", language?: "javascript" | "typescript" } QuickJS-WASI in-process VM
Pi shell exec exec { command: "..." } host shell

A policy author writing event.toolName === "exec" && event.params.command.includes("rm") today catches Pi shell exec and the Codex-routed shell relay, but silently misses Openclaw Code Mode because Code Mode's payload has code, not command. The policy author who thinks they have shell coverage actually has a gap.

Why this falls short of "Codex parity" — and whether that framing actually matters

We initially framed the goal as parity with upstream Codex Code Mode. Source-grounded inspection shows upstream Codex Code Mode is a freeform custom tool (ToolSpec::Freeform, raw JavaScript source as ToolPayload::Custom { input }, not a JSON { command } or { code } payload), so the literal payload shape doesn't match either. Upstream Codex also doesn't unify shell-shape policies across Code Mode and shell tools — it uses different tool names:

Shell tool name Code Mode tool name
Codex shell_command / unified_exec exec
Openclaw (Pi) exec exec (collision)

A policy author on upstream Codex writes per-tool rules. The collision in the Openclaw row is what creates the Openclaw policy-author ergonomics gap — Code Mode and shell exec share a tool name, so users expect them to look similar to hook policies even though their payloads diverge.

The honest framing is: does Openclaw want its users to be able to write one shell-shape policy that covers both Pi shell and Code Mode, or do we want them to write per-mechanism rules? This is a product judgment more than a parity argument.

Options we considered

Option 1 — Do nothing

Leave the divergent payloads as-is. Policy authors who want coverage across both runtimes write defensive checks like params.command ?? params.code.

  • Pros: zero churn; no new hook-contract fields; no risk of policy mis-match.
  • Cons: the silent-gap class of bugs (policy author thinks they have coverage, doesn't) is hard to discover; the workaround pattern doesn't compose well when there are 5+ such policies.
  • Codex relevance: matches Codex's per-tool-rule pattern. If we agree Openclaw users should also write per-mechanism rules, this is the answer.

Option 2 — Add command alias only (this PR's current shape)

What #83483 does today: mirror code and command in the hook payload for marked Code Mode control tools, reconcile single-alias rewrites, reject divergent values.

  • Pros: small change; uniform shell-shape policy coverage; preserves model-facing code field.
  • Cons: existing shell policies start matching Code Mode JS payloads where the JS happens to contain shell-looking strings — no opt-out for policy authors who want Code Mode treated separately. This is the ClawSweeper P1 concern.
  • Codex relevance: not a Codex pattern; Openclaw-specific ergonomics.

Option 3 — Add command alias + hook-contract discriminator (the evolved proposal)

Same as Option 2, plus additive toolKind: "code_mode_exec" and toolInputKind: "javascript" fields on PluginHookBeforeToolCallEvent and PluginHookToolContext, set by normalizeCodeModeExecBeforeHookParams for marked outer Code Mode dispatches only (not propagated to nested calls).

  • Pros: preserves uniform shell-shape policy coverage (source-agnostic policies match all three paths), AND lets discriminator-aware policies separate Code Mode JS from shell-shaped exec when they need to. Decoupled from model-facing schema — toolKind is harness-authoritative, not model-emitted.
  • Cons: introduces new hook-contract fields. They are genuinely new — upstream Codex has no tool_kind field; Codex hook events discriminate via tool_name + matcher_aliases. Defensible because Openclaw has the name collision Codex doesn't, but worth being explicit that we're adding a convention rather than copying one.
  • Codex relevance: not a parallel; an Openclaw-specific abstraction that follows from Openclaw's situation.

Option 4 — Rename Openclaw Code Mode's tool to code_mode_exec

Stop overloading the name exec. The hook event already discriminates via tool name in this case; no new fields needed.

  • Pros: cleanest separation; matches Codex's general pattern of different-mechanisms-get-different-names; no new hook-contract fields.
  • Cons: diverges from upstream Codex Code Mode, whose public tool name is also exec (PUBLIC_TOOL_NAME = "exec" in codex-rs/code-mode/src/lib.rs). Renaming would make Openclaw Code Mode less name-compatible with Codex Code Mode at the model-facing layer. Also breaks any existing Openclaw Code Mode user with policies keyed on exec (small population today but non-zero).
  • Codex relevance: half-parity — fixes the name-collision the way Codex does on the shell side, but breaks the name-match Codex has on the code-mode side.

Decision

We're leaning Option 3 but want maintainer input before adding the discriminator fields. Rationale:

  1. Option 1 is the cleanest fit for Codex's actual pattern, but Openclaw's name collision (Code Mode + Pi shell both named exec) creates a silent-gap class of policy bug that Codex users don't face. Asking Openclaw policy authors to write per-mechanism rules is more boilerplate than the equivalent in Codex.
  2. Option 2 is what this PR does today, and ClawSweeper correctly flagged the missing opt-out for shell-policy authors.
  3. Option 4 has a tradeoff we're not certain about: it gains tool-name clarity at the cost of model-facing name divergence from upstream Codex Code Mode. We don't have a strong read on which side maintainers value more.
  4. Option 3 is additive, leaves the model-facing surface stable, and gives both policy-author camps what they want. The "new convention" cost is real but bounded — two new optional fields on the hook event/context, populated only for marked Code Mode dispatches.

Open questions for maintainers

  • Is the Openclaw-vs-Codex parity framing the right one to optimize for here, or is policy-author ergonomics inside Openclaw the more honest motivation?
  • If we go with the discriminator (Option 3), do you want it on event + context, or event only? We'd argue both for symmetry with existing context fields (agentId, sessionId), but we don't want to set toolKind on nested calls — a nested read() from inside Code Mode is a read, not a code_mode_exec. If origin tracking ever becomes desired ("this read came from inside Code Mode"), that's a separate field (originToolKind) and a follow-up PR.
  • If you'd prefer the rename path (Option 4), are you OK with the model-facing name divergence from upstream Codex Code Mode? Or would you rather keep the exec name and live with the policy ergonomics gap?

We're happy to revise this PR in any of those directions or close it in favor of a different approach.

@Kaspre
Kaspre force-pushed the fix/code-mode-hook-agent-context branch from 3b1bc5c to b3bdeac Compare May 18, 2026 15:43
@openclaw-barnacle openclaw-barnacle Bot added size: L and removed size: M proof: sufficient ClawSweeper judged the real behavior proof convincing. labels May 18, 2026
@Kaspre
Kaspre force-pushed the fix/code-mode-hook-agent-context branch from b3bdeac to e8763b3 Compare May 18, 2026 15:49

Kaspre commented May 18, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Current head e8763b3685a3a547353fea717d62978fc57b03ea implements the previously recommended discriminator path: outer code-mode exec hook events and contexts now include toolKind: "code_mode_exec" and toolInputKind, while a plain unmarked tool named exec remains undiscriminated. The targeted regression test covers marked code-mode exec versus unmarked plain exec, and GitHub CI/proof are green on this head.

@clawsweeper

clawsweeper Bot commented May 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 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 May 18, 2026
@Kaspre
Kaspre force-pushed the fix/code-mode-hook-agent-context branch from 1738358 to 3b40c53 Compare May 21, 2026 04:05
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 21, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels May 21, 2026
@clawsweeper

clawsweeper Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🔥 Warming up: real-behavior proof passed; findings, security review, or rank-up moves are still in progress.

Hatch command

Comment @clawsweeper hatch when this PR is hatchable.

Hatchability rules:

  • Merged PRs are hatchable.
  • Open PRs are hatchable when they are status: 👀 ready for maintainer look, status: 🚀 automerge armed, or labeled clawsweeper:automerge.
  • Closed unmerged PRs are hatchable only when one of those hatchable labels is still present in the durable record.
What is this egg doing here?
  • Eggs appear after the PR passes real-behavior proof. It is here for vibes, not verdicts: it does not change labels, ratings, merge decisions, or automation.
  • The shell reacts to review momentum: open follow-up work warms it up, re-review makes it wobble, and a clean final review lets it hatch.
  • Hatchability usually comes from sufficient real-behavior proof, no blocking P0/P1/P2 findings, no security attention needed, and clean correctness. A merged PR is already final, so merge makes the egg hatchable independently.
  • The hatch is seeded from this repository and PR number, so the same PR keeps the same creature; the reviewed head SHA can only change safe visual details.
  • Rarity is just collectible sparkle: 🥚 common, 🌱 uncommon, 💎 rare, ✨ glimmer, and 🌈 legendary.

Kaspre commented May 21, 2026

Copy link
Copy Markdown
Contributor Author

Current-head proof refresh is now in the PR body for 3b40c538ccdcaff62f9a463e689e096285dab9f2. I reran the scoped local checks and the runtime before_tool_call proof on that head.

Maintainer signoff requested on the hook contract: this PR intentionally lets event.toolName === "exec" plus event.params.command policies evaluate outer code-mode cells, with toolKind: "code_mode_exec" / toolInputKind as the discriminator for policy and audit plugins. Please confirm that this is the intended outer code-mode exec policy shape, or point me to the alternative before merge.

@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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels May 21, 2026
@Takhoffman

Copy link
Copy Markdown
Contributor

@clawsweeper ask teach me how code mode works here and how this pr changes current behavior and explain why it is broken

@clawsweeper

clawsweeper Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper assist is taking a look at your question.

I queued a lightweight read-only assist pass. It will post a separate answer comment and will not edit the durable ClawSweeper review comment or trigger close, merge, repair, label, or branch changes.

Request: teach me how code mode works here and how this pr changes current behavior and explain why it is broken

@clawsweeper

clawsweeper Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper assist: Code mode is an opt-in agent mode where the model sees only outer control tools, mainly exec and wait. The outer exec runs JavaScript/TypeScript in OpenClaw’s QuickJS-WASI code-mode runtime, while normal enabled tools remain hidden behind the code-mode bridge and can be called from inside that code.

The broken part is the hook contract for the outer code-mode exec. It reaches before_tool_call with the same hook-facing name as Pi shell exec: exec. But on current main, code-mode source is in params.code, while shell-style exec policies usually inspect params.command. So a policy like event.toolName === "exec" && event.params.command... can look complete but silently miss OpenClaw code-mode cells. #83481 already fixed missing agent/session/run hook context; this PR addresses the remaining payload-shape mismatch.

This PR changes outer code-mode exec so it still accepts the model-facing code field, also accepts command as an alias, mirrors code and command for hook inspection, rejects divergent code/command values, and adds toolKind: "code_mode_exec" plus toolInputKind so hook policies can distinguish code-mode cells from shell-style exec.

Evidence:

Suggested next action: Decide whether OpenClaw wants this contract: broad exec/command policy coverage for code mode, with toolKind/toolInputKind as the opt-out discriminator.


Source: #83483 (comment)
Assist model: gpt-5.5, reasoning low.

@clawsweeper

clawsweeper Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper assist: Code mode makes the model call a small outer tool surface, mainly exec/wait. Outer exec runs JS/TS in OpenClaw’s QuickJS-WASI runtime, while normal tools are hidden behind the code-mode bridge and can be called from inside that code.

The breakage is in the hook-facing shape: outer code-mode exec has the same toolName: "exec" as Pi shell exec, but current main sends source as params.code; shell-style exec policies usually inspect params.command. So broad policies can look like they cover exec but silently miss code-mode cells.

This PR keeps code, accepts command as an alias, mirrors code/command into hook params, rejects divergent values, records reconciled params for after_tool_call, and adds toolKind: "code_mode_exec" plus toolInputKind so policy authors can distinguish code-mode from shell exec.

Evidence:

Suggested next action: Decide whether OpenClaw wants broad exec/command policies to include code-mode cells, using toolKind/toolInputKind as the discriminator.


Source: #83483 (comment)
Assist model: gpt-5.5, reasoning low.

@steipete steipete self-assigned this May 22, 2026
@steipete
steipete force-pushed the fix/code-mode-hook-agent-context branch from 3b40c53 to 516c4c1 Compare May 22, 2026 08:39
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 22, 2026
@steipete
steipete force-pushed the fix/code-mode-hook-agent-context branch from 516c4c1 to 18ae53e Compare May 22, 2026 08:45
@steipete
steipete merged commit 25e4893 into openclaw:main May 22, 2026
97 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Landed via rebase onto main.

  • Source PR commits: d6d9405, 18ae53e
  • Landed commits: 1e1e45b (code-mode hook contract), 25e4893 (maintainer changelog)
  • Local proof: git diff --check; timeout 220s node_modules/vitest/vitest.mjs run --config test/vitest/vitest.e2e.config.ts src/agents/pi-tools.before-tool-call.integration.e2e.test.ts --reporter dot (19 passed); timeout 180s node_modules/vitest/vitest.mjs run --config test/vitest/vitest.agents-core.config.ts src/agents/code-mode.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.test.ts src/agents/pi-tool-definition-adapter.after-tool-call.fires-once.test.ts --reporter dot (34 passed)
  • GitHub proof: PR head checks green on 18ae53e, including CI, CodeQL/Critical Quality, security-fast, OpenGrep, and Real behavior proof.

Thanks @Kaspre!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

3 participants