Commit Graph

3768 Commits

Author SHA1 Message Date
kshitijk4poor
a254de068f fix(image_gen,video_gen): sign direct FAL jobs with the serving profile's own FAL_KEY
On a multiplexed gateway, a routed profile's direct FAL image or video job
went out signed with the launch profile's FAL_KEY, so it was billed to the
launch profile's FAL account. Hermes' own check (fal_key_is_configured) reads
the routed profile's scope and says "configured", but the submit then used
the module-level fal_client.submit: one process-wide SyncClient() that reads
os.environ (the launch profile's .env, loaded at gateway start) on first use
and keeps that key for the life of the process.

Both direct sites now submit through tools.fal_common.direct_fal_client(),
which builds fal_client.SyncClient(key=...) from the same key the check reads
(new tool_backend_helpers.fal_key(), shared with fal_key_is_configured). One
client per key, reused, as the managed client already is. Unscoped
single-profile runs read the same key as before: get_secret falls through to
os.environ there.

The unscoped submit shapes came from 95dc9aaa75 (rewbs, 2026-03-26, #3287,
image) and d04b3c193e (alt-glitch, 2026-05-27, #33259, video). They became a
cross-profile leak once routed profiles started sharing one process.

Part of #151791 step 9-pre (tracker #152308): explicit per-profile SDK keys.
Modal, Vercel token mode and HF upload are separate follow-up slices.
2026-11-14 18:28:19 +05:30
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
8a00155e54 fix(whatsapp): keep contact ids and Signal session keys out of bridge.log (#155542)
Self-chat rejections logged the full chat/sender id of every other chat
on the owner's account, unconditionally; they now go through
redactWhatsAppId() like the debug events. libsignal's console.info
session dumps (private/root/base keys) are collapsed to their label by
the console wrapper, which now also covers console.info. bridge.log
rotates to one .1 generation above 5 MB when the adapter opens it at
spawn, and full/pre-update backups skip both generations.

Fixes #149860
2026-11-14 12:49:21 +01:00
Maciej Lisiewski
c1405617cd fix(security): keep the BlueBubbles password out of gateway logs (#155459)
* fix(security): keep the BlueBubbles password out of gateway logs

Every BlueBubbles request carries the server password as ?password=.
Two paths wrote it to agent.log in clear:

- Inbound: on the shared listener that serves multiplexed profiles,
  aiohttp's default access logger records the full request target; the
  adapter's access_log=None only applies when it binds its own runner.
  RedactingFormatter now masks credential query params on aiohttp.access
  records (the strict URL pass, which ordinary logs keep off so OAuth /
  magic-link URLs survive).
- Outbound: httpx.HTTPStatusError text embeds the request URL. The
  adapter's log lines and SendResult.error now go through one helper that
  applies redact_url_credentials.

Fixes #143550
Fixes #146420

* test(security): pin every BlueBubbles REST error path and the access-line gate

Each remaining _safe_error site (register, unregister, attachment upload,
attachment download) now has a real httpx 401 test, and a RedactingFormatter
test pins that only aiohttp.access records get the strict URL pass.

Refs #143550

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>

---------

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-14 12:48:24 +01:00
Maciej Lisiewski
d8fdbe8a54 fix(plugins): keep config-selected plugin names inside their plugin root (#155450)
* fix(plugins): keep config-selected plugin names inside their plugin root

memory.provider, cron.provider and context.engine were joined onto the
plugin root unchecked, so a path-shaped name loaded a package from
anywhere. Worse, the "is bundled" test was lexical (Path.parents), so a
`<root>/../..` spelling counted as bundled and was imported in-process
even under plugins.isolation: host. Names must now be a plain directory
segment (invalid = not found, so the built-in fallbacks apply), and the
bundled test compares resolved paths.

Fixes #141328

* fix(plugins): a user-dir symlink into the bundled root is not bundled

is_direct_child compared resolved paths only, so $HERMES_HOME/plugins/<x>
linking into a bundled dir counted as bundled and loaded in-process past
plugins.isolation: host (and the link could be swapped between check and
import). Require the path to sit under the root both as written and resolved.

Refs #141328

* test(plugins): satisfy ruff PLR0402 and cover the resolved half of is_direct_child

Use `from plugins import ...` instead of aliased submodule imports (ruff
PLR0402 failed the Python lints lane). Add a bundled-root child symlink that
resolves outside the root, so dropping the resolved comparison in
is_direct_child is caught.

Refs #141328

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>

---------

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-14 12:48:09 +01:00
Teknium
36af5c3f4d fix(telegram): anchor_multipart_replies also covers split Rich Messages
Greptile: Split replies still carry quotes. The split-anchor rule moves into
telegram_split.split_reply_anchor and send_rich_parts applies it before
_deliver_parts, so an opted-out split rich reply carries no reply_parameters.
Docs state the streamed-reply limit (anchor chosen at the first preview; an
edit cannot remove it).
2026-11-14 03:46:01 -08:00
Teknium
ed3ffe8095 fix(telegram): split replies can drop the first-part anchor with opt-in extra.anchor_multipart_replies
Some Telegram Desktop/TDLib clients hide the first part of a multi-part reply
when it carries a native reply anchor (#55059). The default keeps today's
anchor on part one; `platforms.telegram.extra.anchor_multipart_replies: false`
sends a split reply unanchored. Single-message replies keep their anchor, and
private DM-topic sends keep it because the topic routes by it.

Suppression rule from #55060 (@ooiuuii), gated behind the opt-in.

Co-authored-by: ooiuuii <ooiuuii@users.noreply.github.com>
2026-11-14 03:46:01 -08:00
Teknium
899dd45829 fix(agent,gateway): strip <TOOLCALL> markup at send time and from every platform's reply context
<TOOLCALL> (Nemotron-style text tool calls) was missing from the shared tool-call tag
tuples, so strip_think_blocks and the CLI renderer let it through to the delivered text;
that is how it reached Telegram in the first place (#61217). Add it to both tuples, so
closed, cut-mid-JSON and stray-closer forms are dropped like <tool_call>.

Move the reply redaction from the Telegram adapter into gateway reply_pointer: it now
covers every platform's quoted reply, already-sent messages, and adds no new
plugin-to-core import. Match the tag case-insensitively like the other tool-call tags.
2026-11-14 02:52:41 -08:00
arcticloud
ef8937e9fb fix(gateway): strip internal TOOLCALL markup from Telegram reply previews
When a user replies to a bot message whose content carries raw internal
<TOOLCALL> markup from the agent's output stream (echoed text, native
quote, or the rich_sent_store send-time index), the Telegram adapter
exposed the markup verbatim via reply_to_text, leaking protocol details
into the user-facing reply preview and the injected reply context.

Redact <TOOLCALL> blocks (closed and truncated-unclosed) with a
[processing...] placeholder at the single point where reply_to_text is
resolved in _build_message_event. Plain messages pass through unchanged.

Closes #61217
2026-11-14 02:52:41 -08:00
Teknium
4a8e116ccb fix(telegram): land flood windows on disconnect; replay only the boot pass's restart notices
Greptile round 1 on #153107:
- "Shutdown forgets flood windows": the flood-window writer is no longer a
  _background_tasks member (shutdown cancels those). disconnect() awaits it
  shielded, together with the update-receipt flush (land_persisted_state).
- "Later profiles miss restart notices": the whole replay waits until the
  boot pass reaches a notice (it captures the replay context then), so a
  heal while secondary profiles still connect cannot discharge the
  planned-restart marker against a partial profile set.
- "Restart confirmation arrives too early": a replay only answers the
  requester marker the boot pass read, and no replay runs while this process
  drains for a restart, so the next /restart's marker survives for its boot.
Also: a requester send cancelled mid-flight keeps its marker; only a definite
outcome or an exception consumes it.
2026-11-14 02:40:22 -08:00
Teknium
ebf8d65d5d fix(telegram): flood window survives a restart; restart notices wait for the send path
A 429 retry_after arms a per-chat window inside which Telegram sends fail
closed locally, but the window lived in memory only. A gateway restart during
a ban forgot it, and the new process's first reply, stall notice or heartbeat
went straight back into the penalty (#89962). The window (moved out of
adapter.py into telegram_flood_cooldown.py) is now also written per bot to
telegram_flood_cooldown_<bot id>.json in the adapter's own profile home and
loaded on the first window check after boot. Entries carry a wall-clock
deadline, are clamped to the 300 s window cap on load, and expire on their own.

Boot-time restart notices raced Telegram's send-path readiness (#66589): the
adapter refuses sends with send_path_degraded until the polling generation's
first getUpdates, _send_restart_notification unlinked .restart_notify.json
in finally either way, and the planned-restart "online" notice was replayed
only when the adapter was REPLACED, never when it healed in place. Now
(gateway/run_notifications_restart.py):
- the requester marker is kept while the platform has no live transport or
  refuses with the reconnect-only error the delivery ledger already uses
  (is_reconnect_only); permanent refusals and suppression still consume it,
  and a kept marker expires after 30 minutes;
- one replay (requester + planned-restart) runs on every reconnect and on the
  Telegram adapter's degraded -> healthy edge, in the boot pass's context and
  under one lock, so the notice goes out once.

Live (real gateway + Telegram stand-in):
- flood: 429 retry_after=200, SIGTERM, boot, new turn. main: 1 sendMessage
  into the window; head: 0 (refused locally, 193 s left).
- notice: getUpdates 502 for the first 45 s of boot. main: neither notice
  sent, the requester marker deleted; head: both sent once polling healed,
  no markers left.

Fixes #89962, fixes #66589
2026-11-14 02:40:22 -08:00
Teknium
a40a854abc fix(telegram): only the card author is captured, whatever their reply points at
One rule instead of two ad-hoc ones: a reply aimed at a known card (live or
ended) counts only from that card's author, and any other private-chat text
from the author answers their newest live card.

- A private-chat code sent as a reply to some unrelated message fell through
  to chat text: the reply-target branch returned before the private fallback.
- Ended cards now remember their author, so another member's reply to one is
  their own message and is never deleted.
2026-11-14 02:21:34 -08:00
Teknium
18b1de7fa3 fix(telegram): code cards are tracked per card, late replies stay private, failed deletes always warn
From review of the Telegram code card:

- Cards were keyed by (chat, author), so an answered card's timer ended the
  author's next card early and two cards overwrote each other. Each card is
  now its own record keyed by (chat, card message id), and its timer retires
  only that card.
- A reply to a card whose request had ended fell through to the normal text
  path, so a late code reached the agent as chat text. Ended cards are
  remembered (bounded), and a reply to one is deleted and never becomes a turn.
- delete_message() returns True for a delete queued behind a long flood wait,
  which skipped the "please delete it yourself" warning even if the queued
  delete later failed. The interception uses delete_message_confirmed().
- In a group, ForceReply(selective) opens the reply field only for users the
  card mentions, so the card now carries an invisible mention of the author.
2026-11-14 02:21:34 -08:00
Teknium
7ba0189672 fix(telegram): import ForceReply where the code card is built
Test doubles of the telegram package (test_telegram_thread_fallback.py builds
its own module tree) do not define ForceReply, so importing it at adapter
import time failed the whole try block and left ChatType and friends unset.
The code card imports it when it is sent.
2026-11-14 02:21:34 -08:00
Teknium
e9d9b2b139 feat(telegram): enter browser_vault one-time codes by replying to a card the bot deletes
Telegram has no private form a bot can open, so the code arrives as a normal
message. telegram_vault_code.py implements the send_vault_code_prompt hook
the gateway already detects (gateway/session_vault_code_card.py): a ForceReply
card aimed at the turn's author. Their next text in that chat (a reply to the
card in a group, any text in a private chat) is taken off _handle_text_message
after the auth check and before batching: the bot deletes it, hands the code
to submit(), marks the card, and never builds a MessageEvent.

- A different member, or an unrelated group message, is not taken as the code.
- A failed delete (a group where the bot lacks delete rights) posts a notice
  asking the author to remove it.
- python-telegram-bot logs every getUpdates result and webhook body at DEBUG;
  while a code reply is pending those records are dropped.
- Strings: platform.telegram.vault_code.{body,delete_failed} in all 17 catalogs.
2026-11-14 02:21:34 -08:00
Teknium
b46e21495f fix(gateway): a code submitted as the turn ends is dropped, and SDK debug logs never carry it
From an independent review of the head:

- code_card_scope's exit set each request's event but kept its value, so a
  code submitted while the card's send was still unacknowledged survived the
  turn's end and was entered once the ack landed. Exit now cancels the
  request (event set AND value cleared), and wait() reads the value under the
  request lock with the stop flag.
- discord.py (DiscordWebSocket.received_message) and slack_sdk Socket Mode
  ("Received message") log every received frame at DEBUG, before any handler
  runs, so with logging.level: DEBUG a modal submit wrote the code into
  agent.log. Each card module installs a logging.Filter on those SDK loggers
  that drops frames carrying its own input id (Discord's TextInput now has a
  fixed custom_id) or view callback id. Other frames still log.
2026-11-14 01:28:18 -08:00
Teknium
3630f3e6ee fix(slack): read i18n through the adapter facade in the vault code card
The boundary lint counts each new plugin-to-core import per file; the
Slack facade already imports agent.i18n.t, so the sibling late-binds it
from there instead of adding a crossing.
2026-11-14 01:28:18 -08:00
Teknium
a9b059e9da feat(slack): enter browser_vault one-time codes through a private modal
When a site texts or emails a one-time code during a Slack-driven sign-in,
browser_vault enter_code answered prompt_unavailable: no code prompt was
installed for messaging turns. The Discord commit before this one adds the
messaging-turn code callback (gateway/session_vault_code_card.py) and its
send_vault_code_prompt adapter hook; this gives Slack the same hook instead of
a second broker and BasePlatformAdapter surface (#130569's shape).

- plugins/platforms/slack/adapter_vault_code.py: a Block Kit card with an
  "Enter code" button carrying an opaque token. Only the turn's author, in the
  workspace the card was posted to, can open the modal; anyone else gets an
  ephemeral refusal. The view_submission value goes straight to submit() and
  the card is rewritten without its button. A submit after the request ended
  is refused in the modal and enters nothing. The code is never posted,
  echoed or logged.
- The card strings move from platform.discord.vault_code to
  platform.shared.vault_code (all 17 catalogs) so both adapters read one set.

Co-authored-by: Chukwuebuka Ezeokeke <ebulamicheal@gmail.com>
2026-11-14 01:28:18 -08:00
kira-ariaki
ddacd2dbcf feat(discord): enter browser_vault one-time codes through a modal
vault_prompt_scope installs the vault callbacks only for local-viewer
(Desktop/TUI) turns, so on Discord `browser_vault action=enter_code`
returns prompt_unavailable and a sign-in whose code arrives by SMS or
email cannot finish from chat (#141844).

A messaging turn whose adapter implements send_vault_code_prompt now
gets the code prompt (gateway/session_vault_code_card.py). Discord
implements it in a new sibling, adapter_vault_code.py: an "Enter code"
card whose button opens a modal for the turn's author only (base
allowlist admission still applies), so the code goes from the modal
submit to the waiting agent thread and is never posted, echoed or
logged. The wait runs in 1 s slices that honor /stop and feed the
inactivity watchdog. A failed send, a timeout or an interrupt returns ""
(code_declined), and the scope's exit releases a tool thread that is
still parked on a card.

can_prompt_here() keyed only off the unlock callback, so a surface that
installed the code prompt alone was reported as unable to ask. It now
takes the callback the caller is about to use. Only enter_code passes
one; unlock and save_login keep their answer on every surface.

Other messaging adapters, cron, webhooks and the API server are
unchanged: no send_vault_code_prompt means no callback and still
prompt_unavailable. Unlock and save_login are not offered on chat
platforms.

Closes #141844
2026-11-14 01:28:18 -08:00
Maciej Lisiewski
6a0b9d29da refactor(matrix): share read_body_capped with the outbound image fetch
_download_external_media_with_cap kept its own copy of the
Content-Length + streamed-size check; route it through the same reader
as the inbound mxc path so the cap lives in one place. The image/* type
check stays outbound-only.

Refs #55041
2026-11-13 17:30:13 -08:00
Maciej Lisiewski
8963d75e0d fix(matrix): enforce MATRIX_MAX_MEDIA_BYTES on the inbound mxc read
mautrix 0.21.1 Client.download_media() returns `await response.read()`,
so an event that omits or under-reports info.size had its whole body
buffered (and cached) regardless of MATRIX_MAX_MEDIA_BYTES.

Move the capped request into plugins/platforms/matrix/media_download.py,
mirroring download_media (same URL helper, v1.11 auth header, request
logging) but streaming under the cap, and drop the event when the cap is
crossed instead of falling back to the HTTP URL. Replaces the salvaged
commit's in-adapter helper, whose unittest.mock detection kept the
unbounded path reachable, and keeps the facade from growing.

Fixes #55041
2026-11-13 17:30:13 -08:00
luyifan
1d646f5af3 fix(matrix): stream inbound media under cap 2026-11-13 17:30:13 -08:00
Teknium
3eba7c581e fix(telegram): adopt the card's ticks when a re-tap gets "not modified"
After an unconfirmed (timed-out) checkbox edit _toggle keeps the flip. If
that edit never landed, the user's corrective re-tap asks for exactly the
markup Telegram already shows, Telegram answers 400 "message is not
modified", and that was classified as a refusal: every later tap toasted
"tap again" and Send submitted a lost tick (or refused a visible one).

"Not modified" proves the card already shows the requested selection, so
commit it instead of reporting a failure.
2026-11-13 17:13:04 -08:00
Teknium
771c9b7ac1 fix(telegram): keep the old selection when a checkbox edit never left
_toggle treated every NetworkError as an ambiguous delivery and kept the
flip. A connect failure (httpx.ConnectError through PTB's HTTPXRequest,
surfaced as telegram.error.NetworkError) proves the edit never reached
Telegram, so the card still shows the old ticks while Send would submit
the hidden pick.

Classify the failure with telegram_send_errors.send_error_kind, the same
classifier the senders use: only MAY_HAVE_DELIVERED (timeout/lost or a
Telegram 5xx) keeps the flip; refused, flood-waited and never-sent edits
keep the old selection and answer the tap with toggle_failed.
2026-11-13 17:13:04 -08:00
Teknium
72ea735ccc fix(telegram): retire a multi-select card reset during the checkbox edit
The gateway can clear or time out a pending clarify while Telegram's
edit_message_reply_markup is awaited. _toggle then still recorded the
checked option and answered "Selected: 1" on a question the agent no
longer accepts. Recheck after the await that the same pending entry is
still registered (identity, so a re-registered id is not mistaken for it)
and retire the card with the expiry notice instead.

Approach and regression test from kvnloo's add-on 5255eecfdd9 on the PR
review; this version compares entry identity rather than any pending
multi entry.

Co-authored-by: Kevin Rajan <7121943+kvnloo@users.noreply.github.com>
2026-11-13 17:13:04 -08:00
Teknium
db4a025b87 fix(telegram): multi-select toggles track what the card shows
Review follow-up on #154925:

- A toggle updates the saved selection only after Telegram accepts the
  keyboard edit. A refused edit (BadRequest) keeps the old ticks and the
  old selection, and the tap gets a "tap again" toast, so Send never
  submits a pick the card does not show. An unconfirmed edit (timeout)
  keeps the flip, because it may have landed.
- A toggle or Send tap on a card whose question already ended (timed
  out, answered by text, session reset) retires the card with the
  expired notice instead of answering "Invalid choice" forever.
2026-11-13 17:13:04 -08:00
Teknium
cc9c925a30 fix(telegram): multi-select Send returns one answer per pick
Follow-up to the contributor's toggle/Send keyboard (#154195):

- Send resolves the clarify with a JSON array of the checked labels, the
  shape the typed "1, 3" reply already resolves to. The comma string the
  tap path sent decoded as ONE answer ("Nuxt 3 (Recommended), Go
  Microservice") with the display label left in.
- The toggle/Send handling and the shared resolve step move to
  telegram_clarify_multi.py so adapter.py shrinks (6715 -> 6708 lines)
  instead of growing.
- The four new prompt strings are translated into every locale catalog.
2026-11-13 17:13:04 -08:00
Baophan00
3958eba7ba fix(telegram): let multi-select clarify toggle options and submit (#154195) 2026-11-13 17:13:04 -08:00
Victor Kyriazakos
6b8c6e4675 fix(gateway): cron polling, the FIFO claim and Slack thread bookkeeping wait on storage off the event loop
Symptom (an enterprise messaging-only deployment, state.db on NFS, after 0.22.2 -> 0.22.6): the
gateway event loop stalled 5-58 s about every 30 s, Socket Mode reconnected, and the loop watchdog
exited the process (75) three times in 12 h. SIGUSR2 dumps put the loop thread in
hermes_state_runtime.get_session_admission <- gateway/session_cron.operation <-
cron/scheduler_authority.observe, waiting in fcntl(F_SETLK) on state.db-shm.

Cause: the unified runtime (#106742, first in v0.22.3) runs a gateway-owned cron fire's observer on
the owner loop (cdbe8c35ad). f2a717d8c6 and a84cedb53b moved its ledger WRITES off the loop
(tracked_write); its READS stayed: every <= 2 s per running job `status` read the admission (and a
terminal row's result) and `cancel`/`recover` read the ledger, synchronously. `observe` also wrote
the cron journal with file + directory fsync on the loop. A WAL read is cheap on local disk, so the
reads looked harmless; on storage where each -shm lock is a server round trip, one read stops every
socket, timer, Stop and liveness probe. The same shape sat in every turn's FIFO claim
(_claim_next's pending read and its post-preclaim re-reads) and in the Slack adapter, whose thread
watermark (a full routing-index save: replace_gateway_routing_entries + the fsynced sessions.json
mirror, under SessionStore._lock) was persisted synchronously in the message handler on every
thread reply, and whose assistant lifecycle events seeded DM routes the same way.

Change (each read/write runs in a worker; ordering is unchanged because each caller awaits it before
its next step):
- session_cron.operation: status/cancel read the admission (+ saved result) in one worker hop;
  recover lists the ledger in a worker.
- scheduler_authority.observe: save() awaits the fsynced journal write in a worker, before submit
  and after the receipt, as before.
- SessionAuthority._claim_next: the pending read and both re-reads after an awaited preclaim run in
  a worker. The claim still takes exactly the head that read validated (claim_session_input
  head=), so input or a cancel committed meanwhile is re-read, never claimed blind.
- Slack: the thread watermark get/set and the lifecycle DM seed await the store in a worker.

Tests (composed, real owner loop + SessionDB, storage slowed to 2 s per statement at the store's
choke points; max loop-tick gap, base -> branch):
- tests/gateway/test_owner_loop_cron_polling.py: status poll 2.01 s -> < 0.2 s, cancel poll
  4.01 s -> < 0.2 s, journal fsync 1.32 s -> < 0.2 s.
- tests/gateway/test_owner_loop_claim_read.py: claim read 2.01 s -> < 0.2 s, same head claimed.
- tests/gateway/test_slack_thread_watermark_off_loop.py: watermark write 2.03 s -> < 0.2 s; the
  lifecycle seed writes off the loop thread.
2026-11-13 17:02:18 -08:00
Teknium
84654bcb8a fix(telegram): a backslash-escaped mark in a bare URL is never its emphasis closer
_UrlEmphasisScan probed each mark run inside a URL as a candidate closer for
emphasis opened before the URL. _star_token already skipped a backslash-escaped
first star for pairing, but the fallback cut used run.start(), so the escaped
star landed in the closer and the URL lost it:
`***Docs https://ex.com/a\** now` showed `*Docs https://ex.com/a\ now`
(main: `**Docs https://ex.com/a\* now`). `**x https://ex.com/a\** z` was
already wrong at 6b7e6cb6, and escaped `~~`/`||` marks were cut the same way.

The scan now starts a URL run after an escaped first mark (odd backslash run),
so that mark stays URL text and only the marks after it may close; a run that is
only the escaped mark is skipped.

Rows for the four re-review shapes added to
test_emphasis_around_a_url_pairs_as_around_any_word, and
test_no_bare_url_loses_a_character_to_formatting gains backslash-escaped
*, **, ~~ and || shapes (9 red on 8dd38f4f). Both fix-lane corpora (1,526
rows): 0 regressions vs main or 8dd38f4f, 0 URLs losing characters, 0
MarkdownV2 errors; 160k-input fuzz: 0 non-mark characters lost; 20k/80k/320k
timing stays linear.
2026-11-13 16:48:04 -08:00
Teknium
e51387fe80 fix(telegram): the bare-URL scan pairs star runs with the renderer's own rules
_UrlEmphasisScan kept its own star-run bookkeeping, which treated a run as one
indivisible opener. The renderer (_pair_emphasis) closes PART of a run, so for
`***bold* https://example.com/**` the scan saw separate `***` and `*` openers,
refused the URL's final `**` as a closer, and the stars stayed escaped inside
the URL while e4b1353c and main rendered bold.

The pairing loop of _pair_emphasis moves into _StarPairing (feed = pair for
real, probe = dry-run with an undo journal) and _star_token; _pair_emphasis
and the scan both drive it, so a URL star run closes exactly what the
renderer would close: partial runs, reach past literal `*` (`**rm *x
https://x/y**`), the rule of 3. The scan's rule is otherwise unchanged: a mark
run inside a URL is URL text unless it closes emphasis opened before the URL;
a later prose closer wins unless the URL run would have spent that opener.
Probes are bounded by _CLOSER_LOOKBACK, so the scan stays linear.

Greptile P2 4567931541.
2026-11-13 16:48:04 -08:00
Teknium
3c4c9c0f6e fix(telegram): one rule decides where a bare URL ends
Four rounds of URL-emphasis heuristics (right-to-left reopen/closer sets, /-run budgeted
re-pairing) each exposed a new edge; the latest cut `https://example.com/a*;b*c*` at the first
star and rendered `;b` italic, dropping two URL characters (Greptile 4567531365).

Replace them with one left-to-right scan: prose delimiters (`*` runs, `~~`, `||`, line and
paragraph breaks) keep a stack of open emphasis. Inside a URL, the first mark run with prose after
it that matches the innermost open marks is that emphasis's fallback closer; every other mark is
URL text. A later prose closer of the same emphasis wins (`*Open https://x/a*;b*c* now*` keeps the
URL whole); an opener left unclosed at its line/paragraph end, or by an enclosing closer, takes the
fallback and the URL ends there. Linear: each delimiter is pushed and popped once, and a URL run
looks at most 8 openers deep.

Adds the Greptile row, a strike twin and a property test over 56 internal-punctuation URL shapes x
11 wrappers: every URL is shown whole, or cut only at a run closing outer emphasis.
2026-11-13 16:48:04 -08:00
Teknium
e1172d2923 fix(telegram): a URL's emphasis closer survives a later bold span in the same word
`_closing_mark_run` (54c8d0b9) let any later run of the same marks that continued as
URL text "reopen" the URL, so in `**https://example.com/a**,next**word**` the
`**word` opener made the URL swallow its own closing `**`: one bold span with
literal stars instead of bold URL then bold `word`. In the right-to-left pass a run
that a later closer of the same marks pairs is now an opener, not URL text, so it no
longer reopens the URL; `a*;b*c` and `a**,b**c` (no closer after the reopener) stay
whole URLs.

The paragraph re-pairing used for `/`-ended runs cannot decide this: both readings
leave 0 unpaired marks for `Open u*;b*c now` and for `**u**,next**word**`, so it
would turn `a*;b*c` back into italics. Review corpus (616 rows): byte-identical to
54c8d0b9, 0 regressions vs main; 910 internal-punctuation rows: 112 change vs
54c8d0b9, every one to main's rendering (0 rows differ from both).
2026-11-13 16:48:04 -08:00
Teknium
bc1d157d26 fix(display,telegram): rebuilt insertText params never block the call; internal URL punctuation stays URL
browser_exec display masking: `params = {**params}` rebinds a name to itself, so
_dict_text followed the spread back to the same name forever (RecursionError);
masking runs before dispatch, so the browser call never ran. _dict_text now
tracks the names it followed (as _strings does), and a walk that still fails
masks every string literal in the snippet instead of raising (fail closed).

Telegram bare URLs: the first mark run followed by punctuation ended the URL even
when a later run of the same marks reopened it, so `https://example.com/a*;b*c`
was cut at `a` and `*;b*c` became italics. A run now closes emphasis only when no
later run of the same marks continues as URL text (one right-to-left pass); the
616-row review corpus renders byte-identical to the previous head, and the new
internal-punctuation rows match main or fix it, with 0 regressions.
2026-11-13 16:48:04 -08:00
Teknium
3e5b565766 fix(telegram): emphasis around a bare URL pairs as around any word; restore placeholders in one pass
_MarkRuns guessed emphasis closers from run parity on the URL's line, so
bold across a newline (**See\nhttps://x/**), nested emphasis
(*outer **https://x/** end*) and a closer followed by prose
(**https://x**—next, [**https://x/**]) rendered as literal stars where main
formats them. A mark run with prose after it now always ends the URL (main's
reading); only the ambiguous run right after a trailing '/' (/web/* vs a
closer) is decided by the real _pair_emphasis pairing over its paragraph:
kept as URL text only when that leaves fewer marks unpaired. The decision is
budgeted so a huge reply stays linear.

Placeholder restore did one whole-text str.replace per placeholder, and every
bare URL now adds one (30k URLs: 0.05s on main, 7.3s on head). Values are
expanded in insertion order and the text in one regex sub.
2026-11-13 16:48:04 -08:00
Teknium
3b6375e236 fix(telegram): a quoted URL keeps its emphasis closer
The per-URL tail check stripped only marks and `.,;:!?)`, so a closing quote
(`"*https://example.com/*"`) left an empty tail and the closer was never
released, keeping the `*` inside the URL. The tail now strips exactly what
`_url_end` may trim (`_URL_TAIL_CHARS` plus `)`), so quoted italic, bold and
strikethrough URLs render as they do on main.
2026-11-13 16:48:04 -08:00
Teknium
fc6489cc5a fix(telegram): a URL with no trailing mark never consumes an emphasis closer
`_MarkRuns.closers` advanced the per-line closer count for every URL inside open
emphasis, even one ending in plain text (`https://a.example/x`). The next URL
then saw an even count and kept the sentence's closing `*` as URL text, leaving
the opener unmatched. A mark now counts as closing only when this URL's own
tail actually carries it.
2026-11-13 16:48:04 -08:00
Teknium
ecf8fd67c3 fix(telegram): a wildcard inside a later URL never closes emphasis around an earlier one
A trailing `*`/`_`/`~` after `/` is judged against the emphasis marks of the
surrounding prose only: runs inside any bare URL (`/web/*`) are URL text and
are no longer counted. The next prose run of the mark is checked instead of
the parity of everything after the URL, so the sentence's own closer (`now*`)
keeps the earlier URL's wildcard as URL text, and URLs on one line are judged
left to right so two emphasized URLs still pair independently.
2026-11-13 16:48:04 -08:00
Teknium
a8b231e886 fix(display,telegram): mask pre-built insertText dicts; pair URL emphasis closers by run parity
- redact_browser_input: an Input.insertText call that passes a name
  (**params, positional params, {**params}) also masks the "text" value
  inside the dict literal assigned to that name.
- telegram_markdown: a trailing */_/~ after "/" closes emphasis iff an odd
  number of that mark's runs precede the URL on its line and an even
  number follow it, so `*https://a/* and *https://b/*` renders both
  italic. Run offsets and line bounds are precomputed once per call and
  bisected per URL (O(text + urls log n)).
2026-11-13 16:48:04 -08:00
Teknium
5aacc88c15 fix(display,telegram): mask more browser_exec typing shapes; close emphasis opened earlier around a URL ending in /
- telegram_markdown: a trailing */_/~ after "/" closes emphasis when the line
  before the URL leaves an odd number of that mark's runs open and the mark
  does not recur after the URL on the line ("**bold https://x.com/**",
  "*see https://x.com/docs/*" render as on main again); wildcard paths stay URL text.
- redact_browser_input: also mask type_text(...), fill_input selectors with
  parens/commas (selector parsed as a literal), f/r/b-prefixed literals, and the
  literal assigned to a name later passed as a typed value. text= is read only
  inside the insertText call; .value ==/=== is not an assignment.
2026-11-13 16:48:04 -08:00
Teknium
c486802f10 fix(telegram): emphasis around a URL ending in / renders instead of showing stray marks
A trailing * _ ~ right after a / is kept as URL text so wildcard paths like
/web/*/example.com/* survive. When the URL itself opens with that same mark
(*https://example.com/*, **...**, ~~...~~), the trailing mark is the closer of
the emphasis around the URL, so it is trimmed off the URL again.
2026-11-13 16:48:04 -08:00
Teknium
81c716d4e2 fix: address review on typed-secret masking, URL tails and the poll-ack test
- Typed values are found by a linear literal scanner: a backslash escape never ends the literal,
  triple-quoted values are whole, and an unclosed literal masks to the line end (fails closed).
- A `*`/`_`/`~` right after a `/` stays part of the URL (`/web/*`), so an italic sentence around a
  wildcard URL cannot borrow its last character as a closer.
- URL tail trimming counts parentheses once instead of rescanning per trailing `)`.
- The poll-ack test waits with tests.waiting.wait_until instead of a sleep loop.
2026-11-13 16:48:04 -08:00
Teknium
c61ac88a9b fix(telegram): a bare URL reaches the chat as literal text
to_markdown_v2 escaped a bare URL char by char after the emphasis pass, so `*`, `~~` or `||`
inside it paired into italic, strike or spoiler marks: Telegram dropped the characters or hid
part of the URL (#40667). Bare scheme URLs are now stashed whole behind the existing placeholder
and escaped as literal text; trailing prose punctuation stays outside, and a `)` stays only while
it closes a `(` in the URL.
2026-11-13 16:48:04 -08:00
Teknium
1af8f7ba23 refactor(telegram): move send-failure helpers out of adapter.py
adapter.py grew 6,705 -> 6,710 lines on this branch; files over the 2,000-line
cap may only shrink. Move the @username "Chat not found" hint (now shared by
the gateway send path and standalone_send) and _classify_send_exception into
telegram_send_errors.py, which already owns send-failure classification.
explain_username_chat_not_found accepts a standalone result dict or a gateway
SendResult, so the adapter calls it directly. adapter.py: 6,710 -> 6,692
(main: 6,707).
2026-11-13 16:42:58 -08:00
Kevin Rajan
b46170017e fix(telegram): include numeric-id hint on live gateway sends (#95121)
An in-process adapter send bypasses standalone_send and therefore teknium1's #154923 diagnostic. Reuse that diagnostic at the live send boundary, preserving numeric-id and unrelated failures.

Regression: test_live_gateway_username_home_error_explains_numeric_id
(cherry picked from commit 25f26daa2185912c04574e32a9be56bf639eacd9)
2026-11-13 16:42:58 -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
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
Teknium
882cbc99e4 fix(slack): one budget and one render per shared message, everywhere
- History (_render_message_text) rendered each forward/linked message with its own
  8000-char allowance; it now goes through the same shared_message_sections as the
  live path: one budget per message, same dedupe.
- Forward bodies render blocks in their original order (header, rich_text, section
  interleaved) instead of all rich_text/tables first and layout blocks after.
- A forward whose body the user already quoted keeps its source line, permalink and
  files; only the body is replaced by a short note.
- The self-echo check compares a linked message's author against every bot user id
  this adapter posts as (multi-workspace installs have one per team), not only the
  current team's.
- A message pasted as a permalink and also forwarded in the same post renders once,
  as the forward.
2026-11-13 15:49:08 -08:00
Teknium
1753f0869e Port from paradigmxyz/centaur#2152: linked Slack messages reach the agent
Pasting a permalink to SOMEONE ELSE's Slack message (no Forward action)
gives the bot an `is_msg_unfurl` attachment with the linked message's
full text, author_id, channel_id and ts — and Slack sends it even when
the bot is not a member of the source conversation. The adapter skipped
every `is_msg_unfurl` attachment as a self-echo, so the agent saw only
"is this valid? <permalink>", could not open the link, and answered
blind (or drove the browser into the Slack sign-in page).

A linked message is now rendered like a forward ("[Linked Slack message
from <author>]", link, body, end marker) on the live inbound path and in
thread/parent hydration. The echo guard stays where it is real: an
unfurl whose author_id is this workspace's bot user, or one Slack does
not attribute at all, is still skipped, so the existing hydration-skip
tests hold unchanged.

Centaur fixed the same gap in slackbotv2 (render message unfurls as
quoted "Shared Slack message from <author>" context). The self-echo
discriminator (author_id vs bot user id) was proposed on #96384 by
@aguung and implemented in #108478 by @itoropitsin.

Refs #96384
2026-11-13 15:49:08 -08:00