Rebasing onto main brought three new detached spawns the ratchet flags:
- gateway exec quick commands: awaited, and the timeout/cancel path kills the group (_stop_exec_tree);
- managed session workers: covered, the worker kills its own group when its owner dies (_die_with_owner);
- runtime gateway start: a gateway daemon launch that must outlive its launcher.
A child started in its own session or group (start_new_session, os.setsid /
setpgid / setpgrp, windows_detach_popen_kwargs) does not die with a SIGKILLed
Hermes: it reparents to init and runs forever. That is how every family this PR
migrates leaked. With the families on spawn_owned, this keeps the class closed.
scripts/check_detached_spawns.py (AST) flags those shapes in the production trees
unless the line, or the line above it, says `detached-spawn: ok — <why>`. It runs
in scripts/check ("detached-spawns") and as a blocking lint.yml step. The baseline
is empty: every remaining site is on spawn_owned / own_process_groups, or carries
its reason. The reasons this commit adds are the census verdicts:
- must outlive the starter on purpose: restart watchers, /update and the updater
hand-offs, dashboard/desktop/service launches, cron and kanban workers
(restart-safe), the update-custody watchdog itself;
- awaited with a group kill on timeout: cron scripts, rg search, the Browser Use
CLI, update completion (holds the checkout lock fd);
- covered by its own parent guard: the compute host (compute_host._parent_guard_loop
flushes sessions; a supervisor KILL could cut that short);
- not a spawn: the wake-word `start_new_session` config key and event field.
tests/scripts/test_check_detached_spawns.py: each shape flagged, non-detached and
commented/string shapes not, the marker opts out on its line or the line above
and nowhere else, tests and the helper are out of scope, main() fails on a new
unmarked spawn, and the repository scan is empty. Teeth: appending an unmarked
start_new_session Popen to tools/file_operations_search.py turns
`scripts/check --only detached-spawns` red (rc 1); restoring it turns it green.
Review finding (P2): the Bot Chat stream callback only held back a reply whose
WHOLE buffer could still become a marker, so "Paris.\n\nNO_REPLY" streamed
'\n\nNO', '_RE', 'PLY' to message.delta and the TTS queue before the final
filter dropped it.
SilenceMarkerStreamHold (gateway/response_filters.py) gates deltas with the
same predicates the gateway stream consumer uses (is_partial_silence_marker /
ends_with_partial_silence_marker): it holds a last line that could still
become a marker, releases it once it diverges, and at turn end releases what
the completed reply delivers, so "NO problem" / "NOTE: done" / a bare final
"NO" still arrive in full. Deltas and TTS share one emit path.
Greptile "Long replies still show markers": at stream end the overflow
split ran on the raw buffer, so a reply just under the limit split right
before its closing NO_REPLY and the bare remainder went out as its own
message. Drop the closing marker from the display buffer before any split
(seal-overflow and first-send paths); the transcript keeps it.
A model that answers and then closes the same message with a marker line
("Here is the answer.\n\nNO_REPLY") had the marker delivered as text: the
silence filters only match a response that is exactly a marker. Strip a
marker on the reply's last line at every delivery door (final send, stream
previews and final edit, crash-left replay, Bot Mode relays). A bare marker
still goes through the silence verdict, a marker inside a line is prose, and
stored history keeps the model's text.
The gateway's timeout notice looked up the Discord-only
`expire_exec_approval` on the adapter's type by name and called it to
strip the card's buttons. That method duplicated `edit_message`'s
channel lookup, formatting and truncation.
Since #145948, every Discord approval card with a request id registers
a settle observer. A card whose request had already ended is retired
right after it is sent. On timeout, the observer's `retire("timeout")`
removes the buttons, so the notice only needs to replace the text.
`_edit_card` now always uses `edit_message`, and
`DiscordAdapter.expire_exec_approval` is gone. A timed-out card
therefore gets one button-removing edit instead of two, and core no
longer probes for a platform method by name.
`edit_message` is the streaming editor: content over the platform's
limit is truncated in place behind a dangling "(1/N)" marker, and the
adapter keeps a saturated-preview entry for it until a final edit that a
card never gets. After the timeout the card's text is the only record of
the command, so the body now gives the command whatever room the
adapter's per-chat limit leaves, measured in the platform's own units
(`max_message_length_for_chat` with `message_len_fn_for_chat`, so
Telegram's UTF-16 count is honoured). `_ea_fit`'s own copy of the
prefix bisection becomes `fit_prefix` in `gateway/platforms/base.py`, a
suffix-adding wrapper over the existing `_custom_unit_to_cp`, shared by
both. A run of three or more backticks in the
command would close the card's fence and let Discord's formatter rewrite
a table after it into a longer bullet list, so such runs are split with
zero-width spaces. The body is built inside `_edit_card`'s guard, so a
failure there still falls back to sending the notice.
The lifecycle test that races the timeout notice against `retire` now
drives the notice through `edit_message`; both orders still end with
the notice text and no controls. A new test drives the real
path, `_post_timeout_notice` → `_edit_card` → Discord's `edit_message`,
with a 5,000-char command, a heredoc holding fenced Markdown tables and
a run of seven backticks: one in-place edit that fills the message
exactly, only the card's own fence, no "(1/" marker, no preview entry,
no new message. Another fills a UTF-16-counting adapter with ASCII and
with emoji, and one whose limit lookup raises still gets the notice as a
new message. Removed the two tests of the deleted method; the two notice tests' fake adapters gain
`max_message_length_for_chat` and `message_len_fn_for_chat`.
Raised by review of #145948. `expire_exec_approval` and the probe came
from 4f86e97791 (Gille, 2026-10-27, #145948).
connect_gateway's restart-wait refusal read the state discovery returned. A restart that began
between discovery and the WebSocket dial still admitted the Kanban worker on its interactive
ticket into the after-turn wait, where each prompt.receipt answer refreshed its silence budget
and held `hermes update` until the forced-restart deadline.
The policy now rides the ticket: inside outside_restart_wait() the session-ticket request carries
`restart_wait: "refuse"`, the ticket store records it on the grant, and GatewayRuntimeAPI decides
admission from the grant at redeem time, so the owner closes the socket (1013) whenever its
restart wait is open by the time the worker connects. Interactive clients still attach (#139041).
An owner older than the client refuses the unknown parameter; the client re-mints without it and
keeps the pre-dial check rather than stranding the worker until that owner restarts.
_drop_remote_media (main, 538755f) strips an uncached remote URL from
media_urls/types/inlined so the rest of the message is admitted. Relay
keeps a public URL whose download failed together with its original
name, so the new media_filenames list stayed one longer than media_urls
and the length check refused the whole message again.
Relay inbound attachments are localized to random relay_media_<x> temp
files, and that random basename was the only name left. The wire
media[].filename was dropped, Content-Disposition only contributed its
extension, and the document note showed the random basename as the
user's filename.
- MessageEvent.media_filenames: per-attachment original name, parallel
to media_urls with the same invariant as media_types ("" = unknown).
- _event_from_wire fills it from media[].filename by URL lookup. Older
connector payloads without the field still parse.
- RelayMediaClient.download_with_name returns (path, name). It prefers
suggested_name, then Content-Disposition parsed with the stdlib MIME
parser (quoted values, RFC 5987 filename* preferred over filename).
download() keeps its path-only signature. Storage stays a random temp
name, so duplicate names never collide.
- _localize_inbound_media carries (url, mime, name) triples, so a failed
download never shifts a neighbour's type or name.
- Document, audio and video notes use the original name when known. A
relay temp file with no known name is labelled
"(original filename unknown)" instead of its random basename. Native
cache paths (doc_<id>_<name>) render exactly as before.
- Names are untrusted: basename only, control/format characters
dropped, 255-char cap, and the existing note regex replaces quotes
and brackets.
- The names survive pending-message merges, text batching, /queue and
the native admission envelope. The envelope omits the field when no
name is known, so existing admissions keep their fingerprint.
A scheduled heartbeat muted interim messages by rewriting the turn's display
settings, and the agent build read that muted value to freeze the session's
delegation mode. Heartbeats run under the user's session key, so on a cold
agent cache a heartbeat built (and cached, and pinned) an inline agent for an
interim-on chat, and the user's later turns ran inline. The heartbeat rewrite
no longer touches interim: TurnRunner already drops interim messages for a
heartbeat turn, and the TurnContext keeps the chat's configured value, which
is what a fresh agent's delegation.gateway_mode reads.
A fresh agent restored its session's tools[] pin (schema bytes) but kept the
build-time inline flag, so the next rebuild from fresh definitions
(compaction boundary, /reload-mcp, Bot Chat refresh) re-derived the other
variant and flipped the chat mid-conversation. restore_agent_tool_prefix now
re-freezes the flag from the restored delegate_task, making the pin
authoritative.
Docs: inline turns past the notify interval still get the long-running
notice (display.long_running_notifications); the stability sentence now
names compaction, /reload-mcp and heartbeats, and the post-update exception;
a deferred delegate_task (tool_search.defer) stays background.
Tests: heartbeat-first turn with an agent cache (interim on stays
background, control, interim off stays inline), a composed cell with agent
cache + real SessionDB pin + heartbeat + restart, and pin restore followed by
a compaction or /reload-mcp refresh in both directions.
On a messaging chat with display.interim_assistant_messages off, a top-level
delegate_task still produced two messages: a "checks are running, I don't have
the findings yet" reply and, later, the real answer. Top-level model
delegations always run in the background (ea8a8b4af8), and the tool text tells
the model to "give a one-line status and END YOUR TURN" (c89f3b8800). That
status is the turn's final answer, not interim text, so no display setting
held it back.
New key delegation.gateway_mode: auto | inline | background (alias async).
auto (default) joins the children inside the turn on a messaging chat whose
resolved interim setting is off (global, display.platforms.<p> override or
platform default). The parent waits in the tool call, gets the results there
and sends one answer. API, local and webhook surfaces keep the background
path under auto. Chats with interim messages on are unchanged: same schema
bytes, same async dispatch.
How it works:
- The gateway resolves the mode from the turn's own profile-scoped config
when it builds a session's agent (gateway/session_execution.py), and the
agent's first tool build freezes it (like the one-shot pin).
- An inline session carries the joined delegate_task variant the one-shot
path already uses: "results return in this tool call", no live-control
parameters, no END YOUR TURN.
- Dispatch follows the delegate_task schema the session carries
(session_joins_delegation), so schema and behaviour cannot disagree. The
schema rides the session's tools[] pin: a config change applies from the
next session (/new), as delegation.backend does, and a cache eviction or
restart never flips a running chat.
- Inline children run on the existing synchronous path: attached to the
parent, so /stop and an interrupting follow-up stop them; the per-child
heartbeat keeps the parent's activity fresh for the inactivity watchdog;
the async completion registry is not used. Nested and one-shot delegation
are unchanged.
Refs #95522.
A drain cancelled while on_processing_start is awaited left the typing refresh running and the
row's bracket in producer_turns, because producer_turn's finally was not entered yet. Release both
before re-raising.
A relay chat message has been admitted natively since the session authority shipped (e75bc52f50,
first released in 0.22.3; e3fdebbf87 moved it into gateway/relay/inbound_admission.py):
RelayAdapter._on_inbound commits it through admit_producer and the authority's drain runs it.
The typing refresh and on_processing_start/on_processing_complete only ever ran in
BasePlatformAdapter._process_message_background, which that path never enters. So a relay
message got no in-progress reaction, no typing / Slack "is working" status, and no outcome
reaction; only tool progress re-sent typing, so a turn without tools showed nothing. Slash
commands still go through handle_message and kept theirs.
The turn executor now brackets producer-admitted turns (relay and webhook deliveries; a messaging
admission's own adapter task already brackets it):
- admit_producer marks the event it commits; SessionAuthority._admitted records a freshly queued
row in the commit's own tracked task. A re-send of a row already running or settled is not
marked again, and a cancelled queued row drops its mark (_settle_cancelled).
- execute_admission opens the bracket when the row starts executing, not when it commits: a
message queued behind a running turn is acknowledged when it runs, as the in-band queue does
(run_turn_followup_ack) and as 0.22.2's drain task did. It starts the adapter typing refresh
with the event's thread metadata and runs on_processing_start.
- Typing lives as long as execution and stops before the reply is sent (#117300 pauses it there).
- The outcome is reported once: an interrupted turn as CANCELLED and a failed one (exception, or a
failed result) as FAILURE when execution ends; a completed one after settlement, from the
reply's send in deliver_settled (deliver_response now reports whether it delivered), or as
FAILURE when settlement dropped the reply.
- Adapters that render neither typing nor processing hooks (webhook) get no bracket; scheduled
wakes and heartbeats are not producer admissions, so they stay silent.
pre_gateway_dispatch still fires once at admission, admission stays off the transport reader and
the ACK semantics are unchanged: the bracket lives entirely on the execution side.
Reuse an eligible housekeeping reply before output transforms, persistence
and receipt generation when the local host requires a reply. Keep permitted
silence and marker-only warnings unchanged.
Reconcile recovered stream finals with their own delivered segment,
including transformed text and split previews. Treat short recovered
answers as successful replies and sanitize them before persistence.
Cover local gateway composition, output hooks, recovery, receipt identity,
stream transports and the unchanged silence controls.
Review finding P2 on #146120: cancelling the hot-serve's bare asyncio.to_thread
await left the reservation worker retrying. Once the transient holder let go it
took the profile's gateway.lock flock AFTER the canceller's ownership cleanup,
with no coroutine left to build the authority or release it (the gateway stop
cancels the reconcile watcher, then releases reservations).
reserve_waiting_out_transient_holders takes a cancel Event: checked before each
attempt, its waits wake on it, and a grant that lands after it is set is
released at once (ReservationCancelled). reserve_profile_home_in_worker runs
the hot-serve reserve with that Event; on CancelledError it sets it, waits for
the worker to finish (absorbing further cancels), undoes a reservation the
worker completed first, then re-raises. Boot's reserve runs synchronously on
the loop before any task can cancel it, so it needs no wrapper.
The flock is never bypassed: one gateway per host, two gateways never both own
a profile.
The running multiplexer's hot-serve reserved a new profile's gateway.lock with one non-blocking
attempt (run_runtime.reserve_profile_home); a client discovery probe holding the flock in that
instant made it OwnershipConflict, and the profile was parked as "home owned by another gateway"
and only retried on an explicit control-socket rescan.
The bounded retry from the boot reserve moves into one shared helper,
runtime_ownership.reserve_waiting_out_transient_holders, used by both the boot reserve and
hot-serve: a contender that is gone by the re-check (a probe) is retried after a 15 ms backoff, a
browse reconcile or unpublished record is waited out, a live foreign owner still refuses at once,
and one fixed deadline bounds it all. Every grant is a real reserve. Hot-serve runs the reserve
in a worker thread so a wait never blocks the event loop.
Tests use real flocks held by a separate process (probe and live owner) through the real
_serve_profile_runtime, plus a persistent-flicker case that still refuses at the deadline; the
boot control asserts refusal well before the deadline instead of an absolute wall-clock bound.
Discovery (`gateway ensure`, every client's liveness check) answers "is a reservation pending?"
by taking gateway.lock's flock for an instant (gateway.status._probe_lock_file). A booting
gateway whose non-blocking reserve landed in that instant re-checked which homes conflict, found
none (the probe had already let go) and still raised: `Cannot reserve gateway profiles`, exit 1,
and the client that started it reported runtime_exited. _conflicting_homes' own docstring already
promised "a home freed meanwhile is simply not listed; the next reserve attempt takes it".
- run_bootstrap._reserve_waiting_out_browse_reconcile: an empty conflict set retries (still
bounded by the existing deadline); a positively identified foreign owner still refuses at once.
- runtime_ownership.lock_record_unpublished: a record naming the CALLER is its own rolled-back
all-or-nothing attempt, so a probe holding that home during the re-check is not an owner.
Fixes the CI flake in test_multiplex_hot_serve_live::
test_named_profile_ensure_during_multiplexer_downtime_starts_the_multiplexer.
CanonicalHostedRoomService's status dropped every service retry row and its
retry_room_task only knew deferred attempts, so on the gateway route the
stalled room showed no Retry and groups.retry answered stale_generation. Keep
the prepare:<room_id> row and hand that task id to the shared service, so both
routes answer the same. The stall test now runs on both routes.
Review of #145981 (P2): after a Send is stored, a room preparation that keeps
failing (a member whose profile was deleted, a full room log) retried on every
driver pass forever, and the error only overwrote the process-wide driver
last_error that no client renders. The user saw "sent" and no member answered.
Now each room counts consecutive preparation failures (contention and
ownership moves never count). The third one appends ONE member.unavailable
event to the room ("Members could not be woken: <reason>"), which Desktop and
the Webapp already render, using the control headroom so a full room can still
say why. The room's status lists a Retry row (groups.retry, task_id
prepare:<room_id>) and a per-room last_error, and the driver stops preparing
that room until the next Send or Retry. A failed Retry stays stalled and is the
RPC's error, without a second notice.
Refs #145977
A room the gateway took over from the standalone backend
(hosted_rooms_gateway_import) refused every groups.send with
invalid_params after storing the message, and no member was woken.
The handoff commits two authority transfers: the standalone copy's fence
(authority.lost, install -> install:gateway-store, epoch 2) and the
gateway store's claim (authority.claimed, gateway-store -> install,
epoch 3). The history reader and the work-record lineage took span
boundaries from authority.claimed rows only, so the chain started at the
gateway store and the epoch-3 claim did not extend it: "authority claim
does not extend its predecessor" from every prepare_room, on Send and on
each driver pass.
authority.lost is the outgoing owner's committed record of the same
transfer (same system actor, same previous/next/epoch payload), so both
readers now count it as a span boundary under the same checks. The chain
reads install@1 -> gateway-store@2 -> install@3. Nothing is rewritten:
rooms users already imported (state.db epoch 3, shared-state.db epoch 2)
work as they are. A fork (a claim whose previous owner is not the
recorded holder, a skipped epoch) is still refused.
Send also stops reporting a stored message as failed: once the user
event commits it is the Send's result, and a failure preparing the room
afterwards is logged and left to the room driver, which runs the same
preparation on its next pass (#143239).
Final-head review folds:
- _protocol_violation_streak's legacy text match now reads only the error head, before
WORKER_OUTPUT_SEP (" Worker's last output: ", now one named constant shared by the writer,
the streak and apply_attempt_note). Every crash quotes the worker's output, and a retry worker is shown
the previous attempt's protocol-violation error, so an ordinary crash that echoed the phrase
lengthened the streak. That drops the worker_lost-only exception added earlier.
- website/docs kanban.md said resolving an unknown admission "does not authorize another Kanban
attempt". On this branch an unbound run whose owner settled the admission is released once its
recorded pids are dead (or, with none recorded, once the claim expires): booked crashed, or
reclaimed if the claim had lapsed, so the card can be retried. The paragraph and owner_reclaim_paused's comment now say so.
- owner_attempt_provably_over's docstring drops the incident count and its outdated premise
(only killed owners), and the lapsed-claim comment matches the code.
- record_worker_loss reads policy.kanban_json directly: its policy is always a LocalSessionPolicy.
Test: a crash whose output quotes "protocol violation" leaves the streak at 0 (fails with the
whole-error match).
The salvaged handler awaited the worker_lost board write (a fresh connection plus BEGIN
IMMEDIATE on the cross-profile board, minutes of busy retries at worst) first in
execute_managed's except arm, with nothing after it guarded: a contended board delayed
settling the admission without bound, and a cancellation during the wait (a drain) skipped
lose_admission_worker and left the admission started.
The order stays (the note must land first: the submitter exits on the settled 'unknown' and the
crash sweep then books the bound interpreter, so a later write is dropped and an exit-0
worker_result reads as a protocol violation), but _settle_lost now waits for the note at most
LOSS_RECORD_WAIT_S (10 s; the write carries on as a tracked mutation, which retirement joins)
and settles in a finally, so a cancellation during the wait still settles. On the
pre-reservation path nothing is bound and the drain settles the admission itself, so the note is
not waited for there. record_worker_loss's policy parse moved inside its try, so it really
never raises; a cancellation is skipped by type, not by matching the class name as a reason
string.
Tests, through the real execute_managed with a lost child: the note lands before the
settlement even when the write is slower; a cancellation while the board write is held still
settles the admission 'unknown'. Each fails on the matching mutation (no wait; no finally).
Also the wiring through _record_lost_attempt (a Stop, a superseded generation and a
cancellation record nothing; a real loss records one event the next tick books), and the
superseded-run drop proves a write happens before it proves one is dropped.
A managed worker that dies in the worker.adopt handshake writes no
worker_bound/worker_result: the gateway logged "Managed worker lost" and
returned, nothing failed the run, and the card said "running" for 49
minutes on a corpse (2026-10-22, t_f5fad63f, run 730: claim_expires 2067 s
past, last_heartbeat_at NULL, consecutive_failures 0).
D1 detection without disposition: gateway/session_kanban.record_worker_loss
writes a run-scoped worker_lost event on the board (dropped when the card
moved past that run) and session_managed_worker calls it on every loss
except a deliberate stop / stale generation.
D2 an elapsed claim lock read as "still running":
- owner_attempt_provably_over treats a SETTLED owner admission as proof the
attempt ended, instead of demanding the owner PROCESS be gone (the owner
is the live gateway, alive by design) - the reason every reclaim path
declined for 49 minutes;
- the reclaim's kill step reads a bare OSError on an absent pid as Windows
does (WinError 87), so "already gone" no longer means "termination not
proven";
- reclaims/reaps name the loss in the run error via owner_attempt_note;
- a loss charges consecutive_failures like any other crash (A3), so the
failure_limit breaker covers this class.
D3 adopt handshake budget: 60 s default, HERMES_WORKER_RPC_OPEN_TIMEOUT
override, and a TimeoutError is retried with backoff (auth/protocol errors
never are).
Tests: tests/hermes_cli/test_kanban_managed_worker_loss.py (A1-A3, D1
write side, kill-step semantics) and tests/agent/test_worker_rpc_adopt_timeout.py
(A4). 16 passed under the production interpreter.
The runner tunnelled the approval request id to Discord as a private
`_approval_request_id` key inside the platform metadata dict. That dict
goes to every adapter that renders approval buttons. The relay adapter
forwards it verbatim, so the private key reached the external connector
in every approval prompt frame.
Add an optional `request_id` to `send_exec_approval` and to
`ExecApprovalPrompt`, have the runner pass `approval_data["request_id"]`,
and have Discord read `prompt.request_id`. The metadata passed to the
adapters is back to the thread routing it carried before the PR (`None`
in a plain chat). The always-true `"timeout_s" in approval_data` guard
goes with it.
Native-button adapters render through `_send_exec_approval_prompt`,
whose signature is unchanged. The only `send_exec_approval` override,
`LocalSessionAdapter`, takes `**kwargs`, as does every test double, so
no other adapter or double changes.
Review follow-ups on #145566:
- Policy checkpoint: turn.deferred receipts (explicit user retries) are bounded on
their own, so a discussion configured to its full max_rounds no longer stalls when
a deferred turn is retried while it runs.
- Both routes run a member's file preparation through prepare_before_submit: a file
the member can never take (over gateway.max_inbound_media_bytes, unbound, expired)
settles the turn as failed; a transient failure is proven not admitted and is
requeued with backoff. Neither pauses the room as uncertain execution.
- Ink TUI: the backends' "not available on this Hermes backend" answer is no longer
read as version skew; it renders a translated methodUnavailable line. The
invalid-params skew warning and older backends' bare wording are unchanged.
Refs #144648 (WA-20)
Any unknown JSON-RPC method on the tui_gateway route answered "the client and the Hermes
backend are out of sync (different versions)", which the Desktop/Webapp toast turns into
"update both" even on matching versions. A JSON-RPC client sends no version, so neither
route can know the versions differ: both now answer -32601 "unknown method: <m> — not
available on this Hermes backend" from one helper (the "unknown method:" prefix clients
match on is unchanged).
The concrete case was the group composer's groups.attachment.upload, which only the
gateway route served, while HostedRoomServerRPC declared accepts_attachments=False so a
member turn with a file failed attachments_unsupported_on_route. The tui_gateway route now
serves groups.attachment.upload/download over the same room attachment store, and its
member transport resolves event-bound bytes per member exactly like the gateway route
(bound_submission_payload, shared): documents ride as prompt path lines, images as an
in-process-only _hosted_images list handed to the turn as its image paths.
Refs #144648 (WA-20)
Refs #145184
Review follow-ups on the engine-routed gateway /compress:
- a plugin result larger than the original is refused like the agent
path does (report: "Compression refused (summary would grow ...)").
- a cold session's engine gets model.context_length (when it describes
this runtime) or the custom provider's window, as agent init passes it.
- a one-off engine gets on_session_end on every exit: no change, a raised
compress(), a refused commit; the compression boundary stays
commit-only.
Agent init assigns compression.model_thresholds to a plugin engine before
its first update_model(); the cold gateway path now does the same. The
context-engine guide states what manual /compress calls and which boundary
hook follows the commit.
Since the unified gateway, session.mutate(compress) always summarized with a
fresh native ContextCompressor and published the rewrite. A plugin context
engine (context.engine: <plugin>) was never asked to compress and never saw
the compaction boundary, so the next agent's engine re-stored the retained
replies it had already stored (LCM-X: 10-11 surplus rows per forced
compaction).
prepare_compress now compresses with the session's own engine when it is a
plugin: the resident agent's engine, else the one the frozen policy names,
selected and bound the way agent init does. After the receipt commits (and
before the boundary eviction), the gateway sends the agent path's
post-commit notification: on_session_start(boundary_reason="compression")
plus the relay/metrics segment hand-off, which the native gateway path also
skipped. A cold session's one-off engine then gets on_session_end, the same
boundary a resident agent's eviction gives. The revision/generation fences
and publication ownership are unchanged.
Fixes#143587
Review of #145629:
- The import skips every room id the gateway store has ever known, held or
reserved in hosted_room_retired_ids, so a room disbanded in the gateway is
not copied back from its fenced standalone source once the tombstone is
pruned. Handed rooms are also recorded in the source
(hosted_room_gateway_handoffs) and never offered again.
- A standalone backend writes locally only when no gateway serves the
profile (absent, or an incompatible one that never imports). A starting or
restarting gateway is waited for (20 s bound), any other present one is a
retryable refusal. The gateway imports once more right after ready, off
the loop, in the owning profile's scope.
- Room calls go to the store that holds the room: standalone-only rooms run
locally, rooms handed to the gateway go to the root gateway (the only one
that imports), everything else to the selected profile's gateway.
groups.list merges them, so a named-profile gateway never hides an
existing room.
A native Desktop on a standalone `hermes serve`/`hermes dashboard` (no session
authority) kept rooms in the root shared-state.db with its own driver, so they
never appeared in the gateway's list that the Webapp and gateway-backed Desktop
share.
- tui_gateway route: when a ready gateway serves the profile, the Desktop's
groups.* calls go to it (owner_forward.forward_rpc, the path prompts already
use); with no gateway they run locally as before. RoomLink peer methods stay local.
- gateway: on hosted-service start the root home's gateway fences each
standalone room in shared-state.db (authority.lost to `<install>:gateway-store`,
so the standalone driver stops binding it and every write there is refused),
then copies the fenced rooms it lacks into its state.db and claims them
(authority.claimed, owner = host owner). Idempotent and crash-safe; the source
rows are kept.
- gateway-less standalone list hides rooms already handed over.
Refs #144648 (WA-19)
Refs #145184
puts back what that build deliberately left for the remote backend, on
main's seam shape:
- RemoteBackend implements main's protocol (read_user_doc, probe_readable)
and is not a FileBackend; _route returns (backend, home) and explicit
files go through _ExplicitFile, so the is_layer branches are gone.
- One bootstrap: _ensure_bootstrap_env / bootstrap_deployment select the
backend from the process env, the launch home's .env and the managed .env.
#134362's _dotenv_backend_override did not survive its file-only refactor,
so nothing stacks; its rules are now tests (stale shell remote + .env file
boots file; empty .env value resets to file; .env-only remote selects
remote; an absent key keeps the shell value).
- The file-tooling gates main removed (backup/import/snapshot restore,
config edit, migration write-back, config backups, profile clone and
distribution install, raw config editor, xAI migration, gateway --config).
- profile_serve_signature uses the backend version for config.yaml.
- restore_config_model_settings_if_rewritten is a no-op without file tooling.
- PM's dependency runtime reads a home's selection from the local file it
publishes to (config_backend.local_file_layer), so a remote deployment
never needs the plane there or fails PM closed.
- Ratchet: _container_slots/_validate_quoted_containers move to
config_value_checks, _count_cron_jobs to backup_restore, the gateway
--config load to gateway/config_loader.
andrexibiza P1-B. ConfigBackendUnavailable subclasses SystemExit on purpose: a fail-open reader
must never serve defaults instead of the selected backend's config, and boot fails closed. That
contract stays. But long-lived consumers caught only Exception, so a plane blip after boot killed
the thread (or, inside an asyncio task, stopped the gateway's event loop).
The six named sites, each with its own outcome:
- gateway/readiness._probe_config: the existence check moved inside the guard; the outage reports
{"status": "degraded", "detail": "config backend unavailable"}.
- cron/scheduler._load_cron_job_config: still refuses defaults (its except Exception lets the
outage through); run_job, the fire's owner, now catches it and returns that fire's failure
result; _run_one_job_body records it like an Exception (mark_job_run(False), finish_execution,
crash notice) instead of re-raising into the ticker.
- cron/jobs._main_model_pin (moved to cron/jobs_model_pin.py to keep jobs.py under its cap):
raises ValueError, so pinned=True create/update is refused as invalid input instead of silently
dropping the lock or exiting.
- tui_gateway/server._profile_configured_cwd: None (logged); the cwd is a hint.
- tui_gateway/server._load_cfg_raw: the designed FailedConfigRead; _refuse_failed_read now
refuses to save it with "could not be read", not "formatting error".
- tui_gateway/prompt_attachments._profile_attachments_storage: "" (logged): attachments stage in
the profile home the sandbox mounts and the vision allowlist cover.
The owners above every other config read on a long-lived path (sweep in the PR body):
- TUI request owner already answers 4064 (_handle_admitted_request); deferred agent-build and
resume-hydration threads now report agent_error / the resume failure and release their waiters;
compute_host turn and frame workers answer turn.error / their error frame.
- gateway platform turn (_process_message_background) notifies the user and ends the turn
instead of re-raising this SystemExit into the loop; api_server gets an outermost
config_unavailable_middleware (503) since entering a profile scope reads config; the served-
profile reconcile watcher and _serve_profile_runtime park the profile for the next rescan.
Tests: tests/plugins/config_backends/test_remote_unavailable_consumers.py (13), each raising the
real ConfigBackendUnavailable from the seam the consumer calls; every production file's fix was
reverted alone and its test(s) went red.
The ratchet (scripts/check --only health, new on main) freezes every
file over 2,000 lines at its main size and blocks blind excepts.
- Facades back at or below their main size: the backend seam's local
imports become module-level ones (config_exists via hermes_cli.config
where that is already imported), and unrelated pure helpers move to
topical siblings: _job_doc_header -> cron/scheduler_prompt.py,
_csv_or_list_to_set -> gateway/run_common.py, the dotted config-path
pair -> hermes_cli/backup_restore.py, voice/timezone/web checks ->
hermes_cli/config_value_checks.py, a new profile's config document
(seed, migrate, backend read) -> hermes_cli/profiles_config.py, pet
spritesheet helpers -> tui_gateway/pet_sheet.py. Callers import from
the defining module (no re-export).
- BLE001: _load_config_dict catches YAMLError/OSError/UnicodeError;
run_migrations inlines the step loop again (the moved blind except
keeps main's identity); the two intentional fail-opens carry
'# health: allow' with their reason.
plugins/config_backends/remote serves each profile's user layer from the
config plane: boot fetch inside load_hermes_dotenv with bounded retry and
fail-closed exit (D2), per-process ETag poller (D9), key-level diff writes
with CAS and one conflict retry (D10), client-side lock and secret-literal
checks (D7, D17), in-memory migrations (D12), managed config.yaml ignored
(D18), plane credential from auth.json or IdP client credentials only and
never from a secrets: source (D26, D32). Vendored gg conformance fixtures
run against the lock matcher, secret rule and _deep_merge.
Review of #145598 (comment 6448254020):
- Chats a Webapp tab imported before the upgrade open again: session_history_mount._reader read the
import binding by string equality while the sidebar (authorize_history) used the owner rule, so
the sidebar listed the chat and the open refused it. Both now ask binding_names().
- An old chat a Webapp tab edited is adopted again: bind_legacy_target compared the binding exactly.
- gateway.owner_identity.same_owner is now the one owner rule (owns_row_stamp folded into it), and
every comparison of a stored owner/binding/principal with a caller in gateway/ goes through it.
- Local stamps match this machine's account only.
- hosted_auth_probe: restore the refused groups.create over another tab's room id and the
'FORBIDDEN' never reaching the model, adapted to the single-owner contract.
Hermes is single-user (maintainer ruling): sign-in only gates whether a browser may open the
Webapp, it never creates a second identity. Every login (Webapp tab, loopback session token,
a dashboard login forwarded by a standalone backend, the dashboard's PTY child) now acts as the
host owner's OS subject (uid:<n> / sid:<sid>), on both routes:
- gateway route: AuthorityConnection and the REST session-mutation context build the principal
through gateway.owner_identity.principal_subject.
- tui_gateway route: rows a login creates over hermes serve carry the owner subject instead of a
<provider>:<user> label, so native Desktop and the TUI resume them.
Stored login stamps from older builds read as the owner's (read-time, nothing rewritten or
deleted): auth:v1 room owners and history bindings, and <provider>:<user> labels of a bundled or
registered dashboard sign-in on routeless local rows. Messaging ids (telegram:42), other OS users
(uid:N) and nous: stamps on non-Desktop rows stay foreign.
Owner-only sign-in: basic auth has one account and the Nous Portal refuses other accounts for the
registered agent client; self-hosted OIDC admitted every IdP account, so it now admits one:
dashboard.oauth.self_hosted.owner, or the first account to sign in, pinned in
dashboard-auth/self-hosted-owner.json.
Store writers announce a route change outside the store lock, and a worker
thread's announcement is queued onto the owner loop. A worker's /resume of A
that announced after a newer /new had moved the chat to C reattached A to the
chat in memory while the store still named C: the app's next prompt on A ran
in C and its reply reached the chat. The owner now applies an announcement
only while the store still names that conversation (by logical owner); the
newer write announces itself.
Review on #144840 (2.1 store-to-owner route announcements).
Found re-running the live legs on the re-review fixes. A process the app's turn started on a
conversation its chat moved past carries that conversation's detached key. When it finished after
the chat resumed the conversation, the key named nothing and the result was refused not_found; after
a restart that left the conversation unmounted the same. Such a result now runs as the conversation's
own turn on the chat's route once the chat names it again, and mounts it off the chat after a
restart. The conversation's detached source drops the chat's last message id (its replies reach the
apps, never anchored to a chat message), so a result's event is that same source.
Re-review N3 of #144840. A background result on a detached key resolved the live conversation through
the active profile scope, but the completion scope is derived from that very source before any scope
is bound, so for a secondary profile the lookup reached the launch profile's authority. Once the
bounded source cache dropped the conversation, the result was rebuilt without its profile and dropped.
The lookup now resolves the owning authority from the key's profile namespace.
Also: the detached branch runs the same source checks as the local branch.
Re-review N2b of #144840. A background process or async delegation started by the chat's own turn on
a conversation before its /new was pinned to that conversation on the chat's route. Once the app had
used the conversation (its turn reopens the row) the pin no longer read as gone, so the result was
refused on the chat's route with a non-permanent reason and retried forever (the #141562 spin), never
reaching the conversation or the chat.
Such a result is now routed to the conversation's own detached key, the path a result of the app's
own turn already takes: it lands in the conversation once (deduplicated by the admission ledger and
the delivery identity), never in the chat. A conversation not mounted (a restart) mounts off the chat
first. A row the /new left ended stays a boundary and its result is dropped once, as before.
Re-review N2a of #144840. A reminder or background result written into a conversation its chat moved
past as a note (no viewer, no turn) reopened the row the chat's /new had ended. The local path already
skips the reopen for notes; the detached branch now does the same, and a result that runs as a turn
(a viewer is open) reopens it as any first turn does.
Re-review N1 of #144840. A reminder created from the app on a conversation its chat moved past names
that conversation (local:<id>). Its fire mounted it as a local session, which a messaging row never
is, so it failed with storage_unavailable once the chat resumed the conversation or once it was not
mounted (any restart), and a recurring reminder died silently.
The fire now mounts such a row as its route would (restore_routed_session): off the chat while the chat
is elsewhere, where it is written into the conversation, and on the chat when the chat names it again,
where it runs as that conversation's own turn.
Review follow-ups on the background-result path of a conversation its chat moved past:
- a reminder the app set on it (origin platform=local, chat = the conversation) fired into a refused
local-receipt restore (storage_unavailable); the fire is now written into the live conversation;
- the process-event source came from the runner's bounded source cache only, so after eviction the
result was rebuilt as a plain local source and refused; the live conversation's source wins;
- liveness ticks and their withdrawal looked the detached key up in the routing index only, so a
finished process left its "still running" ticks queued; both use the detached-aware lookup;
- a result admitted under the detached key and still queued when the chat /resumed the conversation
was refused (permission_denied) at its claim; the conversation's own detached key is accepted.
None of these reached the chat before; each now reaches the app.
A process the app started on a conversation its chat moved past finished into a refused admission:
the watch injection resolved the chat's adapter and looked the detached key up in the routing index,
where it never is (not_found), so the result was retried and finally dropped, and the app never saw
it. It now lands on that conversation as a Desktop session's result does, through the local adapter:
a note in its history with no viewer attached, a turn of it with the app watching. Nothing reaches
the chat. After a restart that left the conversation unmounted it is still refused and dropped with
a log, never routed to the chat.
Review of #144840 (F7): a detached conversation has no route to reset, so each app prompt failed
compression again with no hint. Its reply now carries the guidance a failed overflow turn already
gives (gateway.errors.context_overflow: /compress or /new).
Review of #144840 (F5): when the chat /resumed a conversation while an app turn on it ran, that turn
kept running under the detached key while the conversation moved back onto the chat's route, so the
chat's /stop answered "No active task" and the app's Stop found no agent. The running turn's key
stays findable (session_detached.running_key): the authority's agent and running-slot lookups and the
chat's /stop look there while it runs.
Review of #144840 (F4): the detached conversation kept running on a row stamped session_reset, so
in_place:false compression was refused (parent already ended), listings showed it ended, and a
background completion addressed to it was dropped as pinned to a gone session. The drain's claim now
reopens it, as an API or local turn reopens its own row (reopen_api_session).