claude-agent-sdk-python icon indicating copy to clipboard operation
claude-agent-sdk-python copied to clipboard

Feature request: configurable API response timeout for subagent calls

Open oneryalcin opened this issue 8 months ago • 2 comments

Summary

When a subagent makes an API call with large context (~83K tokens) and needs to generate large output (~30KB), the API call can hang indefinitely with zero events written to the JSONL transcript. There is no configurable timeout to detect or recover from this state.

Reproduction

  1. Launch a background agent (run_in_background=True) with a task requiring large context
  2. Agent accumulates ~80K+ tokens of context via multiple Read calls
  3. Agent makes a tool call that succeeds (e.g., mkdir)
  4. Next API call (to generate a large Write) hangs — zero JSONL events for 4+ minutes
  5. Parent agent polls via TaskOutput — always sees status: running
  6. No mechanism to detect the hang or kill the subagent

Observed behavior

  • JSONL transcript stops at the successful tool_result — no new entries
  • TaskOutput always returns running (can't distinguish "actively generating" from "API hung")
  • KillShell fails ("not a local bash task")
  • TaskStop kills the agent but destroys any in-progress work

Expected behavior

A configurable timeout (e.g., api_timeout_seconds in ClaudeAgentOptions) that:

  1. Detects when an API response hasn't produced any events for N seconds
  2. Marks the agent as error with a clear timeout message
  3. Writes the error to the agent's JSONL for downstream tracking

Workaround

We implemented a 20-minute wall-clock timeout in our stop hook that unblocks the parent task, but the hung agent process itself stays alive consuming resources.

Environment

  • claude-agent-sdk: 0.1.48
  • Claude Code CLI: 2.1.72 (bundled)
  • Observed on: Python 3.12, Linux (GKE)
  • Original incident: CLI 2.0.72, but the underlying issue (no API timeout) persists

oneryalcin avatar Mar 10 '26 14:03 oneryalcin

This should be already supported. I will make sure the docs point to this more clear for Agent SDK specifically.

Try passing these through options.env:

options = ClaudeAgentOptions( env={ "API_TIMEOUT_MS": "120000", "CLAUDE_CODE_MAX_RETRIES": "2", "CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS": "120000", }, )

  • API_TIMEOUT_MS: per-request timeout on the Anthropic client, in ms. Default 600000 (10 min). Same client is used for the main loop and Task subagents, so it covers both. (Doc)
  • CLAUDE_CODE_MAX_RETRIES: max API retries. Worth lowering since retries compound with the timeout.
  • CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS: stall watchdog for background Task agents. Default 600000. This re-arms on each stream event; if nothing arrives in the window it aborts the agent, marks the task failed, and passes stalled. This is basically the behavior you described wanting.

I reproed your scenario with a local stalling proxy: without API_TIMEOUT_MS the SDK hangs, and with it set to 8s I got a ResultMessage(is_error=True) / "Request timed out" back in ~20s.

Also, we fixed some issues with API_TIMEOUT_MS in v2.1.101, and we recommend updating past that version. Thanks!

qing-ant avatar May 05 '26 00:05 qing-ant

Closing the loop with empirical results from running this against claude-agent-sdk==0.1.60 (bundled claude 2.1.111). Two things qing's recommendation didn't quite cover that future readers will want to know.

TL;DR — config that actually works

ClaudeAgentOptions(env={
    "CLAUDE_ENABLE_STREAM_WATCHDOG": "1",
    "CLAUDE_STREAM_IDLE_TIMEOUT_MS": "90000",
    "CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK": "1",
})

With this, a wedged Anthropic SSE stream aborts in ~90s with a structured ResultMessage(is_error=True) carrying a synthetic AssistantMessage(text="API Error: Stream idle timeout - no chunks received"). Without all three, the SDK either ignores the config or silently re-wedges. Details below.

1. The env var name in qing's snippet doesn't exist in the released CLI

CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS is not present in CLI 2.1.111. Verified by grepping the bundled binary:

$ grep -aoE 'CLAUDE_[A-Z_]*STALL[A-Z_]*' .venv/lib/.../_bundled/claude | sort -u
CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL
CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL
CLAUDE_CODE_STALL_TIMEOUT_MS_FOR_TESTING
CLAUDE_CODE_SYNC_PLUGIN_INSTALL
CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS

The functional pair, per the official env-vars docs, is:

  • CLAUDE_ENABLE_STREAM_WATCHDOG — event-level idle watchdog, off by default
  • CLAUDE_STREAM_IDLE_TIMEOUT_MS — timeout in ms

The docs claim CLAUDE_STREAM_IDLE_TIMEOUT_MS defaults to 300000 with a 5-min floor for both watchdogs. The binary disagrees:

let oH=VH(process.env.CLAUDE_ENABLE_STREAM_WATCHDOG),
    uH=parseInt(process.env.CLAUDE_STREAM_IDLE_TIMEOUT_MS||"",10)||90000,
    yH=uH/2,

So the event-level path actually defaults to 90000 (90s) — no floor. The 300000 floor (Math.max(parseInt(...)||90000, 300000)) appears in a different code path, likely the byte watchdog. Worth pinning the value explicitly so a future binary that aligns itself with the docs doesn't silently 5x your watchdog window.

2. CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK is required, not optional

This was the surprise. With only CLAUDE_ENABLE_STREAM_WATCHDOG=1 set, against a fake server that wedges mid-SSE, my repro got:

[server] POST /v1/messages stream=True
[server] sent first delta, switching to keepalive-only mode
[server] keepalive #1 (t+15s)
...
[server] keepalive #5 (t+75s)
[server] client disconnected after 5 keepalives (t+90s)        ← watchdog fired ✅

[server] POST /v1/messages stream=None                          ← non-streaming fallback ❌
[server] sent first delta, switching to keepalive-only mode
[server] keepalive #1 (t+15s)
...
[server] keepalive #22 (t+330s)                                 ← still wedged

So the streaming watchdog correctly aborts the original stream at 90s, the SDK then retries via non-streaming, my fake server happily wedges that too, and the parent process gets exactly one event from this whole 7-minute saga.

Notes for future readers:

  • CLAUDE_CODE_MAX_RETRIES=0 does NOT block the non-streaming fallback. The fallback is a separate code path — only CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK=1 blocks it.
  • With both flags set, the SDK gives me the structured error result at t+90.034s and exits cleanly. The parent's existing error path can take it from there without needing a wall-clock timeout layer.

3. Possible bug or doc question for the team

The byte watchdog (CLAUDE_ENABLE_BYTE_WATCHDOG, default-on for the Anthropic API per docs) did not fire in my baseline run despite 360+ seconds of no real events arriving. The most plausible cause: the Anthropic API emits SSE keepalive comment lines (: keepalive\n\n) periodically, those bytes count as on-the-wire activity, and the byte watchdog can't distinguish them from real progress.

If that's correct, two options worth considering:

  • Skip SSE comment lines (: prefix) when counting bytes-seen for the byte watchdog, OR
  • Default the event-level watchdog to on for Anthropic API connections so users don't have to know about this distinction

This is the failure mode in the original issue — bytes flow forever, events never arrive, and the byte watchdog's "default-on for Anthropic API" promise doesn't help.

Standalone repro

Two ~100-line scripts. aiohttp + claude-agent-sdk only.

wedge_server.py:

"""Fake Anthropic API that wedges mid-stream after one delta.

Emits message_start + one content_block_delta, then switches to
keepalive-comment-only mode (`: keepalive\n\n` every 15s). No real events,
no message_stop. Defeats the byte-level idle watchdog (bytes flow) but
should be caught by the event-level watchdog (no events).

Run: python wedge_server.py
"""
import asyncio, json, os, time
from aiohttp import web

KEEPALIVE_INTERVAL_S = int(os.environ.get("WEDGE_KEEPALIVE_INTERVAL_S", "15"))
WEDGE_DURATION_S = int(os.environ.get("WEDGE_DURATION_S", "1200"))


def ts() -> str:
    return time.strftime("%H:%M:%S")


async def handle_messages(request: web.Request):
    body = await request.json()
    print(f"[server {ts()}] POST /v1/messages model={body.get('model')!r} stream={body.get('stream')}", flush=True)

    resp = web.StreamResponse(
        status=200,
        headers={
            "Content-Type": "text/event-stream",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "anthropic-request-id": "req_wedge_test",
        },
    )
    await resp.prepare(request)

    msg_id = "msg_wedge_test"
    model = body.get("model", "claude-sonnet-4-6")

    async def send(event: str, data: dict):
        await resp.write(f"event: {event}\ndata: {json.dumps(data)}\n\n".encode())

    await send("message_start", {
        "type": "message_start",
        "message": {
            "id": msg_id, "type": "message", "role": "assistant", "content": [],
            "model": model, "stop_reason": None, "stop_sequence": None,
            "usage": {"input_tokens": 10, "cache_creation_input_tokens": 0,
                      "cache_read_input_tokens": 0, "output_tokens": 0},
        },
    })
    await send("content_block_start", {
        "type": "content_block_start", "index": 0,
        "content_block": {"type": "text", "text": ""},
    })
    await send("content_block_delta", {
        "type": "content_block_delta", "index": 0,
        "delta": {"type": "text_delta", "text": "wedge"},
    })

    print(f"[server {ts()}] sent first delta, switching to keepalive-only mode", flush=True)

    start = time.monotonic()
    n = 0
    try:
        while time.monotonic() - start < WEDGE_DURATION_S:
            await asyncio.sleep(KEEPALIVE_INTERVAL_S)
            await resp.write(b": keepalive\n\n")
            n += 1
            print(f"[server {ts()}] keepalive #{n} (t+{time.monotonic()-start:.0f}s)", flush=True)
    except (asyncio.CancelledError, ConnectionResetError, ConnectionError) as e:
        print(f"[server {ts()}] client disconnected after {n} keepalives "
              f"(t+{time.monotonic()-start:.0f}s): {type(e).__name__}", flush=True)
        return resp

    return resp


def main():
    app = web.Application()
    app.router.add_post("/v1/messages", handle_messages)
    print(f"[server {ts()}] starting on http://127.0.0.1:8888", flush=True)
    web.run_app(app, host="127.0.0.1", port=8888, print=None)


if __name__ == "__main__":
    main()

wedge_client.py:

"""Run claude-agent-sdk against the fake wedge server.

Run: python wedge_client.py [on|off] [max_wait_seconds]
  on  = set CLAUDE_ENABLE_STREAM_WATCHDOG=1 + CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK=1
  off = baseline (no watchdog flags)
"""
import asyncio, sys, time
from claude_agent_sdk import query, ClaudeAgentOptions

WATCHDOG = sys.argv[1] if len(sys.argv) > 1 else "off"
MAX_WAIT_S = int(sys.argv[2]) if len(sys.argv) > 2 else 420


def ts() -> str:
    return time.strftime("%H:%M:%S")


async def main():
    env = {
        "ANTHROPIC_BASE_URL": "http://127.0.0.1:8888",
        "ANTHROPIC_API_KEY": "sk-test-fake-wedge-key",
        "CLAUDE_CODE_MAX_RETRIES": "0",
        "DISABLE_TELEMETRY": "1",
        "DISABLE_AUTOUPDATER": "1",
        "DISABLE_ERROR_REPORTING": "1",
        "CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL": "1",
    }
    if WATCHDOG == "on":
        env["CLAUDE_ENABLE_STREAM_WATCHDOG"] = "1"
        env["CLAUDE_STREAM_IDLE_TIMEOUT_MS"] = "90000"
        env["CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK"] = "1"

    print(f"[client {ts()}] watchdog={WATCHDOG}", flush=True)

    opts = ClaudeAgentOptions(env=env, model="claude-sonnet-4-6", max_turns=1)

    start = time.monotonic()
    n = 0
    try:
        async with asyncio.timeout(MAX_WAIT_S):
            async for msg in query(prompt="say wedge", options=opts):
                n += 1
                elapsed = time.monotonic() - start
                print(f"[client {ts()}] t+{elapsed:6.1f}s msg#{n} "
                      f"{type(msg).__name__}: {repr(msg)[:300]}", flush=True)
    except asyncio.TimeoutError:
        elapsed = time.monotonic() - start
        print(f"[client {ts()}] t+{elapsed:6.1f}s HARD-TIMEOUT after {MAX_WAIT_S}s "
              f"(client cap, not SDK) — got {n} messages", flush=True)
    except Exception as e:
        elapsed = time.monotonic() - start
        print(f"[client {ts()}] t+{elapsed:6.1f}s EXCEPTION {type(e).__name__}: {e}", flush=True)


if __name__ == "__main__":
    asyncio.run(main())

Three-run results

Config Result
baseline (no watchdog flags) Hung 360s+ silently. Client got only 3 init SystemMessages; never any AssistantMessage or ResultMessage. Byte watchdog never fired.
CLAUDE_ENABLE_STREAM_WATCHDOG=1 only Streaming watchdog fired at t+90s, but SDK silently retried via non-streaming, which re-wedged. Net: still hung at 420s cap.
Both flags + pinned timeout Clean abort at t+90.034s with ResultMessage(is_error=True, duration_ms=90034) carrying synthetic error message. CLI exits cleanly.

Hope this saves the next person a few hours of binary-grepping. Happy to share more detail or run additional probes if useful.

oneryalcin avatar May 06 '26 13:05 oneryalcin