Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ has the checklist.

### Fixed

- 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.
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <landed tip>..autohelix/<id>`; 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 <id>` only for `ahead`, `git merge autohelix/<id>` for `diverged`, the sentence's `state` without its advice and `missing`, `<id>'s N accepted commits aren't in <target>`; "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/<id>/`, 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`).
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}
```
Expand Down
4 changes: 3 additions & 1 deletion docs/concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 ("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.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion src/autohelix/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
9 changes: 5 additions & 4 deletions src/autohelix/agents/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -286,16 +286,17 @@ 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),
))
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
Expand Down
12 changes: 10 additions & 2 deletions src/autohelix/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,17 @@ 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"
# 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
26 changes: 26 additions & 0 deletions tests/test_formatting.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Tests for autohelix.formatting."""

import pytest

from autohelix.formatting import format_cost, format_total_cost


Expand All @@ -17,3 +19,27 @@ 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():
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": "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
Loading