Kanban workers no longer run `chat -q`: the spawned process is
hermes_cli.kanban_worker_client, which submits kanban.run to the profile's
owner gateway, and the owner runs the attempt in _run_task_turns. Those
three run_conversation calls (first turn, in-place recovery, goal turns)
passed no turn_author, so memory providers still filed the dispatcher's
prompt and the worker's notes under the operator (#137406). They now pass
a fixed bot author. Its id is kanban:dispatcher rather than bot:kanban,
which a Bot Mode profile named kanban would also produce.
Under multiplex, authorization reads each profile's own secret scope, so the
DISCORD_ALLOWED_USERS the YAML bridge copies from discord.allow_from into os.environ is never
seen. The fallback to the adapter's extra then read group_allow_from for 'group' sources:
Telegram's group-only list, which Discord does not have. An allowlisted user's guild-channel
messages were dropped and their button clicks refused, while threads and DMs worked.
Discord declares allow_from_covers_groups, so its groups read allow_from. Adapters with a
separate group list (Telegram) are unchanged; a test pins that a Telegram DM-only allow_from
still does not admit the user in a group.
_admission_outcome read the admission row, then its result blob, in two
statements. The drain settles from a worker thread (commit_and_publish), so
the commit could land between them: the result was present while the stale
started row had no outcome, and a completed turn projected as a terminal
`failed` receipt carrying the reply as its error. Terminal receipts leave
_bot_receipt_index, so the settle wake re-read nothing and no reply watcher
existed; the sender kept the false failure for good.
Read the result first; when one exists but the row read was not terminal,
re-read the row (the result and terminal outcome commit together, and
terminal is final).
This is the CI flake test_paused_receipt_rearms_on_resume_without_polling_rpc
("the paused delivery never settled"). Repro: an in-process loop of that
scenario with a 0-20 ms stall between the two reads strands 251/2400
receipts on main (all `failed`/error=reply, row terminal/completed), 0/2400
with this fix. The new test commits the settlement between the two reads
through refresh_receipt and fails on main with ('failed', 'pong').
Two paths left a moved local conversation's mount wrong (Greptile on 757486d):
- Startup recovery of a lane's queued input (`recover_native_sessions`) and an
automation wake built the mount without `handed_off`. Once the chat's idle
local routing entry is pruned (session_store_max_age_days), recovery is what
mounts it after a restart, and when another chat was then handed off to the
lane the moved chat stayed writable. Every mount of a messaging route now
goes through `session_route_recovery.mount`, which reads `handed_off` from
the row (`moved_local`).
- `_publish_route` moved a mount's source and route only for a local ->
platform move. A chat a `/resume` brought to another chat kept its old
route, so a viewer's turn or Stop through it acted on the conversation that
replaced it there. A mount published on a different route now moves there.
Not routed through `mount`: the local receipt restore (a LOCAL source is never
a moved chat), the hosted-room bind and the two exhaustion-rotation mounts (rows
minted by that platform path), the source-less history mount.
Independent review of ff6409bf1ba: Bot Chat X, a local reset to X2, then /handoff of X.
follow_hand_off flagged the Desktop's mount of X as handed off, but the X2 head it then
published was a plain LiveSession (handed_off and history_mount both false). When another
chat was handed off to the same lane, or the platform's /new and its next inbound published a
new conversation, the takeover supersede loop skipped X2: it still authorized session:submit
and session:control, and the turn resolver ran its turns in the new conversation.
The same hole existed without a reset whenever the head was mounted by anything other than
the Desktop that followed it: the lane's inbound after a restart (a fresh LiveSession), or a
viewer's cold open (a history mount the next inbound clears).
Handoff provenance now comes from the row, not from the path that mounts it:
session_route_recovery.moved_local (a row created by a local surface, published on a
messaging route) sets LiveSession.handed_off on every newly constructed mount, in
SessionAuthority._publish_route and in restore_routed_session. Reads stay open; submit and
control answer session_superseded once the lane takes up another conversation.
Review finding on #144708 (independent review)
Refs #143286
Round-3 re-review of #144708:
- A lane's /new frees a handed-off Bot Chat's title from the store's worker
thread, outside the titled-create lock. A Bot delivery it landed in the
middle of (after the title read, or under the lock before its own displace
write) re-read an empty title and crashed on row['id'], so the delivery
failed and nothing was minted. _create_bot_chat now mints when its displace
write lost to that rename and the title is free; _target mints when its
re-read finds the title gone.
- The platform's /resume of a local conversation resolved its title to the
first segment, so after a local /new it moved that stale segment onto the
lane and released the receipt of the live segment, which stayed local and
was refused storage_unavailable after a restart. It now resolves the
conversation's current head through the same conversation_head step
/handoff uses, and a Desktop still viewing it follows it onto the lane.
Greptile on df9746d5f09:
- A chat handed off to a route again after another one took it (H, then Y,
then H) skipped the supersede loop because it was already on that route, so
Y stayed writable while the route named H. _publish_route now treats a
superseded session coming back as a takeover too.
- The Bot Chat a delivery minted under its automatic creation id, reset
locally and handed off, leaves its first segment untitled on the lane once
the name follows the head. _bot_chat_creation_id read that untitled row as an
interrupted creation and reused its id after the platform's /new, so the next
delivery hit the released receipt (storage_unavailable). A creation handed
off to a messaging lane is spent.
- A moved receipt whose lineage holds a non-string entry raised TypeError in
the boot heal and stopped the profile's start; hand_off_conversations now
leaves such a receipt as it is (its own reads refuse it, logged).
- The title follow-the-head rule ranks provenance with SessionDB._title_rank
instead of a copy (a pre-provenance title ranks as the user's).
Three defects an independent re-review found on #144708 (#143286):
- Data safety. After a local /new (receipt now names the new segment), a
/handoff of the chat's id moved the stale first segment to the lane and the
owner-row branch of moved_receipts released the receipt guarding the
post-/new segment, which was still local: that transcript was reachable from
nowhere and the platform resumed the stale history. The handoff now repoints
the receipt's current head (latest /new segment, then its compression tip,
hermes_state_local.handoff_head); a receipt is released only when the row its
CURRENT target names moved to a messaging lane, and the rest of that
conversation moves with it in the same write (hand_off_conversations): its
earlier segments open as the lane's read-only history and its name follows
the head over a generated title. A Desktop still holding the chat follows it
(follow_hand_off).
- Bot Chat after the platform's /new. The roster's canonical_session (raw title
registry) still named the superseded handed-off chat while the title lookup
hid it, so Desktop's bot row failed closed ("Could not confirm ... not
starting a new chat") on every click. The title now moves aside at the moment
the lane moves off the chat (SessionStore._promote_session_reset, every route
transition, and at boot), so the registry, the roster and the lookup agree
at every step; the lookup-side filter and the create-side move-aside go.
- Second handoff to the same home chat. A live local chat handed off to a route
that already carried a handed-off chat skipped the supersede loop, leaving
the first chat writable while the route named the second. _publish_route now
supersedes every other handed-off/history mount on a route whenever a
session takes it over.
The PR's own history='reset' case asserted the old (stale-segment) behaviour;
it now asserts the head carries on and the earlier segment is read-only history.
Desktop's titled create renamed and unhid the handed-off Bot Chat before staging the new one,
so a refused create (an invalid cwd) left the saved chat renamed with nothing minted in its
place (Greptile, #144708). The rename now runs after the replacement commits, right before it
takes the title.
Review of #144708 (Bot Mode keeps one canonical forever-chat per profile + title):
- A Bot/cron delivery after the handoff treated the handed-off Bot Chat as displaceable
(a messaging row with no receipt), renamed it aside and minted a new canonical chat, so
the bot row silently switched chats. `displaceable_bot_chat` keeps a handed-off chat whose
lane still holds it, and `_target` delivers to it on that lane.
- The Desktop view that followed the chat onto the lane stayed writable after the platform's
own /new, with a route naming the new conversation (Stop, agent lookup and turns would act
on it). A handed-off live session is now superseded like a history mount when its lane
publishes another conversation.
- After that /new and a restart the bot row adopted the read-only chat forever. The title
lookup no longer resolves a handed-off Bot Chat whose lane moved on, and Desktop's titled
create (and the delivery door) move it aside, `Bot Chat (<platform> <id>)`, before minting
a fresh one.
- The in-handoff receipt release applies the startup heal's messaging-lane filter.
Also: a chat with a /new reset segment handed off by its conversation id (a platform
`/resume <title>` or a resumed CLI) kept a receipt naming the reset segment while its owner
row moved to the lane, so every cold open failed the lineage check. A receipt whose owner
row a repoint moved is released too (in the write and by the startup heal).
A compressed local chat's receipt names its newest compression child.
The handoff repointed the route at the logical id, so the rewrite walked
only that row and its ancestors, missed the receipt, and left the tip on
its local identity (the next turn's tip walk then broke it the old way).
Resolve the compression tip before repointing: the whole chain moves onto
the lane with its receipt, the handoff carries the live transcript, and the
still-open viewer is published by its logical owner.
The repoint moves into GatewayStartupMixin._handoff_repoint; the
regression test drives it on the real store, plain and compressed.
Greptile review on #144708.
`/handoff <platform>` repoints the platform route at the local session
(SessionStore.switch_session -> record_gateway_session_peer), which rewrites
the row's routing identity to the platform's. Its local receipt
(gateway.local_policy.v1 / gateway.local_legacy.v1) stayed behind, so the row
matched neither lane:
- authorize took restore_local_session (receipt present) and _checked_entry
refused it with `stored identity mismatch`: resume, pin/unpin, rename and
archive answered storage_unavailable, and every boot logged
`receipt refused`.
- the title registry (session.list title=, session.resume title=, the Bots
roster's Bot Chat lookup) sent the row to legacy adoption, which answers
not_found for a messaging row and for any non-native actor (browser
Webapp), so a handed-off canonical Bot Chat could never be opened again.
Now:
- the explicit repoint retires a local receipt whose target row it moved to
another route, in the same write (hermes_state_gateway ancestors mode);
- gateway boot heals stores an older build left that way: receipts whose
target row a messaging lane now holds are released (logged once);
- the title resolver returns a local conversation a messaging lane took over
(created by a local surface, mountable on its route) through the routed
mount, so `/resume <title>` and the Bot Chat registry open it there;
- the handoff publishes the lane on the authority, and _publish_route moves a
still-open LOCAL live entry onto it, so the Desktop that ran /handoff keeps
its view without a restart;
- resume refreshes the creation policy only for local routes (a platform
lane has none; it logged `keeps its stored policy` on every open).
Fixes#143286
Review finding 3 on #144850. The flush (up to 3 s with a managed call wedged
in flight) ran before _mark_exited, so a supervisor kill during it recorded a
graceful stop as an unclean death. Order is now release locks, stamp the clean
exit, flush metrics, drain logs; the early-exit paths keep releasing the
PID/lock first. The wedge test now drives the real exit funnel with a real
Relay managed call in flight and asserts both the bound and the ordering.
Every graceful gateway stop (SIGTERM, update restart, idle exit, --replace takeover)
funnels through _exit_after_graceful_shutdown, which ends in os._exit and so skips the
shared-metrics runtimes' atexit hook. Sessions still open at the stop (a messaging or
Desktop chat) never closed, so their hermes.session.count / context-peak / tool-usage
rows never reached the local store.
shared_metrics_process.flush_before_hard_exit runs that hook's work (shutdown_runtimes)
on a daemon thread joined for at most 3 s, never raises, and never imports the runtime
module, so with collection off nothing is created. The gateway runs it first, before
the PID/lock release.
Review follow-up. An id entered _rows_pending before a save that can raise, and the fresh-route
path only cleared it inside _finish_route_transition, so a failed save left the id pending for
good and _is_session_ended_in_db would never call that row ended again. Every publisher now
clears its own id in a finally (get_or_create's create path, reset_session, switch_session),
_replace_route_locked marks the id only after its save returns, and the create kwargs are
computed before the entry is published. The test uses tests.waiting.async_wait_until.
SessionStore publishes a route transition in two halves: the new entry under _lock, then the
state.db row (insert for /new and a fresh route, reopen for /resume) after releasing it. Anything
that resolved the route in between saw the named conversation's row missing or still ended and
took the #54878 stale-route self-heal: drop the entry and recover the newest open row, which is
the conversation the user just left. A Desktop/Webapp turn finishing on a chat's previous
conversation does exactly that (its post-turn bookkeeping calls get_or_create_session), so after
/new the chat's route named A again and its next message could land there.
The store now remembers the ids it published whose row is not live yet, and
_is_session_ended_in_db does not call those ended. Every reader of that check (the routing
self-heal, the reaped-run eviction, the cached-agent liveness check) gets the fix.
With terminal.docker_shared_container_key set, every session reuses one
shared:<key> container, which mounts the cwd of the session that created
it. The previous commit took a cwd-mounted session's /workspace from that
session's own cwd, so a second session at another folder read that folder,
and Save (which own_sandbox_only allowed) overwrote it while the agent's
file in the container's real mount stayed unchanged.
Nothing records which cwd a shared container mounted: shared containers
carry no mount fingerprint label, and a cross-process attach never inspects
the container's mounts. So a session on a shared container reads from the
profile's cwd again, as before the previous commit, and a session Save that
resolves there answers 409 "File is no longer in this session's workspace".
Per-workspace containers still mount the session's own cwd.
With terminal.docker_mount_cwd_to_workspace on, a session bound to its own
workspace runs in a container that mounts that workspace at /workspace: the
gateway turn's TERMINAL_CWD is the session's cwd, which bind_turn_workspace
also registers and hashes into the :ws: key. The file routes still took the
mount root from the profile's terminal.cwd (or the process cwd), so a preview
showed that folder's copy and Save wrote it while the agent's file stayed
unchanged.
A session with a workspace key now mounts the cwd that key hashes (the live
binding's cwd, else the session row's), looked up in the session's profile
scope; a cwd whose digest does not match gives no mount root. Its sandbox
is still tried after the mount. MEDIA delivery and requests without a
session binding keep the profile's cwd.
The spawn ledger records psutil's epoch create_time, which on Linux is the
kernel's start ticks plus the /proc/stat btime psutil re-reads on every call.
An NTP or VM-resume step of more than 2 s therefore made a live gateway fail
its own ledger match: the scratch prune disowned it and killed the shell it
ran inside an idle scratch entry, then deleted the entry.
Ledger entries now also carry boot_start / spawner_boot (seconds since boot,
Linux only) and every ledger comparison uses them exactly when present. Older
epoch-only entries keep the 2 s match, except that readers protecting a
process (ledger pruning, the scratch prune's owner check, the data-cleanup
holder refusal) treat a live pid's epoch mismatch on Linux as unprovable
instead of dead, and spawner_is_dead never calls an epoch-only spawner dead
under a boot-stamped child. gateway.status's /proc start-ticks parse reads
bytes after comm's last ")" so a comm with spaces or non-UTF-8 bytes no
longer falls back to the clock-dependent psutil epoch.
- gateway/config_loader.read_yaml_layers was the only production caller
that reached into the backend object (get_config_backend(),
backend.exists(home), backend.read_user_layer(home).doc). It now uses
config_exists/read_config_doc like every other reader; same backend
calls underneath, so the protocol stays internal to config_backend.
- xai_retirement hand-rolled `if not supports_file_tooling(): raise
ConfigBackendUnavailable(...)`, which is require_file_tooling().
Review of the rebased stack found the same "version, or None when the
config is absent" shape written out at three call sites
(`config_version(p) if config_exists(p) else None`), a private
try/except copy of it in profiles_cache, and the gateway importing the
TUI's private `_version_token` from tui_gateway.methods_config.
- config_backend gains `config_version_or_none()` (one backend call, no
exists-then-stat race) and `version_token()`, moved from
tui_gateway/methods_config.py unchanged.
- tui_gateway (methods_config, server), the classic CLI config watcher,
gateway/session_config and the profile roster cache use them;
profiles_cache drops its private copy.
No behaviour change: same version tuples, same numeric token.
Rebasing onto current main brought in direct config.yaml readers that the
seam's reader gate (scripts/check_config_yaml_readers.py) now rejects:
- gateway/session_config.py: the session `config.get mtime` getter uses
config_exists/config_version + the TUI's _version_token, like
tui_gateway/methods_config.py already does.
- hermes_cli/profiles.py: _strip_multiplex_flag checks config_exists.
- hermes_cli/config_backups.py: the byte comparison sits inside the
supports_file_tooling()-gated block; marked like its siblings there.
- hermes_cli/update_receipt.py: _bare_collection_enabled runs in the bare
bootstrap interpreter with no config stack; presence stat marked.
Main also turned on UP006/RUF100/B009 since the branch base: builtin
generics in the seam's new modules, stale noqa comments dropped, and the
newly unused typing imports removed.
CI on the salvage was red on the code-health ratchet (over-cap facades grew; two blind excepts)
and on the pm observer fixture, whose isolated source tree carries pm/ + hermes_cli/ but no utils.
- config_backend imports become module-level in the facades (it imports only stdlib); gateway,
auth and telegram take config_exists through the hermes_cli.config import they already have.
- Pure helpers move to topical siblings, offsetting the growth: _csv_or_list_to_set ->
gateway/run_common.py, the dotted config-path pair -> hermes_cli/backup_restore.py, the
voice/timezone/web-backend checks -> hermes_cli/config_value_checks.py, _load_config_dict ->
hermes_cli/profile_memory_config.py (both callers are memory-provider code).
- _load_config_dict catches YAMLError/OSError/UnicodeError instead of Exception.
- _load_config_cache_hit probes readability with config_backend.probe_config_readable (a 1-byte
read through the backend's open) instead of a full parse plus a blind except.
- pm/plugins_state.read_home_selection checks config_exists before importing the YAML stack, so
a home with no config never needs utils.
- developer-guide/config-backend.md describes this build (file backend only).
Same approach as @benbarclay's 74421be709 in #122509, which does not cherry-pick onto current main.
Add hermes_cli/config_backend.py (config-config design §4.1, D10/D11): a
ConfigBackend protocol, the FileBackend (today's behaviour), selection by
HERMES_CONFIG_BACKEND only (default file; 'remote' and unknown values fail
closed with ConfigBackendUnavailable), and path-level helpers
(read_config_doc, read_config_doc_readonly, config_version, config_exists,
write_config_key, write_config_document, supports_file_tooling).
Migrate every direct reader/stat/exists/bypass writer of a user config.yaml
to the helpers (config.py loaders + caches, config_effective, env_loader,
gateway, TUI, CLI watchers, cron, tools, profiles, logging, time). File
tooling (config edit, backups, xAI migration rewrite, raw dashboard editor)
checks supports_file_tooling() first; migrations skip write-back without it.
Add scripts/check_config_yaml_readers.py (CI lint next to the writers gate)
that rejects a direct read of a config path outside the backend.
Ctrl+C, Esc, the Desktop/TUI Stop button, a message that interrupts and
an ACP cancel end the current turn. They also called
async_delegation.interrupt_for_session, so every background subagent the
session had dispatched died with the turn: one Ctrl+C took down a running
/review and both of its sub-reviewers. A background subagent is
independent of the chat that spawned it (Teknium ruling), so a turn stop
now hard-cancels only the turn:
- gateway SessionAuthority.interrupt (Desktop, Ink, classic CLI view,
ACP-through-gateway, messaging interrupts, api_server run cancel)
- tui_gateway session.interrupt (legacy Desktop/TUI stop)
- acp_adapter cancel
The explicit /stop command still ends them (CLI and Ink process.stop,
gateway /stop busy and idle paths), and so does closing or resetting the
session. Reverses the turn-stop half of b71359066c and 659e55ac71d;
tests/gateway/test_canonical_stop_hard_cancel.py now pins the delegation
surviving a canonical Stop.
_resolve_response logged 'unknown server request' even when the id was
open and only the connection's entitlement failed, which made the
sibling routing gap look like a missing request. resolve() only consults
session_ok for an open id, so record that it was asked and name the
reason in the debug line. Behaviour is unchanged.
Refs #143547
A response frame (sudo, secret, vault, Desktop UI reads, plugin choices)
carries no profile, so dispatch settles it before profile routing and
_resolve_response only checked the primary authority. On a multiplexed
gateway the Desktop's host-scoped socket attaches a non-default profile's
session through a sibling connection, so the answer failed may_settle and
was dropped; the tool waited out its timeout and read an empty value.
Check entitlement against this connection and the sibling connections it
holds: the pending request's event stream already identifies its owning
authority, and only the connection that attached the session passes.
Refs #143547
A managed worker (every Kanban card, --safe-mode and --ignore-user-config
chats) built AIAgent from the frozen model.base_url with no api_mode, and
resolved the route only to fill a missing key. The in-process turn takes
api_key, base_url and api_mode from route_runtime(), so a route whose
api_mode or endpoint only resolution knows failed only in the worker:
opencode-go Responses models fell back to chat_completions (400), and
Bedrock, which stores no base_url, landed in us-east-1 where eu./apac.
inference profiles do not exist.
worker_route() runs the same route_runtime() call with the bound launch
key (if any) and returns api_key, base_url and api_mode for the agent. A
bound launch key still wins; on a fallback entry nothing is carried, as
before (#139155). Resolution stays in the worker's own profile home: no
new secret path.
Refs #143547
Co-authored-by: Kazantcev Andrey <45011689+heckad@users.noreply.github.com>
Co-authored-by: Gekiere Aurélien <11493426+aurel282@users.noreply.github.com>
On Linux psutil's create_time() is the cached /proc/<pid>/stat start ticks
plus boot_time(), and psutil 7.2.2 re-reads /proc/stat btime on every call.
WSL2 re-anchors btime after host sleep, so the owner's read of a live
worker's birth drifted from the one the worker reported in its hello, and
the exact-equality fences (reservation, worker.adopt/persist, delegation
dispatch, the launcher signal and the Kanban owner receipt) refused it:
every Kanban card, cron run and subagent ended permission_denied.
worker_birth() reads the kernel start ticks since boot
(create_time(monotonic=True)) on Linux and keeps process_birth() elsewhere;
every managed-worker identity fence now uses it. The spawn ledger keeps
process_birth() so its persisted epoch births still match after an update.
An owner_admitted receipt written before this change reads as another
process: its reclaim pauses, the fail-safe direction.
Refs #143547
Co-authored-by: Sebastian Hänisch <5960303+TKCen@users.noreply.github.com>
require_history_claim let a row stamped with the caller's login through
before any profile check, so a basic:alice row whose profile_name names
another profile (after a restore or a copy) was editable and claimable,
while validate_legacy_row answers not_found for the same row. The
shortcut now requires the same profile_name rule (blank still allowed).
Refs #143547
A remote Desktop signed in through the dashboard (basic or OIDC login)
reaches session.mutate as an HTTP actor. require_history_claim ran before
authorize_history and refused every unrouted, unbound row unless the
actor held a native transport, so archive/pin/rename of the login's own
chats answered 403 permission_denied while a gateway owned the profile.
The claim gate now also passes when the row's login stamp equals the
actor's subject or login label: the same ownership evidence
authorize_history (and adoption) already accept, and which it re-checks
with the capabilities right after. Unstamped rows, another login's rows
and the host's native subject stay refused.
Refs #143547
session.automation recorded viewer_heartbeat before the op ran, so a /heartbeat resume with nothing to resume (no watchdog started) still made the gateway poller stand down. Record it after the op: on due_prompt, or on set/resume returning a state, the CLI's own condition for starting its watchdog.
Refs #143547
The CLI proxy sends due_prompt only once its own copy is due, so marking on
due_prompt alone left the first due tick to a race with the poller. /heartbeat
set and resume start the watchdog: record ownership on those too.
Refs #143547
Any session.automation call marked a session viewer-driven, including the
goal/loop reads a CLI makes on reopen. The CLI starts its heartbeat watchdog
only on /heartbeat set or resume, so the poller stood down with no driver.
Record heartbeat ownership only on the heartbeat due_prompt op, which only a
running watchdog issues, tied to that connection's live subscription.
Refs #143547
The heartbeat poller now admits ticks for local chats, so a classic CLI
armed with /heartbeat had two drivers. When the poller won a tick, the
turn ran as a local_automation_v1 admission that the CLI never painted,
and re-anchoring on the winner's poll kept it winning. The poller now
skips a local session whose classic CLI drives its automation
(viewer_driven: session.automation recorded it and the CLI still holds
its subscription). Desktop and TUI chats, which have no watchdog, still
get their heartbeats from the poller.
Refs #143547
A cron result admitted into a local chat ran as an automation turn over
the Bot Chat framing: a second model call over text that is already
finished. The admission now goes to the existing note executor
(session_completion_notes): a 'cron' producer is always noted, viewer or
not, so at the FIFO head the gateway writes the delivered text into the
chat's history (append_completion_note, keyed by the admission) and
settles it with no model call. The FIFO row is kept rather than a direct
write, which a live turn's lease would refuse. Failure notices are noted
the same way, marked diagnostic. The no-owner/unknown-chat/refusal/
timeout errors are unchanged.
Refs #143547
LocalSessionAdapter is a stub: no gateway_runner, no message handler, and a
send() that acknowledges a turn's own output. Three producers treated it like
a messaging adapter and lost their delivery to Desktop/TUI/CLI chats:
- KB-22: the adapter is built outside _create_adapter, so deliver_wake saw
no runner, skipped admit_route_wake and fell to the missing handler
(WakeNotAccepted). Bind gateway_runner from the authority it holds.
- RT-90: the heartbeat poller returned on a missing message handler before
the authority branch, which needs none. Let a LocalSessionAdapter through.
- CRON-11: a local origin resolved to the stub send() (delivered, nothing
shown) or, with no local chat restored yet, to "platform 'local' not
configured/enabled". A local target is now admitted into the chat's FIFO
by its owner in this process (owner_for_home, as cron execution uses),
through admit_route_wake like a Kanban wake, with the Bot Chat framing.
No owner in this process is an error, never a success.
Refs #143547
Co-authored-by: lucasfdale <89506270+lucasfdale@users.noreply.github.com>
Co-authored-by: gomediacoin <130362016+gomediacoin@users.noreply.github.com>
_drop_remote_media appended each note with a leading newline, so a message with no text stored
"\n[The user sent an attachment ...]". Join only the non-empty parts.
Refs #143547
On a single-profile gateway the connector stamp (source.profile) was cleared only in native
admission, so a stamped slash command (_on_inbound -> handle_message) or a Discord interaction
(_on_passthrough) still reached _binding with the stamp and was refused with profile_mismatch.
RelayAdapter now clears it right after _capture_scope on both ingress paths, before the
native/command split, when the runner is known and multiplex_profiles is off. A bare adapter with
no runner keeps the stamp. The clear in inbound_admission._admit is now redundant and removed.
Refs #143547
When a satellite profile's own bot hits a fatal error, its adapter is
popped from _profile_adapters and parked in _profile_failed_platforms
for reconnect. With a Desktop/CLI LOCAL adapter still in the map,
has_credential_platform() saw no credential platform and the cron tick
and restart-safe drain handed the profile the primary's routed bots, so
its output went out through the wrong bot until the reconnect landed.
has_credential_platform() now also takes the profile's
_profile_failed_platforms entry and counts a parked reconnect as owning
a bot, the same signal _is_shared_bot_satellite already uses for authz.
The drain reads it from the runner; the in-process ticker gets the live
map through a new profile_failed_platforms start kwarg.
Also update the native-ingress guards fixture to the remote-media
contract: an uncached remote URL is dropped with a note and the text
kept, while the trust-upgrade refusals stay.
Refs #143547
The Relay connector stamps source.profile to route a scope to a Hermes
profile. _binding derived the runtime profile only from local
profile_routes (or the /p/ prefix), so a stamp naming a non-primary
profile, or any stamp on a single-profile gateway, raised
profile_mismatch, which Relay treats as permanent: the frame was ACKed
and dropped and that profile's bot went silent.
Multiplex: when no local route matches, accept the stamp from the
process-level relay adapter if it names a reserved served home; a local
route still wins and an unserved stamp is still refused. The relay seal
covers source.profile, so a stored row cannot be rerouted. The route
block moves into _runtime_profile to keep _binding under its CC cap.
Single-profile: clear the stamp before admission; _capture_scope has
already kept it for egress.
Refs #143547
Co-authored-by: Ben Barclay <413810+benbarclay@users.noreply.github.com>
Any local session (Desktop chat, CLI run, Kanban worker) adds a LOCAL
adapter to a satellite profile's adapter map. The shared-bot fallback
at three sites tested that map for truthiness, so once it held LOCAL
the satellite stopped borrowing the primary's routed bot and its cron
results, heartbeats and background notices failed as "not
configured/enabled".
has_credential_platform() ignores LOCAL when deciding whether a profile
has a bot of its own; _adapters_for_profile, tick_adapters_for and
_drain_restart_safe_cron_deliveries use it. _adapters_for_profile keeps
the satellite's LOCAL adapter layered over the borrowed primary map.
Refs #143547
Co-authored-by: liuhao1024 <11816344+liuhao1024@users.noreply.github.com>
An adapter that cannot cache a download leaves its remote URL in
media_urls (DingTalk always does). Native capture takes only local
regular files, so that one entry raised invalid_params and the whole
message, text included, was refused before the agent saw it.
At the envelope boundary, drop each non-local media entry (and its
parallel media_types / media_text_inlined entries) and append a short
note naming the dropped attachment to the text. Malformed media lists
still reach validation and refuse as before.
Refs #143547
_park_last_fatal_platform re-stamped _serving_state() unconditionally, so a
fatal during an external drain turned draining into degraded while
_external_drain_active stayed true; the watcher could not repair it because
_enter_external_drain is idempotent. The parked flag is still set, but the
status stamp is skipped while an external drain or shutdown is active.
_exit_external_drain already stamps _serving_state(), so the release now
reports degraded.
Refs #143547
_start_handle_no_connections tested `startup_nonretryable_errors and not
startup_retryable_errors` twice in a row, once with the ownership-conflict flag
and once without. Test it once and branch on the flag inside. No behaviour change:
the exit-78 conflict tests and the degraded all-fatal test pass unchanged.
Refs #143547
The startup fix kept an all-fatal boot up as `degraded`, but the same unusable
bot still stopped the gateway when it happened mid-run: a Telegram token revoked
while running, or a polling conflict after its retries ran out, made
_handle_adapter_fatal_error_impl log "Shutting down gateway cleanly" and call
stop(). That exits 0, so under systemd Restart=on-failure the gateway stayed
down with cron and the local attach endpoint.
When the last adapter fails non-retryably and the code is not an ownership
conflict (is_global_startup_conflict), _park_last_fatal_platform now parks it
like startup does (_startup_parked_platforms), re-stamps _serving_state() as
`degraded`, logs one ERROR naming the platform, error and remedy, and returns
without stopping. An ownership conflict mid-run still stops. The retryable
branch and on_all_adapters_down are unchanged.
Refs #143547
When every enabled messaging platform failed non-retryably at startup (WhatsApp
unpaired, missing token, Node missing, port held), _start_handle_no_connections
exited 78. That took every local client (CLI, TUI, Desktop) and cron down over one
unusable bot. The mixed and partly-connected cases already parked the platform
and kept running.
The aggregate step now records whether any startup failure was a real ownership
conflict (is_global_startup_conflict: another gateway holds the token/profile).
Only that still exits 78. Every other all-fatal boot parks the platforms, logs an
ERROR naming each one, and runs as `degraded`. The per-platform runtime status
stays `fatal` with its error code.
Refs #143547
Co-authored-by: Tsury <4947581+Tsury@users.noreply.github.com>