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 needpolicies/approvals
can ignore the v1 fields preserved on the v2 schema.
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, noapprovalRunningNoticeMsAgentToolExecSchema— extends base withapprovalRunningNoticeMs
Exec policy presets (runtime)
tools.exec.preset is resolved in resolveExecConfig (src/agents/pi-tools.ts, exported) before the exec tool is built:
presetId= agenttools.exec.preset?? globaltools.exec.preset.security/ask/safeBinsresolve through a 4-level chain: agent explicit > agent preset > global explicit > global preset.allowlistPackfollows the winning preset only (agent preset if set, else global) — an agent presetminimalsuppresses a globalreadonlypack rather than mixing.- Unknown ids fall back to no-preset with a subsystem warning (
infra/exec-policy-presets).
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):- Tool profile (
tools.profileoragents.list[].tools.profile) - Provider tool profile (
tools.byProvider[provider].profile) - Global tool policy (
tools.allow/tools.deny) - Provider tool policy (
tools.byProvider[provider].allow/deny) - Agent-specific tool policy (
agents.list[].tools.allow/deny) - Agent provider policy (
agents.list[].tools.byProvider[provider].allow/deny) - Sandbox tool policy (
tools.sandbox.toolsoragents.list[].tools.sandbox.tools) - 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 supportgroup:* shorthands:
Safe bin implementation
SafeBinProfileFixture defines the argv policy for a safe bin:
$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,-rjq:--argfile,--from-file,--library-path,--rawfile,--slurpfile,-L,-fsort:--compress-program,--files0-from,--output,--random-source,--temporary-directory,-T,-owc:--files0-from
&&, ||, ;) 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):
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=execis set in the spawned command environment (including PTY and sandbox) so shell/profile rules can detect exec-tool context.- On non-Windows: uses
SHELL; ifSHELLisfish, prefersbash/shfromPATH, then falls back tofish. - On Windows: prefers PowerShell 7 (
pwsh), falls back to PowerShell 5.1. - Host execution (
gateway/node) rejectsenv.PATHand loader overrides (LD_*/DYLD_*). - Script preflight checks inspect only files inside the effective
workdirboundary; paths resolving outsideworkdirskip preflight.
elevatedDefault
/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’ssanitizeNodeInvokeParamsForForwarding 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
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:
- Namespace gate —
namespaceMatchesInvocationrejects cross-kind authorization (anexec.argvpolicy withmatch:{}cannot authorizeapproved-scriptormcp-operation). - Per-namespace match — argv mode matches on
executableName(basename,/+\\aware),resolvedPathGlob(whenresolvedExecutablePathis populated),argvPattern(with optionalmatchAnyTrailingArgs). Shell mode walksparsedSegmentsper-segment (chain-injection guard: arm -rf / && git statusrequest with anallow gitpolicy does NOT match). - Deny-first sort —
EFFECT_PRECEDENCE(deny=300, ask=200, allow=100), thenSOURCE_PRECEDENCE(managed=500, project=400, user=300, session=200, approval=100). - PATH re-resolution —
reEvaluatePoliciesForPathre-runs the pipeline afterresolveExecutablePathswaps the executable against the sanitized env (B17). The re-resolved request populatesresolvedExecutablePathforresolvedPathGlobmatching.
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.
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) andBearertoken values, in both bare-token andkey=valueforms.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.
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.allowedExecutablesenumerates the executable - approved-script: matched on scriptId; args validated via
validateApprovedScriptArgs - mcp-operation: matched on (serverId, toolName, operationClass)
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 atsrc/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.