A parent blocked inside delegate_task only drains its steer queue after the tool
returns, i.e. after the child finishes. On Telegram (busy_input_mode=steer, the
/steer command, and the PRIORITY path) the gateway queued the text on that parent
alone and acked "Steered into current run", so a looping delegated child never saw
it (#112095). Fan the text out to running_agent._active_children — the same
identity-scoped snapshot interrupt() uses — and make the ack say where it went.
Closes the remaining atoms of #112600.
A) The CLI startup path already passes `-m` as target_model (c358a6fba0), but
its siblings still resolved credentials against config's `default`: the CLI
auth-fallback rung, `--resume` credential re-resolution, the gateway
provider-override helper (channel overrides, persisted /model switches,
API-server provider refresh), the gateway fallback chain, the TUI /model
switch-from runtime and ACP agent construction. With a `*-free` default the
OpenCode free-tier rung fired first and a Go-only model was built against
the keyless Zen relay ("Model mimo-v2.5 is not supported"). Each now passes
the effective model; `_resolve_runtime_agent_kwargs_for_provider` grows an
optional `target_model` and the two test stubs of it accept the kwarg.
B) normalize_opencode_base_url rewrote the /zen vs /zen/go segment for ANY
provider matched by opencode_provider_family, including custom providers
merely named after a family (`opencode-go-bridge`, #85589) whose relay the
user declared explicitly in `providers:`. The family heal now applies to the
built-in canonical providers only; custom prefix-named providers keep their
per-model api_mode routing and /v1 handling. Documented in the providers
guide.
C) Same function: the official-host check uses parsed.hostname (a port no
longer defeats the heal) and only the path is edited, so query/fragment
round-trip instead of being dropped.
Fixes#112600
The flush payload's ``ts`` is ``int(time.time())`` while ``sessions.started_at`` is a REAL, so
``started_at > not_after`` rejected a row minted later in the same second as the flush — the
common "message arrives, session minted, SIGTERM" shape lost recoverability (file preserved, not
misrouted). Compare ``floor(started_at)`` against the whole-second ``ts`` so same-second rows
are adopted and only rows from a later second are refused.
Spotted by the round-2 gate on the salvage stack.
`_db_for_key` deliberately returns None for a named-profile key whose home cannot be
resolved (fail closed, #66887/#102157), but `resolve_session_id_for_key` returned
`(session_id, None)` on a routing-map hit, and `_recover_one_payload` treated that None
as "fall back to session_db" — the owned ROOT state.db at the production call site. A
profile message with an unopenable home was appended to the root store: the very
split-identity write the fail-closed return exists to prevent.
- resolver: an unresolvable store answers None before the peek and the row fallback
(None already means "preserve the flush file").
- recovery: the resolver's db is authoritative for resolver-resolved payloads; the owned
default store only serves payloads that already carry a session_id (and cap-drop spool).
- `started_at` is `REAL NOT NULL` in the schema, so the `float()` fence stays as is.
resolve_session_id_for_key calls the peer finder directly, while the
sibling _query_recoverable_row also applies _recovered_row_matches_source_scope
and _recovered_row_allowed_for_active_profile. Read both fences against the
resolver's call shape; both are redundant there, so this adds a WHY comment
at the call site rather than a fence call.
- Profile fence: it returns True immediately when recovered.session_key ==
requested key. The resolver passes no chat_id/chat_type, so
find_latest_gateway_session_for_peer returns after the _PEER_BY_KEY_SQL
branch (`s.session_key = ?`) or None; the tuple fallback is unreachable.
Every hit therefore carries the requested key and the fence is a no-op.
- Slack workspace fence: it compares origin_json.scope_id with
source.scope_id. The resolver has no SessionSource (only the key), and a
scoped Slack key embeds the scope_id as its own slot
(`<ns>:slack:<chat_type>:<scope_id>:...`, build_session_key). An exact
key match therefore already pins the workspace, regardless of whether
the row lives in a profile store or a non-multiplexed root store — the
store choice (_db_for_key) partitions by profile, not by workspace, and
the key does the workspace work in either store. The sibling needs the
fence only because it also looks up the UNscoped legacy key, whose row
can belong to any workspace; the resolver never does that lookup.
_find_gateway_session_row and resolve_session_id_for_key each carried the
same guarded call: getattr the finder off a possibly-None db, check
callable, try/except -> debug log -> None. Extract it as the mixin-private
static `_peer_row(db, *, source, session_key, raise_on_lookup_error=False,
**peer)` and call it from both sites.
Behaviour is unchanged at both call sites: the tuple site passes
user_id/chat_id/chat_type/thread_id through **peer with the same
allow_peer_fallback gating and keeps raise_on_lookup_error; the exact-key
site passes only source + session_key, so the finder's tuple fallback
still never runs there. The only observable difference is the resolver's
failure debug line, which now reads "Gateway session DB recovery failed"
(shared) instead of "Session key->id resolution failed"; no test asserts
on either.
The platform-slot parse (parts[2]) in resolve_session_id_for_key is left
in place: the only key-parsing helper on the mixin,
_profile_from_session_key, returns the profile namespace (parts[1]) and
nothing returns the platform slot, so there is nothing to fold onto.
Follow-up to the #75536 + #106112 picks; changes vs #106112:
- Routing map first: peek_session_id (sessions.json) is authoritative for
the session a message was routed to at shutdown. The durable-row lookup
(find_latest_gateway_session_for_peer under the exact key) is only the
fallback for a pruned map.
- Fence added per gysyl's #106112 review: a row whose started_at is later
than the flush payload's ts (passed as not_after by _recover_one_payload)
cannot be the message's origin and is never adopted; None is returned so
the flush file is preserved instead of appending into a newer session.
- WhatsApp phone<->LID alias expansion dropped: main's session_recovery
does no alias expansion anywhere else, and re-implementing it here made
the resolver diverge from the recovery path it sits beside. Exact-key
match only.
- The private _db_for_key reach stays inside SessionRecoveryMixin so the
(session_id, db) pair lands the append in the owning profile partition;
shutdown_flush never touches store internals.
`recover_pending_to_db` walks the shutdown flush spool and appends each
pending message back into state.db. Its per-file `try` listed
`except BaseException:` above `except Exception as exc:`. Exception is a
BaseException subclass, so the ordinary-error handler was unreachable and
every ordinary failure took the interrupt path: close the owned DB and
re-raise.
The effect is that a single unrecoverable spool file aborts the entire
recovery pass. Because the file is only unlinked after a successful
append, it survives and re-poisons the next boot, and the pass is walked
in `sorted(glob("*.json"))` order over uuid4-named files, so a different
subset of the user's pending messages is stranded each time. The caller in
`gateway/run.py` wraps the call in `except Exception: pass`, so nothing is
logged — the messages simply never come back.
Reordering the two handlers restores the documented per-file behaviour
("Leave the file for next startup retry") while keeping the interrupt
contract exactly as written: a KeyboardInterrupt, SystemExit or
CancelledError still closes an owned SessionDB and propagates.
recover_pending_to_db skipped every real flush file: _serialise_value
captures only the text field from adapter MessageEvent objects (they
have no session_id attribute), so recovery always hit the 'no
session_id' skip branch — messages queued during a gateway drain were
written to disk and then silently never re-ingested, despite the
user-facing 'queued for the next turn' promise. The existing tests
masked it by hand-writing session_id into payloads real events never
produce. Add an optional session_resolver parameter and wire it to
SessionStore.peek_session_id at the startup call site; files remain
preserved (with the warning) when a key genuinely can't resolve.
The probe helpers had been appended to the gateway/run.py facade and the three watchers each
carried their own copy of the "probe → fail open → offload" shell, with gateway code parsing
loop/heartbeat rows itself. One sibling now owns the gate shape (_gate + off_loop_gate), and
hermes_cli.loops.store_has_active_loop / hermes_cli.heartbeat.store_has_active_heartbeat own
what an ACTIVE row is (heartbeat gains the _META_PREFIX loops already had). One fail-open layer
per read: has_pending_handoffs is a bare bounded query, the gate catches. The loop watcher calls
its executor hop directly — it already did so unconditionally for the scan, so the
"runner without a hop" fallback there was dead.
_watched_homes reused _handoff_watch_scopes, which deliberately omits "default" because the
handoff/loop watchers' root poll covers the launch home. For a `hermes -p work` multiplexer the
launch home is profiles/work, so ~/.hermes was probed by nobody and an active heartbeat there
answered "idle" every tick. Probe the served set the sweep can actually resolve to.
The loop watcher's probe used ``list_active_loops()``, which collapses an unavailable
SessionDB (and any read error) to ``[]`` — the gate then skipped that profile on every tick
(fail CLOSED). The heartbeat probe keyed on ``heartbeat:*`` key existence, but ``clear`` and
``pause`` keep their rows, so one past /heartbeat re-enabled the full sweep forever.
Both probes now read the rows through one ``_profile_meta_rows`` helper (None = store
unavailable → treat as work present) and parse the status themselves: only an ACTIVE row
opens the gate; a corrupt row is "unknown" and keeps the historical scan. The heartbeat
gate reuses ``_handoff_watch_scopes`` for the served homes instead of a second resolver.
The handoff watcher (2s interval) and loop wakeup watcher (15s) entered
_async_profile_runtime_scope for EVERY served profile on EVERY tick — a
full config.yaml/.env parse plus secrets hydration per entry — even when
the profile's state.db held zero pending handoffs or active loops. On a
multiplex gateway this, not message traffic, was the idle CPU driver
(py-spy: ~75% of on-CPU time in YAML parsing from these two paths).
Both watchers now probe the profile's cached SessionDB first (only the
HERMES_HOME contextvar installed, off the loop thread via the runner's
executor hop) and enter the scope only when work exists:
- handoff watcher: new SessionDB.has_pending_handoffs() existence probe
- loop watcher: list_active_loops() under the probe context
All probes fail OPEN (error/unknown -> historical always-enter
behavior); runners without the executor hop (test stand-ins) skip the
gate, so existing watcher tests are unaffected. The startup
stale-handoff reclaim stays ungated: it runs once per boot and must
also see 'running' leftovers, which a pending-only probe would miss.
The 5s goals poller calls restore_heartbeat_watches(), which listed every
routed session and entered _profile_runtime_scope for each distinct origin
— a full config.yaml/.env parse plus secrets hydration per session per
scan. With zero heartbeats persisted (the common idle case) the entire
sweep is wasted work; on a 400-session multiplex gateway it dominated
idle CPU (~60% of on-CPU time in YAML parsing).
Gate the sweep on an indexed heartbeat:* prefix probe of each served
profile's SessionDB (HERMES_HOME contextvar only — no config/secret
scopes). Probe failures fail open to the historical full sweep.
Review follow-up on the one-shot state.db -> shared-state.db import (#109775):
- A room id present in both stores is skipped as a unit. Grafting the
legacy events under the store's own room left next_seq behind MAX(seq)
and every later append_event collided on (room_id, seq).
- Columns only the target has are selected with the same defaults the
in-place column migration applies ('legacy' authority, epoch 1, legacy
actor json), and room-scoped tables use a plain INSERT under a
savepoint. INSERT OR IGNORE used to swallow the NOT NULL violations of
a pre-Sep-2 layout, drop every row and still record the marker with
rooms=0. event_bytes is backfilled for the copied rooms.
- An unreadable or refused legacy store is remembered per process, so
the warning fires once and the retry happens on the next start instead
of on every poll.
- The import lives in gateway/hosted_rooms_legacy_import.py; the facade
keeps only the _connect seam.
0e422e0ece repointed default_db_path() at the root shared-state.db but left the hosted_room* rows in the old state.db, so every pre-existing room resolved to HostedRoomError("hosted room not found") after the upgrade.
The first open of a shared-state.db now copies the hosted_room* tables from its sibling state.db inside the schema transaction: INSERT OR IGNORE keeps what the new store already owns, a marker row makes the import one-shot (a later purge is not undone by a re-import), and the driver lease table stays behind because a copied lease names a process that is gone. A locked or unreadable legacy store only skips this open, leaving the marker unset to retry on the next one.
The parent commit only stamped a tool_reason on the watchdog producers, so a
reason-less hard_cancel still minted "explicit stop requested" (a USER reason)
for gateway stop/restart, session eviction while a turn runs, abandoned SSE
runs and TUI/desk shutdown - the exact confusion class of #112647, failing open
toward "user". Pass a system tool_reason at those producers (run_shutdown,
run_agent_cache via the eviction caller only - /stop and /new stay user-owned -
and api_server) so only genuine surface stops book interrupted_by_user.
InterruptScope.cancel now takes tool_reason so the Hermes Console user-cancel
branch is attributed to the user; the console timeout keeps the host slug.
Also repairs the red CI: the cross-process lease tests stub agent.interrupt
with (message, hard_cancel) only, so the new tool_reason kwarg raised TypeError
inside the lease's fallback and the stub never fired. Widen the doubles, and
update the two shutdown mocks that asserted the exact interrupt() call.
Every hard interrupt reached `begin_iteration` through the same `_interrupt_requested`
flag, so the turn loop booked all of them as `interrupted_by_user` — a cron run killed
by the scheduler's inactivity watchdog, a turn aborted by the liveness watchdog, a lost
session turn lease and a gateway inactivity timeout all read as a human pressing stop,
and the investigation went to the wrong subsystem (#112647).
`interrupt()` already records a trusted category per interrupt (`_tool_interrupt_reason`,
fed by the `tool_reason` every producer can pass through `request_hard_interrupt`). The
exit reason is now derived from it: the three categories `interrupt()` itself mints for
human stops keep `interrupted_by_user` / `interrupted_during_api_call`; any other
category names its producer — `interrupted_by_system(cron_inactivity_watchdog)`,
`interrupted_during_api_call(turn_liveness_watchdog)`. The system producers that passed
no `tool_reason` (cron inactivity watchdog, turn liveness watchdog, lease loss, gateway
inactivity timeout) now name themselves, so the model-visible tool-cancellation text
says the same thing. `_publish_interrupt_state` logs ONE line naming the source so the
turn record and the log agree.
No change to WHEN anything interrupts. `interrupted_during_api_call` moves to the
prefix-matched explanation table so the parameterised form keeps its user copy.
Slim redo of #112652 by @KoNit-K, which added a parallel `issuer` attribute and
keyword; this reuses the existing `tool_reason` plumbing instead.
Co-authored-by: KoNit-K <124019182+KoNit-K@users.noreply.github.com>
Follow-up to the #112725 salvage. When a gateway clarify batch stops at an
unanswered question, the batch payload only said `timed_out: true` with blank
answers — so a card the platform REJECTED ("[clarify prompt could not be
delivered]") read exactly like a user who walked away, which is the misreport
#112684 describes ("a timeout must not be presented as user inactivity when the
prompt was never delivered").
- gateway/run_turn_runner.py::_clarify_batch_sync: the unanswered question's
own response text rides along as `notice`.
- tools/clarify_tool.py::_run_batch/_batch_result: pass `notice` through into
the result JSON beside `timed_out` (only when present); schema description
mentions it. CLI/TUI batch callbacks send no notice -> byte-identical output.
- tests: fold the single-question re-arm pin into the existing bracket-answer
test (<=2 new tests), parametrize the end-to-end test over an undeliverable
Telegram-shaped adapter so the delivery sentinel is pinned as `notice`.
- docs: tools-reference.md describes `notice`.
Part of #112684
clarify_tool loops a callback that cannot take its `questions=` batch form one
question at a time, and that loop can only tell "no answer arrived" from the
sentinel text the callback returns. The gateway callback was such a surface:
_clarify_send_then_wait returns "[user did not respond within Nm]", and
_clarify_send_disposition returns "[clarify prompt could not be delivered]".
Neither is recognized by the loop, so the sentinel was stored as that
question's answer and the next question was asked anyway.
Effect: a gateway batch — one clarify call with several questions, the shape
the tool schema prefers ("several INDEPENDENT questions belong in ONE call") —
blocked for one full clarify_timeout per question (10m default), never set
timed_out, and handed the agent a user response the user never gave.
This surface already knows whether an answer arrived: _clarify_send_then_wait
returns `answered`. So the batch is answered here instead of inferred from
text: _clarify_callback_sync(..., questions=[...]) asks one card per question,
stops at the first unanswered one (retiring that card), and returns
{"answers": {qid: raw}, "timed_out": bool} — the shape clarify_tool's batch
path reads and the tui_gateway bridge (tui_gateway/agent_callbacks.py) already
implements.
The per-question body is the extracted _ask_clarify_question, so the
single-question path keeps its exact behaviour: same sentinel text, same card
retirement, same immediate typing re-arm, same "" when no status adapter is
wired. Within a batch the stream/typing re-arm waits for the last question —
between two cards it only opens a bubble that the next question's boundary
finalizes immediately.
Measured with the real TurnRunner._clarify_callback_sync against a duck-typed
card adapter (tests/gateway/test_clarify_card_retire_on_timeout.py):
before, 3 questions, no answer:
cards asked ['One?', 'Two?', 'Three?'] (each waits one clarify_timeout)
payload the sentinel text as each question's answer, no timed_out
after:
cards asked ['One?']
payload {"answers": {}, "timed_out": true}
A committed proactive tool-result prune (`prune_tool_results_only`, driven from
`agent/turn_preflight.py::compress_after_tool_results`) demotes old skill_view and
read_file bodies to one-line markers, but only the full-compaction path called
`_reset_read_dedup_caches`. The repeat-view dedup therefore kept answering
"unchanged / content_returned: false" for content that no longer existed in the
transcript, so the `[SKILL_PRUNED: ... reload with skill_view(...)]` marker asked
for a reload the tool then refused (#112763). Treat the committed prune as the same
content-loss boundary compaction already is: reset the task's read/skill dedup right
where the pruned list is committed.
Sibling surface: manual `/compress` on CLI, TUI and the messaging gateway called
`compress_now()` without `task_id`, so the boundary reset hit the "default" bucket
instead of the session's. Pass the session-scoped task id on all three.
Test double in tests/hermes_cli/test_cli_manual_compress.py gains the `task_id`
kwarg the real `_compress_context` facade already accepts.
Supersedes #103268 (@jo0wz), which reached the same path with a process-global
ghost registry (not task-keyed, skill_view only).
Slim follow-up on the #112160 pick (KoNit-K) that also lands the #113031 mechanism:
- gateway/response_filters.py::display_kind_for_event maps the poller-stamped
`_heartbeat_session_id` provenance to the machinery display kind, so a bare
NO_REPLY / [SILENT] on a scheduled heartbeat turn is honoured instead of being
replaced with the "model returned only a silence marker" warning every interval.
The event stays non-internal on purpose: authorization and the emergency stop
still apply (test_idle_wake_coalesces_intervals_while_adapter_owns_turn).
Ported from #112279 (earliest filer), collapsed onto the existing stamp instead
of a second flag.
- gateway/run_goals.py::_synthetic_prompt_event drops the stored source's
message_id: a synthetic prompt is not a reply to the message that registered
the watch, and every consumer (progress, status, footer, final reply) fell back
to it as the Telegram reply anchor — the stale quote in #112149. Telegram DM
topics route anchorless via direct_messages_topic_id (designed path), so this
replaces #112160's allow_source_message_id_fallback plumbing across
platforms/base.py, run.py and run_turn.py (dropped hunks).
- gateway/platforms/base.py: no typing indicator for a heartbeat turn (re-applied
from #112160 after taking main's file back).
- Tests: poller test asserts the provenance + anchorless source (red on base);
test_gateway_silence_tokens gains the heartbeat-silence invariant (red on base).
#112160's _thread_metadata_for_event test dropped with its mechanism.
- Docs: heartbeat page documents the quiet turn.
Co-authored-by: Kevin Rajan <7121943+kvnloo@users.noreply.github.com>
Co-authored-by: MrAtkeens <99114477+MrAtkeens@users.noreply.github.com>
The parent commit persists a reasoning-only clean stop as ``content=""`` with the
promoted reply in ``api_content``. The messaging gateway rebuilds agent_history
from the transcript every turn, and ``_build_gateway_agent_history`` gated
replay on ``elif content:`` — so that row vanished, the assistant's answer left
the context and the tail replayed user->user. Treat an assistant row whose reply
lives only in a non-empty ``api_content`` sidecar as replayable; the existing
``_build_replay_entry`` keeps the sidecar because content is unchanged.
Also stamp ``api_content`` on the interim row of the stall-guard / codex-ack
continuation branch when the reasoning was promoted, so the wire copy of that
interim assistant turn carries the text instead of only ``reasoning_content``.
Part of #111761
A Matrix `attach_to_session` cron delivery and a CLI→Matrix `/handoff` now land in their own
thread AND a human reply in that thread continues the seeded session (#112918).
The salvaged `MatrixAdapter.create_handoff_thread` (ea-s21, #108367) gives both seeders a
thread root. The second half of the bug is a key-shape mismatch: the handoff watcher and
`_seed_cron_thread_session` seeded `matrix🧵<room>:<root>` while the adapter keys every
in-thread reply on the ROOM's type (`matrix:group|dm:<room>:<root>`), so seed and reply never
met. Following the direction landed for Slack in 1f3f45e87b (#111896), the seeders now mirror
the adapter instead of the adapter moving onto a `thread` slot: rekeying inbound Matrix threads
would orphan every existing Matrix thread session and drop `is_group` in authz for in-thread
messages (`_GROUP_CHAT_TYPES` has no `thread`).
- gateway/run_startup.py: Matrix destinations key `dm`/`group` from the adapter's
`get_chat_info` (`_handoff_home_is_dm`).
- cron/scheduler_delivery.py: `_THREAD_REPLY_CHAT_TYPE` — Slack and Matrix non-DM thread seeds
use `group`. Slack channel cron threads had the same mismatch (adapter `build_source` keys
`group`; the seed said `thread`); the two cron tests that pinned `thread` for Slack channels
asserted the wrong shape and now assert the adapter's.
- Dropped from #108367: the `chat_type="thread"` inbound rekey (see above) and its tests;
contributor tests trimmed to two invariants.
- Docs: Matrix listed among thread-capable handoff/cron platforms.
Live probe (in-process, real MatrixAdapter + real handoff destination + real cron seeder):
before create_handoff_thread -> None; handoff key matrix:thread:… ≠ inbound matrix:group:…;
cron seed matrix:thread:… ≠ inbound
after create_handoff_thread -> '$seed'; handoff == inbound == cron seed (room and DM cases)
Co-authored-by: ea-s21 <190767603+ea-s21@users.noreply.github.com>
Review follow-up for #112359:
- gateway `_format_session_info` (the /model info block) printed only
`Model: <preset> / Provider: moa`, so the messaging surfaces still hid
who pays; append the same "Acting model (billed for the run)" line the
CLI switch summary prints.
- `_provider_mismatch_notice` compared providers case-sensitively and
treated the routing pseudo-provider `auto` as a billing seat, printing a
misleading "not to OpenAI" / "not to auto" line; lower-case both sides
and skip `auto`.
- "references only advise once per user turn" is only true for the
default `fanout: user_turn`; say "by default" on the inventory row, the
`hermes moa list` header, the Desktop pill/description (en/zh/zh-hant)
and the docs line.
The in-code comment beside _inflight_agent_runs listed the cap's routes as the
OpenAI-compatible and Runs endpoints only, mirroring the gap the previous commit
closed. Keep the route list next to the counter truthful so the next reader does
not re-derive the exemption from it.
Part of #112690.
POST /api/sessions/{id}/chat and its /stream variant run their turn through _run_agent, so each
one already counts toward gateway.api_server.max_concurrent_runs. Neither ever called
_concurrency_limited_response, so the two routes could never be refused while their turns pushed
every other caller — /v1/chat/completions, /v1/responses, /v1/runs — into HTTP 429. A gateway at
its cap therefore refused the endpoints that check it and admitted the ones that do not.
Cross-machine agent DMs land on exactly these routes (hermes peer dm posts the turn to
/api/sessions/{id}/chat), so on a fleet gateway N simultaneous DMs started N full agent turns
regardless of the configured cap, each one an agent in its own executor thread.
Both routes now take the same guard the other run-starting routes take, before the session is
prepared. One table asserts the contract for the whole class: every route that starts a turn
answers 429 with Retry-After at the cap and starts no turn, and is admitted under it.
Docs: the cap's scope in the API server guide named only the OpenAI-compatible and Runs
endpoints, which is what the code did.
Slim follow-up to the cherry-picked #112447 (@Yongcheng123): same outcome —
an MCP server whose FIRST connect failed is retried by the gateway without a
config edit — with less machinery.
- `_mcp_config_reconciler` now calls `reconcile_mcp_servers_with_config()`
every housekeeping tick after the baseline one, instead of gating on the
config.yaml stat signature (plus a `pending` retry set). The reconcile is a
signature-cached config read plus set compares when nothing moved, so the
gate bought nothing but the bug: drift (a server enabled on disk, absent
from `_servers`) never changed the signature.
- Dropped `mcp_servers_missing_from_live()`: it duplicated the `wanted -
known` compare that `reconcile_mcp_servers_with_config()` already does.
- `reconcile_mcp_servers_with_config()` excludes servers inside their
per-server connect cooldown from `added`, so a chronically failing server
neither enters `discover_mcp_tools()` (cross-process discovery lock, up to
120 s of waiting when another process holds it, a "(1 failed)" log line)
every minute, nor is reported as "added" when nothing was attempted.
- A discovery-pass timeout now stamps the cooldown for the servers it
strands: their attempt is still running on the MCP loop and the next
reconcile tick would otherwise spawn a second one beside it.
- Tests trimmed to two invariants: the chore reconciles each tick after the
baseline with OAuth suppressed (gateway); the reconcile skips a server in
cooldown, retries it once the cooldown lapsed, and a timed-out pass stamps
the cooldown (tools).
Fixes#112445
`_mcp_config_reconciler` (added in #109906) runs only when `config.yaml`'s
signature changes. A server that is configured and enabled but whose FIRST
connect failed never reaches `_servers`, its config never changes, and nothing
else comes back for it: the parked self-probe belongs to an `MCPServerTask`
that connected at least once, and the gateway — unlike the CLI, which re-runs
`discover_mcp_tools()` per session — discovers once at startup. So a transient
failure at boot costs those tools for the life of the gateway process, and
does it silently: the model simply does not have them and reports the server
as absent, which reads as a config mistake rather than a runtime failure.
Seen in production: a remote MCP server whose `mcp-remote` OAuth wanted a
browser on a headless host blew the 120s discovery bound at 09:50; its
credentials completed at 09:52 and every later connection attempt succeeded
cleanly — but the gateway never asked again, and for seven hours every agent
session was missing those 17 tools while a second Hermes process on the same
box, whose own discovery had won the race, had them.
`reconcile_mcp_servers_with_config()` already computes exactly the missing set
(`added = wanted - known`), and `register_mcp_servers` already skips a server
inside its connect cooldown (30s->600s backoff), so a chronically failing
server is retried on that schedule rather than every tick. The only thing
missing was a caller when the file did not change.
- `tools/mcp_tool_discovery.py`: add `mcp_servers_missing_from_live()` — the
same set compare `reconcile_mcp_servers_with_config` does, without
connecting anything (mtime-cached config read + one locked set compare), so
a caller can ask "is a reconcile worth running" cheaply.
- `gateway/run_profile_reconcile.py`: reconcile when the signature changed OR
when something enabled is not live. First tick still records the baseline
only. Log line now says which of the two triggered it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Replace the five string-matching tests from the salvaged commit with two
invariants that spawn a real child carrying a token in argv and check the
actual persistence boundaries: the /proc summary + warning line + JSON
snapshot, and the detached ps/pstree log written by the real writer (which
must also end up 0600 even when an earlier release created it 0644).
Drop the AttributeError guard around os.fchmod: spawn_async_diagnostic
returns None on win32 before reaching it, so the branch was unreachable.
Shutdown diagnostics captured full command lines via ps auxf,
pstree -a, and /proc cmdline, then wrote them to a world-readable
log. Live tokens on child argv therefore survived the stop.
Keep process identity, CPU, tree shape, load, and OOM context, but
never persist argv. Open the diagnostic log 0600.
Fixes#112459
`_send_file` (send_document / send_image / send_video / send_voice, i.e.
the cron `media_files` leg of `_deliver_direct`) awaited the caption and
media `sendmessage` calls without reading `ret`/`errcode`. `_api_request`
only raises on non-2xx HTTP, so a stale-token `ret=-2 errmsg=prepare
failed` (or `errcode=-14`) came back as `success=True` with the token still
attached and the attachment silently never arrived — the previous commit's
claim that the media path shared `_send_text_chunk`'s `_is_session_expired`
handling was wrong; only the text path had it.
Apply the same mechanism inline in `_send_file`: check `ret`/`errcode` on
every item-list send, re-send once without `context_token` (and drop the
cached token) when `_is_session_expired` says so, and raise on any other
non-zero response so `_send_file_result` reports the failure. Clearing the
token covers both the caption and the media item, and bounds the loop.
Also mirrors the `prepare failed` troubleshooting row into the zh-Hans docs.
Part of #112709
The stale-session fallback in `_send_text_chunk` re-sends without
`context_token` via `continue`, which advanced the `for attempt in
range(retries + 1)` loop. With `send_chunk_retries=0` (the setting the
reporter used to surface the raw iLink error) the re-send never happened:
the loop ended with `last_error is None` and `send()` failed with an empty
AssertionError. Count only real failures in `attempt` so the tokenless
re-send is free; backoff timings and log counters are unchanged.
Also documents the `ret=-2 prepare failed` / `unknown error` stale-session
behaviour in the Weixin troubleshooting table.
Part of #112709
`/api/messaging/platforms` still read a not-running gateway's retained
`gateway_state == "startup_failed"` verbatim, so a profile the operator
stopped with `hermes gateway stop` (which keeps the last failure and its
`exit_reason` on disk for diagnostics under `desired_state: stopped`) showed
every configured platform as `startup_failed` with the stale reason ("Port
8642 already in use") — the same symptom #112517 describes, on the sibling
surface `/api/status` had just been fixed for. The two docstrings promise
the sidebar strip and the Channels page "can never disagree on one page
load"; they did.
Lift the verdict into one shared `gateway.status.retained_gateway_state()`
used by both routers: `startup_failed` only while `desired_state` still
wants the gateway running, else `stopped`. Behaviour of `/api/status` is
unchanged (same condition, one call site); messaging now yields
`gateway_stopped` with no error for the operator-stopped case and keeps
`startup_failed` + `exit_reason` when the profile is meant to be running.
Invariant test `test_operator_stopped_gateway_does_not_report_retained_startup_failure`
(red on the previous head: state='startup_failed',
error_message='Port 8642 already in use').
Fixes#112517
`gateway/mirror.py` captured `sessions.json` under the home that was live at
import. Under the multiplexed gateway one process serves every profile, so the
pre-migration fallback in `_find_session_id()` resolved every profile's lookup
against the launch profile's index — a `platform`+`chat_id` pair present in both
indexes returns the launch profile's session id, mirroring a delivery into a
session that belongs to another profile.
Only the fallback is affected: the primary `state.db` query goes through a bare
`acquire()`, which follows `get_hermes_home()` at call time and is already
profile-correct. The access is read-only, so nothing was written to the wrong
profile.
Applies the resolve pattern the rest of the repo already uses (gateway/hooks.py,
gateway/sticker_cache.py, tools/process_registry.py, tools/checkpoint_manager.py):
keep the module constant as the monkeypatch surface, snapshot it at import, and
re-resolve only when unchanged.
The added test reloads the module under a launch home and then serves a lookup
for a second profile; without the fix it returns `sess_launch` instead of
`sess_active`.
Fixes#112844
`hermes profile delete` removes the profile directory and tears its runtime down, but the name is
also baked into durable identity the delete path never touches — `agent:<name>:*` routing keys,
`gateway_heartbeats.profile` and `delivery_obligations`. An inbound event on a chat keyed to the
dead name then enters the routing index, resolves a profile whose directory is gone, and logs
`Profile '<name>' does not exist` on every event for the life of the store (the #111926 flood,
reached from a *deleted* rather than a renamed profile). The delete side is now symmetric with the
rename rekey (`rekey_profile_state` / `rekey_profile_routing` / `migrate-profile-identity`), with
the same ownership rule:
- `SessionDB.purge_profile_state(name)` — the mirror of `rekey_profile_state`, in one
`_execute_write` transaction. Routing keys, heartbeat rows and the telegram topic rows the rekey
also owns are hard-deleted (a binding is matched by `profile_name` OR its `session_key`
namespace, because the rename rewrites both); `delivery_obligations` rows are terminalized
(`state='abandoned'`) rather than dropped, so pending delivery state is not lost silently.
- `SessionStore.purge_profile_routing(name)` — the mirror of `rekey_profile_routing`: drops the
in-memory entries and persists the drop. Mandatory, not belt-and-braces — the owning process
writes its in-memory copy back, so a durable delete made elsewhere is undone by its next save.
- A delete-only control verb `purge-profile-identity`, deliberately NOT inside
`_unserve_profile()`: that hook also unserves a rename's old name, whose identity the rekey still
has to migrate. `hermes profile delete` requires the owner's `{"ok": true}` answer and reports a
partial settlement (naming the retry) instead of a clean success.
- The retry is the new `hermes profile purge-identity <name>`. It refuses a name that is a live
profile again: the purge keys off the name alone, so `delete foo` (settlement pending) →
`create foo` → `purge-identity foo` would otherwise delete the NEW incarnation's identity. The
delete path tombstones the directory before it purges, so the guard never blocks the delete.
- `sessions` rows are not deleted by the purge: it settles identity, not history. What a delete
leaves of a profile's conversation record is `delete_profile`'s business — it removes the
profile's own home, `state.db` included.
Tests (`scripts/run_tests.sh`, red on base → green): `tests/hermes_state/test_purge_profile_state.py`,
`tests/gateway/test_purge_profile_routing.py`, `tests/gateway/test_profile_identity_purge.py`,
`tests/hermes_cli/test_profile_identity_purge_cmd.py` and `TestDeleteProfile` in
`tests/hermes_cli/test_profiles.py` — 95 passed, 0 failed across those five files.
A native hosted room running a second profile calls
tui_gateway.launch_profile_policy.activate_multi_profile_hosting() inside the
messaging gateway process, so get_secret() fails closed for every unscoped read
afterwards. A gateway with gateway.multiplex_profiles: false never bound a scope
(the config flag was the only gate), so its next ordinary turn died in
_resolve_session_agent_runtime with UnscopedSecretError / "Hermes could not read
this profile's API key" until restart (#112878).
Builds on the predicate from #112884: instead of re-entering the routed-profile
scope (which rebuilds credentials from .env alone and would drop a key injected
by systemd / `op run`), the standalone branch binds the launch profile's OWN
scope — launch_secret_scope() (.env + external sources over the env frozen at
activation) plus its terminal policy — exactly what the tui_gateway already
binds for launch-profile RPC bodies. One predicate, GatewayTurnMixin
._standalone_launch_scope(), no-op while the process is single-profile.
Whole class: every standalone entry point now runs under it — the foreground /
background turn wrappers, busy, goals and heartbeat-restore paths already
routed through _profile_scope_for_source, and the primary adapter's message,
busy-session and platform-event handlers (slash commands such as /model,
/status and /compress run inside _handle_message and were equally stranded).
Cron already binds its own per-fire scope. The guard is not weakened: reads
outside any scope still fail closed and a secondary never sees the launch env.
Tests: tests/gateway/test_standalone_gateway_launch_scope.py — real activation
helper, real server-bound secondary scope entered and left, then the standalone
turn and handler resolve both the .env key and the env-injected key (red on
origin/main with UnscopedSecretError); control: no activation → nullcontext and
no scope in the handler. The #112884 test moves here in trimmed form.
Co-authored-by: Lyti4 <205342405+Lyti4@users.noreply.github.com>
Co-authored-by: KoNit-K <124019182+KoNit-K@users.noreply.github.com>
* fix(launchd): park EX_CONFIG token conflicts instead of KeepAlive-looping
systemd already stops restarting on exit 78; launchd KeepAlive=true
respawned the same token/port collision every 30s. Map 78 to a clean
stop under SuccessfulExit=false so the job stays down until the holder
releases the lock.
* test(launchd): pin EX_CONFIG park under SuccessfulExit KeepAlive
The plist must not use unconditional KeepAlive, and the stderr wrapper
must turn gateway exit 78 into a clean stop without swallowing exit 75
or a non-gateway child's 78.
The boot guard logged its refusal once and nothing else knew. A user whose default says multiplex
but whose gateway serves one profile would read `hermes gateway status` and see a healthy gateway.
The verdict now lands in gateway_state.json (multiplex_standalone_reason) and status prints it with
both remedies; a boot that does multiplex clears it.
DEFAULT_CONFIG now ships gateway.multiplex_profiles: true. GatewayConfig keeps an UNSET flag as
None so the boot can tell "the operator chose" from "the default applies"; every reader tests
truthiness, so an undecided flag never multiplexes by accident.
hermes_cli/gateway_multiplex_mode.py settles the unset default once per boot (called from
load_gateway_config_for_runner and `gateway run --config`): the same preflight `hermes gateway
migrate --multiplex` runs — default profile, >= 2 profiles, no secondary running its own gateway
(live pid or installed unit), no duplicate-credential / port-binder blocker, migratable host. A
refusal is a logged warning naming the blocker and the migrate one-liner; the gateway comes up
standalone exactly as before. Explicit values (config.yaml, GATEWAY_MULTIPLEX_PROFILES) pass through
verbatim; `--standalone` already pins false.
Other processes stop guessing the verdict from the merged default: named_profile_served_by_running
_multiplexer, the enroll warning, the dashboard listener guard, the cron-fire port resolver, container
boot and the migration plan (_read_multiplex_flag) read the live gateway's served_profiles record
first and the EXPLICIT flag second — so a per-profile fleet with the flag unset still reads as
"not yet multiplexed" and the fold proceeds.
Docs: multi-profile-gateways.md, multiplexing-gateway.md, hermes_cli/AGENTS.md.
gateway/run_notifications.py::_send_session_db_warning_notifications already
computed profile_arg but left `hermes doctor` (fts_index branch) and
`hermes gateway restart` (default branch) bare; agent/turn_finalizer.py had a
bare `hermes doctor` in the error fallback used when the explainer produced
no text. Same class as the previous commit. Also reflows the explainer
strings so continuation lines break at clause boundaries.