The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor: cron bot-chat delivery has no local CLI fallback lane
Teknium5d87060eb8c1
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.pyindex d9678ff9a35..2ddbeddd578 100644--- a/cron/scheduler_delivery.py+++ b/cron/scheduler_delivery.py@@ -14,13 +14,9 @@ import contextlibimport contextvarsimport loggingimport os-import shutil-import subprocess-import sysfrom dataclasses import dataclassfrom typing import Any, List, Optional-from hermes_cli._subprocess_compat import windows_hide_flags# Log-record parity with the origin module.logger = logging.getLogger("cron.scheduler")@@ -630,27 +626,16 @@ def _resolve_single_delivery_target(job: dict, deliver_value: str) -> Optional[dreturn _home_target(platform_name, chat_id) if chat_id else None-def _get_bot_chat_delivery_timeout() -> int:- """Timeout for one bot-chat delivery turn (a full agent turn — minutes, not seconds).- ``cron.bot_chat_delivery_timeout_seconds``; default 600."""- try:- cfg = _sched.load_config()- value = int(cfg.get("cron", {}).get("bot_chat_delivery_timeout_seconds", 600))- return value if value > 0 else 600- except Exception:- return 600--def _deliver_to_bot_chat(job: dict, content: str, profile: str) -> Optional[str]:- """Hand output to the live Bot Chat owner, or use the legacy unowned CLI lane.+ """Admit job output to the target profile's authority as a real inbound Bot Chat turn.- None means completed; a queued/claimed receipt returns an explicit unverified status- string so existing Optional[str] callers cannot misreport admission as delivery.- ``profile`` is ``""`` for the job's own profile.+ None means the target's durable receipt is settled; anything else is an explicit+ unverified status string so Optional[str] callers cannot misreport admission as+ delivery. ``profile`` is ``""`` for the job's own profile. There is no second-writer+ fallback: without a running authority the payload stays unverified for retry."""import hashlibimport json- import tempfileimport uuidfrom hermes_constants import get_hermes_homefrom hermes_cli.profiles import get_profile_dir@@ -679,92 +664,28 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str) -> Optional[str]ensure_ascii=False, separators=(",", ":"),).encode("utf-8")).hexdigest()# Read BEFORE discovery: the previous owner may have exited after accepting.- # No receipt state, including ambiguous/failed, authorizes a CLI replay.receipt = read_delivery_result(home, key)if receipt is None:owner = find_canonical_live_owner(home)- if owner is not None:- receipt = deliver_to_live_owner(home, owner, message, delivery_id=key)- if receipt is not None:- if receipt["message"] != message:- raise ValueError("delivery id already belongs to a different payload")- status = receipt["status"]- target = f"bot-chat:{profile_label}"- receipts = job.setdefault("_bot_chat_delivery_receipts", {})- receipts[target] = {"status": status, "delivery_id": key}- logger.info("Job '%s': Bot Chat %s receipt=%s status=%s",- job_id, profile_label, key, status)- if status == "settled":- return None- detail = ("completion unverified; do not resend" if status in ("queued", "claimed")- else receipt.get("error") or receipt.get("reason") or "not completed")- return f"{target} {status} (receipt {key}): {detail}"+ if owner is None:+ return f"bot-chat delivery to profile '{profile_label}' unverified: no canonical Bot Chat"+ receipt = deliver_to_live_owner(home, owner, message, delivery_id=key)+ if receipt["message"] != message:+ raise ValueError("delivery id already belongs to a different payload")+ status = receipt["status"]+ target = f"bot-chat:{profile_label}"+ receipts = job.setdefault("_bot_chat_delivery_receipts", {})+ receipts[target] = {"status": status, "delivery_id": key}+ logger.info("Job '%s': Bot Chat %s receipt=%s status=%s",+ job_id, profile_label, key, status)+ if status == "settled":+ return None+ detail = ("completion unverified; do not resend" if status in ("queued", "claimed")+ else receipt.get("error") or receipt.get("reason") or "not completed")+ return f"{target} {status} (receipt {key}): {detail}"except Exception as exc:- # Discovery/admission uncertainty must never open a second-writer fallback.return f"bot-chat delivery to profile '{profile_label}' unverified: {exc}"- hermes_bin = shutil.which("hermes")- if hermes_bin:- argv = [hermes_bin]- else:- try:- import importlib.util as _ilu- found = _ilu.find_spec("hermes_cli") is not None- except Exception:- found = False- if not found:- return "bot-chat delivery failed: hermes CLI not resolvable"- argv = [sys.executable, "-m", "hermes_cli.main"]-- def _fail(msg: str, **log_kwargs) -> str:- logger.warning("Job '%s': %s", job_id, msg, **log_kwargs)- return msg-- from agent.delegation_context import delegated_child_subprocess_env- env = delegated_child_subprocess_env(os.environ)- if profile:- argv += ["-p", profile]- # -p owns profile resolution; this scheduler's HERMES_HOME must not shadow it.- env.pop("HERMES_HOME", None)- else:- # Multiplex workers carry the profile in a ContextVar, not os.environ.- env["HERMES_HOME"] = str(source_home)-- query_file = None- try:- with tempfile.NamedTemporaryFile(- "w", encoding="utf-8", suffix=".txt", prefix="hermes-cron-botchat-", delete=False,- ) as fh:- fh.write(message)- query_file = fh.name-- argv += [- "chat", "--in", "~", "-c", "Bot Chat", "--create-if-missing",- "-Q", "--query-file", query_file,- ]- result = subprocess.run(- argv, capture_output=True, text=True, timeout=_get_bot_chat_delivery_timeout(), env=env,- creationflags=windows_hide_flags())- if result.returncode != 0:- tail = (result.stderr or result.stdout or "").strip()[-500:]- return _fail(- f"bot-chat delivery to profile '{profile_label}' failed (exit {result.returncode})"- + (f": {tail}" if tail else ""))- logger.info("Job '%s': delivered to Bot Chat of profile '%s'", job_id, profile_label)- return None- except subprocess.TimeoutExpired:- return _fail(- f"bot-chat delivery to profile '{profile_label}' timed out "- f"after {_get_bot_chat_delivery_timeout()}s (the bot's turn may "- "still complete; raise cron.bot_chat_delivery_timeout_seconds if "- "this recurs)")- except Exception as e:- return _fail(f"bot-chat delivery failed: {str(e) or type(e).__name__}", exc_info=True)- finally:- if query_file:- with contextlib.suppress(OSError):- os.unlink(query_file)-def _normalize_deliver_value(deliver) -> str:"""Normalize ``deliver`` to its canonical comma-separated string; ``"local"`` when falsy.diff --git a/tests/cron/test_cron_bot_chat_delivery.py b/tests/cron/test_cron_bot_chat_delivery.pyindex e8bc4a7983f..d92c3c05e2c 100644--- a/tests/cron/test_cron_bot_chat_delivery.py+++ b/tests/cron/test_cron_bot_chat_delivery.py@@ -2,16 +2,14 @@into a local profile's canonical Bot Chat session as a real inbound turn.Covers token parsing, target resolution (own profile / named / missing),-preflight exemption, create-time validation, the subprocess delivery lane,+preflight exemption, create-time validation, the canonical admission lane,and the delivery-targets listing used by UI pickers."""-import subprocessfrom unittest import mockimport pytest-from cron import scheduler as schedfrom cron import scheduler_delivery as sched_deliveryfrom cron.scheduler import _resolve_delivery_targetsfrom cron.scheduler_delivery import (@@ -114,95 +112,38 @@ def test_create_validation_accepts_bare_and_existing():# ── delivery lane ────────────────────────────────────────────────────────────-def _completed(returncode=0, stderr=""):- return subprocess.CompletedProcess(args=[], returncode=returncode, stdout="", stderr=stderr)---def test_deliver_runs_canonical_bot_chat_lane():- """The subprocess must use the Bot Mode agent-to-agent chat lane:- chat --in ~ -c "Bot Chat" --create-if-missing -Q --query-file <tmp>."""- calls = {}-- def fake_run(argv, **kwargs):- calls["argv"] = argv- calls["kwargs"] = kwargs- return _completed()-- with mock.patch.object(sched.subprocess, "run", side_effect=fake_run), \- mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "Daily digest"}, "the output", "")-- assert err is None- argv = calls["argv"]- assert argv[0] == "/usr/bin/hermes"- assert "-p" not in argv # own profile: subprocess inherits HERMES_HOME- assert "chat" in argv- assert "Bot Chat" in argv- assert "--create-if-missing" in argv- assert "-Q" in argv- assert "--query-file" in argv- # Message rides a temp file, never inline argv (quote/expansion safety).- assert not any("the output" in str(a) for a in argv)---def test_deliver_named_profile_uses_p_flag_and_clears_home():- calls = {}-- def fake_run(argv, **kwargs):- calls["argv"] = argv- calls["kwargs"] = kwargs- return _completed()-- with mock.patch.object(sched.subprocess, "run", side_effect=fake_run), \- mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"), \- mock.patch.dict(sched.os.environ, {"HERMES_HOME": "/tmp/other-profile"}):- err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "research")-- assert err is None- argv = calls["argv"]- assert argv[1:3] == ["-p", "research"]- # -p owns resolution; the scheduler's own HERMES_HOME must not leak in.- assert "HERMES_HOME" not in calls["kwargs"]["env"]---def test_deliver_failure_returns_error_string():- with mock.patch.object(- sched.subprocess, "run", return_value=_completed(returncode=1, stderr="boom")- ), mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "")- assert err is not None- assert "boom" in err---def test_deliver_timeout_returns_error_string():- with mock.patch.object(- sched.subprocess, "run",- side_effect=subprocess.TimeoutExpired(cmd="hermes", timeout=600),- ), mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "")- assert err is not None- assert "timed out" in err-+def test_deliver_message_carries_cron_attribution(tmp_path, monkeypatch):+ """The admitted turn self-identifies as scheduled output, not the user."""+ from tools import bot_live_delivery as mailbox-def test_deliver_message_carries_cron_attribution(tmp_path):- """The injected turn must self-identify as scheduled output, not the user."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))captured = {}- def fake_run(argv, **kwargs):- qf = argv[argv.index("--query-file") + 1]- with open(qf, encoding="utf-8") as fh:- captured["message"] = fh.read()- return _completed()-- with mock.patch.object(sched.subprocess, "run", side_effect=fake_run), \- mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- _deliver_to_bot_chat({"id": "j1", "name": "Daily digest"}, "the payload", "")+ def fake_deliver(home, owner, message, *, delivery_id):+ captured["message"] = message+ return {"status": "settled", "message": message, "delivery_id": delivery_id}+ monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: {"session_id": "local-bot"})+ monkeypatch.setattr(mailbox, "deliver_to_live_owner", fake_deliver)+ assert _deliver_to_bot_chat({"id": "j1", "name": "Daily digest", "execution_id": "r1"}, "the payload", "") is Noneassert 'Cronjob "Daily digest" output' in captured["message"]assert "not the user" in captured["message"]assert "the payload" in captured["message"]+def test_deliver_without_authority_is_unverified_not_a_second_writer(tmp_path, monkeypatch):+ """No running authority → explicit unverified status; never a local CLI turn."""+ import subprocess+ from tools import bot_live_delivery as mailbox++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(subprocess, "run", mock.Mock(side_effect=AssertionError("no local inference fallback")))+ monkeypatch.setattr(mailbox, "find_canonical_live_owner",+ mock.Mock(side_effect=ValueError("profile authority is not ready")))+ err = _deliver_to_bot_chat({"id": "j1", "name": "n", "execution_id": "r1"}, "out", "")+ assert err is not None and "unverified" in err and "not ready" in err++# ── delivery-targets listing (UI pickers) ────────────────────────────────────def test_delivery_targets_include_local_profiles():diff --git a/tests/cron/test_cron_live_bot_delivery.py b/tests/cron/test_cron_live_bot_delivery.pyindex 057db2224b1..920838f6eed 100644--- a/tests/cron/test_cron_live_bot_delivery.py+++ b/tests/cron/test_cron_live_bot_delivery.py@@ -1,5 +1,6 @@"""Cron admission must not become a second writer or a completed-delivery claim."""from pathlib import Path+import subprocessfrom unittest.mock import Mockfrom cron import scheduler_delivery as delivery@@ -37,7 +38,7 @@ def test_live_delivery_retry_keeps_receipt_across_owner_loss(tmp_path, monkeypatsource = tmp_path / "custom-home"monkeypatch.setenv("HERMES_HOME", str(source))subprocess_run = Mock(side_effect=AssertionError("live owner must not spawn CLI"))- monkeypatch.setattr(delivery.subprocess, "run", subprocess_run)+ monkeypatch.setattr(subprocess, "run", subprocess_run)from hermes_cli.profiles import get_profile_dirauthority = _FakeAuthority()@@ -82,7 +83,7 @@ def test_result_records_pending_until_terminal_receipt(tmp_path, monkeypatch):monkeypatch.setattr(mailbox, "authority_delivery", authority)monkeypatch.setattr(delivery._sched, "load_config", lambda: {})monkeypatch.setattr(config, "load_gateway_config", lambda: None)- monkeypatch.setattr(delivery.subprocess, "run", Mock(side_effect=AssertionError("CLI")))+ monkeypatch.setattr(subprocess, "run", Mock(side_effect=AssertionError("CLI")))updates = []monkeypatch.setattr(jobs, "update_job", lambda key, values: updates.append(values))job = dict(id="digest", execution_id="run", deliver="bot-chat")diff --git a/website/docs/developer-guide/cron-internals.md b/website/docs/developer-guide/cron-internals.mdindex 29b2b42e6c9..82971d21990 100644--- a/website/docs/developer-guide/cron-internals.md+++ b/website/docs/developer-guide/cron-internals.md@@ -286,7 +286,7 @@ Platforms in the first group have explicit, validated target syntax — named chFor **Telegram topics**, use `telegram:<chat_id>:<thread_id>` (e.g., `telegram:-1001234567890:17585`). For **Slack threads**, the third segment is the parent message's `thread_ts` (e.g., `slack:C0123ABCD45:1700000000.000100`), so it only applies when replying under an existing message.-**Bot Chat** (`bot-chat`, `bot-chat:<profile>`) is a machine-local pseudo-platform, not a gateway adapter. A mailbox-capable canonical live owner receives durable admission immediately (idle or busy); only that owner executes the incoming turn. `scheduler_delivery._deliver_to_bot_chat` resolves the target with `get_profile_dir` or the job's current `get_hermes_home`, derives the receipt ID from the source home, job ID, durable `execution_id`, and target home, and checks the receipt before discovering an owner. An existing receipt never permits CLI fallback. Without a mailbox owner it retains `hermes [-p <profile>] chat --in ~ -c "Bot Chat" --create-if-missing -Q --query-file <tmp>` and normal ownership fencing. Both lanes deliver a real inbound turn, not a transcript mirror. Queued/claimed receipts populate `last_delivery_queued` with receipt IDs. The delivery aggregator excludes admission notices from genuine errors and records execution `delivery_outcome=queued`; successful jobs use `last_status=delivery_queued`. Genuine errors on mixed targets take precedence as failed while retaining queued receipt metadata. The target profile’s durable receipt is authoritative for terminal completion. Queued is the historical admission outcome, not proof of delivery. Historical cron status does not automatically track later receipt completion. Bot-chat targets are excluded from `all` and credential preflight. Bot-chat-only external workers bypass the gateway delivery queue; mixed external-worker targets retain gateway handoff. `cron.bot_chat_delivery_timeout_seconds` (default 600) bounds only the legacy subprocess lane.+**Bot Chat** (`bot-chat`, `bot-chat:<profile>`) is a machine-local pseudo-platform, not a gateway adapter. A mailbox-capable canonical live owner receives durable admission immediately (idle or busy); only that owner executes the incoming turn. `scheduler_delivery._deliver_to_bot_chat` resolves the target with `get_profile_dir` or the job's current `get_hermes_home`, derives the receipt ID from the source home, job ID, durable `execution_id`, and target home, and checks the receipt before discovering an owner. There is no local CLI fallback: without a running authority (or without a canonical Bot Chat) the delivery is recorded as unverified and the payload is retained for the next run, so the scheduler can never become a second writer to the profile's store. Delivery is a real inbound turn, not a transcript mirror. Queued/claimed receipts populate `last_delivery_queued` with receipt IDs. The delivery aggregator excludes admission notices from genuine errors and records execution `delivery_outcome=queued`; successful jobs use `last_status=delivery_queued`. Genuine errors on mixed targets take precedence as failed while retaining queued receipt metadata. The target profile’s durable receipt is authoritative for terminal completion. Queued is the historical admission outcome, not proof of delivery. Historical cron status does not automatically track later receipt completion. Bot-chat targets are excluded from `all` and credential preflight. Bot-chat-only external workers bypass the gateway delivery queue; mixed external-worker targets retain gateway handoff.### Response Wrappingdiff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex 36a3aadb1a1..2ccc687f2f6 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -496,7 +496,7 @@ error. A delivery failure does not count toward the job's `failure_streak`- `bot-chat:<profile>` targets another profile **on the same machine**. Names are validated against `hermes profile list` when the job is created; profiles on other gateways or machines can never be targeted, so same-named profiles across machines are unambiguous.- Each delivery costs the target bot one full agent turn — mind the schedule frequency.- Composes with other targets (`bot-chat,telegram`) but is never included in `all`.-- If the canonical chat is open in a mailbox-capable Desktop/TUI backend, delivery is **durably queued immediately**, whether the bot is idle or busy. Only that live owner runs the incoming turn; cron does not start a competing CLI writer. Without a live mailbox owner, the existing `hermes chat -c "Bot Chat" --create-if-missing` lane remains available (normal session ownership checks still apply).+- If the canonical chat is open in a mailbox-capable Desktop/TUI backend, delivery is **durably queued immediately**, whether the bot is idle or busy. Only that live owner runs the incoming turn; cron does not start a competing CLI writer. If the target profile's gateway is not running, the delivery is recorded as unverified and retried on the next run; cron never starts its own Bot Chat turn.- **Queued is not completed.** Cron records receipt IDs and `queued`/`claimed` statuses in `last_delivery_queued`, with delivery outcome `queued` (neither delivered nor failed). A successful job shows `delivery_queued`; genuine errors on other targets still take precedence as delivery failures. The bot may complete later. The durable receipt in the target profile's `runtime/bot_live_delivery/<receipt-id>.json` is authoritative; cron's historical status is not automatically refreshed.- Rechecking the same execution inspects its existing receipt, even if the owner has disappeared. It never falls back to another writer after acceptance. `failed`, `cancelled`, or `ambiguous` receipts are not automatically replayed; inspect the chat and receipt before intentionally starting new work. Each new cron execution has a distinct delivery ID.@@ -725,17 +725,9 @@ cron:Or set the `HERMES_CRON_MEDIA_SEND_TIMEOUT` environment variable. The resolution order is: env var → config.yaml → 300s default. A timed-out attachment is recorded in the job's run status as a partial delivery failure (the text still delivers).-## Bot Chat delivery timeout+## Bot Chat delivery completion-A `bot-chat` delivery runs a full agent turn in the target bot's chat, so its bound is minutes, not seconds — 600s by default:--```yaml-# ~/.hermes/config.yaml-cron:- bot_chat_delivery_timeout_seconds: 900-```--A timed-out delivery is recorded in `last_delivery_error`; the bot's turn may still complete on its own.+A `bot-chat` delivery is admitted to the target profile's running gateway and executed there as a full agent turn. The job's run status records the admission receipt (`delivery_outcome=queued`) until the target's durable receipt settles; a retry of the same run reuses the same receipt and never re-admits. If the target profile's gateway is not running, the delivery is recorded as unverified and no local fallback turn is run.## No-agent mode (script-only jobs)