Repository navigation
fix(claude-code): wait for background work as long as the turn can spare #1000
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
fe2ed3e
b7df0cb
5dba098
3d9c5f5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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,13 +233,23 @@ 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" | ||
| env.update(egress_env(environ, [env.get("ANTHROPIC_BASE_URL", ""), *mcp_urls], armed=clock_armed)) | ||
| 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) | ||
|
Comment on lines
+404
to
+410
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Prompt To Fix With AIThis is a comment left during a code review.
Path: src/agent_env/agents/agents/claude-code/claude_bridge.py
Line: 404-410
Comment:
**Unfinished messages count as answers**
`_last_answer` treats a message as finished as soon as it has text and no tool call yet. But the CLI sends text and tool calls in separate events with the same message ID. If the deadline lands between those events, this returns narration such as “Launching a helper” as a successful answer, even when no answer was completed. Check that the message finished before using it, and keep the timeout failure when none did.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly. |
||
|
|
||
|
|
||
| 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) | ||
|
Comment on lines
+1112
to
+1116
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The timeout fallback also runs when Prompt To Fix With AIThis is a comment left during a code review.
Path: src/agent_env/agents/agents/claude-code/claude_bridge.py
Line: 1112-1116
Comment:
**JSON requests return plain text**
The timeout fallback also runs when `output_format` requests a JSON Schema. If background work keeps the CLI open before it emits `structured_output`, `_last_answer` can supply plain text instead. The bridge then marks the task successful without the requested JSON answer. Only keep a schema response when `structured_output` is available; otherwise return a timeout failure.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly. |
||
| # 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) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using the whole budget for the background wait leaves no time to return the saved answer to
prompt_agent. The first CLI attempt uses the same timeout as the caller's poll. When helpers are still running, the bridge waits until that limit, then kills the CLI, waits for cleanup, and reads the transcript before completing the task. A poll that still sees the task working at its deadline cancels it and raisesTimeoutError, so the saved answer never reaches the caller. Reserve time for cleanup and delivery before the caller's deadline.Prompt To Fix With AI