Skip to content
Open
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,12 @@ Changes are grouped by software version. Entries under Unreleased describe work

### Fixed

- A ChatGPT login whose files are gone when a session is prepared (both the user's login file and the run's shared
copy; `hermit train` checks them only at its start) is a lost sign-in: its error carries Hermit's mark (`[hermit_login_failed]`), so a rollout raises `LoginFailed` and the
run ends, a chat endpoint answers 401 with the code `hermit_login_failed`, and the Trainer ends the run when the
Evolver's own call meets it, instead of a plain failure each task and step met again. A login file there that could
not be read stays a failure of that session. A container worker takes a relative `login_root` as preflight did. A rollout that failed on this machine (an
`OSError`: `host_failed`) keeps what its agent said it spent, as the other failure paths do.
- Continual Harness and Harness² now declare the adapter parts they write (`needs: [llm, skills, agents]` and
`needs: [skills, agents, hooks]`), so a run whose acting agent does not take them (`react`) is refused before it
starts, instead of running a harness whose skills and sub-agents the acting agent drops.
Expand Down
3 changes: 2 additions & 1 deletion docs/guides/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ can make paid calls.
| GEPA/SkillOpt/Harness² cannot import | Installed method group and environment | From the checkout root, run `python -m pip install -e . --group gepa` (or `skillopt` / `harness2`) in the environment running the CLI; requires pip 25.1+ |
| `no such option: --group` | pip version | Run `python -m pip install --upgrade "pip>=25.1"`, then retry the group install |
| Learner authentication fails | Learner endpoint, key variable, backend CLI | Verify the configured variable is set without printing it; authenticate the selected CLI |
| `login: claude signs in with the token ...`, `Not logged in`, or a run that stopped with `hermit_login_failed` | `CLAUDE_CODE_OAUTH_TOKEN` | Run `claude setup-token` and export the token, then rerun `hermit train`: it resumes after the last finished step. See [Claude subscription](claude-subscription.md) |
| `login: chatgpt, but there is no Codex login ...`, or a run on Codex's ChatGPT login that stopped with `hermit_login_failed` and that message | The Codex login file (`~/.codex/auth.json`, or `$CODEX_HOME`'s) | If the file is missing, sign in again with the file-based login cache, `codex -c 'cli_auth_credentials_store="file"' login` (see [Codex plan](../tutorials/codex-plan.md)); if it is there, check that this user can read it and pass its folders. Then rerun `hermit train`: it resumes after the last finished step |
| `login: claude signs in with the token ...`, `Not logged in`, or a run on Claude Code's login (`login: claude`) that stopped with `hermit_login_failed` | `CLAUDE_CODE_OAUTH_TOKEN` | Run `claude setup-token` and export the token, then rerun `hermit train`: it resumes after the last finished step. See [Claude subscription](claude-subscription.md) |
| A task's Harbor environment did not start (`the task's environment could not be given`) | `driver.log` and the trial's `trial.log` under `environment.harbor.jobs_dir/<task>__<id>/` | The image's pull or build, the disk gate (`disk_gate_gb`, `tmp_gate_gb`), Docker's daemon; Harbor's venv (`~/.cache/hermit/harbor-venv`). See [Benchmarks](../framework/task.md#benchmarks) |
| Sessions on a login wait and nothing runs | The plan's files and report under `~/.cache/hermit/claude-login/plan/` (Codex: `codex-login/plan/`) | `plan.json` says which window is over and until when; remove `PAUSE`, raise `MAX_USED`, or wait for the reset. See [The plan](claude-subscription.md#the-plan) |
| `train refuses to start: ... serves [...], not 'responses'` (or `'messages'`) | The model's backend and the caller's dialect | Codex speaks the Responses API only, Claude Code the Messages API only: bind a backend that serves it (vLLM, SGLang, Fireworks, DeepSeek) or a translating proxy; `hermit backends check <ref>` tries each dialect. See [Model backends](model-backends.md) |
Expand Down
5 changes: 4 additions & 1 deletion hermit/agent/base/endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from hermit.agent.base.interface import LOGIN_FAILED, BaseAgent
from hermit.agent.base.interface import LOGIN_FAILED, BaseAgent, login_failure

HEADER_WAIT_S = 120.0
KEEPALIVE_S = 15.0
Expand Down Expand Up @@ -165,6 +165,9 @@ def answer(self, request: dict, authorization: str | None, abort: threading.Even
except (ValueError, Unsupported) as exc: # the session's settings: the client reads why
return 400, json.dumps({"error": {"message": f"{type(exc).__name__}: {exc}"}}).encode(), {}
except Exception as exc: # noqa: BLE001 - the session failed to run
why = login_failure(exc) # no sign-in to run it (login.prepare): as a lost one
if why:
return 401, json.dumps({"error": {"code": LOGIN_FAILED, "message": why}}).encode(), {}
return 502, json.dumps({"error": {"message": f"{type(exc).__name__}: {exc}"}}).encode(), {}
from hermit.agent.model.llm import ChatAborted, ChatHTTPError
try:
Expand Down
19 changes: 17 additions & 2 deletions hermit/agent/base/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,18 @@ def _newer(candidate: Path, than: Path) -> bool:
return mine is not None and (theirs is None or mine > theirs)


def _absent(path: Path) -> bool:
"""Whether `path` is known not to be there (its stat says so), not merely unread: a folder this process cannot
pass hides a file from Path.is_file (Python 3.14) that may well be there."""
try:
os.stat(path)
except (FileNotFoundError, NotADirectoryError):
return True
except OSError:
return False
return False


def _replace(src: Path, dst: Path) -> None:
tmp = dst.with_suffix(".tmp")
if os.path.lexists(tmp): # a link a session left beside the login: never written through
Expand All @@ -96,8 +108,11 @@ def prepare(root: Path, home: Path, user_file: Path | None = None) -> None:
fcntl.flock(lock, fcntl.LOCK_EX)
if user_file.is_file() and _newer(user_file, master):
_replace(user_file, master)
if not master.is_file():
raise RuntimeError(f"login: chatgpt, but there is no Codex login at {user_file} (run `codex login`)")
if not master.is_file(): # no login file: a sign-in to restore, which ends the run
from hermit.agent.base.interface import LOGIN_FAILED # (LoginFailed); one there that could not be read
# (being written, in a folder this process cannot pass) fails this session alone
mark = f" [{LOGIN_FAILED}]" if _absent(user_file) and _absent(master) else ""
raise RuntimeError(f"login: chatgpt, but there is no Codex login at {user_file} (run `codex login`){mark}")
_replace(master, Path(home) / FILE)


Expand Down
2 changes: 2 additions & 0 deletions hermit/isolate.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,8 @@ def __init__(self, config, role: str, params: dict, *, work_root: Path | None =
login = self.params.get("login")
if codex_login.LOGINS.get(login):
self.params = {**self.params, "plan_dir": str(codex_login.plan_dir(self.params.get("plan_dir"), login))}
if self.params.get("login_root"): # its shared copy too, named as preflight and a session
self.params = {**self.params, "login_root": str(Path(str(self.params["login_root"])).absolute())} # do
self.enforce = d["sandbox"].get("enforce", "required")
self.box = Sandbox(enabled=False, role=role) # the worker is on the host; the container is the boundary

Expand Down
3 changes: 2 additions & 1 deletion hermit/trainer/rollout.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,8 @@ def _environment_run(task: Task, given: dict, adapter: Path | None, pipeline, en
out.cost_usd, out.tokens = ledger.cost(None), ledger.tokens(None)
out.api_speed = {**(out.api_speed or {}), "model_calls": ledger.calls()}
elif isinstance(exc, OSError): # this machine's (the runner's host_failed): never run again
out = _infra_output(task, "host_failed", f"{type(exc).__name__}: {exc}", begun, ran=True)
out = _infra_output(task, "host_failed", f"{type(exc).__name__}: {exc}", begun, ran=True,
spent=getattr(exc, "spent", None)) # what the agent said it spent
final = True
else:
read = pipeline_cause(f"{type(exc).__name__}: {exc}")
Expand Down
8 changes: 6 additions & 2 deletions hermit/trainer/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@

from hermit.adapter.manifest import CARD, MANIFEST, read_manifest
from hermit.agent.base import login as subscription
from hermit.agent.base.interface import LoginFailed
from hermit.agent.base.interface import LoginFailed, login_failure
from hermit.agent.model.backends import bindings_of, problems_of, registry
from hermit.config import Config
from hermit.agent.evolver.base import (Access, Context, Evolver, FinalResult, Progress, StepContext, StepResult, Usage,
Expand Down Expand Up @@ -517,7 +517,11 @@ def call(**arguments):

def _raise_login_failed(self, box: dict) -> None:
"""The run ends, unfinished, when the Evolver's call or a tool call in it met a failed sign-in."""
failed = box["error"] if isinstance(box.get("error"), LoginFailed) else self._login_failed
error = box.get("error")
failed = error if isinstance(error, LoginFailed) else self._login_failed
why = login_failure(error) if failed is None and isinstance(error, Exception) else None
if why: # a session's sign-in missing (login.prepare): the run ends,
failed = LoginFailed(why) # as for a lost one
if failed is not None:
raise failed

Expand Down
34 changes: 34 additions & 0 deletions tests/core/test_cli_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,40 @@ def session(self, prompt, **kw):
assert seen == {"waits": 2, "sessions": 2, "holds": 1} and result.reply.endswith("<answer>44,463</answer>")


def test_a_login_session_with_no_login_to_copy_is_a_lost_sign_in(tmp_path, monkeypatch):
"""login.prepare raised a plain RuntimeError: an endpoint answered 502 and a run took it for a failure."""
from hermit.agent.base.endpoint import ChatEndpoint
from hermit.agent.base.interface import login_failure
from hermit.agent.base import login as L
monkeypatch.setattr(L, "wait", lambda *a, **k: "")
monkeypatch.setenv("CODEX_HOME", str(tmp_path / "no-codex-here"))
agent = make("codex", {"web_search": False, "login": "chatgpt", "model": "gpt-x",
"login_root": str(tmp_path / "no-root"), "plan_dir": str(tmp_path / "plan"),
"log": str(tmp_path / "logs/run.jsonl"), "log_dir": str(tmp_path / "logs")})
(tmp_path / "w").mkdir()
with pytest.raises(RuntimeError) as failed:
agent.run("go", environment=tmp_path / "w")
assert "codex login" in login_failure(failed.value) # a rollout's LoginFailed
endpoint = ChatEndpoint.__new__(ChatEndpoint) # the request answered as the endpoint
endpoint.agent, endpoint.place = agent, None # does (cli_answer, a Local session)
status, body, _ = endpoint.answer({"messages": [{"role": "user", "content": "go"}]}, None)
assert status == 401 and json.loads(body)["error"]["code"] == "hermit_login_failed"
(tmp_path / "no-codex-here").mkdir() # a login file not read (written
(tmp_path / "no-codex-here/auth.json").write_text('{"tokens": ') # meanwhile): this session's failure
with pytest.raises(RuntimeError) as failed:
agent.run("go", environment=tmp_path / "w")
assert login_failure(failed.value) is None
if os.geteuid() != 0: # in a folder it cannot pass: unread,
monkeypatch.setattr(Path, "is_file", lambda self: os.path.isfile(self)) # not absent (Python 3.14's is_file
(tmp_path / "no-codex-here").chmod(0) # says False)
try:
with pytest.raises(RuntimeError) as failed:
agent.run("go", environment=tmp_path / "w")
assert login_failure(failed.value) is None
finally:
(tmp_path / "no-codex-here").chmod(0o700)


def test_a_long_window_still_over_holds_after_the_short_one_resets(tmp_path):
import time
from hermit.agent.base import login as L
Expand Down
18 changes: 18 additions & 0 deletions tests/core/test_harbor_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -2202,6 +2202,24 @@ def pipeline(task, adapter, environment=None):
assert record["api_speed"]["model_calls"] == 1 and record["pipeline_extra"]["attempts"]


def test_a_failure_of_this_machine_keeps_what_the_run_spent(tmp_path):
"""An OSError is this machine's (host_failed, never run again); what the agent said it spent before it was
dropped there alone of the failure paths."""
from hermit.task import Task
from hermit.trainer import rollout

def pipeline(task, adapter, environment=None):
exc = OSError(28, "No space left on device")
exc.spent = RunOutput(output=None, tokens=1500, cost_usd=0.02, api_speed={"model_calls": 2})
raise exc

task = Task(id="demo#1", public={"id": "demo#1", "harbor_task": "demo"})
out = rollout.environment_rollout(task, task.given(), None, pipeline, Environments(tmp_path), 0.0,
pause=lambda s: None)
assert out.extra["failure_cause"] == "host_failed"
assert out.tokens == 1500 and out.cost_usd == 0.02 and out.api_speed["model_calls"] == 2


def test_an_attachment_over_the_limit_is_measured_there_and_never_read(tmp_path, monkeypatch):
from hermit.agent.acting import answer as answer_mod
from hermit.agent.model.usage import Usage
Expand Down
13 changes: 13 additions & 0 deletions tests/core/test_isolate.py
Original file line number Diff line number Diff line change
Expand Up @@ -869,6 +869,19 @@ def test_a_declared_path_that_comes_to_hold_a_run_is_refused_before_the_next_cal
agent.close()


def test_a_container_worker_takes_a_relative_login_root_as_preflight_did(tmp_path, monkeypatch):
"""The worker runs in its own folder: a relative `login_root` named another folder there, with no login in it,
and the session's missing login ended the run though preflight had found it."""
from hermit.isolate import ContainerAgent
(tmp_path / "t").mkdir()
config = Config.load(make_task(tmp_path / "t"))
from hermit.agent.base import login as codex_login
monkeypatch.chdir(tmp_path)
for root in ("logins/codex", "~/logins"): # as preflight names its shared copy
given = ContainerAgent(config, "rollout", {"login": "chatgpt", "login_root": root}).params["login_root"]
assert codex_login.master(Path(given)) == codex_login.master(Path(root)).absolute()


def test_a_container_session_ends_before_the_outer_deadline(tmp_path):
"""Killed at agent.timeout_min, the host worker could not remove the container: its session's own clock ends
first."""
Expand Down
20 changes: 20 additions & 0 deletions tests/core/test_training.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import pytest

from hermit.agent.base.interface import LoginFailed
from hermit.config import Config
from hermit.evaluate import evaluate
from hermit.settings_check import run_check
Expand Down Expand Up @@ -98,6 +99,25 @@ def crash_on_third(*a, **k):
assert summary["steps"] == 4


def test_a_missing_login_met_in_the_evolvers_own_call_ends_the_run(tmp_path):
"""login.prepare names a missing login with Hermit's lost-sign-in mark: met in the Evolver's own call (its session),
the step was recorded as failed and the run went on."""
path = make_task(tmp_path)
code = (tmp_path / "toy/evolver.py").read_text()
(tmp_path / "toy/evolver.py").write_text(code.replace(
' mode = ctx.params.get("mode", "learn")\n',
' mode = ctx.params.get("mode", "learn")\n'
' if mode == "signed_out":\n'
' raise RuntimeError("login: chatgpt, but there is no Codex login at /gone/auth.json "\n'
' "(run `codex login`) [hermit_login_failed]")\n'))
trainer = Trainer(load(path, "evolver.params.mode=signed_out"), log=lambda *_: None)
with pytest.raises(LoginFailed, match="no Codex login"):
trainer.train()
journal = tmp_path / "runs/toy-run/steps.jsonl"
assert not journal.exists() or not journal.read_text().strip() # the step is not recorded
trainer._raise_login_failed({"error": RuntimeError("an ordinary failure")}) # recorded as a failed step


def test_budget_stops_the_run(tmp_path):
cfg = load(make_task(tmp_path), "trainer.budget.usd=0.05")
summary = Trainer(cfg, log=lambda *_: None).train()
Expand Down
Loading