Skip to main content

Exec Tool — Developer Reference

Type definitions, policy precedence, and implementation details for the exec tool and its approval system.

Source files

ExecToolConfig

approvalRunningNoticeMs is only accepted on agent-level exec config (AgentToolExecSchema), not the global ToolExecSchema.

AgentToolsConfig

FsToolsConfig

ExecApprovalsFile schema

The exec-approvals store has two coexisting versions. v1 is migrated in-memory to v2 on load; the on-disk file is not auto-overwritten (D18 R3) — callers that only need policies/approvals can ignore the v1 fields preserved on the v2 schema.
Defaults at runtime:

ApprovalsConfig (approval forwarding)

Global vs agent-level precedence

Effective exec policy is the stricter of config (tools.exec.* / agents.list[].tools.exec.*) and exec-approvals.json. Omitted approvals fields fall back to the config value. Global (tools.exec) sets the floor. Agent-level (agents.list[].tools.exec) overrides. exec-approvals.json overrides per-agent at runtime (hot-reloaded, not requiring gateway restart). Config schema uses two separate shapes:
  • ToolExecSchema — global, no approvalRunningNoticeMs
  • AgentToolExecSchema — extends base with approvalRunningNoticeMs

Exec policy presets (runtime)

tools.exec.preset is resolved in resolveExecConfig (src/agents/pi-tools.ts, exported) before the exec tool is built:
  • presetId = agent tools.exec.preset ?? global tools.exec.preset.
  • security / ask / safeBins resolve through a 4-level chain: agent explicit > agent preset > global explicit > global preset.
  • allowlistPack follows the winning preset only (agent preset if set, else global) — an agent preset minimal suppresses a global readonly pack rather than mixing.
  • Unknown ids fall back to no-preset with a subsystem warning (infra/exec-policy-presets).
At the gateway host seam, processGatewayAllowlist (src/agents/bash-tools.exec-host-gateway.ts) unions the pack entries with the agent’s exec-approvals.json allowlist before evaluateShellAllowlist. Pack entries are { pattern } objects constructed at evaluation time and are never persisted: recordMatchedAllowlistUse skips any match whose pattern is in the packPatterns set, so ~/.openclaw/exec-approvals.json is never rewritten by preset usage. minSecurity / maxAsk flooring against the approvals file still applies on top. The tools.catalog RPC response now carries an additive execPolicy block (ToolsCatalogExecPolicy typebox schema, compile-time linked to the resolver return) computed by resolveEffectiveExecPolicy(resolved.cfg, resolved.agentId): { presetId?, security, ask, canExec: none | safebins-only | full | normal, allowlistEntryCount, safeBinCount, sources, warning? } — absent keys are omitted, never null. warning carries the security-floor note when the approvals file floors tools.exec.security (the same text the denials use).

Tool policy filtering order

Tool availability is determined in this order (each level can only further restrict):
  1. Tool profile (tools.profile or agents.list[].tools.profile)
  2. Provider tool profile (tools.byProvider[provider].profile)
  3. Global tool policy (tools.allow / tools.deny)
  4. Provider tool policy (tools.byProvider[provider].allow/deny)
  5. Agent-specific tool policy (agents.list[].tools.allow/deny)
  6. Agent provider policy (agents.list[].tools.byProvider[provider].allow/deny)
  7. Sandbox tool policy (tools.sandbox.tools or agents.list[].tools.sandbox.tools)
  8. Subagent tool policy (tools.subagents.tools)
deny always wins. A non-empty allow makes everything not listed implicitly blocked. Tool policy is the hard stop — /exec cannot override a denied exec tool. If agents.list[].tools.sandbox.tools is set, it replaces tools.sandbox.tools for that agent.

Tool groups

Tool policies support group:* shorthands:

Safe bin implementation

SafeBinProfileFixture defines the argv policy for a safe bin:
Validation is deterministic from argv shape only (no filesystem existence checks). Safe bins force argv tokens to be treated as literal text (no globbing, no $VAR expansion). Long options are fail-closed: unknown flags and ambiguous abbreviations are rejected. Default denied flags per bin:
  • grep: --dereference-recursive, --directories, --exclude-from, --file, --recursive, -R, -d, -f, -r
  • jq: --argfile, --from-file, --library-path, --rawfile, --slurpfile, -L, -f
  • sort: --compress-program, --files0-from, --output, --random-source, --temporary-directory, -T, -o
  • wc: --files0-from
