Commit Graph
3623 Commits
Author SHA1 Message Date
teknium1 f4452169d1 fix(gateway): busy-mode steer also reaches the parent's active subagents
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.
2026-09-17 09:02:55 -07:00
teknium1 ba2bcfa6e7 fix(gateway): auth-fallback test stub accepts the target_model kwarg the fallback resolver now passes
`_try_resolve_fallback_provider()` now resolves each fallback entry with
`target_model=entry["model"]` (intended: the model-keyed ladder rungs must see the
model the fallback will send, not config's primary default). The auth-fallback test
in test_session_model_override_routing.py monkeypatches resolve_runtime_provider with
a stub whose signature lacked `target_model`; the resulting TypeError was swallowed
by the per-entry `except Exception: continue`, the fallback chain returned None, and
the gateway re-raised the primary AuthError ('No Codex credentials stored').

Source behavior is correct (real resolve_runtime_provider accepts target_model; the
other stubs in test_api_server/test_session_api were already updated), so this only
brings the stub in line and additionally asserts the fallback rung is resolved
against the fallback model, locking in the PR's intent.
2026-09-17 08:59:22 -07:00
teknium1 931b5ff9e7 fix(opencode): every credential-resolution surface keys off the model it will send; family heal only for built-in providers
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
2026-09-17 08:59:22 -07:00
kshitijk4poor c39f5424ef fix(gateway): the flush-time fence compares whole seconds
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.
2026-09-17 21:19:05 +05:30
kshitijk4poor f6978426a2 fix(gateway): an unresolvable profile store preserves the flush file instead of writing to the root store
`_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.
2026-09-17 21:19:05 +05:30
kshitijk4poor 43fdc0fef5 test(gateway): trim flush-resolver tests to positive + fence invariants
Keep test_recover_payload_without_session_id_uses_resolver_and_deletes_file
(positive path) and add one negative fence test on the resolver: a row
started after the flush ts is rejected, an older one is adopted with its
owning db. Drop the WhatsApp alias tests (feature removed), the duplicate
positive test and the redundant no-resolver/None-resolver file-preserved
tests, which were exercising the same branch three ways.
2026-09-17 21:19:05 +05:30
briandevans 3f5a5723e7 test(gateway): cover recovery skipping a failing payload and continuing
Pins that an ordinary append failure on one spool file only skips that
file: the remaining files are still recovered, the good file is unlinked,
and the failing one is preserved for the next startup retry.

Fails before the handler reorder — the RuntimeError propagates out of
recover_pending_to_db and the second message is never recovered.
2026-09-17 21:19:05 +05:30
yoyodine-industries 4aac98342b fix(gateway): resolve flush session_key to session_id at recovery 2026-09-17 21:19:05 +05:30
spfcraze 9dbe5d7af7 fix(gateway): resolve session_key in shutdown-flush recovery
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.
2026-09-17 21:19:05 +05:30
kshitijk4poor bb42672178 refactor(telegram): a confirmed stall logs one hand-off line, not a retry promise
_schedule_polling_recovery promised the gateway 'stays alive and will retry' for every error, but a _PollingStallError goes straight to _go_fatal_network (supervisor rebuild). Branch the wording on the error type, drop the watchdog's own pre-log so a stall yields exactly one error-level line (from _go_fatal_network), and carry stalled_for/generation in the stall error text instead. Test module docstring and test name updated to match the hand-off semantics.
2026-09-17 21:17:59 +05:30
kshitijk4poor 5ca3e5546c fix(telegram): a confirmed stall hands off before the reconnect backoff, not after it
Hoist the `_PollingStallError` check in `_handle_polling_network_error` to
right after the teardown/fatal guard, before the retry counter increment,
the exponential sleep, `_stop_updater_or_go_fatal` and both connection
drains. Use a plain `isinstance` (both raise sites construct the error
directly; nothing wraps it). The stall test now also asserts no sleep, no
retry-counter bump, no in-place `updater.stop()` and no drain.

WHY: the check sat after `await asyncio.sleep(delay)` (5-60 s), the
counter bump and a bounded `updater.stop()` (up to 15 s), so a gateway
already confirmed deaf stayed deaf 5-75 s longer and consumed a retry
slot for something that is not a retry.

The in-place `updater.stop()` before the handoff is dropped deliberately:
`_go_fatal_network` -> `_handoff_polling_fatal_error` -> supervisor
rebuild runs `disconnect()`, which performs the same bounded
`updater.stop()` (`_UPDATER_STOP_TIMEOUT`, falls through on timeout) plus
`app.stop()/shutdown()`, so stopping here only duplicated that work on the
slow path. Docstrings for `_handle_polling_network_error` and
`_check_polling_stall` no longer describe the stall as a reconnect-ladder
escalation.
2026-09-17 21:17:59 +05:30
kshitijk4poor d18f45f2d1 test(telegram): fold stall handoff cases into one parametrized invariant
Merge the watchdog and verifier stall tests into a single parametrized
`test_confirmed_stall_hands_off_before_reusing_updater` and assert the
adapter is also marked degraded, keeping two invariant tests for #113618
(stall -> fatal handoff; generic network error -> in-place reconnect).
2026-09-17 21:17:59 +05:30
joaomarcos 4a7ed0029d fix(telegram): rebuild adapter on confirmed polling stall instead of reusing unquiesced updater (#113618) 2026-09-17 21:17:59 +05:30
kshitijk4poor 36221c6d32 test(gateway): idle-gate tests read status, cover the named-routing-home case and the handoff gate
Loop watcher: a cleared row must not open the gate (a key-existence mutation now fails), then
the unavailable-store fail-open. Heartbeat restore: routing home = named profile with the only
active row in the default store must still sweep. The handoff-watcher test from #109497 is
restored (its gate and the has_pending_handoffs query had no coverage).
2026-09-17 20:56:27 +05:30
kshitijk4poor ffab36579a refactor(gateway): idle gates live in run_idle_gates; row semantics live with loops/heartbeat
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.
2026-09-17 20:56:27 +05:30
kshitijk4poor ee8999b6fb test(gateway): two invariant tests for the watcher idle gates
Heartbeat: no active row → no sweep; a cleared row → still no sweep; an active row → sweep;
an unopenable store → sweep. Loop watcher: idle profile never scoped, active loop scoped,
unopenable store scoped. The handoff-watcher test from #109497 is dropped: same shape, and
the salvage bar is two tests per fix.
2026-09-17 20:56:27 +05:30
kshitijk4poor d54a1dee91 fix(gateway): watcher idle probes fail open on an unavailable store and ignore cleared rows
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.
2026-09-17 20:56:27 +05:30
Andre 2e6247fb3e fix(gateway): gate per-profile watcher ticks on actual work in the profile's store
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.
2026-09-17 20:56:27 +05:30
Andre 5d7fa6bc20 fix(gateway): skip heartbeat restore sweep when no heartbeat is persisted
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.
2026-09-17 20:56:27 +05:30
teknium1 00cb8895d4 fix(gateway): pre-isolation room import copies per room, reads pre-actor layouts, warns once
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.
2026-09-17 00:15:35 -07:00
finn763 5e9fe10161 fix(gateway): import pre-isolation hosted_room* rows into shared-state.db (#109775)
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.
2026-09-17 00:15:35 -07:00
teknium1 0635ca6826 test: interrupt() doubles expect the system tool_reason at gateway shutdown / SSE disconnect
The producers now attribute these interrupts to the system issuer (#112647), so the exact-call assertions in the drain and SSE-cancel tests must carry the kwarg.
2026-09-16 17:48:17 -07:00
teknium1 9d0ab880bc fix: attribute gateway lifecycle stops to their system issuer, not the user
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.
2026-09-16 17:48:17 -07:00
teknium1 b3aef45987 fix(clarify): batch result carries the surface's no-answer notice; trim tests
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
2026-09-16 17:47:50 -07:00
KeyArgo 242ff24ff7 fix(gateway): answer a clarify batch on the surface, not by sentinel text
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}
2026-09-16 17:47:50 -07:00
680735174a fix(gateway): scheduled heartbeats end silently, emit no progress and quote no stale message
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>
2026-09-16 17:23:01 -07:00
KoNit-K 95d624e903 fix(gateway): quiet scheduled heartbeat surfaces 2026-09-16 17:23:01 -07:00
teknium1 578bff8ef7 fix(gateway): replay the sidecar-only assistant row when rebuilding history from the transcript
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
2026-09-16 17:21:57 -07:00
teknium1andea-s21 f41ad3bc0a fix(gateway,cron): key Matrix handoff/cron thread seeds the way Matrix replies are keyed
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>
2026-09-16 17:18:44 -07:00
ea-s21 3063d0f2bb feat(matrix): implement create_handoff_thread
The Matrix adapter inherited the base create_handoff_thread (returns None), so
cron attach_to_session and the gateway handoff watcher silently no-op on Matrix
while Telegram/Discord/Slack support them: the alert/handoff is delivered flat
instead of as a replyable thread, and the scheduler logs thread_id=None ->
"Mirror: no session found". A human reply then can't resume the session with
its seeded context.

Implement it Slack-style. Matrix has no channel-level create-thread API -- a
thread is just events whose m.relates_to / rel_type: m.thread reference a root
event's event_id -- so seed a root message and return its event_id as the thread
handle. The implementation reuses the adapter's own send() (chunking + E2EE
retry + formatting) and registers the root with self._threads.mark(), mirroring
inbound thread handling; _apply_relation_metadata already threads later sends off
a supplied thread_id, so the returned id is immediately usable. Returns None on
missing client / failed send (callers fall back to parent_chat_id).

Adds tests/gateway/test_matrix_handoff_thread.py (seed id returned; default seed
on blank name; None on no client, failed send, and missing event id).
2026-09-16 17:18:44 -07:00
teknium1 c8f0f6b136 fix(moa): name the billed aggregator in the gateway /model block and qualify the advise-once copy
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.
2026-09-16 17:11:01 -07:00
teknium1 20ac379ad4 fix(tui): non-local path completion speaks POSIX from a Windows host and honours the composer cwd
Desktop's in-process gateway runs on the user's OS. On a Windows host with an ssh/docker
terminal backend, os.path arithmetic in _dir_listing_items turned the search dir into a
backslash path (`ws` + `sub/` -> `ws\sub`, `/tmp/x/` -> `\tmp\x`) that the backend's POSIX
listing script cannot resolve, so every non-local completion came back empty. The non-local
branch now uses posixpath for join/normpath/dirname/basename/relpath — the backend always
speaks POSIX regardless of the host.

Also: complete.path takes params['cwd'] (the session cwd Desktop's composer sends) as the
backend root when supplied instead of ignoring it on non-local backends, and the per-keystroke
backend listing waits at most 3s instead of 10s so a slow remote does not pin a pool worker.

Review follow-up on #113144.
2026-09-16 17:09:12 -07:00
teknium1 92f7002683 test(tui): path completion under a non-local terminal backend lists the backend tree
Two invariant tests with a fake SSH-like backend (the gateway listing command runs inside a
separate "remote" tree): host-only entries never appear and the listing is addressed to the
session key; `~/` is expanded on the backend, never substituted with the host home. Red on
origin/main (the host tree leaked: ["readme-host.txt"]). See #112963.
2026-09-16 17:09:12 -07:00
John Paul Soliva 9934972e21 fix(api-server): the session-chat routes spend the concurrent-run budget without respecting it
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.
2026-09-16 17:05:32 -07:00
teknium1 ea17e976cd fix(mcp): retry a never-connected server through the existing reconcile seam
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
2026-09-16 17:01:11 -07:00
Yongcheng MuandClaude Opus 5 31d3b948de fix(gateway): reconcile MCP on drift, not only on a config edit
`_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>
2026-09-16 17:01:11 -07:00
teknium1 c45ca8855d test(gateway): two real-process invariants for argv-free shutdown forensics
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.
2026-09-16 16:52:25 -07:00
joaomarcos 1d291102d6 fix(gateway): persist shutdown forensics without process argv
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
2026-09-16 16:52:25 -07:00
teknium1 97066a0eb5 fix(gateway): Weixin media sends honour iLink ret and re-send without a stale token
`_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
2026-09-16 16:50:46 -07:00
teknium1 2995063bcd fix(gateway): Weixin tokenless re-send no longer consumes the retry budget
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
2026-09-16 16:50:46 -07:00
KoNit-K 46ab37ce35 fix(gateway): retry Weixin prepare failures without token 2026-09-16 16:50:46 -07:00
teknium1 0a62d4564e test: give bare profile-dir fixtures an identity marker (#113377 red-fix)
`named_profile_has_identity` now gates listing/serving/resolution, so a
`profiles/<name>` dir created with a bare mkdir is no longer a profile.
Production always publishes identity files (`create_profile` seeds
config.yaml/.env before the rename), so these fixtures were relying on a
contract that never existed in real installs. Each now writes a minimal
`config.yaml` marker next to the mkdir (config.yaml rather than SOUL.md
or auth.json so tests that own those files stay neutral). Where a file
had a shared fixture/helper it is fixed once.

Files:
  tests/gateway/test_multiplex_lifecycle.py
  tests/gateway/test_multiplex_session_db_profile_scope.py
  tests/gateway/test_status_command.py
  tests/hermes_cli/test_apply_profile_override.py
  tests/hermes_cli/test_dashboard_admin_endpoints.py
  tests/hermes_cli/test_gateway_multiplex_served_record.py
  tests/hermes_cli/test_kanban_per_profile_cap.py
  tests/hermes_cli/test_kanban_review_surfaces.py
  tests/hermes_cli/test_pooled_served_profile_backend_unscoped.py
  tests/hermes_cli/test_profiles.py
  tests/hermes_cli/test_web_oauth_dispatch.py
  tests/hermes_cli/test_web_profile_soul_writes.py
  tests/hermes_cli/test_web_profiles_off_loop.py
  tests/hermes_cli/test_webhook_cli.py
  tests/tools/test_kanban_tools.py
  tests/tools/test_local_env_blocklist.py
  tests/tui_gateway/test_groups_methods.py
  tests/tui_gateway/test_groups_replication_methods.py
  tests/tui_gateway/test_hosted_room_settled_retry.py

Contract rewrite (old contract asserted a bare dir IS a profile):
  tests/gateway/test_multiplex_session_db_profile_scope.py::
  test_profile_home_is_not_memoized_before_the_profile_exists — after the
  runtime mkdir the test now asserts `_profile_home_for_key` still returns
  None (a bare dir is not a profile) and only resolves once the identity
  marker exists; the not-memoized-miss invariant is kept.
2026-09-16 16:48:42 -07:00
anhtahaylove f27c719a93 fix(gateway): resolve the mirror sessions index at call time, not import time
`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
2026-09-16 14:34:22 -07:00
teknium1 ba8b458c5b test: trim purge-identity tests to behaviour invariants
Drop the three cases that pin trivia the invariant tests already cover
(idempotence is exercised by the routing-store test; the empty-name /
no-store guard and the default-profile refusal are one-line argument
checks). Salvage bar: invariants only.
2026-09-16 14:21:14 -07:00
xielevi a41552fad4 fix(profiles): purge a deleted profile's session/routing identity on delete
`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.
2026-09-16 14:21:14 -07:00
51c4b6ba9d fix(gateway): standalone gateway binds the launch profile's own scope after hosted activation
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>
2026-09-16 14:20:17 -07:00
KoNit-K 99f68e730b fix(gateway): scope standalone turns after hosted activation 2026-09-16 14:20:17 -07:00
NanPan a213657500 test(gateway): reproduce reaper profile-scope loss
(cherry picked from commit bf7ae2f9d394e395130537eaffa78b34b1260c5e)
2026-09-16 11:06:06 -07:00
teknium1 a10bbf95bb feat(gateway): gateway.multiplex_profiles defaults to on, gated by a boot-time serve guard
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.
2026-09-16 08:57:18 -07:00
kshitijk4poor c622dd53c4 fix(gateway): the free-tier bootstrap runs inside the launch profile's scope under multiplex
Same bug class as the warm-up: `_start_free_tier_bootstrap` ran on a bare executor thread, and
`anon_auth.ensure_portal_identity` resolves the Portal through `_nous_portal_env_override`, so
under multiplex a non-production HERMES_PORTAL_BASE_URL read as absent and the identity would be
minted against the production Portal. Route the hop through `_run_boot_probe_in_launch_scope`.
Gated behind guest onboarding, so latent on today's fleet; one test pins the binding.
2026-09-16 16:16:24 +05:30