Commit Graph

1265 Commits

Author SHA1 Message Date
kshitijk4poor
c12d6009e6 fix(achievements): fall back to the local data dir only when plugin_storage is missing
_data_dir caught every exception from plugin_data_dir, so its dead-home refusal
was retried by the standalone fallback (which refused again, through the same
guard). The fallback now catches ImportError around the import alone.
2026-11-22 02:17:23 +05:30
kshitijk4poor
72b67603d4 fix(plugins): a2a conversation log and achievements writes refuse a dead profile home
persist_message runs right after every a2a security.audit call (inbound,
reply, and the a2a send tool) and still created
get_hermes_home()/a2a_conversations with a raw mkdir(parents=True), so a
session bound to a deleted or renamed profile recreated profiles/<name>.
It now goes through mkdir_under_hermes_home and, like audit, skips the
write. The test drives the real tools._send_task after a delete and a
rename.

The achievements _write_json no longer repeats the data-dir mkdir that
_data_file already did; that second mkdir could only rebuild a home
removed in between. Adds tests for the _data_dir standalone fallback,
for _write_json, and for the disk-cleanup _handle_slash liveness guard
(an unrelated FileNotFoundError on a live home still raises), and fixes
the _on_post_tool_call docstring.

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-22 02:17:23 +05:30
kshitijk4poor
a81ecc281f fix(disk-cleanup): say a cleanup cut short by a deleted profile may have removed files
quick and deep can delete tracked files before save_tracked() refuses the
missing home, so "disk-cleanup did nothing" could be false. The reply now
says disk-cleanup stopped and already-removed files stay removed.
2026-11-22 02:17:23 +05:30
kshitijk4poor
8f239226bc fix(plugins): plugin writes refuse a deleted or renamed profile home
A session still bound to profile b survives `hermes profile delete b` and
`hermes profile rename b c`. Its next plugin write recreated profiles/b
through a raw mkdir, and nothing raised.

Seven plugin state writers now create their directories through
mkdir_under_hermes_home, which refuses a missing or tombstoned named home
with its existing FileNotFoundError: plugin_data_dir (and the
hermes-achievements fallback that duplicates it), the CLI plugins dir,
the update-check markers, disk-cleanup state, the Discord recovery ledger,
the Weixin account dir and the A2A audit log.

Callers that already catch keep skipping the write (Discord recovery,
the update-check writers, the disk-cleanup session-end hook and audit log,
the A2A audit). The disk-cleanup slash commands reply that the profile no
longer exists instead of raising. plugin_data_dir documents the refusal.
2026-11-22 02:17:23 +05:30
BearHuddleston
aeb5a07106 fix(telegram): a late plugin's group-99 handler runs ahead of the observer
Some checks failed
Skills Index Freshness Check / check-freshness (push) Has been cancelled
Skills Index Freshness Check / check-catalog-cors (push) Has been cancelled
Deploy Site / deploy-vercel (push) Has been cancelled
Deploy Site / deploy-docs (push) Has been cancelled
Docs Search Monitor / probe (push) Has been cancelled
auto-fix lint issues & formatting / Generate eslint --fix patch (push) Has been cancelled
auto-fix lint issues & formatting / Apply patch (push) Has been cancelled
PTB's Application.add_handler creates a group by keying it on the
current dict and then replacing app.handlers with a new sorted dict.
_register_handlers kept a reference to app.handlers from before core
registration and read the core handler ids from it afterwards, so only
the first group created during registration was recorded. When no
plugin had a handler at connect (the usual late-install case), group 0
was recorded and the group-99 gateway_platform_event observer was not.
A plugin loaded mid-run that registered a group-99 handler was then
appended behind that catch-all TypeHandler(Update), and PTB, which runs
the first matching handler per group, never ran it. A plugin present
at connect already sat ahead of the observer, so the late re-wire did
not match connect as documented.

The core ids now come from the live table after registration, minus
the handlers that were there before it (the plugin handlers wired at
connect), so a late handler lands after earlier plugin handlers and
ahead of the observer, as at connect.

Ahead of the observer is the order connect already uses, and nothing
the observer does depends on running first: dispatch is counted in
TelegramApplication.process_update, an observer's return never
completes an admission claim (4a2b984fd2), and a plugin callback
accepts the claim on entry. For an update the plugin's own group-99
handler matches, the observer does not emit gateway_platform_event,
the same trade-off as for a plugin wired at connect; updates it does
not match still reach the observer.