Shell chaining (&&, ||, ;) is allowed only when every top-level segment satisfies the allowlist (including safe bins). Redirections are unsupported in allowlist mode. Command substitution ($() / backticks) is rejected during allowlist parsing. Safe bins must resolve from trusted directories (defaults: /bin, /usr/bin). PATH entries are never auto-trusted. Add package-manager paths via tools.exec.safeBinTrustedDirs. safeBinProfiles — per-agent profile keys override global keys.

apply_patch subtool

apply_patch is a subtool of exec for structured multi-file edits (OpenAI models only):
Tool policy: allow: ["exec"] implicitly allows apply_patch. workspaceOnly defaults to true (workspace-contained). Config lives under tools.exec.applyPatch. Non-OpenAI models have no apply_patch; use the workspace-contained delete tool to remove files.

Shell environment notes

  • OPENCLAW_SHELL=exec is set in the spawned command environment (including PTY and sandbox) so shell/profile rules can detect exec-tool context.
  • On non-Windows: uses SHELL; if SHELL is fish, prefers bash/sh from PATH, then falls back to fish.
  • On Windows: prefers PowerShell 7 (pwsh), falls back to PowerShell 5.1.
  • Host execution (gateway/node) rejects env.PATH and loader overrides (LD_*/DYLD_*).
  • Script preflight checks inspect only files inside the effective workdir boundary; paths resolving outside workdir skip preflight.

elevatedDefault

Sets the default elevated level when no /elevated directive is present for a session. "full" skips exec approvals entirely. Related: Exec Tool (user) · Exec Tool (admin) · Sandboxing (developer)

Canonical execution model

The exec tool’s host-execution path runs through a canonical execution model policy engine bolted onto the gateway’s sanitizeNodeInvokeParamsForForwarding entry point (src/gateway/node-invoke-sanitize.ts). The engine is opt-in: when zero policies are loaded, the pipeline is a no-op and the request is allowed (pre-PR behaviour is preserved). Deny-first enforcement only activates when at least one CompiledExecutionPolicy is present in ~/.openclaw/exec-approvals.json (v2 policies array).

CanonicalExecutionRequest shape

The display field is non-authoritative — when the model-supplied rawCommand disagrees with the hardened argv (B8), the gateway logs a warn and proceeds with the argv. The display field is excluded from the approval-replay hash (ADR 0307) so cosmetic drift does not invalidate bindings.

CompiledExecutionPolicy

Policy evaluator

evaluatePolicies(request, policies, defaultEffect) in src/infra/exec-policy-evaluate.ts:
  1. Namespace gate — namespaceMatchesInvocation rejects cross-kind authorization (an exec.argv policy with match:{} cannot authorize approved-script or mcp-operation).
  2. Per-namespace match — argv mode matches on executableName (basename, / + \\ aware), resolvedPathGlob (when resolvedExecutablePath is populated), argvPattern (with optional matchAnyTrailingArgs). Shell mode walks parsedSegments per-segment (chain-injection guard: a rm -rf / && git status request with an allow git policy does NOT match).
  3. Deny-first sort — EFFECT_PRECEDENCE (deny=300, ask=200, allow=100), then SOURCE_PRECEDENCE (managed=500, project=400, user=300, session=200, approval=100).
  4. PATH re-resolution — reEvaluatePoliciesForPath re-runs the pipeline after resolveExecutablePath swaps the executable against the sanitized env (B17). The re-resolved request populates resolvedExecutablePath for resolvedPathGlob matching.

Friendly-rule compiler

compileFriendlyRule("Bash(pnpm test:*)", "allow") in src/infra/friendly-rule-compiler.ts:
  • Splits on the FIRST space: Bash(foo bar baz:*) → executableName: "foo", argvPattern: "bar baz", matchAnyTrailingArgs: true. An executable name containing shell metacharacters is rejected.
  • Bash(*) → no executableName constraint, argvPattern: "*".
  • Bash(git status:*) → executableName: "git", argvPattern: "status", matchAnyTrailingArgs: true.
The friendly-rule compiler is library-only today (deferred per D19); production wiring depends on a config-UI surface that has not shipped.

