Commit Graph

550 Commits

Author SHA1 Message Date
teknium1
605037755a fix(update-check): the passive check's git ls-remote dies with the CLI
`hermes chat` starts check_for_updates in a daemon thread. On an official
source checkout (stable by default since 6a92a2aa49) it verifies the
release tag with `git ls-remote --tags origin`, which forks
`git remote-https`. Spawned with a plain subprocess.run, it shared the
CLI's process group and nothing owned it: a /exit while GitHub was slow
abandoned the thread, and git + its helper reparented to init (the 0.23.2
release E2E caught them, test_terminal_transcript_pty[cli-turns]). Its
60s timeout also killed only git, not the helper.

Both remote-touching probes (the stable tag check and _branch_tip's
ls-remote) now go through source_check.remote_git_run ->
bounded_probe_run(owned=True): own process group, handed to the
owner-death supervisor while it runs, the whole group killed on timeout.

The PTY harness sandbox now sets updates.check: false, as tui_pty's
does: the attached `gateway run` (which outlives /exit by design) runs
the same check, and the E2E must not talk to real GitHub.
2026-11-16 10:12:09 -08:00
teknium1
dd4160aa5a test(e2e-upgrade): handoff tests the restart-pending report, not the removed cap
test_restart_wait_ends_within_its_cap read gateway.log lines ("Restart requested with N active
work unit(s); deferring stop()", "Restart after-turn wait timed out") that the gateway stopped
writing in c9e74fb4be (#155532, restart when idle), so it passed on any log. Its subject, a
timeout force-stopping the restart wait, was removed on purpose.

test_update_leaves_busy_gateway_pending_and_relaunches_after_the_work checks the new contract
over the same held kanban worker (#156542 releases it after `hermes update` returns):

- the update did not stop the old gateway while the worker was mid-turn;
- its output carries "↻ …: still running live work (managed run <session> pid N) — left
  running", naming the worker's managed session (from the card's owner_admitted receipt), and
  the fleet check lists the old PID as restart pending;
- the worker's only run completed, and the gateway that relaunched on the new commit booted
  after it ended.

The n1 column skips it while its start release predates gateway/restart_when_idle.py.
restart_wait_verdict, its log patterns and its unit tests are removed; the new verdict has its
own (test_restart_pending_verdict.py).
2026-11-16 10:07:53 -08:00
Teknium
3007033aeb test(e2e): handoff scenario lets the held kanban worker finish before waiting for the relaunch (#156542)
Since #155532 (c9e74fb4be, "restart when idle — never kill live work on a timer")
a non-forced `hermes update` leaves a busy gateway running with its restart pending
and the gateway relaunches on the new commit once its live work is done; the old
120 s cap that stopped it no longer exists. The handoff scenario held its in-flight
kanban worker inside the fake provider until AFTER settle_gateway() timed out, so the
gateway was (correctly) still waiting on that live worker for the whole settle window
and the 5 relaunch-dependent properties of the head column failed with "gateway alive
but not serving <new sha>" / "update exited 0 though the gateway did not come back".

Release the held worker once the update has returned (it has then spanned the whole
update, which is the property's subject) and then wait for the relaunch. The kanban
"in-flight worker finishes once" property keeps proving the worker is neither killed
nor duplicated across the hand-off.

settle_gateway() now also waits for the API server's /health, as start_gateway() does:
the relaunched gateway answers the control-socket identify in `state: starting` before
its API server listens, so with the relaunch now landing inside the settle window the
next chat raced it (Connection refused) in the first local run of this fix.
2026-11-16 06:38:49 -08:00
alt-glitch
f8acc26834 refactor(gateway): outbound send files move from tools/ to gateway/outbound/
tools/ holds model tools. These three files register none: they send a
message to a platform for `hermes send` and for cron delivery, through
gateway adapters and gateway config. They move to the gateway package:

  tools/send_message_tool.py    -> gateway/outbound/send.py
  tools/send_message_senders.py -> gateway/outbound/senders.py
  tools/send_message_targets.py -> gateway/outbound/targets.py

Twelve test files move with them to tests/gateway/outbound/. Every importer
changes its import line in place. Nothing stays at the old paths: none of
the three names is on the plugin API list, the shipped-release list or the
old-updater list.

Behaviour is unchanged. The logger name stays tools.send_message_tool in
the three files and in the QQ Bot sender that shares it, so the lines stay
under `hermes logs --component tools`. The boundary-lint baseline changes
12 keys and no count, because its keys carry the module path of the
underscore names five bundled plugins import.

The import and docs rewrites were made by scripts/move/rewrite_imports.py
and rewrite_docs.py.
2026-11-16 18:09:07 +05:30
Teknium
2bda0d848b test(telegram): prove quote-replies keep their text through a real gateway
Trim the salvage to its fix: drop the quote-touch refresh (a synchronous
index rewrite on the event loop for every quote-reply, with no report of
eviction in practice) and the HERMES_RICH_SENT_MAX_ENTRIES env knob
(behaviour config does not go in env vars). Replace the mocked unit tests
with two real-gateway invariants against the Bot API stand-in: a
quote-reply to a plain send and to a streamed final, whose echo carries no
body, still reaches the model as [Replying to: "..."]. Both are red on the
base (the quoted text is missing) and green here.

Refs #147287, salvage of #151125.
2026-11-14 05:02:08 -08:00
Teknium
e8f1dfdb5a fix(telegram): only a bare base_url gets the Bot API path; configured proxy paths stay as written
Greptile: Custom proxy routes stop working. bot_api_urls appended /bot to any
path not ending in bot, so base_url https://proxy.example/telegram/ moved to
/telegram/bot<token>; it now appends only when the URL has no path, for
base_url and base_file_url alike.
2026-11-14 03:59:38 -08:00
Teknium
b8241e3453 fix(telegram): a custom base_url without the /bot path no longer reads the token as a port
PTB appends the bot token straight to base_url, so `extra.base_url:
http://127.0.0.1:8081` became `...8081123456:AA...` and httpx parsed the
token's secret half as a port: every connect attempt failed with
InvalidURL("Invalid port: '<secret>'") (#81787). bot_api_urls() appends the
Bot API `/bot` (`/file/bot`) path when the URL doesn't already end in `bot`
or carry PTB's {token} placeholder; the gateway adapter and the standalone
sender both use it.
2026-11-14 03:59:38 -08:00
Maciej Lisiewski
2067fda76a fix(file_safety): read-deny the quarantined auth.json.corrupt credential copy (#155382)
* fix: block quarantined auth stores from file reads

Rebase credential quarantine protection onto current main.

* test(e2e): drop the #121278 KNOWN pin now that auth.json.corrupt is read-denied

The quarantine scenarios in test_workspace_escape.py now assert the denial
outright instead of tolerating the leak.

Fixes #121278

---------

Co-authored-by: KoNit-K <konit.block@protonmail.com>
2026-11-14 12:45:44 +01:00
Teknium
fff87b1e5a fix(update): a worktree or scratch-home update never rewrites or restarts another checkout's gateway
An update run from checkout B with HERMES_HOME a scratch dir under ~/.hermes repointed the
account's live hermes-gateway.service at B's launcher and SIGUSR1'd the live gateway it ran
inside, though its own fleet report called that gateway "separate checkout".

Two holes:
- update_scope_homes(): a HERMES_HOME nested inside ~/.hermes resolves the account root, so
  _profile_homes() put the real default home (and every profile) in the update's scope. A home
  nested inside an inventoried home now owns only itself.
- Nothing compared the runtime's checkout with the updater's. update_fleet_scope now resolves the
  checkout a gateway process runs (cmdline/VIRTUAL_ENV/status argv) and the checkout a unit or
  plist launches (ExecStart/ProgramArguments, incl. the python -c sys.path.insert form); a
  runtime of another checkout is left alone with the existing notice. Wired into the launch-file
  refresh, _systemd_unit_owned_by_update, _scoped_manual_gateway_pids and every
  _drain_or_signal_gateway_for_update caller (the ancestor SIGUSR1 branch included).

Salvage #131105: drop its whole-tree import canary (it imports every shipped module, the very
operation that started the incident, and its audit hook does not refuse os.kill), and the e2e
source-reading AST test; the shim's behaviour is covered by
test_psutil_android_import_outside_an_update_starts_nothing.
2026-11-13 23:49:02 -08:00
ang-fleet-workers[bot]
9481c17fe7 fix(update): importing hermes_cli.psutil_android must not run the update takeover; launchd restart checks label ownership
hermes_cli/psutil_android.py called stop_for_relaunch() at module level,
so any importer (an import smoke, a doc tool) ran a full update takeover:
dependency sync, launcher publication, then finish_update's launchd
restart. Gate the import-time handoff on _old_updater.in_historical_update(),
the same frame-walk gate tools.lazy_deps.install_specs uses; every shipped
caller ran inside _cmd_update_impl.

_restart_launchd_gateway_after_update now applies the
launchd_label_foreign_home rule the sibling loop already applies, so an
invoking label whose plist pins another HERMES_HOME is left alone.

Tests: new tests/hermes_cli/test_import_side_effect_canary.py imports every
shipped module under a temp HOME/HERMES_HOME with an audit hook that refuses
service-manager execs, child interpreters and out-of-root writes. On
be5e9f72c6 it fails naming only hermes_cli.psutil_android; with this change
it passes. Also: test_invoking_label_of_another_home_is_left_alone,
test_psutil_android_import_outside_an_update_starts_nothing, the e2e
import-smoke exclusion of psutil_android dropped (AST check inverted).
2026-11-13 23:49:02 -08:00
Teknium
f730a82558 fix(telegram): name the numeric-id fix when an @username home gets "Chat not found"
The Bot API resolves @username only for public channels and supergroups. A
home channel set to a person's handle (TELEGRAM_HOME_CHANNEL=@name) makes
every `hermes send --to telegram`, send_message and standalone cron delivery
fail with Telegram's bare "Chat not found", while an explicit numeric
telegram:<id> target to the same chat works. The standalone sender now
appends the cause and the fix (numeric chat id via /sethome or
TELEGRAM_HOME_CHANNEL) when the refused chat id is an @username; numeric ids
and other errors are unchanged.

E2E: the real `hermes send` CLI against the Bot API stand-in, red on main.

Fixes #95121
2026-11-13 16:42:58 -08:00
Teknium
2bdf74bf24 test(e2e): routing rows are checked against their owner for every canary
The routing-row scan only checked non-secret canaries, so the launch profile's
provider_key inside an agent:<other>: routing row slipped through: the raw secret
scan treats the launch index as the launch profile's own file, and the row scan
skipped secrets. Each row is now checked for every canary not its owner's; the
raw secret scan stays as the extra WAL/deleted-page check.
2026-11-13 16:40:56 -08:00
Teknium
fc3a8cdec2 test(e2e): the tenancy scanner raw-scans every file for foreign secrets, WAL included
5b5d383 read the launch state.db only through SQLite's current rows and skipped
state.db-wal/-shm, so a foreign credential that was written, committed and then
deleted (its page still in the WAL) was no longer reported; main's raw byte scan
caught it. kvnloo raised this first on the PR.

Secrets (provider_key, api_server_key) are now matched against the raw bytes of
every file again; the per-routing-row owner view applies only to the non-secret
canaries (workdirs) that legitimately sit in another profile's routing row.
2026-11-13 16:40:56 -08:00
Teknium
c172e09c70 test(e2e): peer-route sweep refuses a 200; routing rows are checked as their owner's
- test_peer_route_refuses_every_credential_but_a_peer_pass: a status outside
  the two refusals (a 200 with no `error`, an HTML body) compared None to None
  and passed. It now requires the status to be one of the refusals first. With
  the middleware's no-provider branch mutated to return 200, the old check passed
  and the new one fails.
- file_leaks: the launch home's other-profile routing rows were dropped from the
  scan and never checked at all, since they live only in the shared index. Each
  row is now checked against the canaries of every profile except its owner, so
  beta's workdir in alpha's routing row is a leak in both state.db and
  sessions.json (new scanner test, red before this change).
2026-11-13 16:40:56 -08:00
Teknium
e70202cbd1 test(e2e): the tenancy scanner reads other profiles' routing rows as theirs
eec7e828c0 saves a chat's terminal cwd onto its routing entry
(metadata.terminal_cwd). A multiplexed gateway keeps every profile's routing
entries in the one launch-home index by design (8d74cb52da, #66887), so
alpha's and beta's cwds now sit in the default home's gateway_routing rows and
sessions.json mirror, under agent:alpha:/agent:beta: keys. The byte scan read
that as the default profile carrying their workdirs.

For the launch home, state.db is read through SQLite and sessions.json as
JSON with only other profiles' routing-index rows left out; the default
profile's own sessions rows and routing entries are still scanned, and every
other file stays a raw byte scan. test_file_leak_scanner.py pins both sides.
2026-11-13 16:40:56 -08:00
Teknium
d0e8a9f7dd test(e2e): the dashboard auth sweep holds /api/peer to its own peer-pass contract
3dbdf86402 made /api/peer/ a route only a peer pass opens, never the
dashboard session token: with no pass provider registered it answers 404
peer_access_unavailable (the bit /api/status already publishes as
peer_access: 0); with one, a missing or wrong pass is 401. The route-wide
sweep expected the session-token 401 and went red on every method.

Exempt the prefix from the session-token sweep and hold it to its own
contract instead: every method, every bad credential and the real session
token on each channel is refused by the peer-pass check, and /api/status
agrees with the 404.
2026-11-13 16:40:56 -08:00
Siddharth Balyan
d312b4989e Merge pull request #151880 from NousResearch/sid/migrate-branch-tool
feat(move): just migrate-branch carries a branch across module moves
2026-11-14 05:37:07 +05:30
alt-glitch
fd3c8b4b1f test: entry-point lists follow MOVES, so a chunk that moves an entry point does not edit them 2026-11-13 20:47:05 +00:00
alt-glitch
248337d39e test: guards that scan a package by name scan where it lives now
After a move the old folder holds only generated forwarders (tools/ held 6 files), so these scans
passed on next to nothing. Scan roots go through current_path; allow-lists, exempt trees and the
config-module pattern keep old keys and judge a file by original_path.
2026-11-13 20:47:05 +00:00
Maciej Lisiewski
539af160e8 Merge pull request #154506 from NousResearch/sec/120604-attach-lease-proof
fix(cli): prove lease ownership in the session-attach handshake instead of echoing it
2026-11-13 20:31:40 +01:00
Maciej Lisiewski
ea24dc721e Merge pull request #154211 from NousResearch/sec/56039-stream-secret-redaction
fix(gateway): redact secrets in streamed chat egress; never emit unsettled text
2026-11-13 18:56:30 +01:00
Maciej Lisiewski
4429693a62 Merge pull request #154644 from NousResearch/sec/77471-secrets-config
fix(config): writers store credentials in .env and only a ${VAR}/key_env ref in config.yaml
2026-11-13 18:23:24 +01:00
Maciej Lisiewski
e5bdd74698 fix(config): writers store credentials in .env and only a ${VAR}/key_env ref in config.yaml
`hermes config set model.api_key` (and auxiliary/delegation/custom provider
keys), the dashboard main and auxiliary pickers, `hermes model`'s aux flow and
new custom_providers rows wrote the plaintext secret into config.yaml. Each now
saves the value to the profile's .env under a deterministic name
(HERMES_MODEL_API_KEY, AUXILIARY_<TASK>_API_KEY, HERMES_DELEGATION_API_KEY,
HERMES_CUSTOM_<HOST[_PORT][_PATH]>_API_KEY) and writes the reference the field
already supports: ${VAR} where load_config expands it, key_env on
custom_providers rows. Resolution is unchanged; existing inline values keep
working and are not migrated. Remote Config keeps values as given, since its
document is shared across hosts that do not share .env.

The new HERMES_* key names are stripped from terminal/subprocess children
like AUXILIARY_*_API_KEY already is, so moving a key out of config.yaml does
not hand it to every child process.

The webhook half of the report does not reproduce: WEBHOOK_SECRET is folded
into the in-memory gateway config only; a test pins that config saves never
write it.

Fixes #77471

Co-authored-by: Franco <franco314@users.noreply.github.com>
Co-authored-by: Christopher <210261288+Christopher-Schulze@users.noreply.github.com>
2026-11-13 17:09:29 +01:00
Maciej Lisiewski
971e15cd6d fix(gateway): redact secrets in streamed chat egress, before overflow splits
The stream consumer sent previews, edits, sealed overflow heads and native/draft frames
with only display cleanup; the forced egress redaction lived solely in the non-streamed
final send, so any streamed reply quoting a credential reached the chat raw. Redact in
_clean_for_display, the cleaner every consumer egress already passes through, and route
the native boundary finalize (the one raw bypass) through it too.

Both overflow splitters now redact the settled buffer first: a cut through a key leaves
halves no pattern matches on its own, and the sealed head is never edited again. The
trailing token is held raw (and the seal never cuts into it) until a later delta
completes it, so a half-arrived key is not masked early and its rest appended unmatched.

Fixes #56039
2026-11-13 16:57:16 +01:00
Maciej Lisiewski
27a5f29570 fix(cli): strip only other-user bits from the session registry; bind attach proof to the socket
Forcing the registry to 0600 and runtime/ to 0700 broke shared-group
HERMES_HOME deployments (NixOS module: UMask 0007, setgid 2770 home):
other hermes-group users got EACCES on active_sessions.lock, and the CLI
and gateway claim paths swallow that and run with no lease. Group members
are already trusted with .env and state.db; the threat is other users, so
clear only the 'other' bits and keep group bits and setgid. A loose
registry left by an older build is now also closed on read, since attach
discovery never writes.

attach_proof now MACs profile_home and websocket_url too
("hermes-session-attach:<sid>:<nonce>:<profile_home>:<websocket_url>"),
so a relay holding a genuine proof cannot swap in its own socket.

Fixes #120604
2026-11-13 16:54:40 +01:00
Maciej Lisiewski
6b682bb255 test(security): retire the #120604 attach-impersonator known gate
The lease-keyed attach_proof now refuses an echoing listener, so the E2E
impersonator cell passes; a stale known_gate would hide a regression.
Also drop the redundant utf-8 encode args ruff UP012 flags.

Fixes #120604
2026-11-13 16:54:39 +01:00
Maciej Lisiewski
48451cc646 docs(e2e): point upgrade-suite docstrings at upgrade_base for N-1
git describe --tags --abbrev=0 HEAD~1 is wrong in the merge-release case upgrade_base fixes (v0.22.2: HEAD~1 gives v0.22.0, upgrade_base gives v0.22.1).

Follow-up to #151534 (review nits).

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-13 15:35:08 +01:00
Teknium
ecd13e59c9 fix(discord): a long reply whose file upload fails is sent whole, never cut at 8
Teknium's ruling on PR #153476: Discord must match Telegram. A reply past
MAX_SPLIT_MESSAGES goes out as one .md file; when that upload fails the
gateway falls back to send(), and Discord's send/forum/edit-overflow paths
still ran main's #86581 cap (_cap_split_chunks): 7 chunks plus a
"Response truncated" notice, the rest dropped. Now every chunk goes out.

- plugins/platforms/discord/adapter.py: _cap_split_chunks and its three
  call sites are removed; MAX_SPLIT_MESSAGES stays as the file-handoff cap.
  Pacing is discord.py's own: its per-route buckets wait on
  X-RateLimit-Remaining/Reset-After and a 429 sleeps retry_after and
  retries, so no second pacer is added.
- locales/*.yaml: platform.discord.limits.response_truncated (its only
  user) is deleted from all 17 catalogs.
- tests/fakes/platforms/discord_standin.py: an opt-in per-channel
  create_message bucket that sends discord.py's X-RateLimit headers, and a
  Via header on 429s (without it discord.py treats a 429 as a Cloudflare
  ban and raises instead of retrying).
- Tests that pinned the Discord truncation (test_discord_split_cap.py,
  test_native_warning_coverage.py's Discord case) are rewritten under the
  ruling to assert every chunk is delivered with no notice. New E2E
  test_discord_long_reply_fallback.py: real gateway + adapter, upload
  refused and a 429 mid-fallback, 40k reply arrives whole (red on 52f239ca).

Live (real gateway + Discord adapter vs the stand-in), 52f239ca -> head:
non-streamed 60k, upload refused: 8 msgs, 13,843 chars + notice -> 31 msgs,
the whole reply, no notice; same with a 429 on the 5th message -> retried,
31 msgs, nothing lost; 5-per-5s bucket -> 33 msgs, never more than 5 in
any 5 s. Upload working, 10k/short controls and Telegram unchanged.
2026-11-12 22:36:28 -08:00
Teknium
ff8cbd6e02 fix(telegram): a rich reply never opens more than the 8-message split cap
Rich delivery (sendRichMessage, rich_messages on) split an oversized reply into 32,768-char parts
with no count limit: a 415k reply opened 15 messages, and a part refused mid-send handed the whole
rest to the MarkdownV2 fallback (91 messages live). The parts now go through the same
cap_split_chunks as the legacy split (numbered=False: rich parts carry no (N/M) markers): at most
MAX_SPLIT_MESSAGES, lowered by the stream consumer's _split_budget, the first budget-1 parts and
then the localized notice as a rich part (none, tail still dropped, when warnings are hidden).
Every rich path reports split_capped/dropped_chars like the legacy one: send_rich_parts,
edit_rich_parts, resume_rich_parts and the standalone send (hermes send / send_message, which also
warns its caller). When the cap cut the reply, the MarkdownV2 fallback for a refused part, and the
unattempted_chunks after a timed-out one, are capped to the slots the landed parts left; a part that
landed is never resent. An uncut reply's fallback is unchanged.

Stream consumer: with rich transport on, heads seal at the rich cap, and a prose head goes out as a
capped MarkdownV2 split. That capped seal was the reply's last text, but its tail became a new live
preview, the consumer later dropped the cut, and the gateway re-sent the whole reply beside the
eight messages (16 live). A capped seal now ends the reply (_ceiling_capped_seal).

The Telegram Bot API stand-in learns sendRichMessage and rich editMessageText, and its driver counts
rich sends, so the platform E2E sees rich delivery.
2026-11-12 22:36:28 -08:00
Teknium
87b1272f08 fix(telegram): the classic key exchange also covers the HTTPS-proxy handshake and DoH discovery
Re-review finding (#153171, P2): "Classic TLS opt-in does not reach the TLS
connection to an HTTPS proxy". httpx runs an https:// proxy's own outer TLS
handshake with the Proxy's ssl_context, never the client's verify, so with
tls_classic_key_exchange: true the proxy still got OpenSSL's 1.5 KB
post-quantum hello and a path that resets it failed with ConnectError.

classic_proxy() turns an https:// proxy URL into httpx.Proxy(url,
ssl_context=<classic context>) when the opt-in context is in use; it runs on
both the explicit-proxy pair and the fallback transport's env proxy. Default
contexts and http:// / socks proxies are passed through unchanged.

Same class (P3, also in that report): DoH fallback-IP discovery now gets the
opt-in context too, so dynamic IPs survive the reset path.
2026-11-12 01:17:39 -08:00
Teknium
8f7e767816 test(telegram): the reset leg runs only where OpenSSL sends the PQ hello
Review finding on #153171: on an OpenSSL without the post-quantum default
the default handshake is small and succeeds, so the tests would fail while
the workaround works. The reset leg is gated on the measured default hello
size; the classic-handshake success check always runs.
2026-11-12 01:17:39 -08:00
Teknium
b3472ee8e3 fix(telegram): the classic key-exchange opt-in reaches every Telegram client
Port of the opt-in onto the current request builder (build_ptb_requests),
used by both the gateway adapter and the standalone sender.

httpx.create_ssl_context() is a truststore context whose wrapper does not
forward set_ecdh_curve(), so the hello stayed at the 1.5 KB hybrid size;
classic_key_exchange_context() keeps platform trust plus SSL_CERT_FILE
and sets X25519 on the inner context (517-byte hello). A value that is not
true/false is refused with a warning naming the key. The test drives a
real get_me through a local TLS server that resets large ClientHellos;
the replaced test needed pyyaml, which the CI test env does not ship.
2026-11-12 01:17:39 -08:00
Teknium
916e102745 fix(gateway): no exhaustion re-run behind follow-ups already on the fresh session; deterministic e2e
Review: a follow-up the reset re-homed onto the fresh session sits ahead of a re-admitted request
in the durable FIFO, so the re-run would answer out of order; skip it then (the user has moved on).
The e2e fake model now decides per request (old transcript vs fresh) instead of a flag flipped
after the reset notice.
2026-11-12 00:31:47 -08:00
Teknium
868e2c363c fix(gateway): the request a compression-exhaustion reset dropped runs on the fresh session (#137565)
A turn that exhausts context compression auto-resets the session, and the user's request went with
the old transcript: nothing answered it and the notice asked the user to resend. The reset now puts
the triggering event back in the adapter's head slot, so the post-handler drain re-runs it on the
fresh session after this turn's lease and active slot are released. Once only (a re-run that
exhausts again is not re-run), never for an internal event, a voice note (STT + echo would repeat),
or a turn that already ran a tool or showed the user output.
2026-11-12 00:31:47 -08:00
Teknium
6a1fc81e1a fix(gateway): a flood-frozen streamed reply is finished in place, not sent twice
When Telegram refuses a streamed reply's final edit and the fallback send with a RetryAfter
longer than the adapter's 5 s inline cap, the stream consumer dropped the preview's message id
and left every delivery flag unset. The gateway's normal final send then waited the penalty out
and posted the whole answer again beside the frozen, cursor-ended preview.

The consumer now keeps the preview id when its fallback landed nothing, and the gateway, for an
unconfirmed final with exactly one real preview on screen (no split, no possibly-landed timeout,
not native), edits that preview up to the complete answer, waiting out the flood refusal the way
the final send would (each wait capped at the 60 s inline cap). A refused or failed edit leaves
the normal ledgered send in charge, so nothing is lost. The same flood-aware edit now backs the
stale-finalize, transformed-final and queued-lane reconcile edits.

The cancelled-consumer case (#53449: flags lost, text visible) goes through the same path.

Fixes #96078, fixes #102402, fixes #53449
2026-11-11 23:34:34 -08:00
Teknium
6361e7c98d fix(gateway): a Telegram thread left naming a delegate subagent goes back to its own conversation
#138241 fences peer recovery. Two other routing stores can still hand a DM thread to a
subagent whose row carries the thread's identity: the DM-topic binding and the routing
index (sessions.json / gateway_routing). Both are written by recovery itself, so a thread
that was captured before the fence keeps its poisoned binding and route.

- the topic-binding heal treats a binding naming a delegate row like a rowless one: it keeps
  the current session and rebinds the topic to it
- the route self-heal (_is_session_ended_in_db) treats a route naming a delegate row as stale,
  so recovery returns the thread to its parent
- the peer-recovery fence excludes delegate children only; a /branch child keeps owning the
  route written at its create (the branch's crash-recovery contract)

Live (real gateway + Telegram adapter, stand-in): seeded the reporter's store shape, then a
DM-topic message. main: the message lands in the subagent for all three legs. Head: all
three land in the parent. Reverting any one guard reds its own leg.

Refs #138210
2026-11-11 22:39:16 -08:00
Teknium
63bb441e07 test(gateway): a live Telegram turn on an agent built during a state.db handle blip reaches state.db
Real gateway + Telegram adapter against the Bot API stand-in. A probe plugin puts the
runner's handle cache into its ordinary 2 s retry backoff while the turn's agent is
built; the handle recovers before the turn ends. On main no message row reaches
state.db for that turn or any later turn on the cached agent (rows == []); with the
runner reporting agent_persisted from the agent's own handle, both turns land.

Refs #140823
2026-11-11 22:37:38 -08:00
Teknium
aa886c1f67 fix(telegram): a hung pool close no longer strands the other detached pools (#153150 review)
aclose() detached every pool generation, then awaited each retire() in turn. When one idle
pool's close hung past the adapter's bounded drain, the remaining pools were never marked
retired, so their requests finished without closing them and no later aclose() could reach
them. Every detached pool is now marked retired first and the closes run concurrently.
2026-11-11 22:30:10 -08:00
Teknium
b935c35f1f fix(telegram): the fallback-IP cap trims discovered IPs only; both seed IPs stay at the tail
Review should-fix (PR #153150): [:MAX_FALLBACK_IPS] dropped both SEED_FALLBACK_IPS whenever
discovery returned 4+ addresses, reversing discover_fallback_ips' documented tail invariant.
Seeds no longer count toward the cap; dropped configured/discovered IPs are logged at info.
2026-11-11 22:30:10 -08:00
Teknium
e8a935e6a0 fix(telegram): a drained retired pool drops its grace timer; the FD-cap test pins a small limit
Review findings on #153150: the grace timer held a closed generation for
its whole bound (cancelled on close now), and the FD-budget test read the
host RLIMIT_NOFILE, which can be large enough that the cap never applies
(the test pins 1024 via _nofile_soft_limit).
2026-11-11 22:30:10 -08:00
Teknium
12376838bd fix(telegram): retired-pool bound never cuts off a long upload; keepalive-off survives the cap
Review findings on #153150:
- The 90 s retire bound could close a generation under a media upload whose
  scaled budget runs past 300 s. A lease already ends with its PTB call
  (client.request closes the body, also on cancellation), so the bound only
  catches a body nobody closes: raised to 3600 s.
- fd_bounded_limits turned HERMES_GATEWAY_HTTPX_MAX_KEEPALIVE=0 into the cap
  (`0 or cap`); it is kept at 0 now.
- New real-socket test: a TLS handshake failing inside a CONNECT tunnel on a
  2-connection pool no longer leaves the pool "occupied" (red on main with
  Pool timeout; red with only the _close_unowned_connections call removed).
2026-11-11 22:30:10 -08:00
Teknium
4f7c3cef2b test(telegram): request-pool lifecycle test waits on conditions, not the clock 2026-11-11 22:30:10 -08:00
Teknium
a3ecb81ea6 fix(telegram): retired request pools close only after their requests finish
The fallback transport closed a pool the moment one connect on it failed, and
PTB's shutdown()/initialize() drain closed every pool at once. Requests still
connecting on that pool finished on a connection no pool held: after the edge
or proxy FIN it sat in CLOSE_WAIT until the process exited, and the requests
already being answered there failed with ReadError.

Each path is now a leased PoolGeneration (telegram_pool.py). Retiring one
closes it when idle, else when its last response body closes (90 s bound).
The proxy and direct branches use the same transport with the builder's
proxy decision, so the transport no longer re-resolves HTTPS_PROXY against
api.telegram.org and sends a NO_PROXY'd base_url server through the proxy.
A proxy tunnel left ACTIVE by a failed TLS handshake is closed. Pool size
is capped to a quarter of RLIMIT_NOFILE across every pool, and at most four
fallback IPs are used.
2026-11-11 22:30:10 -08:00
Teknium
7cdf34e59b fix(gateway): MEDIA handback runs off the event loop and never costs the reply; observed-media note keeps the whole note
Review round on #151769:
- validate_media_delivery_path is a pure path check again; the Docker handback
  runs after filtering via asyncio.to_thread (profile scope carried by
  contextvars) on the reply, post-stream and /background delivery paths.
- hand_back_media_file returns False on any docker/record failure instead of
  raising out of reply extraction.
- observed_media_note appends its guidance after the full context_note; the
  video hint names video_analyze only when available (opt-in toolset).
- handback test skips as root; new tests for off-loop and failure paths.
2026-11-10 14:31:00 -08:00
Teknium
5cee680b59 fix(telegram): observed group photos tell the agent where the file is and how to look at it (#47415)
An unmentioned group photo is cached and only a text note reaches the shared
observed context, which is text-only by design. The note named the path but
not that the image was never attached, so on the next @mention the agent
asked users to re-send. The observed note now says the file is not attached
inline and names the tool to open it (vision_analyze / video_analyze), so
image tokens are spent only when someone asks.
2026-11-10 14:31:00 -08:00
Teknium
4f15cf431e fix(gateway): an ack-lost final after a tool call is not sent again unlabelled
A post-tool segment streams with the separator's leading newlines ("\n\n<answer>") while the
final text is stripped. When that segment's first send timed out after it may have landed, the
held prefix no longer matched the final as a prefix, so the fallback sent the whole answer
again as a normal message; the delivery ledger then added its labelled resend (3 copies).
Leading whitespace never renders, so the seen-prefix comparison ignores it: the held copy
stands and only the ledger's one "may be a duplicate" resend follows.

Review: #151930 (comment 6751719660), probe cell None-ack_lost.
2026-11-10 13:40:44 -08:00
Teknium
a8bf7e417a fix(gateway): an unsure interim send no longer marks a clean final as a possible duplicate
Review finding (#151930): _delivery_uncertain, set when a timed-out send is
counted as shown, survived the segment break. An ack-lost commentary segment
("Let me check...") before a tool call then made the gateway ledger the
cleanly delivered final as failed and resend it with the "may be a
duplicate" label. The uncertainty now ends with the segment it came from
(_reset_segment_state); an uncertain FINAL still gets the labelled
redelivery.
2026-11-10 13:40:44 -08:00
unsupportedpastels
e4a0f8732b feat(gemini): Interactions API by default for Gemini 3 and later
Google asks integrations to use the Interactions API by default, and new
models and capabilities launch there. With gemini_api unset (auto), the
gemini provider now sends Gemini 3+ models and the gemini-*-latest aliases
to Interactions on the AI Studio host.

Unchanged:
- Gemini 2.x stays on generateContent: it steers thinking with
  thinkingBudget, which Interactions has no field for. Gemma stays too.
- Vertex express and proxy bases stay on generateContent (Interactions is
  AI Studio only).
- providers.gemini.gemini_api: generate_content (or the per-model form)
  restores the previous behavior; it applies on the next request.

Checked against the live API on gemini-3.8-flash and gemini-4-argon:
implicit prompt caching hits the same in stateless Interactions as in
generateContent (27.9K of 30K prompt tokens cached from turn 2 on both).

The generateContent e2e fake speaks only that dialect, so its homes pin
gemini_api: generate_content.
2026-11-10 11:37:47 -05:00
unsupportedpastels
6835dd55da refactor(gateway): read turn timestamps, overflow queues and stale approvals from SessionState
Drop the _running_agents_ts, _busy_ack_ts, _queued_events and
_pending_approvals legacy dict views from GatewayRunner. The stall
watchdog, shutdown flush/cleanup, /agents and the stale /approve-/deny
path now read SessionState directly (peek, never creating a row), and
tests set SessionState fields instead of the views.
2026-11-09 23:04:25 -05:00
Teknium
d2011903cc fix(telegram): log when allowed_topics drops a forum topic
A message outside allowed_topics was dropped with no log line, so a topic
the operator meant to allow (often a thread-less General message read as
topic 1) looked like a dead gateway (#52635). The first drop per
(chat, topic) is now named at INFO with the allowlist. _topic_gates_pass
moves from adapter.py into the topic-routing mixin.
2026-11-09 15:33:28 -08:00