Repository navigation
Description
What variant of Codex are you using?
Codex CLI and app-server. The behavior was characterized against rust-v0.148.0 at commit 3ba0f711642a888aec92a611a3f3b2211157ff89.
What feature would you like to see?
Add an opt-in fail-closed policy for PreToolUse command hooks, parallel to the UserPromptSubmit proposal in #33630.
Today a PreToolUse hook can block through a valid exit-2 or permissionDecision: "deny" result, but a timeout, spawn failure, crash/non-protocol exit, or malformed output is treated as a failed hook with should_block=false, so the tool is dispatched. That makes a policy hook least reliable precisely when its process is unavailable.
A narrow configuration shape could be:
{
"hooks": {
"PreToolUse": [
{
"matcher": "",
"failureMode": "block",
"hooks": [
{
"type": "command",
"command": "path/to/local-policy-hook"
}
]
}
]
}
}Requested semantics:
failureModeacceptscontinueorblock.- Omitted or
continuepreserves the existing behavior. blockprevents tool dispatch when the hook times out, cannot be spawned, crashes or exits without a valid protocol result, emits malformed output, or encounters event-serialization failure.- The user receives a redacted blocking diagnostic that contains no command, tool-input, or hook-payload values.
- The setting participates in hook trust/config hashing, and effective-config reads expose the resolved value to app-server/Desktop consumers.
- Tests prove every failure class blocks before tool execution while valid allow and deny results remain unchanged.
This is the PreToolUse counterpart to #33630; it does not require changing the compatibility default for advisory hooks.
Activity
vincentkoc commentedon Sep 13, 2026
Status update: OpenClaw delivery is proceeding against released Codex contracts. The local custom-contract prototype described below is abandoned for this fix and is not a merge dependency. The original source findings and earlier prototype test limitations remain recorded below.
This also affects synchronous
mcp_toolpolicy hooks, and the same opt-in needs to coverPermissionRequestto preserve approval precedence. Context: openclaw/openclaw#91009.I inspected
rust-v0.153.4and main source frozen at36f0dbe796d9bb1a18a0fc0640ed08b3e1d54564. At that unpatched main snapshot:Failedwhile leavingshould_block = false.decision = None. The approval router then invokes its reviewer, which can approve. Enforcing only PreToolUse does not cover an outage between the two hook phases.For an MCP reproduction, enable
features.hooksand explicitly trust the exact handler below using the normal hook trust flow. This is the hooks configuration fragment:{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"mcp_tool","server":"policy","tool":"check","input":{},"timeout":1}]}]}}Leave
policyunconfigured, then request a shell command that writes a marker. That unpatched snapshot treats the failed hook as non-blocking. For the PermissionRequest counterpart, use an action that actually enters approval and a reviewer that otherwise approves; full-access settings alone can bypass PermissionRequest and would be a misleading test.The narrow contract I prototyped is:
on_error: "block"on synchronous command/MCP handlers for these two events; omission orcontinueretains existing behavior.hookSpecificOutput.hookEventName. An explicit envelope with no decision acknowledges successful evaluation and retains ordinary approval handling. PreToolUse retains deny with a nonempty reason and allow withupdatedInput; this does not addaskor bareallow. PermissionRequest retains its canonical allow/deny decisions, including the existing default denial message.isError, empty/plain-text, malformed, mismatched, or semantically invalid output blocks PreToolUse or produces an explicit PermissionRequest deny. Deny must win over another matching hook's allow. Cancellation must not dispatch the original tool.supportsFailClosedPermissionHooks; absent means unsupported. A${$}MCP template forwards the complete event, including optional subagent fields, without recursively expanding payload strings.Validation so far is against earlier local prototype revisions on that frozen main source, not an official Codex release: 506 hooks/config tests passed; a core approval test proved required failure prevents full-access reviewer fallback; a test using a real MCP connection to a synthetic server completed a subsequent call on the same connection and confirmed the cancelled command never wrote its marker. The native CLI built and its initialize response advertised the proposed capability.
The latest prototype remains unqualified. The full native MCP dispatch matrices needed a test diagnostic correction because public hook events retain only the outer MCP error, and the corrected rerun was interrupted by validation infrastructure. The corrected fixtures use otherwise-valid delayed acknowledgments/error results plus dispatch markers. Canonical generated schemas and the broader workspace suite are also pending. No official release support or complete integration qualification is claimed.
chrysent commentedon Sep 17, 2026
Independent confirmation on codex-cli 0.153.3 (official release tarball, Linux x86_64), with a minimal repro that isolates the malformed-output sub-case.
Setup. A project-level
hooks.jsonregistering a synchronousPreToolUsehandler for^Bash$:{ "hooks": { "PreToolUse": [ { "matcher": "^Bash$", "hooks": [ { "type": "command", "command": "/usr/local/bin/policy-hook --state-dir /state", "timeout": 5, "mode": "sync" } ] } ] } }Repro.
/hooksreview flow;codex execruns with the hook active.2without writing a decision to stdout (it writes a fixed diagnostic to stderr).printf data > /tmp/out.txt).Observed on 0.153.3:
2.codex execerror surface prefixed withCommand blocked by PreToolUse hook:— so the operator-visible text looks like a block.command_executionJSONL item and the sentinel file is created.codex execexits0.So in this state the hook is worse than absent: the error text reads as enforcement to anyone watching the output, while the tool ran. We only noticed because the absence of the expected filesystem side-effect assertion failed on our side after we fixed the decoder — before the fix, every request from our hook failed decode and nothing was ever actually blocked.
After fixing the hook (well-formed JSON decision on stdout, exit 0): denials are enforced correctly (no
command_executionitem for the turn, command not executed), so the happy path works fine on this version.Ask. As proposed in this issue: an opt-in per-hook (or global)
failureMode: blockso a crashing/malformed/failing hook fails closed, plus — if possible — distinguishing the surfaced text for "hook blocked the command" vs "hook itself failed" (in our repro both render asCommand blocked by PreToolUse hook: ..., which actively misleads during diagnosis).Happy to provide the hook filter script or extra traces if useful.
Addendum: one-shot reproduction script
A self-contained shell script reproduces the issue with no dependencies beyond
codexitself. It creates a minimal project whose single PreToolUse handler for^Bash$always fails (reads stdin, writes a diagnostic to stderr, exits 2, no decision on stdout), runscodex execasking codex to create a sentinel file, then reports which failure mode occurred:Command blocked by PreToolUse hook: policy-hook: could not parse request envelopeThe script (save as run-repro.sh, chmod +x, run it in an empty directory; tested on codex-cli 0.153.3, official release tarball, Linux x86_64). NOTE: it is interactive by necessity — newly written hooks start Untrusted and never run until trusted through the ordinary /hooks flow, so the script pauses once for you to trust the hook (using --dangerously-bypass-hook-trust instead would change what is being tested and is deliberately not used):
The hook deliberately ignores stdin content — any Bash step triggers the same failure path, so nothing about the request matters except that it is a Bash call.
soycarts commentedon Sep 18, 2026
+1, with evidence from codex-cli 0.152.1 on macOS: a
PreToolUsecommand hook that crashed, one that exceeded itstimeout, and one that printed output the harness could not parse each surfaced a hook failure, and in all three cases the shell command then ran, its effect was on disk afterwards, and aPostToolUseevent followed.For the shape: a per-entry opt-in that defaults to today's behaviour, as proposed here (
failureMode: "block"oron_error: "block"), is exactly what I need. A hook that renders a status line should keep proceeding on failure; a hook that answersdenyshould be able to say that its silence means no. ThePermissionRequestcoverage noted above matters for the same reason: an outage between the two phases is otherwise an approval.Runbook and sanitized captures for the three failure trials: https://github.com/approval-md/approval.md/blob/main/docs/codex-hook-probe.md (see the hook-failure observations in the native evidence section).
chiuwill87 commentedon Oct 1, 2026
Source confirmation for released 0.159.3, plus one coverage requirement for native child dispatch.
At 0.159.3 pre_tool_use.rs, callback failures and malformed results still leave
should_blockfalse. No-match and serialization-failure paths also continue. Required managed-hook loading checks startup loading; it does not establish successful runtime validation.Our requirement: a specifically designated mandatory validator must return a valid allow decision before native child allocation. Missing/unmatched required coverage, an untrusted/unavailable validator, crash, timeout, malformed result, or serialization failure must deny before allocation. Optional/advisory hooks can retain current defaults.
Relevant boundary: core pre-tool handling, followed by native child creation.
Acceptance needs valid-allow/explicit-deny cases, every required-validator failure class, coverage after configuration reload, and proof that denied calls create no child. A matched-hook failure policy alone would leave absent/mismatched mandatory coverage unresolved.
Evidence limit: inspected released source; earlier 0.159.2 testing confirmed a sampled explicit native denial before child creation. We have not performed live failure injection on 0.159.3.
Is a supported implementation or tracked patch available for this required-validation boundary? Related contract-visibility dependency: #46939.
vinifonz commentedon Oct 18, 2026
Feature request: opt-in fail-closed policy for synchronous PreToolUse hook failures
Please support an opt-in policy that denies a pending tool when a synchronous
PreToolUsecommand hook fails. This would let deployments that use hooks for policy enforcement stay on the official CLI instead of maintaining a private patch.I tested the official Linux x64 Codex CLI 0.163.0. The native ELF SHA-256 was
399ff69c431c066e40de318fba45c2b07f45a76b19939d247ee4828fc70c4215.With a trusted synchronous hook matching
Bashandapply_patch, both a native file patch and a shell request to a loopback HTTP receiver still executed after each of these hook failures:Healthy hooks allowed both tools. A Python missing-script error returned exit code 2 with stderr and denied both tools, consistent with the documented exit-code contract. The twelve-case test used disposable profiles, a loopback mock provider and a loopback destination; no real outbound message or customer request was made.
For example, this registered and trusted hook times out before the tool runs:
{ "hooks": { "PreToolUse": [{ "matcher": "^(Bash|apply_patch)$", "hooks": [{ "type": "command", "command": "python3 -c 'import time; time.sleep(3)'", "timeout": 1 }] }] } }After trusting it in a disposable test profile, request a harmless file patch or a request to a local test HTTP receiver. The hook reports
hook timed out after 1s, but the native tool still produces its side effect.I understand that hook errors continuing execution are part of the current documented behavior. The request is for an explicit alternative for synchronous policy hooks, while preserving the existing default and asynchronous hooks' advisory behavior. Under the opt-in policy, timeout, launch failure, nonzero non-deny exit, unusable structured output and pre-dispatch input serialization failure should deny the pending tool. Healthy hooks and explicit valid decisions should retain their current behavior.
cortexive commentedon Oct 19, 2026
+1 from a deployment that runs many concurrent Codex CLI agents behind a local policy hook.
Confirmed on the official 0.163.0 Linux x64 build. With a trusted synchronous
PreToolUsecommand hook, allow and explicit deny (exit 2) both behave correctly. When the hook exceeds itstimeout, though, the host marks the hook failed and the original command still runs. A wrapper inside the hook can turn its own child's failures into a deny, but it can't cover the host's own timeout or spawn-failure branch. So there's currently no way to make a policy hook fail closed from the hook side. This is what keeps us from moving Codex onto a consolidated policy hook.The proposed per-entry
failureMode: "block"(default unchanged) covers our need. One addition: once a block-mode hook is loaded, a config reload shouldn't be able to silently remove it or downgrade it tocontinuemid-session. Either refuse that reload and keep the prior snapshot, or require re-trust. Otherwise a policy guard can disappear from a running session without anyone noticing.ion-rbl commentedon Oct 20, 2026
Measurements on Codex CLI 0.162.1 (macOS) that confirm the timeout case still fails open:
Minimal reproduction, run on 2026-10-20. In a trusted project, with the hook trusted:
.codex/hooks.json:
{"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [
{"type": "command", "command": "date +%s > /tmp/hookstart; sleep 30; date +%s > /tmp/hookend", "timeout": 5}]}]}}
Run: codex exec --json - with the prompt "Run this shell command exactly once: echo probe".
Result: the hook started at second 1792487332. Codex stopped it (hookend was never written) and ran the command at 1792487337.1, about 5 seconds later. The command printed "probe" with exit code 0. The JSON event stream held no hook error or hook event, standard error was empty, and codex exec exited 0. The same run with the plain command "sleep 30" gave the same result (about 5.3 seconds, then the command ran).
Default timeout. A hook with no "timeout" field that slept 1500 seconds was stopped after about 599 seconds, then the Bash command ran with no error. This matches a default of 600 seconds.
So a slow or hung PreToolUse guard becomes a silent allow, and nothing in the event stream shows that the guard never decided. A "failureMode": "block" option as proposed here would close this. Until then, a visible event for a hook timeout would at least make the allow auditable.
seankoji commentedon Oct 28, 2026
Reproduced on Codex CLI 0.165.0, macOS arm64, 28 October 2026 AEDT (UTC+11). Native binary SHA-256:
a45099154d7fb4a5ed8a56f40966a95deb938e508bab23e6985035c709e9a85a.I ran an eight-case integration matrix against the installed, unmodified CLI. A loopback-only synthetic Responses transport emitted exactly one native
exec_commandcall (touch timeout-marker, explicit fixture workdir,login: false), then a final message. No real model service or credentials were used. Tool execution and hooks were real; the marker was checked independently from the CLI exit status.timeout: 1continue: falsewith stopReasonFor the timeout case, the hook wrote a start sentinel before sleeping. The tool marker's filesystem timestamp was 0.993 seconds after hook start, well before the five-second hook could finish. The whole isolated case completed in 1.892 seconds. Explicit-deny and exit-2 controls produced no marker, so this was not a skipped/untrusted hook mistaken for a pass. Every CLI turn exited 0, including correctly blocked controls; process exit status alone is not an enforcement check.
Minimal synchronous timeout configuration in a disposable profile:
{"hooks":{"PreToolUse":[{"matcher":"*","hooks":[{"type":"command","command":"python3 /ABSOLUTE/FIXTURE/hook.py","timeout":1}]}]}}Enable
[features] hooks = true. Review and trust the exact hook definition before testing. My fixture used the installed app-server'shooks/listto obtain the definition key/hash, persisted that exact hash only in the isolated profile'shooks.state, and re-readhooks/listto asserttrustStatus: trusted. No trust-bypass or full-access flags were used. Native commands remainedworkspace-writesandboxed. Each profile/repository was disposable and cleaned up; live configuration and host databases were untouched.The negative controls used canonical PreToolUse JSON denial and exit 2 with a fixed stderr reason. Missing-interpreter and crash fixtures replaced only the hook command/script; failed-registration cases moved the fixture to SessionStart. These results cover standalone native CLI hook dispatch, not an embedding client's additional gates, PermissionRequest precedence, Claude or OpenCode.
This confirms that the documented compatibility default remains fail-open in 0.165.0. The requested solution remains an opt-in mandatory/fail-closed execution gate as proposed here, not a longer hook timeout. A hook-local wrapper can emit denial for failures it catches, but cannot enforce the consumer's own deadline/launch-error branch.
Ancienttwo commentedon Oct 28, 2026
Adding an app-server embedding reproduction on codex-cli 0.165.0, macOS arm64, tested 2026-10-28 with the installed, unmodified binary (SHA256
a45099154d7fb4a5ed8a56f40966a95deb938e508bab23e6985035c709e9a85a). This complements the native CLI evidence above.A fake Responses provider on loopback emitted one native
exec_commandwriting a harmless marker in a disposable workspace, then a final text response. The app-server thread usedapprovalPolicy: "never"andsandbox: "danger-full-access"; this intentionally tests an external pre-execution gate without adding native approval prompts. No paid model or real provider credentials were used.timeout: 1For each configured case, the fixture obtained the exact definition key/currentHash from app-server
hooks/list, persisted the correspondinghooks.state.<key>.trusted_hashonly in its isolated config, and opened a new thread. The successful deny control is checked using both the absent marker and the next Responses request's actualfunction_call_output(Command blocked by PreToolUse hook: ...). In the timeout case that output is the real command's exit-0 result. A missing marker or process exit status alone was not treated as proof of enforcement.Minimal hook body for the timeout case:
Register it as a synchronous command hook with
timeout: 1and no matcher (all tools). Have the local Responses fixture return:{"type":"function_call","name":"exec_command","call_id":"probe","arguments":"{\"cmd\":\"printf executed > /ABSOLUTE/FIXTURE/marker\",\"yield_time_ms\":1000,\"max_output_tokens\":100}"}Contract question: is there a released, capability-detectable app-server mechanism for making a required pre-tool callback fail closed, while delivering rejection/timeout/unavailable as a tool error and allowing the owning turn to continue? If not, this is the opt-in guarantee we need from #41979; increasing the deadline or catching failures inside the hook cannot handle the runtime's own timeout/spawn-failure branch. We would also need the supported guarantee to identify which native tools, MCP calls, subagent calls and resumed turns it covers, and whether its input is final after other hook rewrites. Those additional surfaces were not qualified by this reproduction.
sltbrta commentedon Nov 9, 2026
Still fails open on 0.167.0 and current
main.In
codex-rs/hooks/src/events/pre_tool_use.rsatrust-v0.167.0, a hook that times out, fails to spawn, crashes or prints malformed output is markedFailedwithshould_blockleftfalse, so the tool call proceeds. Only exit code 2 with a stderr reason, orpermissionDecision: "deny", blocks.mainbehaves the same and still has no config field for this (hooks/src/schema.rs,protocol/src/hooks.rs).Why it matters for managed hooks: we ship a
PreToolUseguard through/etc/codex/requirements.tomlthat rewrites recursive deletes and refuses secret-shaped arguments. If that script is missing, slow or crashes, Codex runs the original command unguarded. The equivalent Claude Code hook refuses the call withonFailure: "block". An opt-in per-entryfailureMode = "block", as proposed here, would let policy hooks fail closed.VeritasJ commentedon Nov 13, 2026
On Windows with Codex CLI/App Server 0.167.0-alpha.4.1, a synchronous PreToolUse command hook timing out did not stop Bash or apply_patch from running. A separate synthetic apply_patch that failed validation produced matching Hook run events but no fileChange terminal item with the original tool call ID.
Is there a supported way to require a positive PreToolUse decision before execution, and to receive an authoritative terminal event for the same tool call when the write body never started? We also need the behavior of a pending or stale tool delivery across a client reconnect. This is for handing off a shared working directory between two local workers.
chrysent commentedon Nov 15, 2026
This is such a simple change. I cant understand why this is not fixed.
@tibo-openai