Shell parser (library-only, deferred per D19)

src/infra/shell-parse.ts ships three minimum-viable parsers (POSIX, PowerShell, cmd.exe) and a detectDangerousWrapper that unwraps sh -c / bash -c / pwsh -Command / cmd /c / sudo / doas / runas / env / command / exec / xargs. The wrapper detector skips preceding option flags (sh -e -c "rm -rf /" is detected; hasUnterminatedQuote tracks quote spans instead of parity-counting, so echo "it's working" does not false-positive. The parser is not wired into the production argv-mode path today — canonicalizeLegacySystemRunParams always emits mode: "argv". Wiring shell-mode detection (argv[0] is sh/bash with -c) would activate the per-segment chain-injection guard, the dangerous-wrapper detection, and the shellChainPattern deny pattern in one stroke.

Audit record (S8)

emitAuditRecord in src/infra/exec-audit.ts emits a structured audit record via the infra/exec-audit subsystem logger. Redaction covers:
  • sk- prefix (case-insensitive) and Bearer token values, in both bare-token and key=value forms.
  • Authorization: Bearer <token> spans are pre-redacted before whitespace tokenization, so the token cannot leak as separate tokens.
  • Flag-name matching (/token/i, /auth/i, /credential/i, /secret/i) catches --token=... even when the value is not a known prefix.
Early-deny sites (RPC gate, replay binding, PATH re-eval) return early without emitting audit today — see the plan-fidelity review’s SC8 known-open note.

Approval-replay binding (anti-tamper)

bindApprovalToCanonicalRequest in src/infra/approval-replay-binding.ts records a SHA-256 of the authoritative canonical-request fields (display excluded per ADR 0307). replayApproval compares the presented hash against the stored hash using crypto.timingSafeEqual to avoid a timing side-channel. The binding is not one-shot consumed (spec L394 ambiguity) — one-shot consumption happens at the approval-manager layer (manager.consumeAllowOnce), which correctly distinguishes allow-once (consumed) from allow-always (reusable). Consuming the binding here would break allow-always approvals.

SaaS capability profile (library-only, deferred per D18-update / D19)

evaluateSaasProfile in src/infra/saas-capability-profile.ts enforces the SC6 boundary:
  • shell-mode: hard-denied for SaaS agents
  • argv-mode: hard-denied unless profile.allowedExecutables enumerates the executable
  • approved-script: matched on scriptId; args validated via validateApprovedScriptArgs
  • mcp-operation: matched on (serverId, toolName, operationClass)
The SaaS gate is library-only today; production wiring depends on a SaaS-mode provider config that has not shipped. The tenantId-stamping gap (spec L75 says the gateway stamps it from the authenticated identity, not from the request payload) is a known-open deviation flagged in the plan-fidelity review — currently tenantId flows from the client RPC payload verbatim.

Non-interactive ask resolution

resolveNonInteractiveAsk in src/infra/non-interactive-ask.ts is a standalone module (no gateway imports) that resolves an ask effect when no interactive UI is reachable: defaults to deny for SaaS mode, askFallback for local/operator mode. Consumed by the gateway wiring at the policy evaluation site.

Loaders

loadPoliciesForRequest in src/infra/load-policies-for-request.ts composes multiple PolicySourceLoader instances and flattens their policies. createUserPolicySource reads ~/.openclaw/exec-approvals.json via loadExecApprovalsV2; a corrupt or missing store logs a warning and returns [] (the engine stays opt-in — no policies means no enforcement, pre-PR allow).

Wiring status (production argv path)

The argv-mode production path is wired at src/gateway/server-methods/nodes.ts:750 (await sanitizeNodeInvokeParamsForForwarding({... gatewayNodes: cfg.gateway?.nodes})) → src/gateway/node-invoke-sanitize.ts → src/gateway/node-invoke-system-run-approval.ts. Trusted policy inputs (interactive, gatewayNodes RPC command-id gate config) are derived from gateway state, never client payload. Library-only surfaces (deferred per D19): friendly-rule compiler, SaaS capability gate, shell parser (POSIX/PowerShell/cmd), shellChainPattern deny pattern, SC4 denialLayer audit field. These activate when their respective config surfaces (friendly-rule UI, SaaS provider config, shell-mode dispatch) are wired in a future release.