Skip to content

The agent that grows with you

fix(kanban): managed workers book credential start failures as 75/78, not 1

Teknium43cbb0e479f9
diff --git a/agent/managed_worker.py b/agent/managed_worker.py
index 419adab0bc7..06126ef2aed 100644
--- a/agent/managed_worker.py
+++ b/agent/managed_worker.py
@@ -251,7 +251,7 @@ def execute(frame, channel):
agent = None
try:
with policy_scope(policy):
- agent = AIAgent(model=policy.model, provider=policy.provider, base_url=policy.base_url,
+ agent = _construct_agent(frame, AIAgent, model=policy.model, provider=policy.provider, base_url=policy.base_url,
api_key=frame['api_key'], session_db=store, session_id=scope['session_id'],
enabled_toolsets=list(policy.toolsets), max_iterations=policy.max_turns,
reasoning_config=policy.reasoning_config, platform=policy.source,
@@ -299,6 +299,17 @@ def execute(frame, channel):
store.close()
+def _construct_agent(frame, factory, **kwargs):
+ """Agent construction resolves the provider credentials; a Kanban attempt that fails here
+ still books the one-shot exit mapping (quota wall 75, re-login 78) before the crash."""
+ try:
+ return factory(**kwargs)
+ except Exception as exc:
+ from gateway.session_kanban import record_start_failure
+ record_start_failure(frame, exc)
+ raise
+
+
def hello():
"""Identity the owner verifies before it reserves: this interpreter's pid and birth plus
the ancestor chain it observes. Launchers (uv's venv python.exe) put the owner's Popen
diff --git a/gateway/session_kanban.py b/gateway/session_kanban.py
index 28200aa09e4..8c78edcc6a1 100644
--- a/gateway/session_kanban.py
+++ b/gateway/session_kanban.py
@@ -204,25 +204,42 @@ def run_worker_turns(agent, frame, history):
author = frame.get('turn_author')
return agent.run_conversation(frame['text'], conversation_history=history,
**({'turn_author': author} if author is not None else {}))
- from hermes_cli.turn_exit import turn_exit_code
+ from hermes_cli.turn_exit import credential_failure_flags, turn_exit_code
code, last_output = 1, ''
try:
result = _run_task_turns(agent, frame, history, context)
code = turn_exit_code(result, kanban_worker=True)
last_output = str(result.get('final_response') or '')[-500:] if isinstance(result, dict) else ''
return result
+ except Exception as exc:
+ code = turn_exit_code(None, kanban_worker=True, **credential_failure_flags(exc))
+ raise
finally:
- _TURNS_DONE.set()
- import os
- from hermes_cli.kanban_db_connect import connect_closing
- from hermes_cli import kanban_db as kb
- with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):
- if _bound_worker_matches(conn, context):
- # Closing a run clears its claim/PID and replaces metadata; keep the
- # result in the immutable attempt event stream instead.
- kb._append_event(conn, context['task_id'], 'worker_result',
- {'pid': os.getpid(), 'claim_lock': context['claim_lock'], 'exit_code': code,
- 'last_output': last_output}, run_id=context['run_id'])
+ _record_worker_result(context, code, last_output)
+
+
+def record_start_failure(frame, exc):
+ """The worker died before any turn ran (agent construction resolves credentials): book the
+ one-shot CLI's credential exit (75 quota wall / 78 re-login / 1) instead of a bare crash."""
+ context = json.loads(frame['policy'].get('kanban_json') or 'null')
+ if context is None:
+ return
+ from hermes_cli.turn_exit import credential_failure_flags, turn_exit_code
+ _record_worker_result(context, turn_exit_code(None, kanban_worker=True, **credential_failure_flags(exc)), '')
+
+
+def _record_worker_result(context, code, last_output):
+ _TURNS_DONE.set()
+ import os
+ from hermes_cli.kanban_db_connect import connect_closing
+ from hermes_cli import kanban_db as kb
+ with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):
+ if _bound_worker_matches(conn, context):
+ # Closing a run clears its claim/PID and replaces metadata; keep the
+ # result in the immutable attempt event stream instead.
+ kb._append_event(conn, context['task_id'], 'worker_result',
+ {'pid': os.getpid(), 'claim_lock': context['claim_lock'], 'exit_code': code,
+ 'last_output': last_output}, run_id=context['run_id'])
def _bound_worker_matches(conn, context):
diff --git a/hermes_cli/turn_exit.py b/hermes_cli/turn_exit.py
index fc775926f74..6c145d01954 100644
--- a/hermes_cli/turn_exit.py
+++ b/hermes_cli/turn_exit.py
@@ -40,3 +40,20 @@ def turn_exit_code(
from hermes_cli.kanban_db import KANBAN_TERMINAL_PROVIDER_EXIT_CODE
return KANBAN_TERMINAL_PROVIDER_EXIT_CODE
return 1
+
+
+def credential_failure_flags(exc) -> dict:
+ """``turn_exit_code`` credential kwargs for an exception raised before any turn result exists.
+
+ Same predicates as the one-shot CLI's ``_ensure_runtime_credentials``: a quota/rate-limit
+ ``AuthError`` is transient, only an explicit re-authentication requirement is terminal. The
+ cause chain is walked because agent construction wraps the resolver's error."""
+ from hermes_cli.auth import AuthError, is_rate_limited_auth_error
+ seen = set()
+ while exc is not None and id(exc) not in seen:
+ seen.add(id(exc))
+ if isinstance(exc, AuthError):
+ return {"credentials_rate_limited": is_rate_limited_auth_error(exc),
+ "credentials_terminal": bool(exc.relogin_required)}
+ exc = exc.__cause__ or exc.__context__
+ return {}
diff --git a/hermes_cli/web_routers/display.py b/hermes_cli/web_routers/display.py
index 9278775ff84..76193c06454 100644
--- a/hermes_cli/web_routers/display.py
+++ b/hermes_cli/web_routers/display.py
@@ -22,6 +22,7 @@ from __future__ import annotations
import asyncio
import logging
+from pathlib import Path
from typing import Optional
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
@@ -123,7 +124,6 @@ async def _bridge(ws: WebSocket, info: dict) -> None:
from hermes_constants import hermes_home_key
from tools.bot_desktop import lease as _lease
from tools.bot_desktop.rfb_filter import RfbClientFilter
- from pathlib import Path
profile_home = str(info["hermes_home"])
profile_key = hermes_home_key(profile_home)
diff --git a/tests/gateway/test_kanban_result_exit.py b/tests/gateway/test_kanban_result_exit.py
index bb5f8df59d6..014db8a3242 100644
--- a/tests/gateway/test_kanban_result_exit.py
+++ b/tests/gateway/test_kanban_result_exit.py
@@ -10,6 +10,24 @@ from hermes_cli import kanban_db as kb
from hermes_cli.kanban_db_connect import connect_closing
+def _bound_claim(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)
+ kb.init_db()
+ path = kb.kanban_db_path()
+ with connect_closing(path) as conn:
+ task_id = kb.create_task(conn, title="private fixture", assignee="default")
+ task = kb.claim_task(conn, task_id, claimer="private-host:owner")
+ assert task is not None
+ context = {"db": str(path), "task_id": task_id,
+ "run_id": task.current_run_id, "claim_lock": task.claim_lock}
+ with kb.write_txn(conn):
+ kb._append_event(conn, task_id, "worker_bound",
+ {"pid": os.getpid(), "claim_lock": task.claim_lock},
+ run_id=task.current_run_id)
+ return path, context
+
+
@pytest.mark.parametrize(
"result, expected",
[
@@ -26,23 +44,34 @@ from hermes_cli.kanban_db_connect import connect_closing
],
)
def test_managed_result_persists_exact_worker_exit(tmp_path, monkeypatch, result, expected):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)
- kb.init_db()
- path = kb.kanban_db_path()
- with connect_closing(path) as conn:
- task_id = kb.create_task(conn, title="private fixture", assignee="default")
- task = kb.claim_task(conn, task_id, claimer="private-host:owner")
- assert task is not None
- context = {"db": str(path), "task_id": task_id,
- "run_id": task.current_run_id, "claim_lock": task.claim_lock}
- with kb.write_txn(conn):
- kb._append_event(conn, task_id, "worker_bound",
- {"pid": os.getpid(), "claim_lock": task.claim_lock},
- run_id=task.current_run_id)
+ path, context = _bound_claim(tmp_path, monkeypatch)
monkeypatch.setattr(session_kanban, "_run_task_turns", lambda *_args: result)
frame = {"policy": {"kanban_json": json.dumps(context)}}
assert session_kanban.run_worker_turns(SimpleNamespace(), frame, []) is result
assert session_kanban.worker_exit_code(path, context) == expected
assert session_kanban.worker_exit_code(path, context | {"claim_lock": "foreign"}) == 1
+
+
+def _credential_failures():
+ from hermes_cli.auth import AuthError
+ from hermes_cli.auth_constants import CODEX_RATE_LIMITED_CODE
+ wrapped = RuntimeError("agent init failed")
+ wrapped.__cause__ = AuthError("refresh revoked", provider="nous", relogin_required=True)
+ return [
+ (AuthError("quota", provider="openai-codex", code=CODEX_RATE_LIMITED_CODE), kb.KANBAN_RATE_LIMIT_EXIT_CODE),
+ (AuthError("relogin", provider="nous", relogin_required=True), kb.KANBAN_TERMINAL_PROVIDER_EXIT_CODE),
+ (wrapped, kb.KANBAN_TERMINAL_PROVIDER_EXIT_CODE),
+ (RuntimeError("unknown startup failure"), 1),
+ ]
+
+
[email protected]("error, expected", _credential_failures())
+def test_managed_start_failure_books_the_one_shot_credential_exit(tmp_path, monkeypatch, error, expected):
+ """Credentials that fail before any turn (agent construction) keep the one-shot CLI's mapping:
+ a quota wall is EX_TEMPFAIL, an explicit re-login is EX_CONFIG, anything else stays 1."""
+ path, context = _bound_claim(tmp_path, monkeypatch)
+ frame = {"policy": {"kanban_json": json.dumps(context)}}
+
+ session_kanban.record_start_failure(frame, error)
+ assert session_kanban.worker_exit_code(path, context) == expected