Bundled `claude` binary hangs when stdout is not a TTY (pipe / file / launchd / cron / Docker)
Status: workaround in place locally; would benefit from upstream fix.
Reproduced on: macOS 25.4.0 (Darwin), claude-agent-sdk 0.1.x, 2026-05-05.
Affected use case: anything that captures the SDK's output (orchestrators, CI runners, headless launchd / cron jobs, Docker without -t).
Symptom
Any Python script that uses claude_agent_sdk hangs indefinitely when its stdout is a pipe or a regular file (i.e., not a terminal). Once the script hits the first query() call, the process goes to a sleeping state, makes no progress, and consumes near-zero CPU. No output is ever emitted. The hang persists past arbitrary timeouts.
The same script, run with stdout connected to a TTY, completes normally in expected time.
Minimal repro
```python
tty_bug.py
import asyncio from claude_agent_sdk import ( AssistantMessage, ClaudeAgentOptions, ResultMessage, TextBlock, query, )
async def main(): options = ClaudeAgentOptions( system_prompt="Reply with exactly one word.", allowed_tools=[], thinking={"type": "adaptive"}, effort="low", permission_mode="bypassPermissions", model="claude-opus-4-7", setting_sources=None, ) parts = [] async for msg in query(prompt="Say 'hello'.", options=options): if isinstance(msg, AssistantMessage): for block in msg.content: if isinstance(block, TextBlock): parts.append(block.text) elif isinstance(msg, ResultMessage): pass print("response:", "".join(parts).strip())
asyncio.run(main()) ```
| Invocation | Result |
|---|---|
| `python tty_bug.py` | Completes in ~2s |
| `python tty_bug.py > out.txt` | Hangs indefinitely. Kill required. `out.txt` empty. |
| `python tty_bug.py \| cat` | Hangs indefinitely. Kill required. |
| `script -q /dev/null python tty_bug.py > out.txt` | Completes; output written to file |
`script -q` allocates a real PTY, which is then forwarded to its own stdout. The bundled `claude` binary inside claude-agent-sdk sees a TTY and proceeds normally.
Why this matters
This bug bites anyone running the SDK in:
- An orchestrator / pipeline that captures step output (subprocess.PIPE).
- CI / GitHub Actions runners — they pipe stdout to log aggregators.
- launchd / cron jobs — no controlling terminal, stdout redirected to a file via the agent's plist or crontab.
- Docker containers without `-t`.
In all four cases the symptom is identical: silent hang, no diagnostic output, no error.
A real-world impact data point: a launchd-driven nightly pipeline saw analyze steps time out at 1800s every single tick for 24+ hours. Diagnosis required adding custom logging to the SDK consumer to discover the stream was hanging silently after a `RateLimitEvent` was yielded but no further message arrived.
Suspected mechanism
The bundled `claude` binary at `
- `script -q /dev/null` (which gives a PTY) consistently fixes it.
- Setting `PYTHONUNBUFFERED=1` does NOT fix it (so it's not a Python-side stdout buffering issue — it's inside the bundled binary).
- Disconnecting stdin (`< /dev/null`) does NOT fix it.
Additional issue: when an Anthropic-side rate limit fires, the SDK yields a `RateLimitEvent` message and then the stream hangs indefinitely instead of erroring or auto-retrying. Combined with the TTY-required behavior, this means a launchd-style consumer sees no output, no error, no progress — just a 1800s timeout.
Workaround
Wrap the entire SDK-using process in `script -q /dev/null`, OR detect `RateLimitEvent` in the iterator and abort with a retryable error so the caller's retry-with-backoff handles it.
For an orchestrator using `asyncio.create_subprocess_exec`, prepend the wrapper to the command:
```python cmd = ["/usr/bin/script", "-q", "/dev/null", *original_cmd] proc = await asyncio.create_subprocess_exec(*cmd, ...) ```
`script` syntax differs between macOS and Linux:
- macOS: `script -q
<cmd...>` - Linux: `script -q -c "
" `
Real fix (upstream)
Either:
- Don't `isatty()` to switch behavior. The SDK should produce the same output regardless of terminal attachment.
- If terminal-only behavior (progress spinners, ANSI colors) is genuinely useful when interactive, gate it on a `--non-interactive` flag, defaulting to non-interactive when `not isatty(stdout)`.
- Surface `RateLimitEvent` as a retryable Python exception that terminates the iterator, rather than as a continuing stream that may hang.
This pattern matches what we hit building a Rust scheduler that spawns claude as a subprocess on a cron-like interval (so: never under a TTY by definition — launchd on macOS, systemd units / cron on Linux, container entrypoints, etc.). A few notes from the orchestrator side in case they're useful upstream context:
1. The isatty() branch is more than cosmetic. From outside the binary it looks like spinners + ANSI gating, but in practice we observe behavior differences in the JSONL stream framing and in how rate-limit / control-channel events are emitted. The script -q /dev/null … PTY workaround you describe is exactly what we ended up wrapping each spawn in to get parity, and it lines up with what the bundled CLI in claude-agent-sdk does internally on some platforms. The "PTY or it hangs" reality is load-bearing for any unattended use case.
2. The "RateLimitEvent then hangs" failure mode is the more dangerous half of this bug. From a supervisor's perspective, "process is alive, RSS stable, zero stdout" is indistinguishable from "doing useful long-running work" — which is why your 1800s timeout case took 24h to surface. We had to add two defenses externally to make this safe:
- Bounded stdout/stderr drains on separate async tasks with a per-stream byte cap (we use 10MB), so a hung child can't fill kernel pipe buffers and so we can log truncation rather than buffer unboundedly.
- A wall-clock cycle timeout strictly less than the lock TTL, so even if the child is wedged with no output, the supervisor force-terminates at a deterministic boundary.
3. Killing a wedged child cleanly requires the whole process group. Once claude is hung post-RateLimitEvent, sending SIGKILL to just the child PID often leaves MCP server descendants alive (and in our case mutating external state). We spawn with process_group(0) and tear down with killpg(pgid, SIGKILL). Worth being aware of when documenting the workaround — subprocess.PIPE consumers retrying a hung query without a group-kill will accumulate MCP grandchildren.
So strong +1 on the proposed fixes: (a) producing identical stream output regardless of isatty(stdout), (b) defaulting --non-interactive to true when stdout is not a TTY, and especially (c) surfacing RateLimitEvent as a terminating exception rather than a yielded-then-silent event. Of the three, (c) is the one that materially changes whether unattended pipelines are recoverable without external watchdogs.
+1 from another production launchd setup — confirming the symptom on macOS Darwin 25.4.0 with the latest SDK (claude-agent-sdk==0.2.87, bundled CLI 2.1.150). We added one more layer of evidence that pinpoints where the hang happens in the SDK↔CLI handshake.
Symptom variant under launchd ProcessType=Background
Our bots spawn from ~/Library/LaunchAgents/*.plist and the SDK error surfaces as:
! claude SDK failed: Control request timeout: initialize
(With SDK ≤0.1.76 the same condition surfaces as the generic Command failed with exit code 1; #918 unmasked it.) Every query() call burns ~60 seconds before raising — matches Query._initialize_timeout default.
Across our 6-bot fleet, every bot logs these errors. Bots that process items one-by-one mostly survive (one bad call drops one item); a bot that batches 8 items per query() loses the entire batch and posts nothing.
Tap evidence — SDK never reads the CLI's response
Setting ClaudeAgentOptions(cli_path=...) to a tap script that records argv / stdin / stdout / stderr / exit per call:
| File | Content |
|---|---|
.stdin (SDK → CLI) |
127 B, only the initialize control_request:{"type":"control_request","request_id":"req_1_…","request":{"subtype":"initialize","hooks":null,"skills":[]}} |
.stdout (CLI → SDK) |
8.4 KB single line, a well-formed control_response with subtype=success and the full commands+account block |
.stderr |
empty |
.exit |
0 |
.trace |
wrapper start → real claude pid=N → stdin EOF from SDK (60s later) → real claude wait() returned rc=0 |
So at the protocol level: the CLI receives initialize, replies immediately with a valid control_response (8 KB makes it onto its stdout pipe), the SDK never reads that response, after 60s the SDK closes stdin, the CLI sees EOF and exits cleanly with code 0. The bundled CLI is innocent — it's the SDK side that's not draining stdout when spawned in a no-TTY launchd context. That fits @pfrank8's isatty() hypothesis: the CLI may be emitting in a framing the SDK reader doesn't accept in headless mode, or stdio is being buffered such that the response sits in the kernel pipe buffer until forcibly drained.
Things tried that did NOT help
- Upgrading SDK
0.1.76 → 0.2.87(bundled CLI 2.1.132 → 2.1.150) — better error messages, same bug ClaudeAgentOptions(setting_sources=[], skills=[])— eliminates plugin/hook noise but not the initialize timeoutClaudeAgentOptions(stderr=...)callback — registers but receives no lines from the failing calls- Switching the launchd plist from
ProcessType=BackgroundtoLimitLoadToSessionType=Aqua— made things worse (classify Haiku also began to fail-open under Aqua; Background recovered classify but summarize still failed) - Direct invocation of the bundled CLI under the same env-shape (
env -i HOME=… PATH=… /…/claude --model sonnet-4-6 --print "hi"vianohup, no TTY) — succeeds cleanly. So the bug is reproducible only via the SDK's spawn path, not the CLI itself.
Stopgap that worked locally
We shipped a one-shot retry on Control request timeout / error result / exit code 1 in our SDK wrapper. Result is mixed:
- The
Control request timeout: initializevariant — too small a sample yet to claim it retries cleanly, but past observation suggests transience. - The
Claude Code returned an error result: successvariant is deterministic in our setup: the second attempt fails with the identical error text. So retry doesn't recover this one — it just doubles the cost.
Next we'll instrument the failing ResultMessage (is_error, subtype, api_error_status, num_turns) to pin down whether "error result: success" is hiding a rate-limit / capacity / max_turns hit. Will report back. The PTY-allocation workaround (script -q /dev/null …) from the OP is also on the followup list.
Adjacent issues
#922 reports the same control_request:initialize silent-timeout in container env on CLI 2.1.121 — we see it on CLI 2.1.150, so the protocol mismatch (if that's what it is) isn't pinned to that one version.
Happy to share full tap traces / repro script if useful for upstream debugging.
Verified fixed (the TTY-hang half) on claude-agent-sdk 0.2.110 / bundled CLI 2.1.195: a script whose stdout is a non-TTY pipe now completes normally (~4s, actually faster than the script -q /dev/null PTY control). The PTY workaround is no longer required for the hang.
Note: the second half of this report — RateLimitEvent yielded, then the stream hangs — was not re-tested, since it requires a live rate limit to fire. That part may still be open.