Repository navigation
fix(agent-hooks): drain stdin before hook script early exits so agents never hit EPIPE - #8430
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThe change centralizes POSIX and Windows stdin capture and drain behavior for generated agent hooks and managed launchers. Wrappers now handle missing, unreadable, non-executable, and directory targets while consuming stdin. Provider-specific hook scripts use shared guard and payload builders. Matching and command-generation tests were expanded for cross-platform quoting and launcher variants. New lifecycle tests, an in-memory SFTP fixture, and a standalone verifier exercise large payloads, early exits, forwarding, missing scripts, and Windows launch paths. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
thanks for the fix PR. reviewing it now |
Generated agent hook scripts and missing-script launchers could exit successfully before consuming the payload written to their stdin, leaving the writer with a broken pipe (EPIPE/ERROR_BROKEN_PIPE) once the reader closed early. Capture stdin (or drain it via a shared epilogue/fast-path guard) before any whole-script success exit across all POSIX, batch, PowerShell, and Git Bash launcher variants, and add a cross-agent lifecycle test suite plus a live Electron verification script to guard the contract going forward.
- Extend the POSIX launcher guard to also require `[ -r ]`, not just `-f`/`-x`, so an executable-but-unreadable managed script still drains stdin instead of erroring or silently misbehaving. - Add a verifier case (`verifyClaudeDevinSkip`) that spins up a local HTTP server and confirms the Claude hook never forwards a request that Devin already imported, catching accidental double-forwarding. - Update installer-utils tests and stdin-lifecycle docs to match the new readable-file guard and the added verification case.
f951ba6 to
19bea00
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
config/scripts/verify-agent-hook-stdin-lifecycle.mjs (1)
314-350: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert the path substitution actually happened before trusting the missing/failing-script branches.
missingCommand/failingCommandare built viacommand.replaceAll(installedPath, ...), butinstalledPathis independently reconstructed rather than derived from the matched string. If the real installed command's path format ever diverges from this reconstruction,replaceAllsilently no-ops, and the "missing script" case ends up re-running the real, present script — the test would keep passing while no longer verifying the drain-on-missing-script behavior it claims to cover.🛡️ Proposed fix: assert substitution occurred
const missingPath = join(scratch, 'missing-hook.sh') const missingCommand = command.replaceAll(installedPath, missingPath) + if (missingCommand === command) { + throw new Error('Installed launcher command did not reference the expected script path') + } const missingResult = await runShell( missingCommand, payload, withoutOrcaEnvironment({ HOME: home }) ) assertSuccessfulWrite(missingResult, 'installed missing-script launcher') const failingPath = join(scratch, 'failing-hook.sh') writeFileSync(failingPath, '#!/bin/sh\ncat >/dev/null\nexit 7\n', 'utf8') chmodSync(failingPath, 0o755) const failingCommand = command.replaceAll(installedPath, failingPath) + if (failingCommand === command) { + throw new Error('Installed launcher command did not reference the expected script path') + }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: e5481269-1512-4131-ba4e-f6f41eef881c
📥 Commits
Reviewing files that changed from the base of the PR and between f951ba6efe33c56bb0ae8b516cfeb5033bb8e608 and 19bea00.
📒 Files selected for processing (28)
config/scripts/verify-agent-hook-stdin-lifecycle.mjsconfig/tsconfig.cli.jsondocs/reference/agent-hook-stdin-lifecycle.mdsrc/main/agent-hooks/agent-hook-memory-sftp.test-fixture.tssrc/main/agent-hooks/hook-stdin-contract.tssrc/main/agent-hooks/installer-utils.test.tssrc/main/agent-hooks/installer-utils.tssrc/main/agent-hooks/managed-hook-stdin-lifecycle.test.tssrc/main/agent-hooks/managed-hook-timeout.test.tssrc/main/agent-hooks/remote-hook-service-installers.test.tssrc/main/antigravity/hook-service.test.tssrc/main/antigravity/hook-service.tssrc/main/claude/hook-service.test.tssrc/main/claude/hook-service.tssrc/main/codex/hook-service-wsl-runtime.test.tssrc/main/codex/hook-service.tssrc/main/command-code/command-code-managed-script.tssrc/main/command-code/hook-service.test.tssrc/main/copilot/hook-service.test.tssrc/main/copilot/hook-service.tssrc/main/cursor/hook-service.tssrc/main/devin/hook-service.test.tssrc/main/devin/hook-service.tssrc/main/devin/hook-settings.tssrc/main/droid/hook-service.tssrc/main/gemini/hook-service.tssrc/main/grok/hook-service.tssrc/main/kimi/hook-service.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/grok/hook-service.ts
- src/main/claude/hook-service.ts
- src/main/devin/hook-service.ts
Extract the quoted path from the launcher's `if [ -f '...'` clause instead of reconstructing it via join(home, ...), so missing/failing-script test cases can't silently fall through to the real script if the install layout changes.
…8430 regression) Codex, Antigravity, and Devin launch their agent-hook `command` as a program (argv[0]), not through cmd.exe. PR #8430 changed wrapWindowsCmdHookCommand to emit an `if exist "path\." (drain) else if exist "path" (call "path") else (drain)` compound whose argv[0] is the cmd builtin `if` — unspawnable — so every Codex/Antigravity/Devin hook (SessionStart, UserPromptSubmit, Stop, ...) failed with "hook exited with code 1" on Windows starting in v1.4.138. Revert the cmd-safe fast path to the bare, directly-spawnable .cmd path (the proven pre-#8430 form). A cmd-builtin drain and direct-spawnability are mutually exclusive, and nesting cmd.exe /d /c breaks large-payload draining; the missing-script stdin drain stays on the encoded-PowerShell fallback (used for spaced/non-ASCII paths). Upgrades self-heal on first launch: startup install() unconditionally rewrites the command and Codex trust entry, sweeping the old compound form. Add a platform-independent regression guard (launcher must resolve to a real file, never a cmd-builtin fragment), update the lifecycle test + docs, and fix a stale Devin comment.
…8430 regression) (#8737) Codex, Antigravity, and Devin launch their agent-hook `command` as a program (argv[0]), not through cmd.exe. PR #8430 changed wrapWindowsCmdHookCommand to emit an `if exist "path\." (drain) else if exist "path" (call "path") else (drain)` compound whose argv[0] is the cmd builtin `if` — unspawnable — so every Codex/Antigravity/Devin hook (SessionStart, UserPromptSubmit, Stop, ...) failed with "hook exited with code 1" on Windows starting in v1.4.138. Revert the cmd-safe fast path to the bare, directly-spawnable .cmd path (the proven pre-#8430 form). A cmd-builtin drain and direct-spawnability are mutually exclusive, and nesting cmd.exe /d /c breaks large-payload draining; the missing-script stdin drain stays on the encoded-PowerShell fallback (used for spaced/non-ASCII paths). Upgrades self-heal on first launch: startup install() unconditionally rewrites the command and Codex trust entry, sweeping the old compound form. Add a platform-independent regression guard (launcher must resolve to a real file, never a cmd-builtin fragment), update the lifecycle test + docs, and fix a stale Devin comment.
…reachability Order the Orca-env guards ahead of Claude's Devin skip so that skip's drain is reachable only when Orca invoked the hook, guard the Antigravity event wrappers before their standalone drain, and stop emitting the epilogue where nothing can jump to it. Correct the stablyai#8430 rationale: it did cover Orca-less callers, but assumed every caller closes stdin. Co-authored-by: Orca <help@stably.ai>
…s per event (#14828) Grok runs a hook `command` containing a space as `pwsh -Command <cmd>`. Orca registered the encoded PowerShell launcher, whose command line is full of spaces, so every status event walked grok.exe -> pwsh.exe -> powershell.exe -> cmd.exe -> curl.exe before reaching a script whose entire job is one loopback POST. Measured against Grok 1.0.5's own dispatcher on Windows 11, that is 518-719ms per event (mean 607ms). The same script registered as its bare path is spawned directly as `grok.exe -> cmd.exe` and costs 43-213ms (mean 114ms). Orca installs nine Grok events, and a single one-tool-call prompt dispatches roughly ten of them, so this is the difference between a hook chain that is continuously resident during a turn and one that is not. It is also how long the console the agent allocates for a hook can stay on screen, which is the mechanism #15520 fixed for Antigravity -- Grok was worse, paying two interpreters rather than one. Use the shared `wrapWindowsCmdHookCommand`, the same registration Codex, Devin and Antigravity already use (#8430). A profile path that is not cmd-safe still falls back to the encoded launcher, so #6078 stays covered. Tradeoff carried over from those agents: a bare path cannot hold the launcher's missing-script guard, so a deleted script surfaces as a per-event `command not found` in Grok's log rather than a silent stdin drain. Verified that Grok fails open there -- the tool still runs, including on PreToolUse, which Grok declares a blocking event. Verified end to end against the real Grok CLI: 9/9 status posts delivered with full payloads through the bare path, and 12/12 in a controlled A/B spawning both shapes the way Grok does. Also confirmed Grok creates hook processes with CREATE_NO_WINDOW rather than DETACHED_PROCESS, which is the mode where a bare .cmd would have been worse than the launcher.
…s never hit EPIPE (stablyai#8430) * Fix hook scripts to drain stdin before any early-exit path Generated agent hook scripts and missing-script launchers could exit successfully before consuming the payload written to their stdin, leaving the writer with a broken pipe (EPIPE/ERROR_BROKEN_PIPE) once the reader closed early. Capture stdin (or drain it via a shared epilogue/fast-path guard) before any whole-script success exit across all POSIX, batch, PowerShell, and Git Bash launcher variants, and add a cross-agent lifecycle test suite plus a live Electron verification script to guard the contract going forward. * Harden hook scripts against unreadable managed scripts and add a Claude/ - Extend the POSIX launcher guard to also require `[ -r ]`, not just `-f`/`-x`, so an executable-but-unreadable managed script still drains stdin instead of erroring or silently misbehaving. - Add a verifier case (`verifyClaudeDevinSkip`) that spins up a local HTTP server and confirms the Claude hook never forwards a request that Devin already imported, catching accidental double-forwarding. - Update installer-utils tests and stdin-lifecycle docs to match the new readable-file guard and the added verification case. * Fix hook-launcher verification to derive script paths from the installed Extract the quoted path from the launcher's `if [ -f '...'` clause instead of reconstructing it via join(home, ...), so missing/failing-script test cases can't silently fall through to the real script if the install layout changes. --------- Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com>
…tablyai#8430 regression) (stablyai#8737) Codex, Antigravity, and Devin launch their agent-hook `command` as a program (argv[0]), not through cmd.exe. PR stablyai#8430 changed wrapWindowsCmdHookCommand to emit an `if exist "path\." (drain) else if exist "path" (call "path") else (drain)` compound whose argv[0] is the cmd builtin `if` — unspawnable — so every Codex/Antigravity/Devin hook (SessionStart, UserPromptSubmit, Stop, ...) failed with "hook exited with code 1" on Windows starting in v1.4.138. Revert the cmd-safe fast path to the bare, directly-spawnable .cmd path (the proven pre-stablyai#8430 form). A cmd-builtin drain and direct-spawnability are mutually exclusive, and nesting cmd.exe /d /c breaks large-payload draining; the missing-script stdin drain stays on the encoded-PowerShell fallback (used for spaced/non-ASCII paths). Upgrades self-heal on first launch: startup install() unconditionally rewrites the command and Codex trust entry, sweeping the old compound form. Add a platform-independent regression guard (launcher must resolve to a real file, never a cmd-builtin fragment), update the lifecycle test + docs, and fix a stale Devin comment.
Summary
Fixes #8419.
Orca's generated POSIX agent hook scripts read their payload with
payload=$(cat)after an env guard that exits early:When an instrumented agent runs outside an Orca pane (SSH-booted
codex app-serverdaemons, detached tmux sessions, plain-terminal launches — the hooks are registered in global agent config, so they fire there too), the guard exits without ever reading stdin, and the agent's payload write fails withfailed to write hook stdin: Broken pipe (os error 32)on every tool call.This PR drains stdin (
cat >/dev/null 2>&1 || :) before every earlyexit 0that precedespayload=$(cat):antigravity,claude(both guards, including theDEVIN_PROJECT_DIRearly exit),codex,command-code(incommand-code-managed-script.ts),copilot,cursor,devin,droid,gemini,grok,kimi. (openclaudeshares the Claude template, so it's covered;opencode/amp/hermes/mimouse in-process JS/Python plugins that never read a piped stdin, so the bug class doesn't apply to them.)wrapPosixHookCommandininstaller-utils.ts: the wrapper written into agent configs (if [ -x '<hook>' ]; then …; fi) now has anelse cat >/dev/null 2>&1 || :; fibranch, so a missing/non-executable hook script no longer drops stdin either.The normal in-pane forwarding path (
payload=$(cat)→ curl POST) is byte-for-byte unchanged — "agent not running under Orca" is now silent instead of a per-tool-call error.Screenshots
No visual change (generated shell scripts only). End-to-end proof using the deterministic reproduction from the issue (simulated agent writes a 100 KB hook payload to the script's stdin with
ORCA_*env stripped, 5 runs), against the real script produced byCodexHookService.install():Testing
pnpm lintpnpm typecheckpnpm test(2724 test files, 28761 tests passed)pnpm buildpayload=$(cat)(the Claude test covers both guards and counts drains == early exits).installer-utils.test.tsgets an assertion on the newelsebranch plus a live reproduction test: spawns/bin/shon the wrapped command for a missing script, writes 200 KB to its stdin, and asserts exit 0 with zeroEPIPEstdin errors.AI Review Report
Two-axis review (repo standards + issue spec) ran with independent reviewer agents against
origin/main:payload=$(cat)insrc/main— all 12 guard sites across 11 templates are drained; thewrapPosixHookCommandelse-branch matches the issue's suggestion; laterexit 0s afterpayload=$(cat)were correctly left untouched (stdin already consumed). No missing requirements, no scope creep./bin/shtemplates changed; Windows.cmd/PowerShell templates are untouched (EPIPE-on-unread-stdin is POSIX pipe semantics; Windows named-pipe behavior differs and the issue reproduces on Linux). The new live-EPIPE test isit.skipIf(process.platform === 'win32')-gated, consistent with existing suite conventions. Flagged for future work (not this issue): Copilot's PowerShell template has the same early-exit-before-read shape.install(),installRemote()(SFTP), and WSL runtime installs all serialize the same template. The relay scenario from the issue (hooks firing in SSH-booted daemons withoutORCA_*env) is exactly the case the drain fixes.opencode,amp,hermes,mimo) use in-process plugin mechanisms with no piped stdin, confirmed not affected.cat >/dev/nullruns only on the early-exit path (agent outside Orca or missing script) and consumes at most one hook payload; the in-pane hot path is unchanged.Security Audit
cat >/dev/null 2>&1 || :) with no variable interpolation, so it introduces no new quoting/injection surface. Existing single-quote escaping inwrapPosixHookCommandis preserved and its quoting-focused tests still pass (updated for the new else branch)./dev/nulldiscards the payload without persisting or forwarding it anywhere — strictly less data handling than the normal path.|| :guarantees the guard still exits 0 even ifcatfails, so agent-side hook execution never turns into a new error.Notes
ORCA_*env blocks until the agent finishes writing and closes stdin — the same blocking the normalpayload=$(cat)path already has, so no new hang surface for agents (they write-then-close).