From a16ecd4aeffa6931e06e1b2dcb8eaa623e1cdc07 Mon Sep 17 00:00:00 2001 From: mtrager Date: Mon, 23 Nov 2026 11:41:59 -0500 Subject: [PATCH 1/2] Version 0.2.0; with a timeout Claude Code waits for background tasks; an unavailable cost says why - Version 0.2.0 (pyproject.toml, __init__.py, the README's citation): recorded in every segment log, which still said 0.1.1. - With agent.timeout, CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=0 (unless set): claude -p otherwise stops background tasks 10 minutes after its last turn. - When no cost is known and the calls give one reason, the end says it ("cost unavailable: set agent.model ..." for Codex, whose output names no model, checked on a real Codex 0.171). - CLAUDE.md: the setup installs the examples extra (as CI); the Codex model note. --- CHANGELOG.md | 6 ++++ CLAUDE.md | 4 +-- README.md | 2 +- docs/concepts.md | 4 ++- docs/config.md | 5 +++- pyproject.toml | 2 +- src/autohelix/__init__.py | 2 +- src/autohelix/agents/claudecode.py | 4 +++ src/autohelix/agents/codex.py | 2 +- src/autohelix/formatting.py | 8 ++++-- tests/test_agents.py | 46 ++++++++++++++++++++++++++++++ tests/test_formatting.py | 9 ++++++ 12 files changed, 84 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 989d4a25..820dc923 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -172,6 +172,12 @@ has the checklist. ### Fixed +- With `agent.timeout`, Claude Code waits for the agent's background tasks + instead of stopping them 10 minutes after its last turn (the timeout still + ends the call). +- When no cost is known for a run and its calls give one reason, the end says + it (`cost unavailable: set agent.model ...` for Codex, whose output names no + model). - An OpenCode `error` event (an invalid key) fails the call, the main agent's or a judge's: OpenCode exits 0 after one, which read as a successful call that changed nothing. diff --git a/CLAUDE.md b/CLAUDE.md index c07012be..50a9eaf2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,7 +15,7 @@ If the venv doesn't exist yet: ```bash uv venv source .venv/bin/activate -uv pip install -e ".[dev]" +uv pip install -e ".[dev,examples]" # examples: the bundled examples' tests need numpy, scipy, scikit-learn (as CI) ``` ## Project Layout @@ -102,7 +102,7 @@ User-facing docs are plain markdown in `docs/` (see `docs/README.md` for the ind - Read-only evaluation: gate, observe and stop commands, reviews and `ask` must not change candidate files. A gate or observe command's change rejects (checks copy verified after every command; the command's gate item or observe record is marked failed). Stop commands run after acceptance: the acceptance stays, the change is an error (`AutoHelixRunError`). Each stop command that ran is recorded in the record's `stops` (`checks.StopCheckResult.record`: outcome stop/continue/error, return code, `timed_out` as a flag, as gate items have it), shown as a note under the row (`terminal.Table._notes`) and in the viewer. `ask` and `review` judge the same target (`judge.judged`): in a run their own fresh copy of `$AUTOHELIX_CANDIDATE` in its own folder of `$AUTOHELIX_SCRATCH` (`candidate_target`; never the checks copy, where commands leave files and run candidate code), with `candidate.diff` named in the prompt (`describe_change`); by hand the current directory and its working-tree diff (`checkout_target`). One write guard (`DirectoryGuard`, git's listing of the judged directory, a walk outside a repository) around each call: a change fails the call (no retry, nothing sticky). Codex judges get `-c project_doc_max_bytes=0` (no AGENTS.md; unconfirmed against a real Codex). Ordinary review failures are recorded and continue; scripts own `ask` exit codes. - Launcher: harness commands run with PYTHONPATH remapped to the copy, so `iteration.call_folder()` writes `bin/autohelix` (`launcher.py`: the harness's interpreter with `-I`, its own package first on sys.path) and puts it first on PATH; candidate code can't replace modules inside `ask`/`review`. Each command also gets `AUTOHELIX_CANDIDATE` (T as a tree), `AUTOHELIX_BASE` (A), `AUTOHELIX_PROJECT`, `AUTOHELIX_SCRATCH`, stdin `/dev/null` (`checks._execute`), and runs in its own process group, killed whole when it ends. The main agent gets neither `AUTOHELIX_PROJECT` nor `AUTOHELIX_RUN_DIR` (`run_agent`'s `deadline_env` unsets them; it gets `AUTOHELIX_RUN_ID`, `AUTOHELIX_ITERATION`), and its copy has the config file and template removed (`IterationWorkspace.agent_copy(hidden=Config.hidden)`, never through a symlink; frozen, so `snapshot` resets them, and a still-absent one isn't reported as discarded): hygiene, not a boundary. - Exit codes (`cli._segment`, `Harness.run`'s return): `run`/`resume` exit 0 for a polite end (budget, `stop:`, `autohelix stop`), 1 for errors (refused start incl. preflight on resume and no run to resume, the agent failing 3 times or once for its infrastructure, a failed auto landing: `Harness.run` raises an `autohelix_reported` `AutoHelixRunError` after the ending), 130 when interrupted (`run` returns "interrupted" for one in the loop; one in the baseline/summary propagates; `cli._interruptible` maps Ctrl-C anywhere in `run`/`resume`, Harness init and preflight too). `ask`/`review`/`wait` keep their own codes. Documented in docs/cli.md#exit-codes. -- Recovery/accounting: under ownership, repair only a torn unterminated final history record and recover published commits from run/iteration trailers. Each attempted main-agent failure (an unsuccessful or timed-out call) records a rejected, unchecked iteration (`agent_error`), consumes its number, and the loop continues; `harness.MAX_CONSECUTIVE_AGENT_FAILURES` (3) in a row within a segment stop the run (stop reason kind `agent`). A call its backend reports as an infrastructure failure (`AgentRunResult.infrastructure`, `agents.infrastructure_reason`: Claude Code's `api_error` result with `api_error_status` 401/403/429/5xx, Codex's `turn.failed` "unexpected status 401/403", OpenCode's `error` event `statusCode`; an OpenCode `error` event fails the call at exit 0 too) is recorded the same way (plus the record's `infrastructure`) and stops the run at once (kind `infrastructure`, its detail says to fix it and resume); both kinds (`harness.AGENT_STOPS`) exit 1 and skip the summary. Judges don't use it. Failures before the call (copy, prompt) do not consume the number and stop the run with an error. Baseline retries remain iteration 0 and retain earlier call charges. Calls with unavailable usage remain unknown. Codex calls are priced (`agents/codex_cost.estimate_cost`) from the model Codex's JSON output names, else `agent.model`, else unavailable ("set agent.model"); no session files, no `extra_args` guessing. A timed-out OpenCode call has an error and an unknown cost (its finished steps' as `partial_cost_usd`). Every backend's result usage carries `agents.call_fields`: `cli`, `model` (what its output named: Claude Code's `init` event, a Codex event's `model`; OpenCode's events name none, None; unconfirmed against real CLIs) and `executable` (`backend.executable`, resolved once when created; the mock's is `$AUTOHELIX_MOCK_CMD`); so the history's agent call, judge usage records (`cli`, was `agent`) and summary usage have them. The segment start record has the main agent's `executable` (`_run` warns when it differs from the last segment's) and `autohelix_version` (`terminal.version`, as the header shows it; `wait`'s events don't carry it); the header's Agent line is `terminal.agent_text` (configured model; `view`'s run screen and the viewer's run page use `history.latest_agent_call`'s reported model, the run payload's `agent`). +- Recovery/accounting: under ownership, repair only a torn unterminated final history record and recover published commits from run/iteration trailers. Each attempted main-agent failure (an unsuccessful or timed-out call) records a rejected, unchecked iteration (`agent_error`), consumes its number, and the loop continues; `harness.MAX_CONSECUTIVE_AGENT_FAILURES` (3) in a row within a segment stop the run (stop reason kind `agent`). A call its backend reports as an infrastructure failure (`AgentRunResult.infrastructure`, `agents.infrastructure_reason`: Claude Code's `api_error` result with `api_error_status` 401/403/429/5xx, Codex's `turn.failed` "unexpected status 401/403", OpenCode's `error` event `statusCode`; an OpenCode `error` event fails the call at exit 0 too) is recorded the same way (plus the record's `infrastructure`) and stops the run at once (kind `infrastructure`, its detail says to fix it and resume); both kinds (`harness.AGENT_STOPS`) exit 1 and skip the summary. Judges don't use it. Failures before the call (copy, prompt) do not consume the number and stop the run with an error. Baseline retries remain iteration 0 and retain earlier call charges. Calls with unavailable usage remain unknown. Codex calls are priced (`agents/codex_cost.estimate_cost`) from the model Codex's JSON output names, else `agent.model`, else unavailable ("set agent.model"); no session files, no `extra_args` guessing. A timed-out OpenCode call has an error and an unknown cost (its finished steps' as `partial_cost_usd`). Every backend's result usage carries `agents.call_fields`: `cli`, `model` (what its output named: Claude Code's `init` event; Codex 0.171's JSON names none (checked on a real Codex, so its pricing needs `agent.model`; a `model` field is still read if a version adds one); OpenCode's events name none, None, unconfirmed) and `executable` (`backend.executable`, resolved once when created; the mock's is `$AUTOHELIX_MOCK_CMD`); so the history's agent call, judge usage records (`cli`, was `agent`) and summary usage have them. The segment start record has the main agent's `executable` (`_run` warns when it differs from the last segment's) and `autohelix_version` (`terminal.version`, as the header shows it; `wait`'s events don't carry it); the header's Agent line is `terminal.agent_text` (configured model; `view`'s run screen and the viewer's run page use `history.latest_agent_call`'s reported model, the run payload's `agent`). - Resume/landing: one function computes the run/target relation, `runs.landing` (a `Landing`: the run's tip, the target's tip, `same`/`ahead`/`behind`/`diverged`/`landed` (the target lacks the tip and run.json's `landed.tip`, which is the tip or an ancestor of it, and `landed.target` is the branch compared, recorded by `land` and auto landing only on the run's own target and for a run with commits, `runs._record_landed`: a squash-merged PR; nothing compares the code; commits after it are `diverged`, only they count, and `Landing.since` makes their command `git cherry-pick ..autohelix/`; run.json's hashes go to git only if they match `runs.COMMIT`) or None when a side is missing, and the commit counts each way: `ahead` the unlanded ones beyond the base, `behind` the target's the tip lacks; `accepted`, the tip isn't the base), and one words it, `runs.landing_words(landing, run_id, land_mode)` (a `LandingWords`: the runs table's and web run list's cell, a sentence with what works, the end block's note, the commands that land: `autohelix land ` only for `ahead`, `git merge autohelix/` for `diverged`, the sentence's `state` without its advice and `missing`, `'s N accepted commits aren't in `; "diverged" is the one word); `reconcile`, `land`, `delete`, the new-run notices and `land_first` (`run --import`), the harness's ending (`Harness._relation`; `_land` has no pre-check of its own: `land` refuses), `view --json`'s `landing` (`Landing.payload()`) and `landing_words` (`cell`, `text`, `note`, `commands`: what the runs table, the entry screen's suggestion and `view --terminal` (end block, `next`) show, `run_table._words`) read it. `resume` only continues the same run (stored config, own tip): a target branch past the run's tip (`behind`, `landed`) refuses an auto-landing resume before anything is written (`Harness.__init__`, again under the lock in `runs.reconcile`, which no longer fast-forwards the run onto it) and is a warning in manual mode; a resume after a `stop:` condition says it continues (`cli._stopped_note`). Only initial baseline capture requires a clean checkout. After baseline, gates/observe/stop/report use run candidate copies. Auto landing runs before report, with a finally fallback preserving original errors. The pin is deleted at every segment end. Archive retains evidence and unlanded refs; delete removes state/ref while persistent lock files remain outside the deleted directory. - Groups: `run --group NAME` (stored in `run.json`; `resume --group NAME|''` changes it) makes runs of the same project share notes and code. Members are the other non-archived runs with that group (`runs.group_members()`), taken once per iteration (`IterationWorkspace.members`): copied into the copy (not linked) and listed in the prompt (`prompt_template.describe_member()`); their refs go into the copy's `.git`. No group commands: budgets, resume, land, archive stay per run. Landing mode is per run, recorded in `run.json` at creation (`--land`; else `manual` with `--group`; else `auto`; `land:`/`report:` are config errors naming `--land`/`--no-report`, like `budget:`), kept on resume, changed by `resume --land`. The "also running for this config" warning is quiet for group runs and when either run lands manually. - Import: `run --import ID` records `import: {run}` in `run.json` (with `--why`: `why`; `archive --why`: `archive_why`, kept by `--undo`). Each iteration `IterationWorkspace.imported` (`runs.imported_run`, None when unreadable) is shown like a member (`others`: copied into `runs//`, its ref in the copy's `.git`; dropped from `members` if also in the group) and as the prompt's `imported`; at the baseline, `_observe` takes `$AUTOHELIX_PREVIOUS` from the imported run's history by entry name. Not imported: budgets, metric reference, group, notes (the new run's start empty). Harness git calls on the user's repo (`Repo.git`, `runs.git`) retry briefly on lock contention (`workspace.run_git`). diff --git a/README.md b/README.md index 5e840435..9fab0345 100644 --- a/README.md +++ b/README.md @@ -295,7 +295,7 @@ We'd love to hear what you point AutoHelix at. Please title = {AutoHelix: Running Agents with Protocols}, author = {Trager, Matthew and Mansimov, Elman and Zhang, Yi and Xia, Wei and Soatto, Stefano}, year = {2026}, - version = {0.1.1}, + version = {0.2.0}, url = {https://github.com/awslabs/AutoHelix} } ``` diff --git a/docs/concepts.md b/docs/concepts.md index 6899895e..7c049e31 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -505,7 +505,9 @@ subscription charges or provider bills. The normal display uses the same The snapshot was verified on November 6, 2026. It supports listed GPT-6 models and common GPT-5 Codex models; unknown names and expiring promotional prices are not guessed. The model priced is the one Codex's JSON output names, else -`agent.model`; with neither, the cost is unavailable ("set agent.model"). +`agent.model`; with neither, the cost is unavailable, and the run's end says +so ("cost unavailable: set agent.model"). Codex 0.171's output names no model, +so set `agent.model` to have Codex calls priced. AutoHelix doesn't read Codex's session files or guess from `extra_args`: a model chosen there (`-m`, a profile) is priced as `agent.model` says, so set `agent.model` to the model you run. diff --git a/docs/config.md b/docs/config.md index 49575715..9b968bff 100644 --- a/docs/config.md +++ b/docs/config.md @@ -583,7 +583,10 @@ supports it, the agent also sees the time left, so it can wrap up and write notes first: Claude Code through hooks after each tool call, Codex through the same hook on CLI versions that support it (an older Codex warns and runs without hints), OpenCode through a plugin. Every agent can run -`bash "$AUTOHELIX_TIME_LEFT_SCRIPT"`, and the prompt says so. See +`bash "$AUTOHELIX_TIME_LEFT_SCRIPT"`, and the prompt says so. With a timeout, +Claude Code also waits for the agent's background tasks after its last turn +(`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=0`, unless you set it): without one, it +stops them 10 minutes after that turn. See [ML Experiments](ml-experiments.md) for when this matters. ## Prompt template diff --git a/pyproject.toml b/pyproject.toml index 9634b3d6..98f1e4d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "autohelix" -version = "0.1.1" +version = "0.2.0" description = "Agent-powered iterative optimization: put an AI agent in a verified improvement loop" readme = "assets/README-pypi.md" requires-python = ">=3.11" diff --git a/src/autohelix/__init__.py b/src/autohelix/__init__.py index 6c742735..abf2f291 100644 --- a/src/autohelix/__init__.py +++ b/src/autohelix/__init__.py @@ -7,5 +7,5 @@ from autohelix.harness import Harness from autohelix.history import History -__version__ = "0.1.1" +__version__ = "0.2.0" __all__ = ["Config", "ConfigIssue", "load_config", "Harness", "History"] diff --git a/src/autohelix/agents/claudecode.py b/src/autohelix/agents/claudecode.py index 2f6c5428..6886386f 100644 --- a/src/autohelix/agents/claudecode.py +++ b/src/autohelix/agents/claudecode.py @@ -365,6 +365,10 @@ def run( env.pop("CLAUDE_CODE_DISABLE_AUTO_MEMORY", None) else: env["CLAUDE_CODE_DISABLE_AUTO_MEMORY"] = "1" + if self.config.timeout is not None: + # `claude -p` stops background tasks 10 minutes after the last turn; with a + # deadline (which kills the whole process group) wait for them instead. + env.setdefault("CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS", "0") try: result = run_process( diff --git a/src/autohelix/agents/codex.py b/src/autohelix/agents/codex.py index 044fd33a..668d0d11 100644 --- a/src/autohelix/agents/codex.py +++ b/src/autohelix/agents/codex.py @@ -152,7 +152,7 @@ def _handle_line(self, line: str, event_callback: EventCallback) -> None: event_type = payload.get("type") if isinstance(payload.get("model"), str) and payload["model"]: - self._model = payload["model"] # unconfirmed: which events name it (if any) varies by version + self._model = payload["model"] # Codex 0.171 names none (checked); kept for a version that does if event_type in {"thread.started", "turn.started"}: self._emit(event_callback, AgentEventKind.STATUS, event_type) return diff --git a/src/autohelix/formatting.py b/src/autohelix/formatting.py index cd68e59e..c99b22d6 100644 --- a/src/autohelix/formatting.py +++ b/src/autohelix/formatting.py @@ -65,9 +65,13 @@ def format_cap(cost: float) -> str: def format_total_cost(usages: Iterable[dict]) -> str: - """Describe a total as incomplete when some agent calls have no known cost.""" + """Describe a total as incomplete when some agent calls have no known cost; an + unavailable one says why when its calls give one reason (`set agent.model ...`).""" + usages = list(usages) total = summarize_costs(usages) if total.cost_usd is None: - return "cost unavailable" + reasons = {u["cost_unavailable_reason"] for u in usages + if u.get("cost_usd") is None and u.get("cost_unavailable_reason")} + return f"cost unavailable: {reasons.pop()}" if len(reasons) == 1 else "cost unavailable" text = format_cost(total.cost_usd) return f"{text} (incomplete)" if total.incomplete else text diff --git a/tests/test_agents.py b/tests/test_agents.py index 9884e98e..2a4fb901 100644 --- a/tests/test_agents.py +++ b/tests/test_agents.py @@ -330,6 +330,52 @@ def fake_run_process(**kwargs): assert result.error == "API Error: invalid model" +class TestClaudeCodeBackgroundWait: + """With a deadline, `claude -p` waits for background tasks after its last turn + (its default stops them after 10 minutes); without one, the default stays.""" + + @staticmethod + def _env(config, environ=None): + import os + from pathlib import Path + from unittest.mock import MagicMock, patch + from autohelix.agents.claudecode import ClaudeCodeAgent + + agent = ClaudeCodeAgent(config=config) + captured = {} + + def fake_run_process(**kwargs): + captured.update(kwargs.get("env") or {}) + result = MagicMock() + result.exit_code, result.timed_out = 0, False + return result + + with patch("autohelix.agents.claudecode.run_process", side_effect=fake_run_process), \ + patch.dict(os.environ, environ or {}): + agent.run(copy_path=Path("/tmp/fake"), prompt="test", iteration=1, log_path=Path("/tmp/fake.log"), + event_callback=lambda e: None, project_path=Path("/tmp/project")) + return captured + + def test_a_timeout_waits_for_background_tasks(self): + assert self._env(AgentConfig(timeout=600))["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == "0" + + def test_without_a_timeout_claude_codes_default_stays(self): + import os + with patch_env_without("CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"): + assert "CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS" not in self._env(AgentConfig()) + + def test_a_value_the_user_set_is_kept(self): + env = self._env(AgentConfig(timeout=600), {"CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS": "60000"}) + assert env["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == "60000" + + +def patch_env_without(name): + import os + from unittest.mock import patch + environ = {k: v for k, v in os.environ.items() if k != name} + return patch.dict(os.environ, environ, clear=True) + + class TestClaudeCodeAutoMemory: def test_auto_memory_disabled_sets_env(self): """When auto_memory is False, env should include CLAUDE_CODE_DISABLE_AUTO_MEMORY.""" diff --git a/tests/test_formatting.py b/tests/test_formatting.py index ca180862..0b33c58f 100644 --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -17,3 +17,12 @@ def test_complete_partial_and_unavailable_totals(): def test_format_duration_is_compact(): from autohelix.formatting import format_duration assert [format_duration(s) for s in (0, 48, 62, 3599, 3700)] == ["0s", "48s", "1m 02s", "59m 59s", "1h 01m"] + + +def test_an_unavailable_total_says_why_when_its_calls_agree(): + reason = "set agent.model (Codex's output names no model)" + assert format_total_cost([{"cost_unavailable_reason": reason}, {"cost_usd": None, "cost_unavailable_reason": reason}]) \ + == f"cost unavailable: {reason}" + assert format_total_cost([{"cost_unavailable_reason": "a"}, {"cost_unavailable_reason": "b"}]) == "cost unavailable" + # A known part: incomplete, as before (no reason). + assert format_total_cost([{"cost_usd": 0.25}, {"cost_unavailable_reason": reason}]) == "$0.25 (incomplete)" From e453cb9f6839adca53f7408ea636fe42c34fd839 Mon Sep 17 00:00:00 2001 From: mtrager Date: Mon, 23 Nov 2026 12:27:54 -0500 Subject: [PATCH 2/2] Review fixes: no background-wait variable; a cost reason only when every unpriced call gives it, string-only and cleaned - Dropped CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=0: a background task that never ends would keep every call alive until its timeout, which then counts as a failed call; the report agent always has a deadline. - format_total_cost: usage records can come from a file candidate code writes, so only a plain-string reason, cleaned of terminal controls, and only when all unpriced calls give the same one. Codex's reason is now "set agent.model" (fits an 80-column end block); its warning still says why. --- CHANGELOG.md | 9 ++---- docs/concepts.md | 6 ++-- docs/config.md | 5 +--- src/autohelix/agents/claudecode.py | 4 --- src/autohelix/agents/codex.py | 7 +++-- src/autohelix/formatting.py | 10 +++++-- tests/test_agents.py | 46 ------------------------------ tests/test_formatting.py | 25 +++++++++++++--- 8 files changed, 39 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 820dc923..ccb0c7fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -172,12 +172,9 @@ has the checklist. ### Fixed -- With `agent.timeout`, Claude Code waits for the agent's background tasks - instead of stopping them 10 minutes after its last turn (the timeout still - ends the call). -- When no cost is known for a run and its calls give one reason, the end says - it (`cost unavailable: set agent.model ...` for Codex, whose output names no - model). +- When no cost is known for a run and all its calls give the same reason, the + end says it (`cost unavailable: set agent.model` for Codex, whose output names + no model). - An OpenCode `error` event (an invalid key) fails the call, the main agent's or a judge's: OpenCode exits 0 after one, which read as a successful call that changed nothing. diff --git a/docs/concepts.md b/docs/concepts.md index 7c049e31..2a472121 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -505,9 +505,9 @@ subscription charges or provider bills. The normal display uses the same The snapshot was verified on November 6, 2026. It supports listed GPT-6 models and common GPT-5 Codex models; unknown names and expiring promotional prices are not guessed. The model priced is the one Codex's JSON output names, else -`agent.model`; with neither, the cost is unavailable, and the run's end says -so ("cost unavailable: set agent.model"). Codex 0.171's output names no model, -so set `agent.model` to have Codex calls priced. +`agent.model`; with neither, the cost is unavailable ("set agent.model", which +the run's end shows when no call of the run is priced). Codex 0.171's output +names no model, so set `agent.model` to have Codex calls priced. AutoHelix doesn't read Codex's session files or guess from `extra_args`: a model chosen there (`-m`, a profile) is priced as `agent.model` says, so set `agent.model` to the model you run. diff --git a/docs/config.md b/docs/config.md index 9b968bff..49575715 100644 --- a/docs/config.md +++ b/docs/config.md @@ -583,10 +583,7 @@ supports it, the agent also sees the time left, so it can wrap up and write notes first: Claude Code through hooks after each tool call, Codex through the same hook on CLI versions that support it (an older Codex warns and runs without hints), OpenCode through a plugin. Every agent can run -`bash "$AUTOHELIX_TIME_LEFT_SCRIPT"`, and the prompt says so. With a timeout, -Claude Code also waits for the agent's background tasks after its last turn -(`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=0`, unless you set it): without one, it -stops them 10 minutes after that turn. See +`bash "$AUTOHELIX_TIME_LEFT_SCRIPT"`, and the prompt says so. See [ML Experiments](ml-experiments.md) for when this matters. ## Prompt template diff --git a/src/autohelix/agents/claudecode.py b/src/autohelix/agents/claudecode.py index 6886386f..2f6c5428 100644 --- a/src/autohelix/agents/claudecode.py +++ b/src/autohelix/agents/claudecode.py @@ -365,10 +365,6 @@ def run( env.pop("CLAUDE_CODE_DISABLE_AUTO_MEMORY", None) else: env["CLAUDE_CODE_DISABLE_AUTO_MEMORY"] = "1" - if self.config.timeout is not None: - # `claude -p` stops background tasks 10 minutes after the last turn; with a - # deadline (which kills the whole process group) wait for them instead. - env.setdefault("CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS", "0") try: result = run_process( diff --git a/src/autohelix/agents/codex.py b/src/autohelix/agents/codex.py index 668d0d11..ba43e6e3 100644 --- a/src/autohelix/agents/codex.py +++ b/src/autohelix/agents/codex.py @@ -286,8 +286,8 @@ def run( model = self._model or self.config.model if not self._usage["usage_complete"]: self._usage["cost_unavailable_reason"] = "Codex did not report complete successful usage." - elif not model: - self._usage["cost_unavailable_reason"] = "set agent.model (Codex's output names no model)" + elif not model: # Codex's output names no model (0.171) + self._usage["cost_unavailable_reason"] = "set agent.model" else: self._usage.update(estimate_cost( self._usage, model, output_includes_reasoning=self._usage.get("output_includes_reasoning", True), @@ -295,7 +295,8 @@ def run( if self._usage.get("cost_unavailable_reason") and error is None: self._emit( event_callback, AgentEventKind.WARNING, - f"Cost unavailable: {self._usage['cost_unavailable_reason']}", + f"Cost unavailable: {self._usage['cost_unavailable_reason']}" + + (" (Codex's output names no model)" if not model else ""), ) success = result.exit_code == 0 and error is None diff --git a/src/autohelix/formatting.py b/src/autohelix/formatting.py index c99b22d6..5e91e6cb 100644 --- a/src/autohelix/formatting.py +++ b/src/autohelix/formatting.py @@ -70,8 +70,12 @@ def format_total_cost(usages: Iterable[dict]) -> str: usages = list(usages) total = summarize_costs(usages) if total.cost_usd is None: - reasons = {u["cost_unavailable_reason"] for u in usages - if u.get("cost_usd") is None and u.get("cost_unavailable_reason")} - return f"cost unavailable: {reasons.pop()}" if len(reasons) == 1 else "cost unavailable" + # Shown only when every unpriced call gives the same reason, a plain string (usage + # records can come from files candidate code writes: cleaned, never trusted). + reasons = {reason if isinstance(reason := u.get("cost_unavailable_reason"), str) else None + for u in usages if u.get("cost_usd") is None} + reason = reasons.pop() if len(reasons) == 1 else None + reason = clean(reason, 80).rstrip(".") if reason else "" + return f"cost unavailable: {reason}" if reason else "cost unavailable" text = format_cost(total.cost_usd) return f"{text} (incomplete)" if total.incomplete else text diff --git a/tests/test_agents.py b/tests/test_agents.py index 2a4fb901..9884e98e 100644 --- a/tests/test_agents.py +++ b/tests/test_agents.py @@ -330,52 +330,6 @@ def fake_run_process(**kwargs): assert result.error == "API Error: invalid model" -class TestClaudeCodeBackgroundWait: - """With a deadline, `claude -p` waits for background tasks after its last turn - (its default stops them after 10 minutes); without one, the default stays.""" - - @staticmethod - def _env(config, environ=None): - import os - from pathlib import Path - from unittest.mock import MagicMock, patch - from autohelix.agents.claudecode import ClaudeCodeAgent - - agent = ClaudeCodeAgent(config=config) - captured = {} - - def fake_run_process(**kwargs): - captured.update(kwargs.get("env") or {}) - result = MagicMock() - result.exit_code, result.timed_out = 0, False - return result - - with patch("autohelix.agents.claudecode.run_process", side_effect=fake_run_process), \ - patch.dict(os.environ, environ or {}): - agent.run(copy_path=Path("/tmp/fake"), prompt="test", iteration=1, log_path=Path("/tmp/fake.log"), - event_callback=lambda e: None, project_path=Path("/tmp/project")) - return captured - - def test_a_timeout_waits_for_background_tasks(self): - assert self._env(AgentConfig(timeout=600))["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == "0" - - def test_without_a_timeout_claude_codes_default_stays(self): - import os - with patch_env_without("CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"): - assert "CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS" not in self._env(AgentConfig()) - - def test_a_value_the_user_set_is_kept(self): - env = self._env(AgentConfig(timeout=600), {"CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS": "60000"}) - assert env["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] == "60000" - - -def patch_env_without(name): - import os - from unittest.mock import patch - environ = {k: v for k, v in os.environ.items() if k != name} - return patch.dict(os.environ, environ, clear=True) - - class TestClaudeCodeAutoMemory: def test_auto_memory_disabled_sets_env(self): """When auto_memory is False, env should include CLAUDE_CODE_DISABLE_AUTO_MEMORY.""" diff --git a/tests/test_formatting.py b/tests/test_formatting.py index 0b33c58f..c5a798a9 100644 --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -1,5 +1,7 @@ """Tests for autohelix.formatting.""" +import pytest + from autohelix.formatting import format_cost, format_total_cost @@ -20,9 +22,24 @@ def test_format_duration_is_compact(): def test_an_unavailable_total_says_why_when_its_calls_agree(): - reason = "set agent.model (Codex's output names no model)" - assert format_total_cost([{"cost_unavailable_reason": reason}, {"cost_usd": None, "cost_unavailable_reason": reason}]) \ - == f"cost unavailable: {reason}" + assert format_total_cost([{"cost_unavailable_reason": "set agent.model"}, + {"cost_usd": None, "cost_unavailable_reason": "set agent.model"}]) \ + == "cost unavailable: set agent.model" + assert format_total_cost([{"cost_unavailable_reason": "No API pricing for model x."}]) \ + == "cost unavailable: No API pricing for model x" + # Different reasons, or a call without one: no reason. assert format_total_cost([{"cost_unavailable_reason": "a"}, {"cost_unavailable_reason": "b"}]) == "cost unavailable" + assert format_total_cost([{"cost_unavailable_reason": "a"}, {}]) == "cost unavailable" # A known part: incomplete, as before (no reason). - assert format_total_cost([{"cost_usd": 0.25}, {"cost_unavailable_reason": reason}]) == "$0.25 (incomplete)" + assert format_total_cost([{"cost_usd": 0.25}, {"cost_unavailable_reason": "a"}]) == "$0.25 (incomplete)" + + +@pytest.mark.parametrize("reason", [["a"], {"a": 1}, 3]) +def test_a_reason_that_isnt_a_string_is_ignored(reason): + # Usage records can come from a file candidate code writes ($AUTOHELIX_USAGE_FILE). + assert format_total_cost([{"cost_unavailable_reason": reason}]) == "cost unavailable" + + +def test_a_reason_is_cleaned_of_terminal_controls(): + text = format_total_cost([{"cost_unavailable_reason": "\x1b[2Jset agent.model\x1b]0;x\x07"}]) + assert "\x1b" not in text and "\x07" not in text and "set agent.model" in text