Skip to content

fix(agent-hooks): drain stdin before hook script early exits so agents never hit EPIPE - #8430

Merged
AmethystLiang merged 3 commits into
stablyai:mainfrom
kaynansc:fix/hook-scripts-drain-stdin
Jul 13, 2026
Merged

AmethystLiang merged 3 commits into
stablyai:mainfrom
kaynansc:fix/hook-scripts-drain-stdin

Conversation

@kaynansc

Copy link
Copy Markdown
Contributor

Summary

Fixes #8419.

Orca's generated POSIX agent hook scripts read their payload with payload=$(cat) after an env guard that exits early:

if [ -z "$ORCA_AGENT_HOOK_PORT" ] || [ -z "$ORCA_AGENT_HOOK_TOKEN" ] || [ -z "$ORCA_PANE_KEY" ]; then
  exit 0
fi
payload=$(cat)

When an instrumented agent runs outside an Orca pane (SSH-booted codex app-server daemons, 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 with failed to write hook stdin: Broken pipe (os error 32) on every tool call.

This PR drains stdin (cat >/dev/null 2>&1 || :) before every early exit 0 that precedes payload=$(cat):

  • All 11 POSIX script templates that use this pattern: antigravity, claude (both guards, including the DEVIN_PROJECT_DIR early exit), codex, command-code (in command-code-managed-script.ts), copilot, cursor, devin, droid, gemini, grok, kimi. (openclaude shares the Claude template, so it's covered; opencode/amp/hermes/mimo use in-process JS/Python plugins that never read a piped stdin, so the bug class doesn't apply to them.)
  • wrapPosixHookCommand in installer-utils.ts: the wrapper written into agent configs (if [ -x '<hook>' ]; then …; fi) now has an else cat >/dev/null 2>&1 || :; fi branch, 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 by CodexHookService.install():

=== BEFORE (script generated from origin/main) ===
codex-hook.sh: BrokenPipeError 5/5

=== AFTER (script generated from this branch) ===
codex-hook.sh: BrokenPipeError 0/5

=== diff of the two generated scripts ===
25a26
>   cat >/dev/null 2>&1 || :

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test (2724 test files, 28761 tests passed)
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed
    • Each of the 11 templates gets a regression test asserting the generated script drains stdin before every early exit that precedes payload=$(cat) (the Claude test covers both guards and counts drains == early exits).
    • installer-utils.test.ts gets an assertion on the new else branch plus a live reproduction test: spawns /bin/sh on the wrapped command for a missing script, writes 200 KB to its stdin, and asserts exit 0 with zero EPIPE stdin errors.
    • Verified the tests fail on the unfixed code: reverting the source files makes 7 tests fail (claude ×2, codex ×1, installer-utils ×4).

AI Review Report

Two-axis review (repo standards + issue spec) ran with independent reviewer agents against origin/main:

  • Spec compliance: exhaustively enumerated every generated-POSIX-script site with payload=$(cat) in src/main — all 12 guard sites across 11 templates are drained; the wrapPosixHookCommand else-branch matches the issue's suggestion; later exit 0s after payload=$(cat) were correctly left untouched (stdin already consumed). No missing requirements, no scope creep.
  • Cross-platform (macOS/Linux/Windows): only POSIX /bin/sh templates 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 is it.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.
  • Remote/SSH compatibility: the fix is inside the generated script content, so it applies identically through every install path — local install(), installRemote() (SFTP), and WSL runtime installs all serialize the same template. The relay scenario from the issue (hooks firing in SSH-booted daemons without ORCA_* env) is exactly the case the drain fixes.
  • Agent/integration compatibility: all 15 hook generators surveyed; the 4 not touched (opencode, amp, hermes, mimo) use in-process plugin mechanisms with no piped stdin, confirmed not affected.
  • Performance: cat >/dev/null runs 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.
  • What changed as a result of review: test comments were tightened to the repo's 1–2-line "Why" comment standard; no functional findings.

Security Audit

  • The added shell fragment is a constant string (cat >/dev/null 2>&1 || :) with no variable interpolation, so it introduces no new quoting/injection surface. Existing single-quote escaping in wrapPosixHookCommand is preserved and its quoting-focused tests still pass (updated for the new else branch).
  • Draining to /dev/null discards the payload without persisting or forwarding it anywhere — strictly less data handling than the normal path.
  • No changes to input parsing, command execution targets, auth/token handling, path construction, dependencies, or IPC. The hook endpoint/token flow is untouched.
  • Reviewed the failure mode of the drain itself: || : guarantees the guard still exits 0 even if cat fails, so agent-side hook execution never turns into a new error.

Notes

  • POSIX-only by design: the issue and its reproduction are Linux/EPIPE-specific. Windows templates keep their current behavior.
  • Behavior note: with stdin now drained, a hook invoked without ORCA_* env blocks until the agent finishes writing and closes stdin — the same blocking the normal payload=$(cat) path already has, so no new hang surface for agents (they write-then-close).
  • X handle: @KaynanSampaio1

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 72fa0935-77ac-4cab-a6c8-7d14564ebe34

📥 Commits

Reviewing files that changed from the base of the PR and between 19bea00 and 9a04892.

📒 Files selected for processing (1)
  • config/scripts/verify-agent-hook-stdin-lifecycle.mjs

📝 Walkthrough

Walkthrough

The 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.26% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main fix: draining stdin before hook early exits to prevent EPIPE.
Description check ✅ Passed All required sections are present, including summary, screenshots, testing, AI review, security audit, and notes.
Linked Issues check ✅ Passed The changes address #8419 by draining stdin before early exits in affected templates and adding the missing-script wrapper fallback.
Out of Scope Changes check ✅ Passed The added docs, tests, and shared helpers all support the stdin-drain fix and do not appear unrelated to the issue.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@AmethystLiang

Copy link
Copy Markdown
Contributor

thanks for the fix PR. reviewing it now

@AmethystLiang
AmethystLiang self-requested a review July 13, 2026 00:11
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.
@AmethystLiang
AmethystLiang force-pushed the fix/hook-scripts-drain-stdin branch from f951ba6 to 19bea00 Compare July 13, 2026 06:28

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
config/scripts/verify-agent-hook-stdin-lifecycle.mjs (1)

314-350: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the path substitution actually happened before trusting the missing/failing-script branches.

missingCommand/failingCommand are built via command.replaceAll(installedPath, ...), but installedPath is independently reconstructed rather than derived from the matched string. If the real installed command's path format ever diverges from this reconstruction, replaceAll silently 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.mjs
  • config/tsconfig.cli.json
  • docs/reference/agent-hook-stdin-lifecycle.md
  • src/main/agent-hooks/agent-hook-memory-sftp.test-fixture.ts
  • src/main/agent-hooks/hook-stdin-contract.ts
  • src/main/agent-hooks/installer-utils.test.ts
  • src/main/agent-hooks/installer-utils.ts
  • src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts
  • src/main/agent-hooks/managed-hook-timeout.test.ts
  • src/main/agent-hooks/remote-hook-service-installers.test.ts
  • src/main/antigravity/hook-service.test.ts
  • src/main/antigravity/hook-service.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-service.ts
  • src/main/codex/hook-service-wsl-runtime.test.ts
  • src/main/codex/hook-service.ts
  • src/main/command-code/command-code-managed-script.ts
  • src/main/command-code/hook-service.test.ts
  • src/main/copilot/hook-service.test.ts
  • src/main/copilot/hook-service.ts
  • src/main/cursor/hook-service.ts
  • src/main/devin/hook-service.test.ts
  • src/main/devin/hook-service.ts
  • src/main/devin/hook-settings.ts
  • src/main/droid/hook-service.ts
  • src/main/gemini/hook-service.ts
  • src/main/grok/hook-service.ts
  • src/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.
@AmethystLiang
AmethystLiang merged commit c3ab805 into stablyai:main Jul 13, 2026
OrcaWin added a commit that referenced this pull request Jul 14, 2026
…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.
OrcaWin added a commit that referenced this pull request Jul 14, 2026
…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.
nwparker added a commit to nwparker/orca that referenced this pull request Aug 2, 2026
…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>
OrcaWin added a commit that referenced this pull request Aug 20, 2026
…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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Generated agent hook scripts exit without draining stdin → per-tool-call "failed to write hook stdin: Broken pipe (os error 32)"

2 participants