From fe2ed3e80ebc94c5139c428b5594cab0967bce6c Mon Sep 17 00:00:00 2001 From: t Date: Thu, 3 Dec 2026 16:26:13 -0500 Subject: [PATCH 1/4] fix(claude-code): keep subagents and shells inside the turn The CLI backgrounds subagents and shells by default and tells the model to answer meanwhile. In a -p run the turn then ends with them still working, and the CLI kills them 600 s later, so their writes and reports are lost. Set CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 unless the run sets it, so an Agent or Bash call returns only when its work is done. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/agents/claude-code/claude_bridge.py | 5 +++++ tst/unit/agents/claude_code/test_cli_env.py | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/src/agent_env/agents/agents/claude-code/claude_bridge.py b/src/agent_env/agents/agents/claude-code/claude_bridge.py index 478922137..9121d5597 100644 --- a/src/agent_env/agents/agents/claude-code/claude_bridge.py +++ b/src/agent_env/agents/agents/claude-code/claude_bridge.py @@ -228,6 +228,11 @@ def cli_env(environ: Mapping[str, str], *, model: str | None = None, project_id: env["MAX_THINKING_TOKENS"] = str(max_thinking_tokens) # Left on, the CLI sends no MCP tool and only some of its own until the model searches for them. env.setdefault("ENABLE_TOOL_SEARCH", "false") + # Left on, the CLI runs subagents and shells in the background and tells the model to answer meanwhile; a `-p` + # run then ends its turn with them still working, and kills them 600 s later, so their writes and reports are + # lost. Off, an Agent or Bash call returns only when its work is done, even when the model asks for the + # background. + env.setdefault("CLAUDE_CODE_DISABLE_BACKGROUND_TASKS", "1") # Older CLIs prepend a changing attribution block to the system prompt on custom base URLs, which defeats the # provider's prefix cache. env["CLAUDE_CODE_ATTRIBUTION_HEADER"] = "0" diff --git a/tst/unit/agents/claude_code/test_cli_env.py b/tst/unit/agents/claude_code/test_cli_env.py index 8206b5d8d..dce25cb4b 100644 --- a/tst/unit/agents/claude_code/test_cli_env.py +++ b/tst/unit/agents/claude_code/test_cli_env.py @@ -54,6 +54,12 @@ def test_the_cli_offers_its_tools_up_front_unless_tool_search_is_asked_for(): assert claude_bridge.cli_env({**GATEWAY, "ENABLE_TOOL_SEARCH": "auto"})["ENABLE_TOOL_SEARCH"] == "auto" +def test_subagents_and_shells_finish_inside_the_turn_unless_background_tasks_are_asked_for(): + assert claude_bridge.cli_env(GATEWAY)["CLAUDE_CODE_DISABLE_BACKGROUND_TASKS"] == "1" + assert claude_bridge.cli_env({**GATEWAY, "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS": "0"})[ + "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS"] == "0" + + @pytest.mark.parametrize("model, disabled", [ ("fireworks_ai/glm-5p3-flash", "1"), ("claude-sonnet-5-5", None), From b7df0cba2a21a67a4c44deea27efb8ab9ed16918 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 3 Dec 2026 18:35:31 -0500 Subject: [PATCH 2/4] fix(claude-code): let a foreground Bash call use what the turn can spare With background tasks off, a Bash call runs in the foreground until its timeout, which the CLI caps at 10 min (2 min by default) and no longer moves to the background when it passes, so a long build or test suite was killed though the turn had time for it. Raise BASH_MAX_TIMEOUT_MS to the attempt's budget less 2 min of headroom, and give a call without a timeout the old 10-min cap, so one hung command can't hold the turn to its deadline. Values already set are kept, and nothing changes with background tasks on. Co-Authored-By: Claude Opus 5.5 --- .../agents/claude-code/claude_bridge.py | 29 ++++++++++-- tst/unit/agents/claude_code/test_cli_env.py | 44 +++++++++++++++++++ 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/src/agent_env/agents/agents/claude-code/claude_bridge.py b/src/agent_env/agents/agents/claude-code/claude_bridge.py index 9121d5597..ae08eb69d 100644 --- a/src/agent_env/agents/agents/claude-code/claude_bridge.py +++ b/src/agent_env/agents/agents/claude-code/claude_bridge.py @@ -202,10 +202,12 @@ def _api_root(url: str) -> str: def cli_env(environ: Mapping[str, str], *, model: str | None = None, project_id: str | None = None, task_id: str | None = None, max_thinking_tokens: int | None = None, - clock_armed: bool = False, mcp_urls: Iterable[str] = ()) -> dict[str, str]: + clock_armed: bool = False, mcp_urls: Iterable[str] = (), + turn_budget_s: int | None = None) -> dict[str, str]: """The CLI's environment: this process's, pointed at the endpoint agent-env configured (its key as a bearer token, so an API key too would conflict), with the endpoint's headers and the run's attribution, and the model's - aliases pinned to ``model`` on that endpoint. A variable already set is kept, LITELLM_* too, so a script the model + aliases pinned to ``model`` on that endpoint, and with background tasks off, a Bash call allowed as much of + ``turn_budget_s`` as the turn can spare. A variable already set is kept, LITELLM_* too, so a script the model runs can call the endpoint.""" env = dict(environ) if not env.get("ANTHROPIC_AUTH_TOKEN") and env.get("LITELLM_API_KEY"): @@ -233,6 +235,8 @@ def cli_env(environ: Mapping[str, str], *, model: str | None = None, project_id: # lost. Off, an Agent or Bash call returns only when its work is done, even when the model asks for the # background. env.setdefault("CLAUDE_CODE_DISABLE_BACKGROUND_TASKS", "1") + if turn_budget_s and env["CLAUDE_CODE_DISABLE_BACKGROUND_TASKS"].strip().lower() not in ("", "0", "false"): + env.update(_bash_timeouts(env, turn_budget_s)) # Older CLIs prepend a changing attribution block to the system prompt on custom base URLs, which defeats the # provider's prefix cache. env["CLAUDE_CODE_ATTRIBUTION_HEADER"] = "0" @@ -240,6 +244,25 @@ def cli_env(environ: Mapping[str, str], *, model: str | None = None, project_id: return env +# The CLI's own Bash limits: a call gets 2 min unless the model asks for more, and at most 10 min. +_CLI_BASH_MAX_TIMEOUT_MS = 600_000 +# What the turn keeps once a Bash call that may use the rest has timed out: time for the model to read the timeout and +# answer before agent-env's deadline. +_BASH_TURN_HEADROOM_S = 120 + + +def _bash_timeouts(env: Mapping[str, str], turn_budget_s: int) -> dict[str, str]: + """With background tasks off a Bash call runs in the foreground until its timeout, which the CLI caps at 10 min + and, unlike with them on, doesn't move to the background when it passes: so a long build or test suite would be + killed though the turn has time for it. The cap becomes what the turn can spare, and a call the model gives no + timeout gets the old cap, so one command left hanging can't hold the turn to its deadline. Values already set are + kept.""" + max_ms = max(_CLI_BASH_MAX_TIMEOUT_MS, (turn_budget_s - _BASH_TURN_HEADROOM_S) * 1000) + max_ms = int(env.get("BASH_MAX_TIMEOUT_MS") or max_ms) + default_ms = env.get("BASH_DEFAULT_TIMEOUT_MS") or str(min(_CLI_BASH_MAX_TIMEOUT_MS, max_ms)) + return {"BASH_MAX_TIMEOUT_MS": str(max_ms), "BASH_DEFAULT_TIMEOUT_MS": default_ms} + + _DEFAULT_API_ERROR_RETRIES = 2 _MIN_RETRY_BUDGET_S = 120 # agent-env polls with the timeout it posts, so a resume that spent the budget to zero would leave it no answer. @@ -1011,7 +1034,7 @@ async def _spawn_claude( stderr=asyncio.subprocess.PIPE, env=cli_env(os.environ, model=model, project_id=project_id, task_id=task_id, max_thinking_tokens=max_thinking_tokens, clock_armed=clock_armed(), - mcp_urls=[info["url"] for info in (mcp_servers or {}).values()]), + mcp_urls=[info["url"] for info in (mcp_servers or {}).values()], turn_budget_s=timeout_s), cwd=WORKSPACE_DIR, start_new_session=True, )) diff --git a/tst/unit/agents/claude_code/test_cli_env.py b/tst/unit/agents/claude_code/test_cli_env.py index dce25cb4b..e8bfa41ca 100644 --- a/tst/unit/agents/claude_code/test_cli_env.py +++ b/tst/unit/agents/claude_code/test_cli_env.py @@ -60,6 +60,34 @@ def test_subagents_and_shells_finish_inside_the_turn_unless_background_tasks_are "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS"] == "0" +def test_a_foreground_bash_call_may_use_what_the_turn_can_spare_and_one_without_a_timeout_gets_ten_minutes(): + env = claude_bridge.cli_env(GATEWAY, turn_budget_s=1800) + + assert (env["BASH_MAX_TIMEOUT_MS"], env["BASH_DEFAULT_TIMEOUT_MS"]) == (str((1800 - 120) * 1000), "600000") + + +def test_a_short_turn_keeps_the_clis_own_bash_cap(): + env = claude_bridge.cli_env(GATEWAY, turn_budget_s=300) + + assert (env["BASH_MAX_TIMEOUT_MS"], env["BASH_DEFAULT_TIMEOUT_MS"]) == ("600000", "600000") + + +def test_bash_timeouts_already_set_are_kept_and_the_default_never_passes_the_cap(): + env = claude_bridge.cli_env({**GATEWAY, "BASH_MAX_TIMEOUT_MS": "300000"}, turn_budget_s=1800) + assert (env["BASH_MAX_TIMEOUT_MS"], env["BASH_DEFAULT_TIMEOUT_MS"]) == ("300000", "300000") + + env = claude_bridge.cli_env({**GATEWAY, "BASH_DEFAULT_TIMEOUT_MS": "60000"}, turn_budget_s=1800) + assert env["BASH_DEFAULT_TIMEOUT_MS"] == "60000" + + +@pytest.mark.parametrize("environ", [{}, {"CLAUDE_CODE_DISABLE_BACKGROUND_TASKS": "0"}]) +def test_bash_keeps_the_clis_timeouts_with_no_turn_budget_or_with_background_tasks_on(environ): + budget = None if not environ else 1800 + env = claude_bridge.cli_env({**GATEWAY, **environ}, turn_budget_s=budget) + + assert "BASH_MAX_TIMEOUT_MS" not in env and "BASH_DEFAULT_TIMEOUT_MS" not in env + + @pytest.mark.parametrize("model, disabled", [ ("fireworks_ai/glm-5p3-flash", "1"), ("claude-sonnet-5-5", None), @@ -207,3 +235,19 @@ def test_the_cli_runs_in_the_workspace(spawned, monkeypatch, tmp_path): asyncio.run(claude_bridge.run_claude(prompt="p", session_id="s", resume=False, web_tools=True)) assert spawned["cwd"] == tmp_path / "repo" and (tmp_path / "repo").is_dir() + + +def test_a_spawned_cli_gets_bash_timeouts_from_its_attempts_budget(monkeypatch, tmp_path): + spawned = {} + + async def fake_exec(*cmd, env, **_): + spawned.update(env) + raise RuntimeError("not starting the CLI") + + monkeypatch.setattr(claude_bridge.asyncio, "create_subprocess_exec", fake_exec) + monkeypatch.setattr(claude_bridge.os, "environ", dict(GATEWAY)) + monkeypatch.setattr(claude_bridge, "WORKSPACE_DIR", tmp_path) + with pytest.raises(RuntimeError, match="not starting the CLI"): + asyncio.run(claude_bridge._spawn_claude("hi", "s", False, timeout_s=3600, web_tools=True)) + + assert spawned["BASH_MAX_TIMEOUT_MS"] == str((3600 - 120) * 1000) From 5dba0981e796f83899b5a9e68e6013b4b4ba3e46 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 4 Dec 2026 12:43:46 -0500 Subject: [PATCH 3/4] fix(claude-code): wait for background work as long as the turn can spare, instead of turning it off Turning background tasks off kept subagents and shells inside the turn, but it took away the parallel work the CLI does on its own: the model could no longer run helpers and work while they ran. The kill that lost their work is the CLI's `-p` wait for background work after the turn ends, 10 min by default. Set it to the turn's budget less 120 s, so the CLI keeps waiting and wakes the model as each helper finishes; background tasks and the CLI's Bash timeouts stay as they are. Co-Authored-By: Claude Opus 5.5 --- .../agents/claude-code/claude_bridge.py | 43 ++++++++----------- tst/unit/agents/claude_code/test_cli_env.py | 38 +++++----------- 2 files changed, 29 insertions(+), 52 deletions(-) diff --git a/src/agent_env/agents/agents/claude-code/claude_bridge.py b/src/agent_env/agents/agents/claude-code/claude_bridge.py index ae08eb69d..2ffbde8a7 100644 --- a/src/agent_env/agents/agents/claude-code/claude_bridge.py +++ b/src/agent_env/agents/agents/claude-code/claude_bridge.py @@ -206,9 +206,9 @@ def cli_env(environ: Mapping[str, str], *, model: str | None = None, project_id: turn_budget_s: int | None = None) -> dict[str, str]: """The CLI's environment: this process's, pointed at the endpoint agent-env configured (its key as a bearer token, so an API key too would conflict), with the endpoint's headers and the run's attribution, and the model's - aliases pinned to ``model`` on that endpoint, and with background tasks off, a Bash call allowed as much of - ``turn_budget_s`` as the turn can spare. A variable already set is kept, LITELLM_* too, so a script the model - runs can call the endpoint.""" + aliases pinned to ``model`` on that endpoint, and with the subagents and shells the model runs in the background + allowed as much of ``turn_budget_s`` as the turn can spare. A variable already set is kept, LITELLM_* too, so a + script the model runs can call the endpoint.""" env = dict(environ) if not env.get("ANTHROPIC_AUTH_TOKEN") and env.get("LITELLM_API_KEY"): env["ANTHROPIC_AUTH_TOKEN"] = env["LITELLM_API_KEY"] @@ -230,13 +230,11 @@ def cli_env(environ: Mapping[str, str], *, model: str | None = None, project_id: env["MAX_THINKING_TOKENS"] = str(max_thinking_tokens) # Left on, the CLI sends no MCP tool and only some of its own until the model searches for them. env.setdefault("ENABLE_TOOL_SEARCH", "false") - # Left on, the CLI runs subagents and shells in the background and tells the model to answer meanwhile; a `-p` - # run then ends its turn with them still working, and kills them 600 s later, so their writes and reports are - # lost. Off, an Agent or Bash call returns only when its work is done, even when the model asks for the - # background. - env.setdefault("CLAUDE_CODE_DISABLE_BACKGROUND_TASKS", "1") - if turn_budget_s and env["CLAUDE_CODE_DISABLE_BACKGROUND_TASKS"].strip().lower() not in ("", "0", "false"): - env.update(_bash_timeouts(env, turn_budget_s)) + # The CLI runs subagents and shells in the background when the model asks, and the model may end its turn while + # they work. With stdin closed, a `-p` run then waits for them, waking the model as each finishes, but only for + # 10 min after it first goes idle; then it kills them, so their writes and reports are lost. + if turn_budget_s: + env.setdefault(_PRINT_BG_WAIT_ENV, str(_background_wait_ms(turn_budget_s))) # Older CLIs prepend a changing attribution block to the system prompt on custom base URLs, which defeats the # provider's prefix cache. env["CLAUDE_CODE_ATTRIBUTION_HEADER"] = "0" @@ -244,23 +242,18 @@ def cli_env(environ: Mapping[str, str], *, model: str | None = None, project_id: return env -# The CLI's own Bash limits: a call gets 2 min unless the model asks for more, and at most 10 min. -_CLI_BASH_MAX_TIMEOUT_MS = 600_000 -# What the turn keeps once a Bash call that may use the rest has timed out: time for the model to read the timeout and -# answer before agent-env's deadline. -_BASH_TURN_HEADROOM_S = 120 +_PRINT_BG_WAIT_ENV = "CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS" +# The CLI's own wait for background work after a `-p` turn ends. +_CLI_PRINT_BG_WAIT_MS = 600_000 +# What the turn keeps once the wait ends: time for the model to read what the background work left and answer before +# agent-env's deadline. +_BACKGROUND_TURN_HEADROOM_S = 120 -def _bash_timeouts(env: Mapping[str, str], turn_budget_s: int) -> dict[str, str]: - """With background tasks off a Bash call runs in the foreground until its timeout, which the CLI caps at 10 min - and, unlike with them on, doesn't move to the background when it passes: so a long build or test suite would be - killed though the turn has time for it. The cap becomes what the turn can spare, and a call the model gives no - timeout gets the old cap, so one command left hanging can't hold the turn to its deadline. Values already set are - kept.""" - max_ms = max(_CLI_BASH_MAX_TIMEOUT_MS, (turn_budget_s - _BASH_TURN_HEADROOM_S) * 1000) - max_ms = int(env.get("BASH_MAX_TIMEOUT_MS") or max_ms) - default_ms = env.get("BASH_DEFAULT_TIMEOUT_MS") or str(min(_CLI_BASH_MAX_TIMEOUT_MS, max_ms)) - return {"BASH_MAX_TIMEOUT_MS": str(max_ms), "BASH_DEFAULT_TIMEOUT_MS": default_ms} +def _background_wait_ms(turn_budget_s: int) -> int: + """How long a `-p` run waits for its background work: what the turn can spare, and never less than the CLI's own + wait.""" + return max(_CLI_PRINT_BG_WAIT_MS, (turn_budget_s - _BACKGROUND_TURN_HEADROOM_S) * 1000) _DEFAULT_API_ERROR_RETRIES = 2 diff --git a/tst/unit/agents/claude_code/test_cli_env.py b/tst/unit/agents/claude_code/test_cli_env.py index e8bfa41ca..08ea0d304 100644 --- a/tst/unit/agents/claude_code/test_cli_env.py +++ b/tst/unit/agents/claude_code/test_cli_env.py @@ -54,38 +54,22 @@ def test_the_cli_offers_its_tools_up_front_unless_tool_search_is_asked_for(): assert claude_bridge.cli_env({**GATEWAY, "ENABLE_TOOL_SEARCH": "auto"})["ENABLE_TOOL_SEARCH"] == "auto" -def test_subagents_and_shells_finish_inside_the_turn_unless_background_tasks_are_asked_for(): - assert claude_bridge.cli_env(GATEWAY)["CLAUDE_CODE_DISABLE_BACKGROUND_TASKS"] == "1" - assert claude_bridge.cli_env({**GATEWAY, "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS": "0"})[ - "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS"] == "0" - - -def test_a_foreground_bash_call_may_use_what_the_turn_can_spare_and_one_without_a_timeout_gets_ten_minutes(): +def test_background_work_may_use_what_the_turn_can_spare_after_the_model_answers(): env = claude_bridge.cli_env(GATEWAY, turn_budget_s=1800) - assert (env["BASH_MAX_TIMEOUT_MS"], env["BASH_DEFAULT_TIMEOUT_MS"]) == (str((1800 - 120) * 1000), "600000") - - -def test_a_short_turn_keeps_the_clis_own_bash_cap(): - env = claude_bridge.cli_env(GATEWAY, turn_budget_s=300) - - assert (env["BASH_MAX_TIMEOUT_MS"], env["BASH_DEFAULT_TIMEOUT_MS"]) == ("600000", "600000") - + assert env["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == str((1800 - 120) * 1000) + assert "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS" not in env -def test_bash_timeouts_already_set_are_kept_and_the_default_never_passes_the_cap(): - env = claude_bridge.cli_env({**GATEWAY, "BASH_MAX_TIMEOUT_MS": "300000"}, turn_budget_s=1800) - assert (env["BASH_MAX_TIMEOUT_MS"], env["BASH_DEFAULT_TIMEOUT_MS"]) == ("300000", "300000") - env = claude_bridge.cli_env({**GATEWAY, "BASH_DEFAULT_TIMEOUT_MS": "60000"}, turn_budget_s=1800) - assert env["BASH_DEFAULT_TIMEOUT_MS"] == "60000" +def test_a_short_turn_keeps_the_clis_own_wait_for_background_work(): + assert claude_bridge.cli_env(GATEWAY, turn_budget_s=300)["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == "600000" -@pytest.mark.parametrize("environ", [{}, {"CLAUDE_CODE_DISABLE_BACKGROUND_TASKS": "0"}]) -def test_bash_keeps_the_clis_timeouts_with_no_turn_budget_or_with_background_tasks_on(environ): - budget = None if not environ else 1800 - env = claude_bridge.cli_env({**GATEWAY, **environ}, turn_budget_s=budget) +def test_a_wait_already_set_is_kept_and_none_is_set_without_a_turn_budget(): + env = claude_bridge.cli_env({**GATEWAY, "CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS": "1000"}, turn_budget_s=1800) - assert "BASH_MAX_TIMEOUT_MS" not in env and "BASH_DEFAULT_TIMEOUT_MS" not in env + assert env["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == "1000" + assert "CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS" not in claude_bridge.cli_env(GATEWAY) @pytest.mark.parametrize("model, disabled", [ @@ -237,7 +221,7 @@ def test_the_cli_runs_in_the_workspace(spawned, monkeypatch, tmp_path): assert spawned["cwd"] == tmp_path / "repo" and (tmp_path / "repo").is_dir() -def test_a_spawned_cli_gets_bash_timeouts_from_its_attempts_budget(monkeypatch, tmp_path): +def test_a_spawned_cli_waits_for_background_work_as_its_attempts_budget_allows(monkeypatch, tmp_path): spawned = {} async def fake_exec(*cmd, env, **_): @@ -250,4 +234,4 @@ async def fake_exec(*cmd, env, **_): with pytest.raises(RuntimeError, match="not starting the CLI"): asyncio.run(claude_bridge._spawn_claude("hi", "s", False, timeout_s=3600, web_tools=True)) - assert spawned["BASH_MAX_TIMEOUT_MS"] == str((3600 - 120) * 1000) + assert spawned["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == str((3600 - 120) * 1000) From 3d9c5f52ddc5427e594b57f48a109d87851139de Mon Sep 17 00:00:00 2001 From: t Date: Fri, 4 Dec 2026 16:04:18 -0500 Subject: [PATCH 4/4] fix(claude-code): keep a turn's answer when its deadline cuts off background work The CLI's wait for background work counts from when the model first goes idle, not from the turn's start, so no wait shorter than the budget is safe from the deadline and none longer is needed: the wait is now the whole budget, without the 2 min headroom or the 10 min floor. The turn's deadline is what ends it, and a `-p` run prints its `result` events only as it exits, so a run cut off there had streamed its answer as an assistant message but no `result`, and the bridge dropped both the answer and the trajectory. Now a run cut off after the model ended a turn returns that turn's text, with what it streamed, as a completed turn that says it was cut off (`cut_at_deadline`). Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/claude-code/a2a_server.py | 2 + .../agents/claude-code/claude_bridge.py | 58 +++++++++++++------ tst/unit/agents/claude_code/test_cli_env.py | 17 +++--- .../claude_code/test_message_contract.py | 11 ++++ tst/unit/agents/claude_code/test_usage.py | 46 ++++++++++++++- 5 files changed, 107 insertions(+), 27 deletions(-) diff --git a/src/agent_env/agents/agents/claude-code/a2a_server.py b/src/agent_env/agents/agents/claude-code/a2a_server.py index 991e305bd..44b6661eb 100644 --- a/src/agent_env/agents/agents/claude-code/a2a_server.py +++ b/src/agent_env/agents/agents/claude-code/a2a_server.py @@ -632,6 +632,8 @@ async def _turn(self, request: TaskRequest[ClaudeCodeConfig], cfg: ClaudeCodeCon data: dict[str, Any] = {"tool_call_count": result.tool_call_count} if result.attempts > 1: data["cli_attempts"] = result.attempts + if result.cut_at_deadline: + data["cut_at_deadline"] = True builder = TaskResult.builder() if result.error: builder.failed("cli_error", result.error[:_ERROR_MESSAGE_LIMIT]) diff --git a/src/agent_env/agents/agents/claude-code/claude_bridge.py b/src/agent_env/agents/agents/claude-code/claude_bridge.py index 2ffbde8a7..ae66aaf45 100644 --- a/src/agent_env/agents/agents/claude-code/claude_bridge.py +++ b/src/agent_env/agents/agents/claude-code/claude_bridge.py @@ -167,6 +167,9 @@ class ClaudeResult: subagent_calls: int = 0 # The model calls of runs that ended without a `result`, by message id: their usage is unknown. unreported_calls: int = 0 + # The turn had answered when its deadline cut off background work it was still waiting for: the answer is its + # last successful `result`, written before that work finished. + cut_at_deadline: bool = False def _attribution_headers(project_id: str | None, task_id: str | None) -> dict[str, str]: @@ -232,9 +235,11 @@ def cli_env(environ: Mapping[str, str], *, model: str | None = None, project_id: env.setdefault("ENABLE_TOOL_SEARCH", "false") # The CLI runs subagents and shells in the background when the model asks, and the model may end its turn while # they work. With stdin closed, a `-p` run then waits for them, waking the model as each finishes, but only for - # 10 min after it first goes idle; then it kills them, so their writes and reports are lost. + # 10 min after it first goes idle; then it kills them, so their writes and reports are lost. Its wait counts from + # that idle moment, so a wait of the whole budget always outlasts the turn: the turn's deadline is what ends it, + # and a turn cut off there keeps the answer it had given. if turn_budget_s: - env.setdefault(_PRINT_BG_WAIT_ENV, str(_background_wait_ms(turn_budget_s))) + env.setdefault(_PRINT_BG_WAIT_ENV, str(turn_budget_s * 1000)) # Older CLIs prepend a changing attribution block to the system prompt on custom base URLs, which defeats the # provider's prefix cache. env["CLAUDE_CODE_ATTRIBUTION_HEADER"] = "0" @@ -243,17 +248,6 @@ def cli_env(environ: Mapping[str, str], *, model: str | None = None, project_id: _PRINT_BG_WAIT_ENV = "CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS" -# The CLI's own wait for background work after a `-p` turn ends. -_CLI_PRINT_BG_WAIT_MS = 600_000 -# What the turn keeps once the wait ends: time for the model to read what the background work left and answer before -# agent-env's deadline. -_BACKGROUND_TURN_HEADROOM_S = 120 - - -def _background_wait_ms(turn_budget_s: int) -> int: - """How long a `-p` run waits for its background work: what the turn can spare, and never less than the CLI's own - wait.""" - return max(_CLI_PRINT_BG_WAIT_MS, (turn_budget_s - _BACKGROUND_TURN_HEADROOM_S) * 1000) _DEFAULT_API_ERROR_RETRIES = 2 @@ -398,6 +392,24 @@ def saved_session_tally(session_id: str) -> dict | None: return tally if tally is not None else (None if called else {}) +def _last_answer(trajectory: list[dict]) -> str | None: + """The text of the main agent's last message that ended a turn: one with text and no tool call. The CLI streams a + message one content block per event, under the message's id, and a turn that goes on to call a tool does so in + the same message.""" + messages: dict[str, tuple[list[str], bool]] = {} + for event in trajectory: + message = event.get("message") or {} + if event.get("type") != "assistant" or event.get("parent_tool_use_id") or not message.get("id"): + continue + texts, called = messages.pop(message["id"], ([], False)) + for block in message.get("content") or []: + if block.get("type") == "text" and block.get("text"): + texts.append(block["text"]) + called = called or block.get("type") == "tool_use" + messages[message["id"]] = (texts, called) # re-inserted, so the dict keeps the order messages last streamed + return next(("\n\n".join(texts) for texts, called in reversed(messages.values()) if texts and not called), None) + + def _ends_in_result(trajectory: list[dict]) -> bool: return bool(trajectory) and trajectory[-1].get("type") == "result" @@ -1093,10 +1105,22 @@ def on_line(line: str) -> None: await _reap(proc) # A CLI that wrote its `result` and then hung keeps the usage it reported. used = _usage_of_run(trajectory) - return ClaudeResult(response="", tool_call_count=tool_count, session_id=session_id, - error=f"claude CLI timed out after {timeout_s}s", run_usage=used.results, - model_usage=used.model_usage, subagent_calls=used.subagent_calls, - unreported_calls=used.unreported_calls) + usage = dict(run_usage=used.results, model_usage=used.model_usage, subagent_calls=used.subagent_calls, + unreported_calls=used.unreported_calls) + # A `-p` run prints its `result` events only as it exits, so one still waiting on background work has none: + # its answer is the last turn the model ended. + answer = json.dumps(structured_output) if structured_output is not None else ( + final_response if final_response is not None else _last_answer(trajectory)) + if answer is None: + return ClaudeResult(response="", tool_call_count=tool_count, session_id=session_id, + error=f"claude CLI timed out after {timeout_s}s", **usage) + # The model had answered and the CLI was waiting on background work, or the model was working on what that + # work had reported: the answer it gave stands. + logger.warning(f"claude CLI turn reached its {timeout_s}s deadline after answering; keeping its last answer") + response = answer + return ClaudeResult(response=response or "", tool_call_count=tool_count, + session_id=cli_session_id or session_id, trajectory=trajectory, + structured_output=structured_output, cut_at_deadline=True, **usage) except Exception: # Reading failed, as when an event_callback raises: the CLI mustn't keep running. _kill_cli(proc) diff --git a/tst/unit/agents/claude_code/test_cli_env.py b/tst/unit/agents/claude_code/test_cli_env.py index 08ea0d304..57ce46a7f 100644 --- a/tst/unit/agents/claude_code/test_cli_env.py +++ b/tst/unit/agents/claude_code/test_cli_env.py @@ -54,15 +54,14 @@ def test_the_cli_offers_its_tools_up_front_unless_tool_search_is_asked_for(): assert claude_bridge.cli_env({**GATEWAY, "ENABLE_TOOL_SEARCH": "auto"})["ENABLE_TOOL_SEARCH"] == "auto" -def test_background_work_may_use_what_the_turn_can_spare_after_the_model_answers(): - env = claude_bridge.cli_env(GATEWAY, turn_budget_s=1800) +def test_background_work_may_use_the_whole_turn_after_the_model_answers(): + """The CLI's wait counts from when the model first goes idle, so the turn's budget always outlasts the turn; a + short turn gets less than the CLI's own 10 min, which it couldn't use.""" + for budget in (1800, 300): + env = claude_bridge.cli_env(GATEWAY, turn_budget_s=budget) - assert env["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == str((1800 - 120) * 1000) - assert "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS" not in env - - -def test_a_short_turn_keeps_the_clis_own_wait_for_background_work(): - assert claude_bridge.cli_env(GATEWAY, turn_budget_s=300)["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == "600000" + assert env["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == str(budget * 1000) + assert "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS" not in env def test_a_wait_already_set_is_kept_and_none_is_set_without_a_turn_budget(): @@ -234,4 +233,4 @@ async def fake_exec(*cmd, env, **_): with pytest.raises(RuntimeError, match="not starting the CLI"): asyncio.run(claude_bridge._spawn_claude("hi", "s", False, timeout_s=3600, web_tools=True)) - assert spawned["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == str((3600 - 120) * 1000) + assert spawned["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == "3600000" diff --git a/tst/unit/agents/claude_code/test_message_contract.py b/tst/unit/agents/claude_code/test_message_contract.py index d978096af..8f70b6720 100644 --- a/tst/unit/agents/claude_code/test_message_contract.py +++ b/tst/unit/agents/claude_code/test_message_contract.py @@ -65,6 +65,17 @@ def test_a_resumed_turn_reports_its_attempts(calls, client): assert data == [{"tool_call_count": 1, "cli_attempts": 3}, {"usage": {"tool_call_count": 1}}] +def test_a_turn_cut_off_at_its_deadline_after_answering_completes_and_says_so(calls, client): + calls.result_for = lambda kwargs: claude_bridge.ClaudeResult( + response="done", tool_call_count=1, session_id=kwargs["session_id"], cut_at_deadline=True, + ) + + state, text, data = terminal(send(client, "hello")) + + assert (state, text) == ("completed", "done") + assert data == [{"tool_call_count": 1, "cut_at_deadline": True}, {"usage": {"tool_call_count": 1}}] + + def test_a_cli_error_is_a_failed_task_with_the_capped_message(calls, client): error = "claude CLI exited 1: " + "x" * 2000 calls.result_for = lambda kwargs: claude_bridge.ClaudeResult( diff --git a/tst/unit/agents/claude_code/test_usage.py b/tst/unit/agents/claude_code/test_usage.py index d78359379..2f1d0a815 100644 --- a/tst/unit/agents/claude_code/test_usage.py +++ b/tst/unit/agents/claude_code/test_usage.py @@ -261,10 +261,54 @@ async def hung(*cmd, printed=printed, **kwargs): timeout_s=0.2, web_tools=True))) after, before = results - assert after.error and (after.run_usage, after.model_usage, after.unreported_calls) == (RESULTS_2, TALLY_2, 0) + assert (after.run_usage, after.model_usage, after.unreported_calls) == (RESULTS_2, TALLY_2, 0) assert before.error and (before.run_usage, before.unreported_calls) == ([], 1) +def _said(message_id, *blocks, parent=None): + return _event(type="assistant", parent_tool_use_id=parent, session_id="s", + message={"id": message_id, "content": list(blocks)}) + + +def test_a_turn_cut_off_at_its_deadline_after_answering_keeps_its_answer_and_trajectory(monkeypatch): + """A `-p` run prints its `result` events only as it exits, so a run still waiting on background work, or working + on what that work reported, has none when the deadline comes: the answer is the last turn the model ended, and + what it streamed is kept.""" + text = lambda t: {"type": "text", "text": t} # noqa: E731 + call = {"type": "tool_use", "id": "t1", "name": "Agent", "input": {}} + printed = (_event(type="system", subtype="init", session_id="s") + + _said("m1", text("Launching a helper.")) + _said("m1", call) + + _said("m2", text("LAUNCHED")) + + _said("h1", text("helper narration"), parent="t1") + + _event(type="system", subtype="task_notification", status="completed", session_id="s") + + _said("m3", text("The helper reported.")) + _said("m3", call)).encode() + + async def hung(*cmd, **kwargs): + return FakeCLI(printed, 0, hang=True) + + monkeypatch.setattr(asyncio, "create_subprocess_exec", hung) + result = asyncio.run(claude_bridge.run_claude(prompt="p", session_id="s", resume=False, timeout_s=1, + web_tools=True)) + + assert result.error is None and result.cut_at_deadline + assert result.response == "LAUNCHED" + assert len(result.trajectory) == 8 and result.run_usage == [] + + +def test_a_turn_cut_off_before_it_answered_is_still_a_timeout(monkeypatch): + printed = (_event(type="system", subtype="init", session_id="s") + + _said("m1", {"type": "tool_use", "id": "t1", "name": "Bash", "input": {}})).encode() + + async def hung(*cmd, **kwargs): + return FakeCLI(printed, 0, hang=True) + + monkeypatch.setattr(asyncio, "create_subprocess_exec", hung) + result = asyncio.run(claude_bridge.run_claude(prompt="p", session_id="s", resume=False, timeout_s=1, + web_tools=True)) + + assert result.error and "timed out" in result.error and not result.cut_at_deadline and result.response == "" + + def test_the_atif_turn_record_counts_the_turn_apart_from_its_cache_and_not_at_all_when_its_a_lower_bound(): """What the atif/1 adapter gives a compaction's step from: the turn's counts as a session record counts a call's.""" counted = Usage(input_tokens=1000, output_tokens=50, cache_read_tokens=600, cache_write_tokens=100,