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 478922137..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]: @@ -202,11 +205,13 @@ 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 - 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"] @@ -228,6 +233,13 @@ 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") + # 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. 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(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" @@ -235,6 +247,9 @@ def cli_env(environ: Mapping[str, str], *, model: str | None = None, project_id: return env +_PRINT_BG_WAIT_ENV = "CLAUDE_CODE_PRINT_BG_WAIT_CEILING_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. @@ -377,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" @@ -1006,7 +1039,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, )) @@ -1072,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 8206b5d8d..57ce46a7f 100644 --- a/tst/unit/agents/claude_code/test_cli_env.py +++ b/tst/unit/agents/claude_code/test_cli_env.py @@ -54,6 +54,23 @@ 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_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(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(): + env = claude_bridge.cli_env({**GATEWAY, "CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS": "1000"}, turn_budget_s=1800) + + 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", [ ("fireworks_ai/glm-5p3-flash", "1"), ("claude-sonnet-5-5", None), @@ -201,3 +218,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_waits_for_background_work_as_its_attempts_budget_allows(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["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,