The gateway test's _PtbApp appended with setdefault, which hid the
swap; it now mirrors PTB 22.8. A real-PTB dispatch test covers both
load orders where python-telegram-bot is installed. The snapshot came
with the late re-wire in 21d0b12958 (#119266).

Reported-by: AliZakaee (#152827)
2026-11-21 01:30:48 -06:00
BearHuddleston
e75272d80e fix(telegram): read ParseMode from telegram.constants in vault-code prompts
telegram_vault_code.py landed after this PR was first written and imported
ParseMode from plugins.platforms.telegram.adapter at both send and card-edit
sites. On a first gateway run after on-demand python-telegram-bot install,
that sibling copy still binds ParseMode = None while only the running
hermes_plugins copy is rebound, so send_vault_code_prompt raised
AttributeError and _mark_vault_code_card failed silently.

Read ParseMode from telegram.constants at both sites and extend the lazy
install probe to exercise send_vault_code_prompt and _mark_vault_code_card.
2026-11-20 23:55:04 -06:00
Kevin Rajan
da753b1b2e fix(telegram): preserve disconnected draft result before lazy PTB install
Credit BearHuddleston for the first-run draft fix and AliZakaee for reporting the lazy-install problem.
Keep the no-bot failure contract while the optional Telegram dependency is still absent.

The ParseMode import now runs after the no-bot guard: a disconnected adapter returns
not_connected again instead of raising ModuleNotFoundError when python-telegram-bot is
missing. The added probe assertion fails on d1f52f77f2 and passes here.

(cherry picked from commit bda1e423d754b07aa65f8cbd7af3b929803cc40f)
2026-11-20 23:55:04 -06:00
BearHuddleston
aa0400f06d fix(telegram): drafts stream on the first gateway run after the on-demand python-telegram-bot install
send_draft read ParseMode from plugins.platforms.telegram.adapter, but the gateway
runs the hermes_plugins.platforms__telegram.adapter copy. When python-telegram-bot is
missing at plugin load, both copies bind ParseMode = None, and the registry's
installer (check_telegram_requirements) rebinds only the running copy. The first
draft frame then raised AttributeError ('NoneType' object has no attribute
'MARKDOWN_V2'), the stream consumer logged it at DEBUG and turned drafts off, and
every DM turn streamed through edits until the gateway restarted.

Regression from 7222595b82 (#151863), which moved the send_draft body out of
adapter.py, where it read the running module's global. ParseMode now comes from
telegram.constants at call time, as standalone.py already does.

The new test runs real plugin discovery with telegram blocked, then the registry's
create_adapter install path, and asserts the first draft goes out as MarkdownV2.

Reported-by: AliZakaee (#152827)
2026-11-20 23:55:04 -06:00
Teknium
a0097551b6 Merge pull request #155300 from victor-kyriazakos/fix/cron-suppressed-tick-session-leak
fix(cron): end the gateway-admitted session row when a gate suppresses or refuses a fire
2026-11-20 14:41:55 -08:00
Gabby Ong
845acdd9e9 feat(gemini): add Gemini 4 Neon and its xhigh thinking level
Adds gemini-4-neon to the Gemini provider catalog and official pricing snapshot ($3/$15/$0.15 per 1M input, output, and cache-read tokens) while keeping gemini-3.8-flash as the silent default. Enables the xhigh thinking level for Gemini 4 Neon alongside Hydrogen on xhigh, max, and ultra efforts, inheriting the existing 1M context window, 64K single-request cap, long decode continuation, and Interactions API routing.
2026-11-20 16:38:21 +05:30
Victor Kyriazakos
a01f997497 Merge origin/main into fix/cron-suppressed-tick-session-leak
Preserve preparation exception propagation and admission cleanup ownership.
Port suppressed-session cleanup and its regression fixtures to main's
persistence repositories, retaining bounded end-before-cosmetics ordering.
2026-11-19 23:22:46 +00:00
Maciej Lisiewski
e97efa9c35 fix(feishu): import the card mixins package-relative so a reload reaches cards/
adapter.py still imported adapter_choice_cards and adapter_synthetic_events by absolute path, so their own `.cards` imports resolved to plugins.platforms.feishu.cards, which a plugin reload never evicts: clarify/choice clicks and synthetic events kept running the pre-reload card helpers. The reload test now overrides the helpers in the copied cards/authz.py and drives the chat-info, clarify and synthetic-event lanes.

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-19 15:23:56 +01:00
Maciej Lisiewski
797be253e1 refactor(feishu): card authz as a cards/ package imported package-relative
The directory loader imports the plugin as hermes_plugins.<slug> and evicts that
namespace on reload; the absolute import of adapter_card_authz registered it under
plugins.platforms.feishu.*, so a reload kept serving the old helpers. The six
helpers become plain functions in cards/authz.py (the adapter is passed in), the
FeishuCardAuthzMixin base goes away, and every consumer imports `.cards`.

test_feishu_table_markdown.py loaded adapter.py with no parent package, which a
relative import cannot resolve; it now imports the adapter from its package.
Card-authz log records now come from the ...feishu.cards.authz logger.

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-19 14:46:56 +01:00
yoniebans
be3d6affc8 refactor(state)!: remove the old session store
hermes_state.py becomes the stand-in plugins import, the rest of the legacy store and its test folder go, and the per-process modules the backend imported from main move under persistence/sqlite/_state/. The backend checks PID namespaces and lease holders through process_identity and its WAL setup through sqlite_support, and its error module takes the shared predicates and classification from storage_errors, so neither helper set has a second copy. The backend, sqlite_support.py and the tests that pin those modules reach their final imports, and the backend-import guard allows no file outside persistence/. The modules no caller imports any more go with it: the agent's onboarding rules (now in session_rules) and gateway/session_admission.py.

The stand-in's SessionDB releases its store on close() and, used again afterwards, opens it again with a warning, as the old class reopened its connection, unless the file at its path was replaced or the store is latched corrupt; a read-only one raises. A close during a call releases the store when the call returns. A named source wins over a source list in its session listing and count.

An agent given a writable stand-in SessionDB as session_db= and no persistence= takes the store handle that SessionDB forwards to as its persistence, so its turn flush, token counts, compression and session row writes go through the storage interface, as an agent given the old SessionDB wrote through it.

The backend-import guard also holds the backend's remaining reads of the process or task home, each with its reason, and refuses any other and any import of the stand-in inside persistence/sqlite/.

Plugin context engines get the agent's store as persistence= beside the deprecated session_db=, in each hook whose signature accepts that keyword, including the rebind after /new, /resume and /branch, and the context engine guide and the plugin guide's replacement table name it. A test fails once the running release reaches the stand-in's removal release, listing what goes with the stand-in.

release_unheld_media and collect_unheld_api_images take a store only: their SessionDB branches, which no caller reaches, go with the gateway's own copies of the admission and transcript queries.
2026-11-17 19:10:57 +01:00
yoniebans
eeca5465ba test(telegram): the photo pairing and batch routing cases run their topic rig on a store handle
main's text-then-photo and batch routing property cases share one topic-mode rig that opens a legacy SessionDB and hands it to the gateway runner. The rig opens a storage handle on the test home, enables topic mode and binds each topic through the routing interface and seeds sessions with seed_session, as the stack's Telegram topic cases do; the cases and their assertions are main's.
2026-11-17 17:51:23 +01:00
yoniebans
aa768b20d4 test(gateway): the newer Telegram and session cases run over the persistence interface
Main's new or changed cases that seeded or read the old store run on the storage interface with main's assertions: the observed transcript timestamp, the observe-mode /resume ownership guard, the dead private topic prune and the kept binding of an unconfirmed send, the oversized file admission, the idle /new that drops a held burst, the adoption of a chat on an external-process provider, and the send-path recovery sweep after a profile stop. Rows are seeded through the storage handle, the ledger's store follows the test's HERMES_HOME, and each authority's stores close by profile folder.

The private topic send ladder's docstring names the interface verb that prunes a dead topic's binding.
2026-11-17 17:51:22 +01:00
yoniebans
0caa608079 test(tools): tools, ACP, plugin and cron cases over the persistence interface
The tests of those areas seed and read the store through the storage fixtures. The legacy alternation-repair test goes: its cases run in the ACP and backend copies.
2026-11-17 17:51:20 +01:00
alt-glitch
40d1e95f37 refactor(teams): move the Microsoft Graph auth and client into the teams_pipeline plugin
Some checks failed
Skills Index Freshness Check / check-freshness (push) Has been cancelled
Skills Index Freshness Check / check-catalog-cors (push) Has been cancelled
Docs Search Monitor / probe (push) Has been cancelled
Deploy Site / deploy-vercel (push) Has been cancelled
Deploy Site / deploy-docs (push) Has been cancelled
Build Skills Index / build-index (push) Has been cancelled
Build Skills Index / trigger-deploy (push) Has been cancelled
auto-fix lint issues & formatting / Generate eslint --fix patch (push) Has been cancelled
auto-fix lint issues & formatting / Apply patch (push) Has been cancelled
Canary Release / Tag, draft, and start the canary build (push) Has been cancelled
Canary Release / Prune canaries older than 14 days (push) Has been cancelled
Live provider canaries / Live provider canaries (push) Has been cancelled
tools/microsoft_graph_auth.py and tools/microsoft_graph_client.py register
no tool and only Teams code imports them, four of six imports from
plugins/teams_pipeline/. They move there as graph_auth.py and
graph_client.py, with their two tests under tests/plugins/teams_pipeline/.

- Importers change one import line where it stands; summary_writer.py
  keeps its imports inside _build_graph_client.
- The Graph client's only core import, parse_retry_after_seconds, is on
  the published plugin API.
- boundary_lint baseline drops the 8 rows for these imports; an import of
  another in-tree plugin is not a crossing (module_to_core 833 -> 825).
- The Graph app registration guide and its zh-Hans copy name the new path.
- Nothing stays at the old paths; neither module is on a frozen list.

Measured: with teams_pipeline disabled, Graph delivery from the Teams
summary writer still works, but its first call now imports the
teams_pipeline package (17 Hermes modules instead of 2), because
plugins/teams_pipeline/__init__.py imports its CLI.
2026-11-17 09:09:45 +05:30
Maciej Lisiewski
f821b5bac1 Merge pull request #155430 from NousResearch/sec3/134019-standalone-npmrc
fix(security): release-age gate for the standalone WhatsApp bridge and Photon sidecar npm packages
2026-11-15 01:32:38 +01:00
Maciej Lisiewski
03ab6e9d01 Merge pull request #155427 from NousResearch/sec3/136773-dashboard-auth-hardening
fix(dashboard): HTTPS-only prefixed cookies, kanban WS host/origin gate, media-proxy per-hop allowlist
2026-11-14 22:21:38 +01:00
Maciej Lisiewski
4a580658c2 Merge pull request #155558 from NousResearch/sec3/154609-env-loader-home-key
fix(env_loader): key secret-source state by hermes_home_key()
2026-11-14 20:31:23 +01:00
Teknium
803b3ec70c fix(telegram): an album's command caption still leads after an absorbed comment 2026-11-14 10:34:27 -08:00
Teknium
0896d4df55 fix(telegram): a comment absorbed by an inlined document survives the album's command caption 2026-11-14 10:34:27 -08:00
Teknium
f670c8b4a8 fix(telegram): a comment and the video, voice or file sent right after it are one turn
#151809 held a short text for the image sent right after it. Forward-with-comment and
"here's the clip:" then a clip send the TEXT first too, but for video, voice, audio and
documents the comment still flushed alone and the attachment became a second turn. The
media handler now claims the pending comment for any attachment and the generic dispatch
path absorbs it, the same claim/absorb seam the image path uses.

Co-authored-by: mene-crab <mene-crab@proton.me>
2026-11-14 10:34:27 -08:00
Maciej Lisiewski
61be8bf593 fix(gemini): keep length when an Interactions call ends truncated
The Interactions transport (default for Gemini 3+/-latest on AI Studio) let
any function_call step override an incomplete/budget_exceeded status, and the
long-decode hop ceiling reported tool_calls when a call had streamed, so a
cut-off call executed. Report tool_calls only when the status maps to stop;
the hop ceiling always reports length. Also pin the native stream case where
finishReason arrives in a later event than the functionCall.

Fixes #144949
2026-11-14 15:11:41 +01:00
Teknium
da8e0d8c9d fix(gateway): an explicit config.yaml platform key beats an inherited env value
The YAML -> env bridge skipped any name already present in os.environ unless
its ownership marker matched. A value merely inherited from the launcher
(TELEGRAM_REACTIONS=true from a parent process, not .env, not a previous
bridge write) therefore beat platforms.telegram.reactions: false, against
configuration.md's "config.yaml wins for non-secret settings".

Now only a .env / managed .env / external secret source value is kept over
the YAML key (#109032); any other preset value is replaced and the bridge
takes ownership via its marker. Removed-key retraction is unchanged: it only
drops the bridge's own marked values.

Fixes #110295
2026-11-14 05:00:31 -08:00
kshitijk4poor
802b57261c docs(fal): describe the shared direct-client cache in fal_common and its tests 2026-11-14 18:28:19 +05:30
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
Maciej Lisiewski
c7e046bf73 test(dashboard): pin the media-proxy redirect cap and relative Location; scope the kanban WS test
Adds a relative-redirect chain test that fails if the 3-hop cap or the urljoin resolution
is dropped. The kanban /events Host/Origin test docstring now says what it pins: the route's
own check (defence in depth), since PluginApiWebSocketGate already gates the socket in the
dashboard app.

Refs #136773

Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-14 13:24:26 +01:00
Maciej Lisiewski
9f569dc14e test(dashboard-auth): plant __Host- session cookies in the HTTPS-origin tests
The HTTPS cookie reader no longer honours bare hermes_session_* names, so
tests added since the salvaged PR that planted bare cookies on an https
TestClient now use the __Host- names the server actually sets there.

Fixes #136773
2026-11-14 13:24:26 +01:00
Adolanium
73cb700bcb fix(kanban): apply the dashboard Host/Origin/peer guard to the /events WebSocket
Every core dashboard WS route runs _ws_request_is_allowed after
_ws_auth_ok; the kanban plugin's /events stream only ran the credential
check, and fell open (accepted) whenever web_server_chat failed to
import. Run both gates and drop the fail-open import fallback, so the
stream can no longer drift from core WS policy.
2026-11-14 13:24:25 +01:00
Adolanium
cb8d354190 fix(dashboard-auth): read only prefixed session cookies over HTTPS
Over HTTPS the setters only ever write __Host-/__Secure- cookie names, but
_read_with_fallback still fell back to the bare hermes_session_* name when
no prefixed one was present. A bare cookie on an HTTPS origin can only come
from elsewhere, e.g. a sibling subdomain setting Domain= on the parent,
which is exactly what the prefixes exist to stop (login CSRF / session or
PKCE-state fixation). Drop the bare fallback when detect_https(request) is
true; plain-HTTP loopback, where prefixes cannot be set, keeps it.

Tests that planted bare cookies on an https TestClient now use the
__Host- name the server actually sets there.
2026-11-14 13:24:25 +01:00
Maciej Lisiewski
c0ef1ccba4 test(photon): pin the sidecar .npmrc mirror behaviourally; fix gate wording
Follow-up to the salvaged #134062 commit. Drop its repo-walking
structural test (banned shape per tests/AGENTS.md) and instead assert the
read-only-tree mirror actually carries .npmrc to where npm ci runs. The
.npmrc comments now say what the gate mirrors: the root .npmrc carries
only engine-strict; the 14-day floor lives in pnpm-workspace.yaml's
minimumReleaseAge, which npm never reads.

Fixes #134019
2026-11-14 13:24:16 +01:00
Kevin Rajan
47a59f1640 fix(env_loader): key secret-source state by canonical home identity
Use hermes_home_key for per-home snapshots, reset, process-global writes,
and MCP hydration cooldown so Windows case aliases cannot keep stale secrets.

Add a portable key-provider contract regression and a native Windows
case-alias regression; align existing cache fixtures with canonical keys.

Refs NousResearch/hermes-agent#154609
Reported-by: c2h5oh

(cherry picked from commit 5b1314326f832dd36b992de581a6b686b58a7117)
2026-11-14 12:50:49 +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
Maciej Lisiewski
353f743d5f test(a2a): synthesize a 40+ char dot-led body for the AQ. Gemini pattern
The corpus test builds one token per _PREFIX_PATTERNS entry from the
pattern's literal prefix; 'AQ\.[A-Za-z0-9_-]{40,}' extracts prefix 'AQ'
and the only dot-led body was 33 chars. Add a longer dot-led body so the
new pattern is covered instead of skipped.

Refs #66920
2026-11-14 02:19:19 -08:00
Maciej Lisiewski
dc965932a0 Merge pull request #155303 from NousResearch/fix/multiplex-host-allowlist-revoke
fix(gateway): a multiplexed host profile's allowlist edit revokes under its own scope
2026-11-14 04:35:05 +01: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
d8eb43e424 fix(gateway): retract a removed setting's bridge leftover before env overrides read it
4c13c06 (#154562) moved the outer yaml_env_refresh() up to load_gateway_config() so a load
that fails in typed construction rolls its bridged writes back. The nested refresh in
load_yaml_layer() then only participated, so retraction of unchanged bridge-owned
leftovers moved to the outer exit, after GatewayConfig.from_dict and _apply_env_overrides.
A restart child that inherited TELEGRAM_REPLY_TO_MODE / DISCORD_REPLY_TO_MODE (plus marker)
for a key since removed from config.yaml built its first config with the stale value.

Split the two roles: yaml_env_transaction() is the rollback scope held across the whole
load; yaml_env_refresh() (the YAML layer) commits the retraction at its own end, before
anything reads the env. Each retracted value's prior is recorded first, so a load that
later raises restores it along with its writes. A bare yaml_env_transaction() with no
layer inside still retracts at exit, as the old single scope did.
2026-11-13 16:48:50 -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