The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): cron run notices carry real usage; stdin errors name the fix
Tekniumbf904a84cef9
diff --git a/tests/tools/test_cron_run_notice_usage.py b/tests/tools/test_cron_run_notice_usage.pynew file mode 100644index 00000000000..1ebdfd0162c--- /dev/null+++ b/tests/tools/test_cron_run_notice_usage.py@@ -0,0 +1,82 @@+"""A manual cron run's completion notice reports the model and API calls its run session recorded.++The background ``cronjob(action='run')`` completion used to render ``Model: ?`` and ``API calls: 0``+whatever the job did: the runner hard-coded ``api_calls: 0`` and the dispatch only knew the job's+model pin (None for a job on the default model). The run's own session in state.db is the record.+"""+import time+from unittest.mock import patch++import pytest++from cron import jobs+from tests.fakes.cron_owner import admit_fire, cron_owner+from tools.cronjob_tools import _try_dispatch_background_run+from tools.process_registry_notifications import format_process_notification+++def owner(tmp_path, monkeypatch):+ authority = cron_owner(tmp_path / "home", monkeypatch)+ yield authority+ authority.db.close()+++def _completion(job, run_one_job):+ """Dispatch ``job`` through the real background path and return its completion event."""+ from tools.approval_context import _approval_session_key+ from tools.process_registry import process_registry++ token = _approval_session_key.set("agent:main:telegram:dm:4242")+ try:+ with patch("tools.cronjob_tools.claim_job_for_fire", side_effect=lambda jid, **kw: dict(job)), \+ patch("cron.scheduler.run_one_job", side_effect=run_one_job):+ res = _try_dispatch_background_run(dict(job))+ assert res["dispatched"] is True+ for _ in range(200):+ try:+ evt = process_registry.completion_queue.get_nowait()+ except Exception:+ time.sleep(0.05)+ continue+ if evt.get("delegation_id") == res["delegation_id"]:+ return evt+ process_registry.completion_queue.put(evt)+ time.sleep(0.05)+ finally:+ _approval_session_key.reset(token)+ raise AssertionError("completion event never reached the queue")+++async def test_notice_carries_the_run_sessions_model_and_api_calls(owner):+ job = jobs.create_job(prompt="report", schedule="every 1h", deliver="local")+ run_sid, fire = await admit_fire(owner, job["id"])+ owner.db._conn.execute("UPDATE sessions SET model = ?, api_call_count = ? WHERE id = ?",+ ("vendor/run-model", 3, run_sid))+ owner.db._conn.commit()++ def run_one_job(claimed, **kw):+ claimed["execution_id"] = fire # what the real run_one_job stamps on the claimed snapshot+ jobs.mark_job_run(claimed["id"], True)+ return True++ evt = _completion(job, run_one_job)+ assert (evt.get("model"), evt.get("api_calls")) == ("vendor/run-model", 3)+ text = format_process_notification(evt)+ assert "Role: cron_run Model: vendor/run-model" in text+ assert "API calls: 3" in text+++def test_notice_omits_fields_no_run_session_recorded(owner):+ job = jobs.create_job(prompt="report", schedule="every 1h", deliver="local")++ def run_one_job(claimed, **kw): # no execution id, no run session (e.g. a refused fire)+ jobs.mark_job_run(claimed["id"], True)+ return True++ evt = _completion(job, run_one_job)+ assert "api_calls" not in evt and not evt.get("model")+ text = format_process_notification(evt)+ assert "Model: ?" not in text and "API calls" not in text+ assert "Role: cron_run" in textdiff --git a/tests/tools/test_process_stdin_unavailable_error.py b/tests/tools/test_process_stdin_unavailable_error.pynew file mode 100644index 00000000000..5d2c65aa8b0--- /dev/null+++ b/tests/tools/test_process_stdin_unavailable_error.py@@ -0,0 +1,51 @@+"""process_manage write/submit on a background process without stdin names the fix that works.++A local ``terminal(background=true)`` spawn without ``pty=true`` connects stdin to /dev/null by+design; the old error blamed a "non-local backend or stdin closed", so agents retried blind.+"""+import pytest++from tools.process_registry import ProcessRegistry+++def registry():+ reg = ProcessRegistry()+ yield reg+ for sid in list(reg._running):+ reg.kill_process(sid)+++def _spawn_reader(registry):+ # Alive and waiting; a bare ``read`` would hit EOF on /dev/null and exit before the write.+ return registry.spawn_local("sleep 30", cwd=None, task_id="t-stdin")++[email protected]("posix")+def test_pipe_mode_write_says_to_relaunch_with_pty(registry):+ session = _spawn_reader(registry)+ result = registry.write_stdin(session.id, "hello\n")+ assert result["status"] == "error"+ assert "pty=true" in result["error"] and "non-local" not in result["error"]++[email protected]("posix")+def test_no_pty_advice_where_a_pty_cannot_be_had(registry, monkeypatch):+ import tools.process_registry_stdin as stdin_mod++ session = _spawn_reader(registry)+ monkeypatch.setattr(stdin_mod, "_pty_available", lambda: False)+ error = stdin_mod.stdin_unavailable_error(session)+ assert "pty=true would not help" in error+ session.output_log = "worker.log" # an isolated worker's log-backed spawn+ monkeypatch.setattr(stdin_mod, "_pty_available", lambda: True)+ assert "pty=true would not help" in stdin_mod.stdin_unavailable_error(session)+++def test_non_local_session_keeps_the_backend_explanation():+ from types import SimpleNamespace++ from tools.process_registry_stdin import stdin_unavailable_error++ error = stdin_unavailable_error(SimpleNamespace(process=None, output_log=""))+ assert "non-local terminal backend" in error and "pty=true" not in errordiff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex 6caf2188f7b..af73f6a1389 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -1012,8 +1012,10 @@ def _push_completion_event(record: dict[str, Any], result: dict[str, Any], statu"total_duration_seconds": result.get("total_duration_seconds"),**({"group": result["group"]} if result.get("group") is not None else {})}else:+ # A runner with no measured count (a cron run without a session) omits api_calls: never a fake 0.payload = {- "summary": result.get("summary"), "error": result.get("error"), "api_calls": result.get("api_calls", 0),+ "summary": result.get("summary"), "error": result.get("error"),+ **({"api_calls": result["api_calls"]} if result.get("api_calls") is not None else {}),"duration_seconds": result.get("duration_seconds", round(completed_at - dispatched_at, 2))}evt = {"type": "async_delegation", "delegation_id": record.get("delegation_id"),diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex 4ddee5a0e34..9563ccfd85d 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -503,9 +503,40 @@ def _background_session_key(session_id: Optional[str]) -> str:return session_key or (str(session_id) if session_id else "")+def _run_session_usage(job_id: str, execution_id: Optional[str]) -> dict[str, Any]:+ """``{"model", "api_calls"}`` the fire's run session recorded in state.db (summed over its+ compression chain), or ``{}`` when no run session exists (no_agent job, refused fire)."""+ if not execution_id:+ return {}+ import sqlite3++ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB+ # A missing or locked state.db costs the notice its usage line, never the completion.+ try:+ db = SessionDB(db_path=get_hermes_home() / "state.db", read_only=True)+ except (sqlite3.Error, OSError):+ return {}+ try:+ run = next((r for r in db.list_cron_job_runs(job_id, limit=50)+ if r.get("cron_execution_id") == execution_id), None)+ if run is None:+ return {}+ rows = [db.get_session(sid) or {} for sid in db.get_compression_chain(run["id"])]+ except sqlite3.Error as exc:+ logger.debug("cronjob run: run-session usage lookup failed for %s: %s", job_id, exc)+ return {}+ finally:+ db.close()+ model = next((r["model"] for r in reversed(rows) if r.get("model")), None)+ return {"api_calls": sum(int(r.get("api_call_count") or 0) for r in rows), **({"model": model} if model else {})}++def _manual_run_completion(- res: dict[str, Any], job_id: str, job_name: str, deliver: str, started_at: float) -> dict[str, Any]:- """Async-delegation completion block for a finished background manual run."""+ res: dict[str, Any], job_id: str, job_name: str, deliver: str, started_at: float,+ execution_id: Optional[str] = None) -> dict[str, Any]:+ """Async-delegation completion block for a finished background manual run. Model and API+ calls come from the run's own session; without one they are omitted, never guessed."""duration = round(time.time() - started_at, 2)refreshed = get_job(job_id) or {}lines = [@@ -521,7 +552,7 @@ def _manual_run_completion(lines += ["--- JOB OUTPUT ---", excerpt]return {"status": "completed" if res.get("success") else "error", "summary": "\n".join(lines),- "error": res.get("error"), "api_calls": 0, "duration_seconds": duration,+ "error": res.get("error"), "duration_seconds": duration, **_run_session_usage(job_id, execution_id),}@@ -604,7 +635,9 @@ def _try_dispatch_background_run(def _runner() -> dict[str, Any]:res = _run_claimed_job(claimed_job, extra_prompt=extra_prompt)- return _manual_run_completion(res, job_id, job_name, deliver, started_at)+ # run_one_job stamps the fire's ledger id onto this claimed snapshot.+ return _manual_run_completion(res, job_id, job_name, deliver, started_at,+ (claimed_job or {}).get("execution_id"))dispatch = dispatch_async_delegation(goal=f"Manual run of cron job '{job_name}' ({job_id})",diff --git a/tools/process_registry.py b/tools/process_registry.pyindex 5dbde9ea765..a23e12fd7e5 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -2285,8 +2285,8 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOureturn Nonedef _stdin_op(self, session_id: str, pty_op, pipe_op, ok: dict) -> dict:- """Run a stdin operation on a running session — ``pty_op(pty)`` under PTY mode,- else ``pipe_op(stdin)`` on the Popen pipe — and return *ok* on success."""+ """``pty_op(pty)`` under PTY mode, else ``pipe_op(stdin)`` on the Popen pipe; *ok* on success."""+ from tools.process_registry_stdin import stdin_unavailable_errorsession = self.get(session_id)if session is None:return _not_found(session_id)@@ -2296,7 +2296,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOuif session._pty:pty_op(session._pty)elif not session.process or not session.process.stdin:- return {"status": "error", "error": "Process stdin not available (non-local backend or stdin closed)"}+ return {"status": "error", "error": stdin_unavailable_error(session)}else:pipe_op(session.process.stdin)return okdiff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.pyindex 27ab6006742..cdc6b419bbb 100644--- a/tools/process_registry_notifications.py+++ b/tools/process_registry_notifications.py@@ -169,7 +169,7 @@ def _preamble(evt: dict, title: str, intro: str, completed_at: float, *, with_golines.append(f"Context you provided: {evt['context']}")if evt.get("toolsets"):lines.append(f"Toolsets: {', '.join(evt['toolsets'])}")- lines.append(f"Role: {evt.get('role') or 'leaf'} Model: {evt.get('model') or '?'}")+ lines.append(f"Role: {evt.get('role') or 'leaf'}" + (f" Model: {evt['model']}" if evt.get("model") else ""))return lines@@ -297,7 +297,8 @@ def _format_async_delegation(evt: dict) -> str:"you can act on the result or re-dispatch if things have changed.",completed_at, with_goal=True)lines += _notice_lines([evt]) + [- f"Status: {status} API calls: {evt.get('api_calls', 0)} Duration: {evt.get('duration_seconds', '?')}s"+ f"Status: {status}" + (f" API calls: {evt['api_calls']}" if evt.get("api_calls") is not None else "")+ + f" Duration: {evt.get('duration_seconds', '?')}s"+ (" [TRUNCATED: hit max_iterations — work may be incomplete]" if truncated else ""),"--- RESULT ---"]if status in _DONE and summary:diff --git a/tools/process_registry_stdin.py b/tools/process_registry_stdin.pynew file mode 100644index 00000000000..ce4daea3490--- /dev/null+++ b/tools/process_registry_stdin.py@@ -0,0 +1,25 @@+"""Why a background process has no writable stdin, phrased as the fix the agent can act on."""+import importlib.util+import sys+++def _pty_available() -> bool:+ return importlib.util.find_spec("winpty" if sys.platform == "win32" else "ptyprocess") is not None+++def stdin_unavailable_error(session) -> str:+ """Error for process_manage write/submit on a session without a stdin pipe or PTY.++ A local pipe-mode spawn connects stdin to /dev/null by design, so only a PTY relaunch can take+ input; that advice is wrong where ``spawn_local`` cannot give a PTY (an isolated worker writes+ output to a log, or the PTY library is missing), and a non-local backend has no live stdin."""+ if session.process is None:+ return ("Process stdin not available: it runs on a non-local terminal backend (or was recovered "+ "after a restart), which has no live stdin. Pass input non-interactively instead "+ "(arguments, a here-doc, or `printf ... | cmd`).")+ if session.output_log or not _pty_available():+ return ("This process was started without stdin, and this session cannot give background "+ "processes a pseudo-terminal, so pty=true would not help. Pass input non-interactively "+ "instead (arguments, a here-doc, or `printf ... | cmd`).")+ return ("This process was started without stdin (terminal background=true without pty=true). "+ "Relaunch it with terminal(background=true, pty=true) to send input.")