Commit graph

14582 commits

Author SHA1 Message Date
teknium1
f26ae4f683 fix(mcp): align OAuth login connect_timeout floor at 315s across CLI and GUI
Raise the CLI login floor from 180s to 315s (OAuth callback window 300s
+ headroom, matching web_server's existing constant), and let the GUI
re-auth path honor a configured connect_timeout larger than 315s.
2026-07-05 19:10:00 -07:00
teknium1
8a9e30dbd5 chore: AUTHOR_MAP entries for #54494/#56699 salvage 2026-07-05 19:10:00 -07:00
Sam Beran
d52d2973a1 feat(cli): add --connect-timeout flag to hermes mcp add
Persists as the server's connect_timeout in config, which the probe
now honors. CLI-flag portion of PR #54494; the probe-wrapper portion
was superseded by resolving connect_timeout inside _probe_single_server.
2026-07-05 19:10:00 -07:00
Michael Musser
a348368019 fix: honor configured connect_timeout on MCP OAuth login path
_reauth_oauth_server (hermes mcp login / reauth) called
_probe_single_server without a timeout, so it always used the 30s
probe default — far too short for a human browser OAuth round-trip
(open → sign in → consent → loopback redirect). The server-level
connect_timeout in config.yaml was silently ignored, so login timed
out at ~40s no matter what the user configured.

Pass the server's configured connect_timeout through, with a 180s
floor for the interactive login path. Update the two TestMcpLogin
probe mocks for the new kwarg and assert the login path propagates a
>=180s timeout.
2026-07-05 19:10:00 -07:00
Stephen Schoettler
087aa74e6e fix(cli): honor MCP probe connect timeout
(cherry picked from commit b106dbe1c6a892789dcc4a0fdd460e1d100b8a66)
(cherry picked from commit 2142c95ccfd9fc882f4252be561c844752c76a37)
2026-07-05 19:10:00 -07:00
teknium1
6133285596 chore(release): map Alix-007 author email for PR #54620 salvage 2026-07-05 17:38:36 -07:00
teknium1
2bcb893d87 fix(feishu): set client_max_size on the webhook Application
Follow-up to the salvaged #54938: the bounded reader gives a proper 413 +
anomaly telemetry for oversized chunked bodies; client_max_size makes
aiohttp enforce the same 1 MiB cap on every other read path
(#58536/#58902/#59180 pattern). Test fixture's fake Application now
accepts kwargs.
2026-07-05 17:38:36 -07:00
luyifan
a26680eb2d Enforce Feishu webhook body limit while reading 2026-07-05 17:38:36 -07:00
teknium1
e82d71db40 fix(whatsapp): set client_max_size on the webhook Application
Follow-up to the salvaged #54944: before this, aiohttp's implicit 1 MiB
default client_max_size tripped BEFORE the intended 3 MB Meta cap could
apply on read() paths — the explicit value makes the documented limit
real while the bounded reader keeps chunked bodies from buffering past
3 MB (#58536/#58902/#59180 pattern).
2026-07-05 17:38:36 -07:00
luyifan
eec92a92c0 Enforce WhatsApp Cloud webhook body limit while reading 2026-07-05 17:38:36 -07:00
teknium1
deae37e33b fix(tests): add missing json import in msgraph webhook test fixture
The salvaged #25296 fixture's _FakeRequest.read() calls json.dumps but the
test module never imported json — the NameError was swallowed by the
handler's generic except → 400, failing 10 payload tests.
2026-07-05 17:38:36 -07:00
binhnt92
4f4cbff8bd fix(msgraph): enforce webhook body limits 2026-07-05 17:38:36 -07:00
teknium1
3dd5ce236a fix(sms): set client_max_size on the Twilio webhook Application
Follow-up to the salvaged #54620: the post-read length check bounds
processing but a chunked body is still buffered by aiohttp first.
client_max_size enforces the same 64 KiB cap mid-read on every path
(#58536/#58902/#59180 pattern).
2026-07-05 17:38:36 -07:00
Alix-007
940b69b1a8 fix(sms): bound Twilio webhook body reads to prevent OOM
_handle_webhook() called request.read() with no size guard. Since the
endpoint is publicly reachable, an attacker can send an arbitrarily large
POST body to exhaust gateway memory.

Add _TWILIO_WEBHOOK_MAX_BODY_BYTES (64 KiB — well above any real Twilio
payload) and gate on both Content-Length and actual read size, returning
HTTP 413 with an empty TwiML Response on oversized requests. Mirrors the
guard already present in the Raft adapter.
2026-07-05 17:38:36 -07:00
teknium1
c5a8df3af2 chore(release): map jashlee+microsoft@microsoft.com -> s905060 (PR #57943 salvage) 2026-07-05 17:38:32 -07:00
teknium1
127d2ee87a fix(photon): bound the sidecar dep self-heal npm run with a timeout
Follow-up to the salvaged #57943: a wedged npm (dead registry, network
blackhole) ran unbounded inside asyncio.to_thread, holding the photon
connect path hostage. Cap npm ci / npm install at 600s; on timeout, log
and leave the stale deps in place so the readiness check reports the
real error and the next reconnect tick retries.
2026-07-05 17:38:32 -07:00
Jash Lee
3cd93f6aa8 fix(photon): auto-reinstall stale sidecar deps before start
A `hermes update` that bumps the spectrum-ts pin rewrites the Photon
sidecar's package-lock.json but never reinstalls node_modules. The sidecar
then spawns against the old install and the v8 postinstall patch throws
"@spectrum-ts/imessage dist not found", so the gateway retries the photon
platform every 300s forever without ever repairing the deps. Observed in
the wild: a June pin bump to spectrum-ts 8.0.0 left node_modules at 3.1.0,
and inbound/outbound iMessage stayed dead for days with the reconnect loop
faithfully restarting into the identical broken state.

_start_sidecar only checked that node_modules exists, not that it matches
the lockfile, so restart never became repair. Detect the skew with the same
signal npm ci uses: the top-level package-lock.json being newer than npm's
node_modules/.package-lock.json install marker. When stale, reinstall
(npm ci, falling back to npm install) before spawning. The reinstall runs
via asyncio.to_thread so a cold install can't block the event loop and stall
every other platform's traffic; worst case it heals on the next reconnect
tick instead. First-run "deps not installed" behavior is unchanged, and a
missing/unreadable marker fails safe to "not stale" so start is never
blocked.

Reuses the existing npm ci -> npm install fallback from
`hermes photon install-sidecar`. Adds unit tests for the staleness signal
(stale / fresh / missing-marker).
2026-07-05 17:38:32 -07:00
teknium1
ede7e31636 fix(auxiliary): gate main api_key inheritance on same-host aux base_url
Follow-up to the #55911 salvage: inherit model.api_key only when the aux
base_url resolves to the same hostname as the main model's base_url
(runtime override or config). A misconfigured aux endpoint on a different
host keeps the fail-safe no-key-required placeholder instead of leaking
the main credential cross-host.
2026-07-05 17:38:06 -07:00
Tranquil-Flow
8e09afda27 fix(auxiliary): inherit model.api_key for custom endpoint when per-task key is empty (#9318)
When an auxiliary task is configured with provider=custom and an explicit
base_url but an empty api_key, the custom_key fallback chain in
resolve_provider_client() jumped straight to the no-key-required
placeholder without consulting model.api_key from config.yaml.  Users
on self-hosted gateways who share the same endpoint and credentials for
both the main model and auxiliary tasks got 401 auth errors.

Add _read_main_api_key() following the same pattern as _read_main_model()
and _read_main_provider(): checks _RUNTIME_MAIN_API_KEY (runtime override)
first, then config.yaml model.api_key.  Insert it into the fallback chain
before no-key-required so real credentials are used when available, while
local servers without auth still get the placeholder.
2026-07-05 17:38:06 -07:00
Teknium
6fad6f1dd8
fix(whatsapp): contain and surface inbound media download failures (port nanoclaw#2895) (#59261)
Port from nanocoai/nanoclaw#2895's never-silently-drop guarantee.

Before: saveMedia() in scripts/whatsapp-bridge/bridge_helpers.js awaited
downloadMedia() with no try/catch. A failed CDN fetch (expired media URL,
transient network error — Baileys throws 'Failed to fetch stream from
https://mmg.whatsapp.net/...') rejected out of extractBridgeEvent, which
bridge.js awaits inside its messages.upsert for-loop with no per-message
guard — dropping the failed message AND every remaining message in the
same upsert batch, silently.

After:
- saveMedia catches download/write failures, records the media type, and
  logs a console.warn instead of rejecting.
- appendMediaFailureNote() (exported pure helper, mirroring the file's
  testable-helper convention) surfaces '[<type> could not be downloaded]'
  in the event body, so the agent learns media was sent rather than the
  attachment vanishing. Applied before the '[<type> received]' fallback
  so an uncaptioned failed image reads as a failure, not an arrival.

The reuploadRequest recovery half of nanoclaw#2895 is already wired in
bridge.js (downloadMediaMessage(..., { reuploadRequest:
sock.updateMediaMessage })); this ports the containment half hermes was
missing.

Tests: 3 new cases in bridge.native.test.mjs (note formatting, uncaptioned
failure containment, captioned failure note). All 5 bridge test files pass.
2026-07-05 17:21:28 -07:00
HexLab98
a05b64d677 test(setup): blank-slate disabled list must not overlap kept tools
Overlap-invariant regression test from PR #58686 — no toolset in the
blank-slate disabled_toolsets may share a tool with a kept toolset,
since the subtraction happens at tool granularity (#57315, #58281).
2026-07-05 14:51:49 -07:00
Brett Bonner
e5636da5d8 fix(toolsets): preserve core tools when a posture toolset is in disabled_toolsets (#57315)
The disabled_toolsets subtraction loop in _compute_tool_definitions
preserved shared core tools only for hermes-* platform bundles (#33924),
subtracting bundle_non_core_tools(); every other name took the else
branch and got a full resolve_toolset() subtraction. The `coding`
toolset is a posture toolset (posture: True) that re-lists the shared
_HERMES_CORE_TOOLS it does not own, so disabled_toolsets=["coding"]
stripped those core tools from the whole schema (34 tools collapsed to a
handful; terminal/read_file/write_file/web_search/execute_code gone).

Extend the core-preserving branch to also match posture toolsets, so
they subtract only the non-core delta. Only `coding` carries
posture: True, so atomic toolsets stay fully removable. The
bundle-misconfiguration info log is gated to hermes-* names, since its
wording is bundle-specific and disabled_toolsets=["coding"] is a
legitimate config written by older `hermes setup` runs.

Adds a regression test (TestDisabledToolsetsPostureToolset) alongside
the existing #33924 bundle tests.
2026-07-05 14:51:49 -07:00
liuhao1024
b57fe5ca01 fix(setup): exclude posture toolsets from blank-slate disabled_toolsets
Blank Slate's _blank_slate_minimal_toolsets() adds every TOOLSETS entry
to agent.disabled_toolsets except file and terminal.  The coding
posture toolset (session-level, selected by agent/coding_context.py)
slips through because the loop only skips hermes-* composites and
includes-only groups.

At runtime, model_tools.get_tool_definitions() resolves coding and
subtracts its tools — terminal, read_file, write_file, patch,
search_files, process — erasing the entire Blank Slate minimal surface.
The agent ends up with only cronjob.

Skip posture toolsets in the disabled-list computation.  Posture
toolsets are not user-facing capabilities to disable; they are
per-session selections that should never appear in agent.disabled_toolsets.

Fixes #57315
2026-07-05 14:51:49 -07:00
HexLab98
c9adbaff5e test(mcp): cover probe capability + config gating for prompts/resources
Assert the "Test server" probe skips prompts/list when tools.prompts is false,
skips both families when the server advertises neither capability (the Unreal
MCP server case), probes both when advertised and enabled, and falls back to
the legacy always-try behaviour when no capability info was captured.
2026-07-05 14:51:36 -07:00
HexLab98
1f2a33f4ac fix(mcp): gate probe prompts/resources on config + advertised capabilities
The "Test server" probe (`_probe_single_server`, used by the Desktop/dashboard
MCP tab, `hermes mcp add`, and `hermes mcp test`) called `prompts/list` and
`resources/list` on every server unconditionally whenever `details` was
requested. This ignored the user's `tools.prompts` / `tools.resources` config
and the server's own advertised capabilities.

Servers that don't implement those optional families (e.g. Unreal Engine's MCP
server, which answers `Call to unknown method "prompts/list"`) therefore logged
a hard error during discovery, and setting `tools.prompts: false` — the
documented workaround — had no effect because the probe never consulted it.

Mirror the runtime gating in `tools.mcp_tool._select_utility_schemas`: only
probe a family when it is enabled in config AND advertised in the server's
`initialize` capabilities. Falls back to the previous always-try behaviour when
no capability info was captured.
2026-07-05 14:51:36 -07:00
Teknium
de7e0a8875
fix(docker): heal pairing-dir ownership after docker exec writes (#10270) (#59130)
* fix(docker): heal pairing-dir ownership after `docker exec` writes (#10270)

The official Docker image runs the gateway as the unprivileged `hermes`
user (uid 10000) via `gosu`, but `docker exec` defaults to root. Approval
files written by `docker exec <container> hermes pairing approve <code>`
end up as `-rw------- root:root`, and the post-gosu gateway process
cannot read them. The approval is silently ignored — the user keeps
hitting 'Unauthorized user' on every message.

The entrypoint's existing top-level chown is gated on the top-level
$HERMES_HOME being mis-owned, so on warm boots (where /opt/data is
already hermes:hermes) the recursive chown is skipped — meaning a
container restart does NOT self-heal the bug either.

Three-part fix:

1. docker/entrypoint.sh: chown the platforms/pairing/ (and legacy
   pairing/) subtree on every container start, regardless of the
   top-level decision. The directory is tiny (a few JSON files), so
   the unconditional chown is effectively free. Container restart
   now self-heals.

2. gateway/pairing.py: PairingStore._load_json was swallowing
   PermissionError under its bare 'except OSError' branch, which is
   what made this a silent failure. Split it out: log a WARNING that
   names the file, the gateway's uid, the file's owner/mode, and the
   exact docker exec -u hermes workaround. Still falls back to {} so
   the gateway stays up.

3. website/docs/user-guide/security.md: add a Docker tip to the
   pairing-CLI section pointing users at `docker exec -u hermes …`
   up front.

Reproduced end-to-end in a containerized harness — before the fix
the gateway sees 0 approved users after `docker exec` + restart;
after the fix it sees the expected 1, and the file on disk goes
from `root:root 600` back to `hermes:hermes 600` on next start.

Fixes #10270

* fix(pairing): gate os.geteuid for Windows in PermissionError warning
2026-07-05 14:48:50 -07:00
Teknium
e2fe529efb
feat(approvals): user-defined deny rules that block commands even under yolo (#59164)
Adds approvals.deny to config.yaml — a list of fnmatch globs matched
against terminal commands. A match blocks unconditionally, BEFORE the
--yolo / /yolo / approvals.mode=off bypass, making it the user-editable
counterpart to the code-shipped hardline blocklist.

- Checked in both command gates (check_dangerous_command and
  check_all_command_guards), after the hardline floor and sudo-stdin
  guard, before the yolo bypass and permanent allowlist.
- Matching runs over the same normalized/deobfuscated command variants
  as the dangerous-pattern detector, case-insensitive.
- Opt-in: empty/absent list is a no-op; behavior unchanged.

Supersedes the trust-engine approach from #21500 with a minimal
config-native design: the only capability the existing stack lacked
was deny-that-beats-yolo. Allow already exists (command_allowlist),
ask already exists (session approvals).
2026-07-05 14:48:40 -07:00
Teknium
8986981df4
security(gateway): set explicit client_max_size on 3 uncapped aiohttp servers (#59180)
Sibling sweep from the #58902 raft review found aiohttp servers still
running on the implicit 1 MiB default with no explicit body cap:

- bluebubbles webhook (127.0.0.1): 1 MiB explicit cap — events are small
  JSON/form payloads; attachments arrive via the REST API
- teams Bot Framework listener (0.0.0.0 bind — most exposed): 1 MiB cap;
  activities are JSON well under that
- hermes proxy server: 10 MB cap mirroring api_server's MAX_REQUEST_BYTES
  (chat-completion payloads can be large, but must stay bounded)

client_max_size bounds every read path including chunked transfer-encoding
requests that carry no Content-Length (#58536/#58902 pattern).

Deliberately excluded: feishu, whatsapp_cloud, sms, line, wecom, msgraph —
open contributor PRs (#54938, #54944, #54620, #54931, #54934, #25296)
already cover those; reviewing them separately preserves their credit.

3 regression tests pin the wiring.
2026-07-05 14:48:28 -07:00
Teknium
0823230545
fix(computer-use): sanitize env on the 4 remaining cua-driver spawn sites (#59165)
PR #58889 fixed the CLI-fallback transport; review of that fix found the
same leak class at four sibling spawn sites of the third-party cua-driver
binary:

- _resolve_mcp_invocation (cua-driver manifest): no env= at all — full
  parent environment inherited
- cua_driver_update_check (check-update --json): telemetry env but no
  secret sanitization
- doctor._drive_health_report (<binary> mcp Popen): telemetry env only
- permissions._run (every macOS/Linux permission probe): telemetry env only

All now route through _sanitize_subprocess_env(cua_driver_child_env()),
matching the sanctioned MCP spawn and the #53503/#55709/#58889 strip-by-
default policy for non-terminal spawns. Sanitization degrades gracefully
(falls back to the telemetry env) so doctor/permission probes never break
on an import error.

4 regression tests covering each site.
2026-07-05 14:48:20 -07:00
Teknium
65117671e3
fix(gateway): apply platform-disabled skill gate to bundle invocations (#59156)
Skill bundles load their member skills via _load_skill_payload directly,
bypassing the scan-time disabled filter in get_skill_commands(). PR #58888
closed this gap for stacked slash-skill invocations, but /<bundle> dispatch
in the gateway had the same class of bypass: a skill an operator disabled
for a platform via skills.platform_disabled still got its full content
injected when referenced by a bundle.

build_bundle_invocation_message() now accepts a platform kwarg, filters
members against get_disabled_skill_names(platform=...), and reports skipped
skills in the bundle header. Gateway dispatch passes the event's platform
explicitly (env-var resolution can't be trusted in the multi-platform
gateway process, same reasoning as the #58888 gate).
2026-07-05 14:48:11 -07:00
teknium1
f514132ff3 fix: disclose mid-line clamp in truncation hint
When a single line exceeds the entire char budget, its tail is
unreachable via offset pagination (offsets are line-granular). Tell
the model so it doesn't assume it saw the full line.
2026-07-05 14:42:05 -07:00
teknium1
25f0cecf5e Port from nearai/ironclaw#5029: graceful char-budget truncation for read_file
read_file previously hard-rejected any read whose formatted output exceeded
the ~100K char safety limit, returning an error with zero content. A file
with few but very long lines (logs, wide CSV rows, minified data) sails past
the line-count limit and then trips the char guard, so the model gets nothing
and must guess a smaller limit — wasting a full round-trip.

Now the read is trimmed to the last complete line that fits the budget and
returns the partial content plus truncated_by="bytes" and a next_offset, so
the model paginates forward instead of starting over. A single line larger
than the whole budget is clamped on a code-point boundary (never empty) and
the cursor still advances. Applies at both read paths (normal + extracted
documents).

Adapted from IronClaw's Rust dual line/byte cap to hermes's Python tool-layer
char guard, which is the single uniform chokepoint over the gutter-rendered
content for every backend.
2026-07-05 14:42:05 -07:00
teknium1
2f2e60801c chore: add l0h1nth to AUTHOR_MAP for PR #32210 salvage 2026-07-05 14:41:57 -07:00
Lohinth
1197d2bc96 fix(mattermost): accept leading-space slash commands 2026-07-05 14:41:57 -07:00
teknium1
3167dbaee2 fix(docker): widen docker_network to file/code-exec paths + guard container reuse
Follow-up to the salvaged toggle commit:

- file_tools.py / code_execution_tool.py: carry docker_network in their
  container_config dicts so those environment-creation paths honor the
  lockdown instead of silently defaulting back to bridge (the probe/exec
  asymmetry class reported on #46358).
- docker.py: cross-process reuse now inspects HostConfig.NetworkMode when
  docker_network=false and removes a mismatched (networked) container
  before starting a fresh air-gapped one. Fails closed when inspect fails.
  Default-network config never churns containers, so operators using
  docker_extra_args --network=none are unaffected.
- tests: AST invariant that every container_config site carrying
  docker_run_as_host_user also carries docker_network, plus three reuse
  guard tests (reject bridge under lockdown / keep matching none /
  no inspect when network enabled).
- docs: configuration.md gains terminal.docker_network + env var row.
2026-07-05 14:41:51 -07:00
Teknium
cd2b360d64 feat: add Docker terminal network toggle
Port from qwibitai/nanoclaw#2713: expose Hermes' existing Docker network isolation primitive through terminal config so operators can opt out of container egress.
2026-07-05 14:41:51 -07:00
falkoro
9ad912a791 fix(agent): honor auxiliary.<task>.base_url/api_key when provider is passed explicitly
_resolve_task_provider_model returns early on an explicit provider arg,
which skips the config block that consults auxiliary.<task>.base_url /
api_key. Any caller passing provider explicitly (e.g.
resolve_vision_provider_client(provider="custom", ...)) bypasses the
configured custom endpoint and falls through to main-runtime resolution,
silently routing the task to the wrong backend.

Adopt the task's configured base_url/api_key before the early returns,
but only when no explicit base_url was given and the config targets the
same provider (or names none) — a caller forcing a *different* provider
keeps full explicit-arg priority, and an explicit base_url still wins
over config.

Fixes #58515
2026-07-05 14:41:43 -07:00
teknium1
e985e34659 chore: add falkoro to AUTHOR_MAP 2026-07-05 14:41:40 -07:00
falkoro
e3203e4d80 fix(config): invalidate load_config cache when referenced ${VAR} env values change
The load_config() cache is keyed on config file mtime/size only, so a
load_config() that runs before load_hermes_dotenv() populates the process
environment caches the unexpanded ${VAR} literal and serves it for the
life of the process — auxiliary.<task>.api_key/base_url env refs reach the
provider client verbatim (auth failure / silent fallback), while
providers.* appear to work because provider credential resolution re-reads
the environment at call time.

Record a snapshot of every ${VAR} name referenced in the raw config
(user + managed) with its os.environ value at expansion time, and treat
the cache as stale when any of those values change. Covers both the late
.env load and in-process key rotation; an unchanged environment still
takes the cache-hit path.

Fixes #58514
2026-07-05 14:41:40 -07:00
kshitij
c9a150d640
Merge pull request #59131 from kshitijk4poor/revert/58698-pre-tool-approve
Revert "feat(plugins): pre_tool_call approve action escalates to human gate" (#58698)
2026-07-06 02:45:11 +05:30
kshitijk4poor
74cc9ee3f0 Revert "Merge pull request #58698 from kshitijk4poor/feat/pre-tool-call-approve-escalation"
This reverts commit 368e5f197e, reversing
changes made to abf9638f4e.
2026-07-06 02:36:52 +05:30
Teknium
747386ecfa
refactor: consolidate gateway session metadata into state.db (#58899)
Moves gateway routing metadata (display_name, origin_json, expiry_finalized)
into state.db, making SQLite the single source of truth for gateway session
discovery. Eliminates the dual-file (sessions.json + state.db) polling
dependency that caused the mcp_serve new-conversation race (#8925).

- hermes_state.py: schema v18 (3 new sessions columns + sessions.json
  backfill migration), record_gateway_session_peer gains
  display_name/origin_json, new set_expiry_finalized(),
  list_gateway_sessions(), find_session_by_origin()
- gateway/session.py: peer recorder persists display_name + full origin
  JSON; new SessionStore.set_expiry_finalized() single write-path
- gateway/run.py: expiry watcher success + give-up paths use the store
  helper so the flag lands in both sessions.json and state.db
- mcp_serve.py: routing index reads state.db first (sessions.json fallback
  for pre-migration DBs); _poll_once collapses to a single state.db mtime
  check — the #8925 race is structurally impossible now
- gateway/mirror.py, gateway/channel_directory.py, hermes_cli/status.py:
  query state.db first, sessions.json fallback

Closes #9006
2026-07-05 14:01:03 -07:00
teknium1
0b67ff222a fix(agents): bound streaming error-response body reads
Port from openclaw/openclaw#95108: an unbounded response.read() on a
non-OK *streaming* response can balloon memory (huge body) or hang the
agent forever (body opens then stalls with no further bytes). The
diagnostic body is only ever shown truncated, so reading megabytes or
blocking indefinitely buys nothing.

Add agent/bounded_response.read_streaming_error_body() which caps the
read at a byte limit and enforces a hard wall-clock deadline (run on a
worker thread so it can interrupt a socket read that stalls mid-chunk,
which a between-chunk wall-clock check cannot). Wire it into all three
streaming error-body sites that previously did a bare response.read():
native Gemini, Gemini Cloud Code, and Antigravity Cloud Code. The
existing error builders now accept an optional pre-read body_text so
classification (status code, RESOURCE_EXHAUSTED, free-tier guidance,
Retry-After) is preserved unchanged.

Tests use a real in-process socket server (no mocks): oversize body is
capped, stalled body hits the deadline with partial text preserved,
normal error envelope reads intact and parses.
2026-07-05 14:00:20 -07:00
srojk34
a573066543 fix(redact): skip env-lookup exception for JSON/YAML config field redaction
_redact_env already skips redaction when a KEY=value assignment's value is
a programmatic env lookup (os.getenv(...), os.environ[...], process.env.X)
per issue #2852 — masking it would corrupt a code snippet, not redact a
secret. _redact_json (JSON "key": "value" syntax) and _redact_yaml
(unquoted key: value syntax) are separate closures in the same function
and never got the same check, so the identical code-snippet-in-config-
syntax case still gets mangled:

  {"apiKey": "os.getenv('OPENAI_API_KEY')"}  ->  {"apiKey": "os.get...EY')"}
  api_key: os.getenv("OPENAI_API_KEY")       ->  api_key: os.get...EY")

Fix: apply the same _ENV_LOOKUP_VALUE_RE.match(value) check in both
closures before masking, mirroring _redact_env exactly. Real secret
values in JSON/YAML syntax are still redacted (verified live and via new
tests) — this only skips the case where the "value" already look like a
code snippet.
2026-07-05 13:58:19 -07:00
srojk34
2e2212be1b fix(discord): dedup saturated mid-stream overflow previews to stop edit-rate-limit storms
a0a3c716f fixed the exact same failure mode for Telegram (#58563):
post-#48648, oversized mid-stream edits truncate to a one-message preview
instead of splitting. Once a long streamed reply grows past that cap, every
subsequent progressive edit truncates to the SAME preview text — re-sending
an identical edit every tick still counts against the platform's edit rate
limit for the rest of the stream.

Discord's edit_message() has the identical architecture (mid-stream
truncate-in-place, both pre-flight and reactive-after-50035 truncation
paths) and this file's own docstring already calls out "the Telegram #48648
lesson" it's built on — but the saturated-preview dedup fix itself was never
ported over.

Fix: track the last truncated preview per (chat_id, message_id), mirroring
a0a3c716f exactly. Skip the edit call when the new truncation is identical;
still deliver when the visible content actually changes (e.g. the
chunk-count marker crosses (1/2) -> (1/3) as the stream grows). State
clears on finalize and when content shrinks back under the cap, so dedup
can never mask a real edit.
2026-07-05 13:58:11 -07:00
srojk34
cdcbc3a31d fix(gateway): clear last-resolved-model cache on 3 more conversation-boundary resets
11b4a21a5 cleared the per-session _last_resolved_model cache on /new and
the compression-exhausted auto-reset, so a resumed/reset conversation
resolves the model from current config instead of a stale cached value
(#58403). Three other sites documented as the same "full conversation
boundary" treatment — pop _session_model_overrides, clear the reasoning
override, pop _pending_model_notes — still missed _last_resolved_model:

- _session_expiry_watcher's permanent finalization block (gateway/run.py):
  a session that goes idle and is finalized, then resumed, could serve a
  model cached before it went idle on a transient config-cache miss.
- The daily/idle/suspended auto-reset cleanup (_was_auto_reset handling,
  gateway/run.py): same failure mode, different trigger.
- /resume (gateway/slash_commands.py), whose own comment already says
  "conversation boundary just like /new" for the sibling dicts it clears.

Fix: pop the session's _last_resolved_model entry in all three, mirroring
the exact pattern 11b4a21a5 established.
2026-07-05 13:58:03 -07:00
srojk34
3817ff180d security(raft): enforce body-size limit on chunked requests
_handle_wake() and _handle_activity() enforced max_body_bytes only via
the Content-Length header. A Transfer-Encoding: chunked request
(content_length=None) or a spoofed small Content-Length bypassed the
cap entirely, letting the actual read be bounded only by aiohttp's
implicit 1 MiB client_max_size default (64x the 16 KB default) — the
same pattern ec29590a0 just fixed for gateway/platforms/webhook.py.

Fix: web.Application(client_max_size=self._max_body_bytes) so aiohttp
enforces the cap on every read path including chunked bodies, catch
HTTPRequestEntityTooLarge -> 413 on both endpoints (was swallowed into
a generic 400), and re-check the actual bytes read as defense in depth.
Exposure here is narrower than the webhook adapter (binds to 127.0.0.1
by default and requires the bridge token), but the bypass is otherwise
identical.
2026-07-05 13:57:37 -07:00
srojk34
1e2914b40a fix(telegram): redact bot token from connect/disconnect/send_document/send_video errors
_redact_telegram_error_text() strips bot tokens from api.telegram.org
URLs embedded in transport-error text, and is already applied across the
send/edit transient-error paths. Four sites still built their message
from the raw exception:

- connect()'s fatal-error handler is the most severe: the raw text is
  passed to _set_fatal_error(), which persists it via
  write_runtime_status() to a dashboard/admin-facing runtime status
  file, not just a log line. A transient network error during startup
  commonly embeds the request URL
  (https://api.telegram.org/bot<TOKEN>/getMe), so this could leak the
  live bot token into that surface.
- disconnect(), send_document(), send_video() build the same unredacted
  pattern into a warning log line (lower blast radius, but the same
  leak class).

Fix: route all four through the existing _redact_telegram_error_text()
helper before building the message/log line, mirroring the send/edit
paths exactly. Also drops exc_info=True from the two logger.error/
logger.warning calls that had it — exc_info prints the exception's own
traceback (including its unredacted message) separately from the format
string, which would otherwise defeat the redaction; the already-redacted
sibling call sites in this file follow the same convention.
2026-07-05 13:57:28 -07:00
srojk34
f10851e3fd fix(computer-use): sanitize subprocess env in cua-driver CLI fallback transport
_CuaDriverSession._call_tool_via_cli() (the EAGAIN/silent-empty MCP
fallback transport) invokes `cua-driver call <tool> <json>` via
subprocess.run() with no env= argument, so the third-party cua-driver
binary inherits the full, unsanitized parent environment. The primary
MCP spawn site (_lifecycle_coro) already applies
_sanitize_subprocess_env(cua_driver_child_env()) before opening the
stdio client, per the same policy #53503/#55709 established for other
subprocess spawn points — this fallback path, added alongside the
EAGAIN/silent-empty-capture hardening, missed it.

Fix: apply the same env=_sanitize_subprocess_env(cua_driver_child_env())
to the subprocess.run() call in _call_tool_via_cli(), mirroring the
sanctioned spawn site exactly (telemetry policy applied first, then
Hermes-managed secrets filtered).
2026-07-05 13:57:20 -07:00
srojk34
04d732dc56 fix(gateway): re-check every stacked skill against the platform-disabled list
_handle_message() re-checks a slash-skill command's per-platform disabled
status before dispatch, because get_skill_commands() only applies the
global disabled list at scan time. That check only covered the leading
skill: split_stacked_skill_commands() resolves additional /skill tokens
that follow it (stacked invocations, up to 5 skills, #57987), and
build_stacked_skill_invocation_message() loads every one of them via
_load_skill_payload() with no disabled-status check of any kind.

A message on a platform with skills.platform_disabled configured for a
given skill could still get that skill's full SKILL.md content injected
into the agent's context for the turn, as long as it was typed after an
allowed skill: `/allowed-skill /disabled-skill do X`.

Fix: after computing the stacked extra_keys, look up each one's skill
name and re-check it against the same get_disabled_skill_names(platform=)
set already used for the leading skill. If any stacked skill is disabled
for the platform, reject the whole invocation with the same style of
message the leading-skill check already returns, instead of partially
loading it.
2026-07-05 13:57:11 -07:00