Skip to content

fix(agents): apply tool policy to Anthropic native calls - #128805

Merged
steipete merged 2 commits into
mainfrom
fix/anthropic-agent-sdk-native-policy
Aug 25, 2026
Merged

steipete merged 2 commits into
mainfrom
fix/anthropic-agent-sdk-native-policy

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Anthropic Agent SDK native tools reached OpenClaw's exec approval boundary without first running the same registered before_tool_call policies, loop detection, argument rewrites, and requester context used by other agent tools. The original implementation also matched Claude names like WebFetch incorrectly, exposed native file_path instead of the canonical path inspected by file policies, and rejected valid OpenClaw write/edit plugin matchers.

Why This Change Was Made

The generic CLI execution host now owns one canonical policy decision before native approval and execution. It maps backend-native names such as Bash, WebFetch, and WebSearch to exec, web_fetch, and web_search; projects Read/Write/Edit file operands into canonical policy arguments; maps approved rewrites back into the exact native SDK schema; rejects conflicting or unrepresentable edits; and revalidates admitted-run authority after awaited policy work.

Anthropic's existing SDK-native PreToolUse protection remains intact. The Agent SDK documents that caller-supplied managed settings may be discarded when enterprise-managed settings exist, so removing PreToolUse or relying only on a managed ask rule would permit native-tool bypass. User-preapproved tools and disabled user hooks therefore still reach the OpenClaw owner. No SDK version bump, lockfile change, third-party notice, or additional dependency is necessary.

Canonical lowercase write and edit matchers are now accepted while upstream Codex's exact Write/Edit compatibility aliases remain rejected; its independent apply_patch projection is unchanged. OpenClaw-owned MCP calls retain their existing Gateway authorization boundary.

Release note: Claude Agent SDK native shell, web, and file tools now honor canonical OpenClaw plugin policy, safe argument rewrites, and existing native approvals without weakening enterprise-managed protections.

User Impact

Operators get the same tool-policy vetoes, path-based controls, canonical tool matching, argument rewrites, session restrictions, and fail-closed approval behavior across SDK-native and ordinary OpenClaw tools. Warm SDK sessions, resume, operator questions, cancellation, and protected credential forwarding remain unchanged.

Evidence

  • Head: d3081504c9446029b7a4bcabb9c3400635426d19.
  • Before the fix, owner-boundary regressions failed in nine distinct cases: native web policy bypass, native file-path bypass, invalid write/edit matchers, conflicting paths, and nonrepresentable edit rewrites. All now pass.
  • Focused and sibling suites: 850 passing tests across the CLI owner, dedicated policy suite, native approvals, session lifecycle, plugin matchers and trusted-policy contracts, Codex hook relay, Anthropic SDK runtime/permissions/questions, Gateway questions, and plugin packaging boundaries.
  • Real installed Claude subprocess with a controlled local Anthropic-compatible API: 233 HTTP exchanges, including exact-PR canonical exec/read/write vetoes, executed command rewrites, hooks-disabled/preapproved Bash denial, 120 consecutive warm turns on one process/session, 24 alternating allow/deny turns, parallel owners, 12 owner-replacement cycles, stale/late-approval fencing, malformed streams, provider errors, and zero surviving processes across 47 tracked subprocesses.
  • Real authenticated Anthropic Haiku sessions using the designated live-test API key over protected subprocess fd3: 15 baseline successful turns plus two additional exact-PR owner-boundary calls. A registered canonical exec policy blocked a real Bash call even with hooks disabled and Bash preapproved; another rewrote the real command and returned LIVE_POLICY_REWRITTEN. Also verified 10-turn process/conversation reuse, real operator-question round trip, native allow/deny, cancellation, nine zeroized credential buffers, and zero surviving subprocesses. This proof uses the dedicated API test credential, not a Claude subscription.
  • node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo: passed.
  • node scripts/run-tsgo.mjs -b test/tsconfig/tsconfig.core.test.agents-other.json --builders 1: passed.
  • node scripts/run-tsgo.mjs -b test/tsconfig/tsconfig.core.test.plugins-platform.json --builders 1: passed.
  • Changed-file oxlint, formatting, max-lines ratchet, git diff --check, and structured Codex autoreview/TruffleHog: passed. The full all-shard test-type command reaches the unchanged base failure in ui/vite.config.ts because the shared checkout lacks declarations for the existing pako dependency; both changed owner shards pass independently.
  • Full PR production TypeScript: +129/-6 (net +123), justified by the previously missing security-critical canonical policy owner, bidirectional provider-schema boundary, and stale-run fencing. Tests: +436/-0; docs: +13/-8; dependency/lockfile/notice delta: zero.
  • Both latest ClawSweeper P1/rank-up findings are addressed: enterprise-managed settings cannot bypass restored PreToolUse, and provider-native web/file names and operands are projected into canonical policy before matching.

