Skip to content

The agent that grows with you

fix(cron): Bot Chat delivery creates the missing Bot Chat instead of failing the run

teknium1364a0e22b910
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index e7008c853a6..951670bf2c8 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -29,13 +29,14 @@ def _home(authority, actor, profile):
def _target(authority, actor):
row = authority.db.get_session_by_title('Bot Chat')
if row is None:
- raise RuntimeStoreError('not_found')
- tip = authority.db.get_compression_tip(row['id'])
- target = authority.db.get_session(tip)
- if target is None:
- raise RuntimeStoreError('not_found')
- from gateway.session_local_migration import resolve_local_target
- ref = resolve_local_target(authority, actor, target['id'])
+ ref = _create_bot_chat(authority, actor)
+ else:
+ tip = authority.db.get_compression_tip(row['id'])
+ target = authority.db.get_session(tip)
+ if target is None:
+ raise RuntimeStoreError('not_found')
+ from gateway.session_local_migration import resolve_local_target
+ ref = resolve_local_target(authority, actor, target['id'])
authority.authorize(actor, ref, 'session:submit')
live = authority.sessions[ref.session_id]
entry = authority.runner.session_store.lookup_by_session_key(live.route)
@@ -44,6 +45,22 @@ def _target(authority, actor):
return ref, live, entry
+def _create_bot_chat(authority, actor):
+ """No Bot Chat yet: mint it the way ``hermes chat --in ~ -c "Bot Chat" --create-if-missing``
+ did on the CLI lane this door replaced, so a fresh profile's first delivery has somewhere
+ to land instead of being recorded as failed. Same owner step as ``session.create`` with a
+ title: no await between the lookup and the titled creation. Creation is the actor's own
+ capability; a submit-only principal (owner recovery) still gets ``not_found``."""
+ if 'session:create' not in actor.capabilities:
+ raise RuntimeStoreError('not_found')
+ from gateway.session_local import create_local_session
+ from gateway.session_local_title import title_new_session
+ ref = create_local_session(authority, actor, {
+ 'request_id': 'bot-chat:' + authority.profile_id, 'source': 'cli', 'cwd': str(Path.home())})
+ title_new_session(authority, ref, 'Bot Chat')
+ return ref
+
+
def _result(authority, record):
row = get_session_admission(authority.db, admission_id=record['admission_id'])
if row is None:
diff --git a/tests/cron/test_cron_bot_chat_create_if_missing.py b/tests/cron/test_cron_bot_chat_create_if_missing.py
index e6246027a6e..5b48e15d736 100644
--- a/tests/cron/test_cron_bot_chat_create_if_missing.py
+++ b/tests/cron/test_cron_bot_chat_create_if_missing.py
@@ -5,14 +5,15 @@ door must keep that semantics, or a fresh profile's very first ``deliver: bot-ch
recorded as failed with nowhere to land.
"""
from contextlib import closing
+from http.server import ThreadingHTTPServer
import json
from pathlib import Path
import sqlite3
+import threading
import pytest
-from tests.gateway.fixtures.local_recovery_probe import child_env, daemon
-from tests.gateway.test_normal_runtime_boot import model_peer
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon
@pytest.mark.linux_only
@@ -21,11 +22,17 @@ def test_cron_bot_chat_delivery_creates_the_missing_bot_chat_and_admits(tmp_path
home, user = tmp_path / 'state', tmp_path / 'user'
home.mkdir(mode=0o700)
user.mkdir()
- with model_peer() as (url, peer):
+ model = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ model.requests = []
+ model.blocked, model.release = threading.Event(), threading.Event()
+ threading.Thread(target=model.serve_forever, daemon=True).start()
+ url = f'http://127.0.0.1:{model.server_port}/v1'
+ try:
(home / 'config.yaml').write_text(json.dumps({
'gateway': {'multiplex_profiles': False},
'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': url},
- 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)}}))
+ 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)}}),
+ encoding='utf-8')
env = child_env()
env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')
@@ -48,3 +55,6 @@ def test_cron_bot_chat_delivery_creates_the_missing_bot_chat_and_admits(tmp_path
assert db.execute("SELECT count(*) FROM sessions WHERE title='Bot Chat'").fetchone()[0] == 1
targets = {row[0] for row in db.execute('SELECT target_session_id FROM session_admissions')}
assert len(targets) == 1, (first, second, targets)
+ finally:
+ model.shutdown()
+ model.server_close()
diff --git a/tests/tools/test_bot_live_owner_delivery.py b/tests/tools/test_bot_live_owner_delivery.py
index c87126856f3..0f48cdc62e2 100644
--- a/tests/tools/test_bot_live_owner_delivery.py
+++ b/tests/tools/test_bot_live_owner_delivery.py
@@ -117,7 +117,9 @@ def test_canonical_owner_is_the_authority_and_follows_compression(tmp_path, monk
try:
db.create_session(session_id="scratch", source="cli")
db.set_session_title("scratch", "Scratch")
- assert mailbox.find_canonical_live_owner(tmp_path) is None # no Bot Chat
+ # No Bot Chat yet is still a deliverable owner: the authority creates the chat on
+ # first delivery (create-if-missing), so discovery reports an empty tip, not None.
+ assert mailbox.find_canonical_live_owner(tmp_path)["session_id"] == ""
db.create_session(session_id="chat", source="cli")
db.set_session_title("chat", "Bot Chat")
owner = mailbox.find_canonical_live_owner(tmp_path)
diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.py
index 19e3306ac02..1c6f3b3047c 100644
--- a/tools/bot_live_delivery.py
+++ b/tools/bot_live_delivery.py
@@ -25,7 +25,11 @@ _TERMINAL = frozenset({"settled", "failed", "cancelled", "ambiguous"})
def find_canonical_live_owner(profile_home: Path | str) -> dict[str, Any] | None:
- """Discover the profile authority and exact Bot Chat without acquiring a lease."""
+ """Discover the profile authority and its exact Bot Chat without acquiring a lease.
+
+ ``session_id`` is the current Bot Chat tip, or ``''`` when the profile has none yet: the
+ authority's deliver door creates it on first delivery (main's ``--create-if-missing``),
+ so a missing chat is not a refusal. None only when the profile has no store at all."""
from hermes_cli.gateway_runtime import discover_gateway_endpoint
from hermes_state import SessionDB
@@ -41,10 +45,8 @@ def find_canonical_live_owner(profile_home: Path | str) -> dict[str, Any] | None
tip = db.get_compression_tip(row['id']) if row else None
finally:
db.close()
- if not tip:
- return None
- return dict(profile_home=str(home), session_id=tip, canonical=True,
- lease_id=discovery.endpoint.instance_id, live_session_id=tip)
+ return dict(profile_home=str(home), session_id=tip or '', canonical=True,
+ lease_id=discovery.endpoint.instance_id, live_session_id=tip or '')
def authority_delivery(home, params):
@@ -75,7 +77,9 @@ def authority_delivery(home, params):
def _owner(home: Path | str, owner: dict[str, Any]) -> dict[str, str]:
pinned = {key: owner.get(key) for key in _OWNER_KEYS}
- if not all(isinstance(value, str) and value for value in pinned.values()):
+ # An empty session_id is the discovered "no Bot Chat yet" state; the door creates it.
+ if not all(isinstance(value, str) and (value or key in ("session_id", "live_session_id"))
+ for key, value in pinned.items()):
raise ValueError("owner requires profile_home, session_id, lease_id and live_session_id")
if pinned["profile_home"] != str(Path(home).resolve()):
raise ValueError("owner belongs to a different profile home")
@@ -133,7 +137,7 @@ def deliver_to_live_owner(
home = Path(profile_home).resolve()
return authority_delivery(home, dict(id=_delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex),
profile=home.name if home.parent.name == "profiles" else "default",
- message=message, session_id=pinned["session_id"],
+ message=message, **({"session_id": pinned["session_id"]} if pinned["session_id"] else {}),
**({"author": dict(author)} if author else {})))
diff --git a/website/docs/developer-guide/cron-internals.md b/website/docs/developer-guide/cron-internals.md
index 15772cad74f..3d4d44699c8 100644
--- a/website/docs/developer-guide/cron-internals.md
+++ b/website/docs/developer-guide/cron-internals.md
@@ -327,7 +327,7 @@ Platforms in the first group have explicit, validated target syntax — named ch
For **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. 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.
+**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. A profile with no Bot Chat yet gets one created by the authority on first delivery (the `--create-if-missing` semantics of the retired CLI lane). There is no local CLI fallback: without a running authority the run is recorded `delivery_failed` with the reason in `last_delivery_error` and the output kept under `hermes cron runs`; it is not redelivered automatically, and the scheduler never becomes 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 Wrapping
diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.md
index 08e848104c3..efe4728aa9a 100644
--- a/website/docs/user-guide/features/cron.md
+++ b/website/docs/user-guide/features/cron.md
@@ -542,7 +542,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. 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.
+- 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. A profile that has no Bot Chat yet gets one created on first delivery. If the target profile's gateway is not running, the run is recorded `delivery_failed` with the reason (the output stays in `hermes cron runs`; it is not redelivered automatically) and 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.
@@ -778,7 +778,7 @@ Or set the `HERMES_CRON_MEDIA_SEND_TIMEOUT` environment variable. The resolution
## Bot Chat delivery completion
-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.
+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 run is recorded `delivery_failed` and no local fallback turn is run.
## No-agent mode (script-only jobs)