Commit graph

8164 commits

Author SHA1 Message Date
Paulo Nascimento
90d3ba5be9 fix(cli): warn once per path for UTF-32 .env refuse-to-mangle
Hot-reload and multi-entry load_hermes_dotenv can hit the same UTF-32
file repeatedly; gate the refuse-to-mangle warning on a module-level
seen-set (house style: _WARNED_KEYS sibling) so logs are not spammed.
2026-07-18 19:01:10 -04:00
Paulo Nascimento
7d597cc5d4 fix(cli): sanitize UTF-16 .env without corrupting the first key
Notepad "Unicode" saves write UTF-16 with a BOM. The sanitizer decoded
those bytes as utf-8-sig with errors=replace, glued U+FFFD onto the first
key name, stripped NULs, and rewrote the mangled content permanently.

Sniff leading BOMs before any text decode (UTF-32 before UTF-16, because
UTF-32-LE's BOM starts with UTF-16-LE's FF FE). Decode UTF-16 correctly
and rewrite as clean UTF-8. Refuse UTF-32 (leave untouched + warning).
After errors=replace, do not persist a first line that starts with U+FFFD.

Does not touch _load_dotenv_with_fallback (#65124's surface).
2026-07-18 19:01:10 -04:00
Paulo Nascimento
4441e11c77 fix(cli): quote .env values with internal whitespace in save_env_value
_quote_env_value previously left internal spaces unquoted (only #/"/'
and leading/trailing whitespace triggered). Spaced macOS paths written
via hermes setup SSH / Google Chat SA path / hermes config set produced
lines that python-dotenv still parsed but shell `set -a; . file` word-split.

Extend needs_quoting with any(c.isspace()); escaping dialect unchanged.
2026-07-18 19:01:10 -04:00
brooklyn!
ed957aeb26
Merge pull request #67182 from NousResearch/bb/p0-salvage
fix(install): keep install.ps1 pure ASCII so Windows PowerShell 5.1 doesn't misparse it (#66994/#67000)
2026-07-18 18:58:31 -04:00
Brooklyn Nicholson
1cec5c69d3 test(mcp): e2e integration coverage for #63892 poll-loop OOM spin
The salvaged unit tests hand-construct completed futures to lock the
_run_on_mcp_loop contract. Add a live-loop test that reproduces the actual
field trigger: an inner asyncio.wait_for expiry stores a real TimeoutError
on a real future scheduled on the MCP loop. Asserts the fixed loop surfaces
it once, promptly -- not spinning to the outer deadline (which both leaked
memory and masked the real error behind the generic wrapper message).
2026-07-18 18:49:56 -04:00
PRATHAMESH75
97249cfc8a fix(install): keep install.ps1 pure ASCII so Windows PowerShell 5.1 doesn't misparse it
A commit added a bullet and an em-dash inside two Write-Host/Write-Info string
literals in scripts/install.ps1. The file has no UTF-8 BOM, so Windows
PowerShell 5.1 (which the bootstrap runs the cached script under) reads it in
the system ANSI code page (CP1252), not UTF-8. The em-dash's UTF-8 tail byte
decodes to a smart close-quote (U+201D) that the tokenizer treats as a string
delimiter, prematurely closing the string and desyncing the parser -- surfacing
as the reported cascade of syntax errors at lines 1619/1770 and aborting the
Windows GUI installer before it does anything.

Non-ASCII bytes in '#' comments are harmless (skipped to end-of-line), so the
file carried em-dashes in comments for months; only the two chars in code
broke it. Convert all non-ASCII to ASCII equivalents (em-dash -> '--', already
this file's own comment convention; bullet -> '-') and add a source-level test
locking the pure-ASCII invariant, since Linux CI cannot run the PS installer.

Fixes #66994
Fixes #67000
2026-07-18 18:40:59 -04:00
Jupiter363
3df8bd3478 fix(mcp): propagate stored timeouts from completed futures 2026-07-18 18:40:34 -04:00
Teknium
7a43ab042f
fix(computer_use): reconnect a dead cua-driver session instead of hanging (#67138)
Bug 1 of #55048: when the MCP connection dropped (driver crash / restart),
_lifecycle_coro exited but left _started=True, so the next list_apps/capture
passed _require_started() and then operated on a None session — hanging
forever instead of reconnecting.

- _lifecycle_coro's finally now resets _started=False on ANY exit, so a dead
  session is re-enterable (idempotent no-op on the normal stop() path; atomic
  bool write, safe from the bridge-loop thread without the lock stop() holds).
- call_tool() re-enters start() when the session isn't active, rebuilding it
  before the call. The start_session/end_session handshake (driven by start()/
  stop() themselves) is exempted so bootstrap doesn't recurse.

Tests: two cases in test_computer_use_delivery_ladder.py — finally resets
_started, and call_tool restarts a dead session exactly once. Full
computer_use suite green (233).

Refs #55048 (Bug 1). Bug 2 (expose foreground dispatch) is covered by the
delivery_mode work in #67123.
2026-07-18 15:07:04 -07:00
Austin Pickett
ca0703feae
fix(cli): try bundled TUI before requiring ui-tui workspace (#67116)
_make_tui_argv() called _ensure_tui_workspace(tui_dir) unconditionally
before checking for a prebuilt bundle. That function sys.exit(1)s when
ui-tui/ doesn't exist, which it never does on a pip/pipx install — the
wheel ships hermes_cli/tui_dist/entry.js but never ships ui-tui/ at all
(that directory only exists in a git checkout).

Every dashboard Chat tab connection on a pip/pipx install therefore
hard-exited before ever reaching _find_bundled_tui(), surfacing as the
unhelpful "Chat unavailable: 1" banner despite having a fully valid
bundled entry.js on disk.

Move the bundled-wheel/HERMES_TUI_DIR shortcut ahead of the workspace
check. --dev is unaffected (it never uses the bundled path and still
requires the workspace), and the checkout-without-bundle path is
unaffected (bundled lookup returns None, falls through to the existing
git-restore/npm-install/build flow).

Adds a contributors/emails mapping for the original author.

Fixes #56665

Co-authored-by: lucaskvasirr <lucaskvasir@duck.com>
2026-07-18 17:17:25 -04:00
teknium1
11cb9e571f fix: harden /model --once against persistence and config-sync leaks
Fixes the two review defects that kept PR #29923 open, plus docs:

- gateway: exclude --once from the session-store write-through. The
  once-override lived only in memory before, but the write-through
  persisted it, so a gateway restart before the finally-restore
  rehydrated a supposedly one-turn model permanently.
- TUI: skip _sync_agent_model_with_config while a one-turn restore is
  pending. The once-model is deliberately not pinned as a session
  model_override, so the config sync saw a model mismatch and clobbered
  the once-override back to the config model before the turn ran.
- tests: real _handle_model_command drive asserting --once never
  touches set_model_override while --session still does; restore-pop
  idempotency.
- docs: /model --once in configuring-models.md with an honest
  prompt-cache cost note (one-shot switch breaks the cached prefix
  twice; wins for short sessions and cheap-to-expensive escalation).
2026-07-18 14:01:56 -07:00
deusyu
3f84b7a163 feat: add /model --once one-turn model override (#29914)
Adds --once to /model across CLI, TUI, and gateway: switch model for the
next turn only, restoring the previous model in a finally block so
success, exception, and interrupt all revert. Parsing extends
parse_model_flags_detailed(); resolve_persist_behavior() treats --once
as a persistence opt-out; --global + --once is rejected.

Salvaged from PR #29923 (image-generation lane split to #59815 per
review; conflict resolution against current main by the maintainers).
2026-07-18 14:01:56 -07:00
Teknium
38b39b87ef fix(discord): keep recovery ledger I/O off event loop
Offload scan bookkeeping and final-delivery writes so SQLite contention cannot stall Discord heartbeats or message delivery.
2026-07-18 14:01:33 -07:00
Teknium
2b2203e3a7 fix(discord): advance cursors only after final delivery
Round-robin configured Discord histories under the global scan cap, but move each channel/thread cursor only when its source message reaches successful final delivery.
2026-07-18 14:01:33 -07:00
Teknium
bc0e5adb1d fix(discord): persist per-channel recovery cursors
Resume each configured Discord channel/thread after its last scanned message so busy sources cannot permanently starve later history windows.
2026-07-18 14:01:33 -07:00
Teknium
92a7145297 test(streaming): include original reply anchor metadata 2026-07-18 14:01:33 -07:00
Teknium
9412f2dd84 fix(discord): persist streamed final delivery
Carry the original reply anchor through stream metadata so a successful final Discord edit marks the recovered source message complete.
2026-07-18 14:01:33 -07:00
Teknium
d5b9c1ee37 fix(discord): guard recovery claims and ledger failures
Honor configured bot senders at shared ingress, fail closed when durable state is unavailable, and suppress duplicate reconnect work while a fresh queued/processing claim is active.
2026-07-18 14:01:33 -07:00
Teknium
da955a643e fix(discord): preserve recovery message identity
Admit recovered events without consuming live dedup first, bypass split-message debounce, report actual dispatch admission, and require explicit reply correlation before suppressing a missed request.
2026-07-18 14:01:33 -07:00
Teknium
fad6cbaed3 fix(discord): make reconnect recovery lifecycle-safe
Preserve monotonic final-delivery completion, isolate recovery config and storage per adapter/profile, coalesce reconnect scans, release cancelled claims, bypass split-message debounce for historical events, and move bounded ledger setup into a short-timeout state module.
2026-07-18 14:01:33 -07:00
Teknium
95ce3344c4 test(discord): assert global recovery scan cap
Keep the scan-cap regression focused on the invariant instead of depending on per-channel ordering.
2026-07-18 14:01:33 -07:00
Teknium
80744bc2bc fix(discord): close reconnect recovery edge cases
Include allowed mention-gated channels in default recovery scope, keep the newest bounded history window, narrow outage-message detection, avoid disabled-path ledger I/O, and persist forum replies.
2026-07-18 14:01:33 -07:00
Teknium
2278f2cb7e fix(discord): harden reconnect message recovery
Route recovered messages through the live Discord ingress policy, preserve dedup and completion invariants, bound and retain the recovery ledger, and expose the opt-in config with docs and backup coverage.
2026-07-18 14:01:33 -07:00
emo-eth
867037bced test: update Discord backfill import for plugin adapter 2026-07-18 14:01:33 -07:00
James
a52041b2e0 fix: avoid masking missed Discord parent messages
Preserve startup missed-message backfill behavior while avoiding false address classifications from unrelated parent-channel messages.
2026-07-18 14:01:33 -07:00
James
303949acdc fix: backfill missed Discord messages on startup (#3) 2026-07-18 14:01:33 -07:00
Teknium
9d6d772837
feat(computer_use): follow cua-driver's verify → escalate ladder (#67123)
Hermes' computer_use wrapper dropped cua-driver's structured action verdicts,
exposed no delivery_mode, and injected background-only guidance — so the agent
reported unverified no-ops as success and concluded cua-driver 'cannot drive'
Electron/Chromium surfaces (observed live on tldraw offline). Fixes #67052.

Phase A — preserve the result contract:
- ActionResult carries verified/effect/escalation/path/degraded/code/delivery_mode
- CuaDriverBackend._action() reads structuredContent (was data-only); a helper
  normalizes it, additive and None-safe on old drivers
- _text_response surfaces the fields additively (ok stays transport-only)

Phase B — bounded, model-reachable foreground:
- delivery_mode (background|foreground) + bring_to_front on the schema, dispatcher,
  ABC, and all input methods
- foreground is capability-gated (input.delivery_mode); old drivers get a
  structured foreground_unsupported refusal, never a silent background downgrade
- no automatic/hidden foreground retry — the model selects it from the signal

Phase C — guidance + isolation:
- system prompt (prompt_builder) and bundled skills/computer-use/SKILL.md go from
  background-ONLY to background-FIRST, teaching the AX→PX→foreground ladder driven
  by returned effect/escalation, not predicted from the app being Electron
- foreground approval scoped by (action, delivery_mode): a background approval
  never silently authorizes foreground
- approval state keyed per session_id so concurrent gateway runs don't leak unlocks

Tests: tests/tools/test_computer_use_delivery_ladder.py (15) cover confirmed/
unverifiable/suspected_noop/degraded/old-driver verdicts, delivery_mode gating +
foreground_unsupported, and session-scoped foreground approval. Existing 265
computer_use tests still green.

Live E2E (real cua-driver 0.8.3 + tldraw offline on Linux/X11): a background click
returned effect='unverifiable'/path='ax' (no fabricated success), and a foreground
request returned code='foreground_unsupported' — correct on a driver that predates
the input.delivery_mode capability.
2026-07-18 13:59:35 -07:00
Austin Pickett
2637aa607f
fix(desktop): preserve in-flight turns across gateway reconnects (rebase of #66234) (#67114)
* fix(desktop): preserve turns across gateway reconnect

* chore(release): map UnathiCodex attribution

* fix(desktop): prefer rotated resume projection

* fix(desktop): refresh warm session transcripts

* chore(contributors): use email mapping file

* fix(desktop): restore live prompts after restart

---------

Co-authored-by: UnathiCodex <theunathi@gmail.com>
2026-07-18 16:12:59 -04:00
HexLab98
862b1b37bf test(error_classifier): cover empty-response max_tokens misclassification 2026-07-18 12:54:58 -07:00
teknium1
d4396797c3 feat(gateway): live per-tool status line on Slack
Builds on the salvaged typing_status_text plumbing (PR #62007): instead
of a static 'is thinking...', Slack's assistant status line now updates
live as the agent works — 'is running pytest tests/…', 'is reading
docs/api.md…' — and reverts to the static text between tool calls.

Mechanics:
- agent/display.py: build_status_phrase() derives a <=49-char present-
  tense phrase from the existing _TOOL_VERBS table (+ 'is using <name>'
  for plugin/MCP tools; None for _thinking).
- base adapter: supports_status_text capability flag + set_status_text()
  per-chat store, cleared when the typing loop winds down.
- Slack adapter: send_typing() renders the live phrase when set, falling
  back to typing_status_text then 'is thinking...'.
- gateway/run.py: progress_callback stashes the phrase on tool.started
  and clears on tool.completed. Rendering rides the existing
  _keep_typing refresh cadence — zero additional Slack API calls, no
  rate-limit exposure. Works with tool_progress: off (Slack default);
  the callback is now armed whenever the adapter supports status text.
- display.live_status config (full|verb|off, default full): 'verb' hides
  argument previews for shared/customer-facing channels.

Also fixes a latent crash in the cherry-picked from_dict: malformed
non-dict 'extra' sections broke typing_status_text resolution (uses the
already-coerced extra dict).

Design notes: status text is a side-effect display channel only — never
enters the transcript, no prompt-cache impact. Lifecycle guarantees from
the stuck-status fix family are preserved (per-thread tracking,
clear-on-finish via existing stop_typing paths). Related: #45109
(closed; same direction via lifecycle states), #59010/#51363 (native
task cards — complementary, larger scope).
2026-07-18 12:28:59 -07:00
George Drury
21d01149c7 test(gateway): cover typing_status_text through load_gateway_config
Loader-level coverage for both YAML routes (top-level platform block via
the shared-key bridge; nested platforms.slack via _merge_platform_map),
per review — from_dict alone didn't exercise the bridge.
2026-07-18 12:28:59 -07:00
George Drury
dc0c778b22 feat(gateway): make the working-state status text configurable
Adds PlatformConfig.typing_status_text for the two platforms that render
text for the working-state line: Slack's assistant.threads.setStatus
status (hardcoded 'is thinking...') and Google Chat's visible marker
message (hardcoded 'Hermes is thinking…'). None keeps each platform's
built-in default; to_dict omits the field when unset so existing configs
serialize unchanged. Plumbing mirrors typing_indicator exactly (typed
field, from_dict extra fallback, shared-key bridge).

Also documents that Slack's status line requires the assistant:write
scope — without it setStatus fails silently and Slack shows its own
generic placeholder, which previously made the behaviour undiagnosable
from config alone.
2026-07-18 12:28:59 -07:00
UnathiCodex
e45d12642d
fix(tui_gateway): prevent resume stalls during submit and teardown (#66573)
* fix(tui_gateway): keep busy submits resume-safe

* chore: map contributor email

* fix(tui_gateway): release resume lock before teardown
2026-07-18 14:51:06 -04:00
teknium1
5988fe6cd5 fix: widen headed-mode gate to config, add browser.headed default, tests, docs
Follow-up to @vishnukool's #24064 salvage:
- cleanup skip now uses _is_headed_mode() (config browser.headed OR
  AGENT_BROWSER_HEADED env) instead of env-var-only, with env fallback
  if browser_tool import fails
- browser.headed added to DEFAULT_CONFIG (default false)
- 14 regression tests: resolution precedence, cleanup skip, --headed
  argv injection (local vs cloud), VM cleanup unaffected
- docs: Headed Mode section in browser.md
2026-07-18 10:07:46 -07:00
kshitijk4poor
af6b41b18b test: add coverage for manual-skill curator guard
Some checks failed
CI / Detect affected areas (push) Has been cancelled
CI / OSV scan (push) Has been cancelled
Deploy Site / deploy-vercel (push) Has been cancelled
Deploy Site / deploy-docs (push) Has been cancelled
auto-fix lint issues & formatting / Generate eslint --fix patch (push) Has been cancelled
Build Skills Index / build-index (push) Has been cancelled
CI / Python tests (push) Has been cancelled
CI / Python lints (push) Has been cancelled
CI / JS & TS checks (push) Has been cancelled
CI / Docs Site (push) Has been cancelled
CI / Deny unrelated histories (push) Has been cancelled
CI / Check contributors (push) Has been cancelled
CI / Check uv.lock (push) Has been cancelled
CI / package-lock.json diff (push) Has been cancelled
CI / Lint Docker scripts (push) Has been cancelled
CI / Build&Test Docker image (push) Has been cancelled
CI / Supply-chain scan (push) Has been cancelled
CI / All required checks pass (push) Has been cancelled
CI / CI timing report (push) Has been cancelled
auto-fix lint issues & formatting / Apply patch (push) Has been cancelled
Build Skills Index / trigger-deploy (push) Has been cancelled
Adds two tests for the _background_review_write_guard manual-skill check:
- refuses delete on a skill with created_by=None (manually authored)
- allows delete on a skill with created_by='agent' (agent-created)
2026-07-18 20:17:22 +05:30
StellarisW
f57157a128 fix(gateway): recover Discord websocket and event-loop stalls
Replace REST-based Discord liveness probe with local WebSocket/heartbeat
state detection. REST success doesn't prove Gateway event delivery — a
half-closed WebSocket can leave Bot.start() alive while REST returns 200.
Now samples ready/open/ACK state and heartbeat latency; consecutive
unhealthy samples emit one retryable fatal code so GatewayRunner rebuilds
the adapter through the existing reconnect path.

Also fixes three lifecycle gaps in the recovery path:
1. asyncio.wait_for() can remain blocked if adapter cleanup swallows
   cancellation — now uses bounded asyncio.wait() with task detachment.
2. Multiplexed secondary-profile adapters had no profile-scoped reconnect
   owner — now uses one runner-owned reconnect slot per profile.
3. An in-flight turn could send its final text through the disconnected
   adapter after a replacement was registered — now resolves the live
   same-profile replacement for unsent final responses only (message IDs
   never migrate, edits/deletes stay on the old transport).

Adds an opt-in Linux/systemd event-loop watchdog (gateway.systemd_watchdog_seconds,
default 0) for the failure mode where the whole asyncio loop stops making
progress and no in-process liveness task can run. stdlib-only sd_notify,
Type=notify/WatchdogSec generation, READY/STOPPING lifecycle.

Co-authored-by: 王鑫 <wx.xw@bytedance.com>
2026-07-18 20:01:55 +05:30
davidb73-hub
4fa67d2014 fix(streaming): block stale stream deltas 2026-07-18 19:55:16 +05:30
HexLab98
e378ed0c91 test(gateway): cover shutdown watchdog and loop heartbeat (#66892)
Pin delay math, disarm-before-fire, fire-with-dump, heartbeat refresh,
and the runner state attrs used by the stop/start wiring.
2026-07-18 19:53:00 +05:30
nanami7777777
7942a77586 fix: normalize multimodal list content in build_assistant_message (#66267)
Second call site (non-streaming / gateway path) now flattens list-type
content with flatten_message_text before the inline <think> regex and the
surrogate sanitizer, matching the interim-text fix from the prior commit.

Adds regression tests (tests/run_agent/test_66267_multimodal_interim.py)
covering:
- build_assistant_message with list content does not raise TypeError
- inline <think> inside list content is extracted + stripped correctly
- _interim_assistant_visible_text is safe for tool messages (list content)
- duplicate_previous_interim dedup guards against tool messages

Verified the tests fail without the fix (TypeError: expected string... got
'list') and pass with it.
2026-07-18 19:39:07 +05:30
Burke Autrey
fdcf352797 fix(review): pass 2 — Bedrock reasoning-floor matches both dashed & dotted keys
_bedrock_reasoning_stale_floor only matched dashed floor-table keys (opus
'claude-opus-4-6'), so sonnet reasoning models keyed with a dotted version in the
shared table ('claude-sonnet-4.5'/'4.6') got no reasoning floor from the dashed
Bedrock inference-profile id — premature stale-abort if the base timeout is set
below 180s. Generate both version-separator forms (digit-dash-digit <-> digit-dot-
digit, via lookbehind/lookahead so only version numbers flip) and try all
candidates; matches the table however each model is keyed, no edit to the shared
table. Verified: opus->240 (unchanged), sonnet-4.5/4.6->180, haiku->None. New
TestBedrockReasoningStaleFloor (8 cases).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 19:38:21 +05:30
Burke Autrey
ff9519d447 fix(review): pass 1 — consecutive supervisor cap + Bedrock reasoning-floor modelId
- _spawn_supervised restart cap was lifetime-cumulative (never reset), so a
  watcher crashing _MAX_SUPERVISED_RESTARTS times over a days-long process was
  permanently abandoned despite the 'consecutive' wording. Make it time-based:
  reset the attempt counter when the task ran healthily (>= _SUPERVISED_HEALTHY_SECS
  = 300s) before crashing, so only rapid repeated crashes accumulate toward the
  ceiling. Reword docstring/log. New regression: healthy-run-then-crash is not
  abandoned.
- _derive_stream_stale_timeout read only 'model', so the reasoning stale-floor
  never applied to Bedrock (payloads key the model as 'modelId', dotted
  us.anthropic.claude-opus-4-6-v1:0 form). Resolve model||modelId and normalize
  the Bedrock dotted/region-prefixed form to match the floor. (Sonnet's dotted
  vs dashed floor-table key is a pre-existing table mismatch, left out of scope.)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 19:38:21 +05:30
Burke Autrey
d920954747 fix(gateway): launchd ThrottleInterval + portable respawn-storm circuit breaker
Re-applied against v0.18.2. Still unconditional KeepAlive <true/> with no
ThrottleInterval, and upstream's new restart_loop_guard only skips session
auto-resume (never throttles the boot), so the launchd respawn storm is
unguarded.

- launchd plist: add ThrottleInterval=30 + ExitTimeOut=25.
- status: record_start_and_check_storm — portable breaker (atomic gateway-starts.log,
  backs off when too many starts land in a window); run_gateway sleeps it before
  asyncio.run. Env HERMES_GATEWAY_MAX_STARTS (<=0 disables) / _START_WINDOW_S.
  Separate file from upstream's restart_loop.json — no collision.
- tests: breaker (threshold/prune/atomic) + plist throttle keys.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 19:38:21 +05:30
Burke Autrey
71f4de3cd8 fix(gateway): supervise long-lived watcher tasks (task-level)
Re-applied against v0.18.2. Upstream now wraps each watcher's INNER loop in
try/except (kept — not re-added), but the 9 long-lived watchers in start() are
still bare asyncio.create_task: no handle, no exception logging, no restart. A
raise in _platform_reconnect_watcher's OUTER while-loop / pre-try region still
dies silently, permanently losing platform reconnection. Add _spawn_supervised
(track + log + bounded-backoff restart; no respawn on clean return to avoid
busy-spin) and route all 9 watchers through it.

- tests: clean-return spawned exactly once; exception-restart bounded at ceiling+1.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 19:38:21 +05:30
Burke Autrey
ff56251555 fix(streaming): Bedrock liveness watchdog (into #58962 breaker) + finite local timeout
Re-applied against v0.18.2. Upstream now covers the OpenAI-path stall watchdog
(cross-turn give-up breaker #58962) and the tool-batch deadline, so those are
dropped. Two gaps remain:

- Bedrock streaming had NO liveness watchdog and was excluded from the #58962
  breaker (it returns before _check_stale_giveup). Add an on_event hook to
  stream_converse_with_callbacks (fires per yielded event = true wire-level
  liveness), drive a stale timer from it, and wire Bedrock INTO the existing
  breaker: entry _check_stale_giveup, _bump_stale_streak on stall, raise to end
  the call (invalidate_runtime_client can't abort the in-flight botocore stream,
  so the streak escalates across turns like the OpenAI path), and reset the
  streak on success.
- local providers still got float('inf') stale timeout (watchdog disabled) — give
  a finite ceiling (HERMES_LOCAL_STREAM_STALE_TIMEOUT, default 900s).
- tests: on_event per-event + swallow; Bedrock stall bumps streak + aborts;
  pre-elevated streak aborts at entry; success resets streak.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 19:38:21 +05:30
Siddharth Balyan
7668d289d6
Terminal-billing client hardening: shared wire types, wire-layer tests, dead RPC removal (#61067)
* refactor(shared): move terminal-billing wire types to @hermes/shared

The billing/subscription wire shapes (plus UsageBarData/UsageModelData,
which they reference) move verbatim from ui-tui/src/gatewayTypes.ts into
apps/shared/src/billing-types.ts so the desktop app can share the same
gateway contract. gatewayTypes.ts re-exports every moved name from the
new @hermes/shared/billing subpath, so no ui-tui consumer changes.

The subpath export keeps DOM-less ui-tui from pulling the barrel (whose
WebSocket helpers need the DOM lib). ui-tui also now declares its
@hermes/shared dependency explicitly instead of relying on workspace
hoisting.

* test(cli): pin nous_billing wire-layer status-to-exception mapping

The HTTP layer's error handling had zero coverage through _request:
only 2xx parsing and request shaping were tested, and the mapping cases
in test_remote_spending_gate_contract.py hit _raise_for_error directly.

Adds 19 tests driving _request via a monkeypatched urlopen: the
401-refresh-retry path (success, terminal plain/session_revoked,
idempotency-key preservation, base re-resolution), 403 variants through
the wire, 429/503 retry-after, non-JSON error bodies, 404/502
fallbacks, and URLError normalization.

Two behaviors are pinned as findings rather than fixed: a JSON-body
retryAfter hint is ignored unless the Retry-After header is present,
and a bare socket.timeout propagates uncaught (real urllib wraps
timeouts in URLError before this layer).

* fix(cli): normalize read-phase timeouts to the typed billing error

urlopen wraps connect-phase timeouts in URLError (already mapped to
network_error), but a timeout during resp.read() raises a bare
TimeoutError that escaped the typed-BillingError contract and reached
callers as an unhandled exception. Catch it narrowly and normalize.
The boundary test now asserts normalization instead of documenting the
leak.

* fix(shared): stop typing mutation success payloads as error payloads

BillingMutationResponse.payload was declared BillingErrorPayload, but on
ok:true the gateway passes through the raw NAS success body (rail,
changeType, cancelAtPeriodEnd, ...). The TUI never reads it so nothing
broke, but the shared contract now feeds the desktop app too — widen the
field deliberately and document both shapes.

* feat(shared): typed billing refusal and charge-failure unions

- BillingRefusalCode covers every code the gateway serializes today, with a
  (string & {}) arm so unknown future codes (the NAS W3 card-health family)
  stay assignable — consumers keep their unknown-code fallback.
- ChargeFailureReason models the four NAS terminal reasons plus the raw
  subscription_payment_intent_requires_action code NAS leaks pre-#711.
- billing.state now carries the server-derived can_change_plan the gateway
  emits; capability comments updated (canChangePlan is capability-based, not
  an OWNER/ADMIN role gate).

* feat(shared): closed Known* halves for the refusal and charge-failure unions

- KnownBillingRefusalCode / KnownChargeFailureReason are closed literal sets,
  so classification tables, copy maps and tests can be Record-exhaustive and
  break at compile time when a code is added but not mapped. The wire types
  keep the (string & {}) open arm for unknown future codes.
- Add network_error (client-originated transport code the gateway already
  serializes) to the known set.
- Export the union types from the root barrel alongside the other billing
  names.

* feat(shared): canonical billing refusal policy and charge-settlement driver

- billing-policy.ts: one exhaustive Record<KnownBillingRefusalCode,
  BillingRefusalPolicy> classifying every known code (recovery kind,
  mid-poll ambiguity, idempotency-key reuse) with a documented unknown-code
  fallback. Surfaces keep their own copy; the behavior classification now
  has a single home that breaks the build when a new code goes unmapped.
- charge-settlement.ts: the settlement poll state machine (2s cadence,
  5-minute cap, bounded retry-after backoff, ambiguous-on-revocation) as a
  pure dependency-injected driver returning a discriminated outcome.
- The TUI's pollCharge becomes a thin renderer over the shared driver —
  byte-identical output, and the desktop poller can now share the same
  machine instead of a drifting copy.
2026-07-18 07:05:58 -07:00
kshitijk4poor
8f657b8f74 test: add happy-path + no-markers coverage for autostash recovery
Port stronger test coverage from #52305 (avrum):
- Add test_install_sh_repository_stage_clean_apply_drops_stash: verifies
  non-conflicting restore still applies changes and drops the stash (no
  regression of the happy path).
- Add no-conflict-markers assertion to _assert_conflict_was_recovered:
  ensures <<<<<<< / >>>>>>> markers are never left in tracked source after
  recovery (they would crash the backend on import).
2026-07-18 19:18:03 +05:30
konsisumer
de90f5831b fix(install): continue after autostash restore conflicts 2026-07-18 19:18:03 +05:30
Bruce-anle
56db7a5e6c test(tui): keep watchdog checks behavior-focused 2026-07-18 04:15:13 -07:00
Bruce-anle
68f7f15207 fix(tui): use direct parent identity in slash worker
Remove process creation time and pid_exists from the slash worker parent-death predicate. The worker remains attached while its original PPID matches and keeps the existing in-flight grace behavior.\n\nRefs #62505
2026-07-18 04:15:13 -07:00
Bruce-anle
3d031bdb29 fix(mcp): use direct parent identity in stdio watchdog
Use the direct POSIX parent relationship instead of process creation time and pid_exists checks. Remove the dead create-time argument chain while preserving process-group cleanup and signal forwarding.\n\nRefs #62505
2026-07-18 04:15:13 -07:00
Teknium
4c96172d9b test: stub discover_local_cdp_url in CLI connect context-note test
The dual-stack discovery change made the default-local /browser connect
path call discover_local_cdp_url instead of is_browser_debug_ready, so
the old is_browser_debug_ready patch no longer short-circuited the
probe. On the CI runner nothing listens on 9222, so the test fell
through to a REAL chromium launch (which dies headless:
'The platform failed to initialize') and no context note was queued.
Patch the new discovery helper at the mixin's import site instead.
2026-07-18 02:49:28 -07:00