@clawsweeper

clawsweeper Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling extensions: anthropic size: M maintainer Maintainer-authored PR labels Aug 24, 2026
@vincentkoc vincentkoc self-assigned this Aug 24, 2026
@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 24, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 24, 2026, 2:45 PM ET / 18:45 UTC.

ClawSweeper review

What this changes

This PR routes Anthropic Claude CLI native-tool calls through OpenClaw’s shared policy and approval host, updates the Agent SDK, and revises tests and docs.

Merge readiness

⛔ Blocked until real behavior proof is added - 11 items remain

Keep open: the shared host-policy direction is useful, but two P1 gaps leave native policy enforcement bypassable for canonical tool policies and enterprise-managed Claude settings.

Priority: P1
Reviewed head: f66f27449161e26c5e4c1f8ed940b9ecdbac1fe2
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The intended shared-owner refactor is useful, but unresolved reachability and canonical-identity defects make it unsafe to merge.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: Authority-chain proof required: the PR has mock callback tests but no redacted after-fix SDK/Claude trace showing that a denied canonical policy prevents native execution in both ordinary and enterprise-managed settings. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦪 silver shellfish (2/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: Authority-chain proof required: the PR has mock callback tests but no redacted after-fix SDK/Claude trace showing that a denied canonical policy prevents native execution in both ordinary and enterprise-managed settings. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 4 items Raw SDK names miss canonical policy IDs: The host passes the raw native name into shared policy; the shared normalizer lowercases and aliases Bash only, while the core catalog uses web_fetch. The new test explicitly accepts WebFetch becoming webfetch, so policies targeting web_fetch do not match.
Dependency-backed callback reachability is unproven: The branch removes the PreToolUse fence and relies solely on managedSettings ask-all plus canUseTool. The latest PR discussion records an exact-head enterprise-settings matrix where first-wins administrative settings drop the managed ask rule and default-allowed Read can skip the callback; the changed tests invoke canUseTool directly rather than exercising that SDK decision.
Dependency signal and scope: The PR directly upgrades and executes @anthropic-ai/claude-agent-sdk 0.3.241, so its permission-setting contract is authoritative for the claim. Direct upstream inspection was unavailable because the review environment could not resolve external hosts.
Findings 2 actionable findings [P1] Map native names before canonical policy matching
[P1] Keep policy reachability safe under managed settings
Security Needs attention Enterprise settings can bypass the sole callback: If managed settings suppress the ask-all rule, a default-allowed native tool can execute without reaching OpenClaw’s canonical policy or approval owner.
Canonical policy names are not preserved: Forwarding WebFetch as webfetch prevents policies written for the canonical web_fetch tool from matching before execution.

How this fits together

The Anthropic plugin runs the locally authenticated Claude Code executable through Anthropic’s Agent SDK. Native tool calls pass from the SDK callback to OpenClaw’s CLI execution host, which should apply shared policy and approval before allowing the executable action.

flowchart LR
A[Agent turn] --> B[Anthropic CLI plugin]
B --> C[Agent SDK]
C --> D[Native tool callback]
D --> E[OpenClaw policy and approval]
E --> F[Claude Code tool execution]
Loading

Decision needed

Question Recommendation
Which enforcement model should protect native Claude calls when enterprise-managed settings can override the managed ask rule? Keep a non-bypassable policy fence: Retain or redesign a pre-execution fence that always reaches the single canonical host decision, while preventing duplicate policy application.

Why: Choosing between a retained reachability fence, fail-closed native-tool availability, or accepting the upstream callback contract changes the security boundary and operator behavior.

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: Authority-chain proof required: the PR has mock callback tests but no redacted after-fix SDK/Claude trace showing that a denied canonical policy prevents native execution in both ordinary and enterprise-managed settings. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Map native names before canonical policy matching (P1) - WebFetch is passed into the policy chain and becomes webfetch; the canonical OpenClaw tool is web_fetch. The new test asserts that mismatch, so policies or hooks targeting web_fetch cannot block or rewrite this native call. Map native names and input shapes before invoking the canonical policy.
  • Keep policy reachability safe under managed settings (P1) - This removes the PreToolUse fence and relies on managedSettings.ask. The recorded exact-head enterprise matrix shows first-wins administrative settings can drop that rule, allowing an admin-approved native tool to skip canUseTool; the direct-callback tests cannot cover that path. Preserve a non-bypassable fence or fail closed before claiming every native call reaches policy.
  • Resolve security concern: Enterprise settings can bypass the sole callback - If managed settings suppress the ask-all rule, a default-allowed native tool can execute without reaching OpenClaw’s canonical policy or approval owner.
  • Resolve security concern: Canonical policy names are not preserved - Forwarding WebFetch as webfetch prevents policies written for the canonical web_fetch tool from matching before execution.
  • Resolve merge risk (P1) - Enterprise-managed settings can bypass the sole callback, allowing a native executable action to miss OpenClaw policy and approval.
  • Resolve merge risk (P1) - Native names such as WebFetch reach policy as webfetch rather than the canonical web_fetch identifier, so matching policies can be skipped.
  • Complete next step (P2) - A maintainer must choose the security boundary for enterprise-managed SDK settings before a safe repair can be finalized.
  • Improve patch quality - Map each supported Claude native tool and its input shape to the canonical OpenClaw policy identity, with boundary coverage for WebFetch/web_fetch.
  • Improve patch quality - Add final-effect proof for a denied policy and prove that administrative settings cannot bypass it before native I/O.

Findings

  • [P1] Map native names before canonical policy matching — src/agents/cli-runner/execute-plugin.ts:89-90
  • [P1] Keep policy reachability safe under managed settings — extensions/anthropic/agent-sdk.runtime.ts:218-235
  • [high] Enterprise settings can bypass the sole callback — extensions/anthropic/agent-sdk.runtime.ts:218
  • [medium] Canonical policy names are not preserved — src/agents/cli-runner/execute-plugin.ts:89
Agent review details

Security

Needs attention: The patch can weaken the final authorization boundary for native executable tools.

PR surface

Source -3, Tests +95, Docs +6, Config 0, Other +91. Total +189 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 2 61 64 -3
Tests 3 215 120 +95
Docs 2 12 6 +6
Config 1 1 1 0
Generated 0 0 0 0
Other 1 93 2 +91
Total 9 382 193 +189

Review metrics

Metric Value Why it matters
Implementation versus tests production -3, tests +95, docs +6, lockfile +91 Production code is net-reduced, but the added tests mock the SDK callback and do not establish the changed external authorization boundary.

Merge-risk options

Maintainer options:

  1. Restore a non-bypassable owner boundary (recommended)
    Keep a reachability fence and canonical-name adapter so both regular and enterprise-managed deployments receive one policy decision before native execution.
  2. Fail closed where the callback cannot be guaranteed
    Make affected native tools unavailable in administrative settings that can suppress the SDK callback, with an explicit diagnostic and upgrade documentation.
  3. Pause the dependency-driven rewrite
    Do not merge the SDK-only authorization path until its managed-settings behavior is proven safe across supported Claude Code deployments.

Technical review

Best possible solution:

Map Claude native identifiers and input shapes to canonical OpenClaw tool identities before policy evaluation, and retain one non-bypassable enforcement boundary for SDK deployments where callback reachability cannot be guaranteed.

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

Yes for the canonical-name defect: WebFetch is forwarded as webfetch while the core policy surface uses web_fetch. The enterprise callback bypass is also recorded in the PR discussion, though direct SDK inspection was unavailable locally.

Is this the best way to solve the issue?

No: moving policy into the shared host is the right boundary, but raw native names and an overrideable managed ask rule cannot safely enforce it alone.

Full review comments:

  • [P1] Map native names before canonical policy matching — src/agents/cli-runner/execute-plugin.ts:89-90
    WebFetch is passed into the policy chain and becomes webfetch; the canonical OpenClaw tool is web_fetch. The new test asserts that mismatch, so policies or hooks targeting web_fetch cannot block or rewrite this native call. Map native names and input shapes before invoking the canonical policy.
    Confidence: 0.99
  • [P1] Keep policy reachability safe under managed settings — extensions/anthropic/agent-sdk.runtime.ts:218-235
    This removes the PreToolUse fence and relies on managedSettings.ask. The recorded exact-head enterprise matrix shows first-wins administrative settings can drop that rule, allowing an admin-approved native tool to skip canUseTool; the direct-callback tests cannot cover that path. Preserve a non-bypassable fence or fail closed before claiming every native call reaches policy.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: A policy or approval bypass can affect active Anthropic CLI users with native tools.
  • merge-risk: 🚨 compatibility: The new SDK permission configuration changes behavior for existing Claude Code settings, including enterprise-managed deployments.
  • merge-risk: 🚨 security-boundary: The proposed callback-only path can allow an executable native action to evade OpenClaw’s policy and approval boundary.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: Authority-chain proof required: the PR has mock callback tests but no redacted after-fix SDK/Claude trace showing that a denied canonical policy prevents native execution in both ordinary and enterprise-managed settings. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

Security concerns:

  • [high] Enterprise settings can bypass the sole callback — extensions/anthropic/agent-sdk.runtime.ts:218
    If managed settings suppress the ask-all rule, a default-allowed native tool can execute without reaching OpenClaw’s canonical policy or approval owner.
    Confidence: 0.94
  • [medium] Canonical policy names are not preserved — src/agents/cli-runner/execute-plugin.ts:89
    Forwarding WebFetch as webfetch prevents policies written for the canonical web_fetch tool from matching before execution.
    Confidence: 0.99

What I checked:

  • Raw SDK names miss canonical policy IDs: The host passes the raw native name into shared policy; the shared normalizer lowercases and aliases Bash only, while the core catalog uses web_fetch. The new test explicitly accepts WebFetch becoming webfetch, so policies targeting web_fetch do not match. (src/agents/cli-runner/execute-plugin.ts:89, f66f27449161)
  • Dependency-backed callback reachability is unproven: The branch removes the PreToolUse fence and relies solely on managedSettings ask-all plus canUseTool. The latest PR discussion records an exact-head enterprise-settings matrix where first-wins administrative settings drop the managed ask rule and default-allowed Read can skip the callback; the changed tests invoke canUseTool directly rather than exercising that SDK decision. (extensions/anthropic/agent-sdk.runtime.ts:218, f66f27449161)
  • Dependency signal and scope: The PR directly upgrades and executes @anthropic-ai/claude-agent-sdk 0.3.241, so its permission-setting contract is authoritative for the claim. Direct upstream inspection was unavailable because the review environment could not resolve external hosts. (extensions/anthropic/package.json:8, f66f27449161)
  • Patch provenance: The changed policy bridge and SDK configuration were introduced by the current one-commit PR head. (extensions/anthropic/agent-sdk.runtime.ts:218, f66f27449161)

Likely related people:

  • Vincent Koc: The timeline assigns this PR to Vincent Koc, and blame attributes the changed policy bridge to the current head commit; the local history contains no older lineage for these new lines. (role: assigned current implementation owner; confidence: medium; commits: f66f27449161; files: extensions/anthropic/agent-sdk.runtime.ts, src/agents/cli-runner/execute-plugin.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

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

History

Review history (2 earlier review cycles)
  • reviewed 2026-08-24T17:02:55.107Z sha f66f274 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-24T17:09:48.279Z sha f66f274 :: needs real behavior proof before merge. :: [P1] Map native names before canonical policy matching

@vincentkoc

Copy link
Copy Markdown
Member Author

Independent exact-head review of f66f27449161e26c5e4c1f8ed940b9ecdbac1fe2: not merge-ready.

  1. P1: the managed ask rule is not an invariant under enterprise/admin managed settings. The shipped @anthropic-ai/[email protected] types explicitly state that Options.managedSettings is dropped by default when an IT-controlled managed tier exists, unless that tier opts into parentSettingsBehavior: "merge". A sanitized exact-head AWS Crabbox run confirmed the effective settings:

    • parent only: ask: ["*"]
    • admin first-wins with allow: ["Read"]: only allow: ["Read"] remains
    • admin merge: both ask: ["*"] and allow: ["Read"] remain

    That matters because the upstream open issue documents that an in-cwd Read can skip both PreToolUse and canUseTool when it is default-allowed: PreToolUse options.hooks never fire for built-in tools (Read) — updatedInput unreachable; canUseTool also skipped for in-cwd reads anthropics/claude-agent-sdk-typescript#401. In the admin first-wins case, extensions/anthropic/agent-sdk.runtime.ts:218 therefore does not guarantee that the call reaches OpenClaw's canonical before_tool_call owner. The statement in docs/gateway/cli-backends.md:139 that every schema-valid executable call reaches the callback is currently false for a supported deployment state.

    Best fix: make callback reachability fail closed when the parent ask rule is ineffective, or replace/disable the affected native built-ins until Anthropic provides a permission/hook contract that cannot be skipped. Add dependency-backed coverage for the admin first-wins case. Moving canonical policy into the generic CLI host is the right owner boundary; the SDK enforcement mechanism is the incomplete part.

  2. Fresh install is currently blocked by the repository's dependency-age policy. Exact-head pnpm install --frozen-lockfile rejects the nine 0.3.241 SDK/platform packages under minimumReleaseAge: 2880. With that gate disabled only for diagnosis, the two focused shards passed 41/41 and reproduced the settings matrix above. This is transient as the packages age, but hosted proof is not green now.

No duplicate OpenClaw authorization was found: exact mcp__openclaw__* calls are bounded by strict generated MCP config, the scoped grant/tool schema, and the Gateway's canonical hook plus grant recheck. Production TypeScript is +61/-64 (net -3); tests are +215/-120. Package/lock pins are internally consistent. Privacy and PR release-note policy are clean.

@clawsweeper clawsweeper Bot added 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. P1 High-priority user-facing bug, regression, or broken workflow. 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 Aug 24, 2026
@steipete
steipete marked this pull request as ready for review August 25, 2026 06:45
@steipete
steipete merged commit df83ff5 into main Aug 25, 2026
301 of 302 checks passed
@steipete
steipete deleted the fix/anthropic-agent-sdk-native-policy branch August 25, 2026 06:58
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

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 extensions: anthropic gateway Gateway runtime maintainer Maintainer-authored PR 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. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants