Commit graph

14658 commits

Author SHA1 Message Date
Taylor H. Perkins
8a76de962f fix(secrets): make 1Password bootstrap token reliable outside systemd
The 1Password secret source resolves op:// references using
OP_SERVICE_ACCOUNT_TOKEN read from os.environ. Under systemd the gateway
gets that token via EnvironmentFile, but cron jobs, subprocesses, CLI
runs, macOS launchd, and Docker containers spawn fresh interpreters with
no inherited shell state — so they silently failed to resolve any
reference and fell back to empty strings.

Two patches close the gap, matching Bitwarden's reliability guarantees:

1. env_loader: auto-load ~/.hermes/.op.env after .env so the gitignored
   bootstrap token is available everywhere. override=False plus an
   explicit guard ensure it never clobbers a token already in env (e.g.
   from a systemd EnvironmentFile, which keeps precedence).

2. credential_pool: _get_env_prefer_dotenv() now prefers the resolved
   value in os.environ when .env still holds a raw op:// reference,
   instead of handing a URL to provider auth. Non-op:// values keep the
   existing .env-takes-precedence behaviour.

Also gitignore .op.env, document the three bootstrap-token options, and
add tests covering auto-load, no-override, and the resolved-vs-raw
precedence (plus regression guards).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 04:58:07 -07:00
Taylor H. Perkins
2dc4286e00 fix(secrets): remove unused masked_secret_prompt import from onepassword CLI
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-06 04:58:07 -07:00
Taylor H. Perkins
5c4c0e9d9b feat(secrets): add 1Password (op://) secret source
Resolve provider credentials from 1Password op://vault/item/field references
at startup via the official `op` CLI, alongside the existing Bitwarden source.
Users map env-var names to references in secrets.onepassword.env; after .env
loads, each is resolved with `op read` and injected into os.environ. Auth is
whatever `op` already uses (service-account token or desktop/interactive
session) — Hermes never authenticates or installs `op` itself.

Startup-safe and fail-open: a missing binary, expired auth, a bad reference,
or an empty value each warn and fall back to existing credentials, never
blocking startup. Successful, complete pulls are cached in-process and on disk
(<hermes_home>/cache/op_cache.json, 0600) via the shared DiskCache; only
secret values are stored, never the token (auth is fingerprinted into the
key). Adds `hermes secrets onepassword {setup,status,set,remove,sync,disable}`
(aliases op/1password), config defaults, the cli-config example, docs, and
hermetic tests.

Hardening applied across both backends in env_loader: each source runs in its
own guard, config sections are coerced to dict, and cache_ttl_seconds is
coerced defensively — so a malformed secrets: section can't abort startup.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 04:58:07 -07:00
Taylor H. Perkins
db495b0fba refactor(secrets): extract shared cache/result substrate for secret sources
Pull the disk-cache + FetchResult substrate out of bitwarden.py into a new
agent/secret_sources/_cache.py: FetchResult, CachedFetch, is_valid_env_name,
and a generic DiskCache (atomic mkstemp -> chmod 0600 -> os.replace write,
0700 cache dir, TTL-gated read AND write). Bitwarden now consumes it via a
module-level DiskCache instance and thin wrappers, so the security-sensitive
atomic-write/0600/TTL logic lives in exactly one place instead of being
copy-pasted per backend (and drifting). Behavior is unchanged — the full
Bitwarden suite passes untouched.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 04:58:07 -07:00
teknium1
2d16ec7fb7 feat(secrets): pluggable SecretSource interface + multi-source orchestrator
Introduces a first-class secret-source contract so password managers
(Bitwarden today, 1Password next, third-party vaults as plugins) plug
into one orchestrated startup path instead of each hardcoding into
env_loader.

- agent/secret_sources/base.py: SecretSource ABC (fetch-only contract:
  never raises, never prompts, sync with orchestrator-enforced timeout),
  shared ErrorKind taxonomy, FetchResult, run_secret_cli() minimal-env
  subprocess helper, API versioning for plugin compatibility.
- agent/secret_sources/registry.py: registration gating (name/scheme
  uniqueness, api_version, shape), apply_all() orchestrator owning
  precedence (mapped-beats-bulk, first-claim-wins, override_existing
  never crosses sources, protected bootstrap tokens), conflict warnings,
  per-var provenance, per-source wall-clock timeout.
- Bitwarden converted to a registered BitwardenSource (bulk shape);
  behavior unchanged, apply_bitwarden_secrets kept as legacy shim.
- env_loader._apply_external_secret_sources now drives the orchestrator;
  provenance labels resolve through registry (e.g. '(from 1Password)').
- PluginContext.register_secret_source() for external backends.
- secrets.sources optional ordering key in DEFAULT_CONFIG + example.
- tests/secret_sources/: 47 new tests incl. reusable conformance kit
  (SecretSourceConformance) that plugin authors run against their source.
2026-07-06 04:58:07 -07:00
Teknium
d345b9fbfe
refactor(cron): derive one-shot run-claim TTL from HERMES_CRON_TIMEOUT (#59567)
Follow-up to #59524. The one-shot running-claim stale-recovery window was a
fixed 30-min constant. Derive it from the cron inactivity timeout instead
(HERMES_CRON_TIMEOUT, the same limit the scheduler enforces per run) so the
safety valve tracks how long a run may actually go quiet:

- unset/invalid -> default 600s inactivity -> TTL 1800s (unchanged behaviour)
- positive N    -> max(N * 3 headroom, 1800s floor)
- 0 (unlimited) -> no finite bound -> fall back to the 1800s constant

The fixed constant is kept as the floor + unlimited-case fallback. Resolved
once per due-scan. HERMES_CRON_TIMEOUT is a pre-existing internal env var
(already read by cron/scheduler.py); no new config surface.

E2E: with HERMES_CRON_TIMEOUT=1200 the claim now survives to 60min where the
old fixed 1800s constant wrongly expired it at 30min mid-run. +1 derivation
test; 640/640 cron tests pass.
2026-07-06 04:57:09 -07:00
Teknium
27f74b26c5
fix(web): correct 'disabled plugin' diagnosis for web backends (#59573)
When a bundled web provider (firecrawl, tavily, exa, ...) is listed in
plugins.disabled, its provider never registers and the web_search/
web_extract dispatchers emitted the misleading "No web extract provider
configured. Set web.extract_backend to ..." — even though the backend was
configured correctly. The real fix is to re-enable the plugin.

- web_tools.py + web_search_registry.py: when the configured backend names
  a disabled bundled web plugin, both dispatchers now point the user at the
  actual cause (re-enable the plugin) instead of a wrong config hint.
- plugins_cmd.py cmd_enable: enabling by canonical key now also clears the
  manifest-name alias (web-firecrawl) from plugins.disabled, so the
  suggested command actually re-enables the plugin ('explicit disable wins'
  matches on the name too).
- plugins_cmd.py cmd_toggle / _run_composite_ui / _run_composite_fallback:
  the interactive 'hermes plugins' menu now persists the canonical key
  (web/firecrawl), never the bare manifest name — the drift that put the
  offending entry in plugins.disabled in the first place.

Follow-up to #59518 (which fixed web credential resolution, a different
cause). Fixes the disabled-plugin symptom reported after that PR.
2026-07-06 04:38:17 -07:00
Teknium
d84a2af3d4
docs: correct Python support to 3.11-3.13 (#59572)
requires-python is >=3.11,<3.14, so '3.11+' was misleading (implied
3.14+ works). Fixed in CONTRIBUTING.md and the docs-site mirror.
2026-07-06 04:38:07 -07:00
Hermes Agent
1fcf6e58b6 chore: map waseemshahwan in AUTHOR_MAP for #56841 salvage 2026-07-06 03:53:52 -07:00
Waseem Shahwan
777cfa81f3 fix(gateway): drop interrupt sentinel before chat delivery (#7921) 2026-07-06 03:53:52 -07:00
Hermes Agent
09466971ff chore: map AIalliAI id-form noreply email in AUTHOR_MAP for #44222 salvage 2026-07-06 03:42:14 -07:00
Hermes Agent
7487afbd99 test(gateway): update stale expectation — #31884 surfaces retry hint for uninterrupted zero-call drops
The PR predates #31884, which changed the non-interrupted api_calls==0
empty path from silence to a retry hint. Flip the contributed test to
assert the current (correct) behavior.
2026-07-06 03:42:14 -07:00
AIalliAI
a14caf7759 fix(gateway): stop post-/stop stale interrupt from silently swallowing the next message
A /stop sets _interrupt_requested on the session's cached agent, but the
flag is only cleared by the turn finalizer.  When the stopped run is hung
or still draining, the flag survives the forced lock release and the
session's NEXT user message is killed at the top of the tool loop
(conversation_loop.py interrupt check): the run completes with
interrupted=True, api_calls=0 and an empty response, which
_normalize_empty_agent_response passed through as pure silence — the
user's message was swallowed with no trace except a
'response ready: ... api_calls=0 response=0 chars' log line.

Two-layer fix:

- _interrupt_and_clear_session now evicts the cached agent whenever it
  releases the running state.  The next message rebuilds the agent from
  session history (mirroring the /new and /model paths), while the old
  agent object keeps its interrupt flag so a hung drain still dies when
  it unblocks.  This intentionally does NOT clear the flag in place:
  turn_context deliberately preserves a pending interrupt across turn
  start (it carries interrupt-message delivery), and clearing it could
  revive a hung run the user just stopped.

- _normalize_empty_agent_response distinguishes a drain from a swallowed
  turn: an interrupted run that did work (api_calls > 0) stays silent as
  before (deliberate stop/steer; queued messages are delivered by the
  recursive drain inside _run_agent), but an interrupted run with ZERO
  api_calls never processed the user's message at all and now surfaces a
  'send it again' notice instead of nothing.

Same silent-delivery class as a1f76ba7e (#29346), which covered the
extract-stripped case; regression tests added next to that coverage.

Fixes #44212
2026-07-06 03:42:14 -07:00
teknium1
83e6a487eb test(tui_gateway): isolate verification.status not_applicable test from stray tmp markers
test_verification_status_outside_workspace_is_not_applicable passed tmp_path as
the cwd and asserted status == not_applicable, relying on tmp_path having no
project-marker ancestor. _marker_root() walks up to ~6 levels, so a stray marker
in a shared tmp-root ancestor (e.g. a /tmp/package.json left by another tool)
made project_facts_for() resolve tmp_path as a workspace and flip the status to
unverified. Green in clean CI, red on any dev box with a polluted /tmp.

Force the no-facts precondition by monkeypatching project_facts_for -> None so
the test deterministically exercises the not_applicable branch regardless of
ambient filesystem state. Test-only; no production change.
2026-07-06 03:34:16 -07:00
teknium1
4df2536f21 chore: map Ahmett101 noreply email in AUTHOR_MAP for #59455 2026-07-06 03:28:30 -07:00
Ahmett101
2e828d4b75 fix(background-review): guard summarize against list-shaped tool responses (#59437)
`summarize_background_review_actions` was structured on the assumption
that every parsed tool response is a fully-typed dict-of-fields. In
practice the memory/skill tools — and their wrappers over Mem0 OSS and
the skill_manage MCP server — sometimes serialize `_change` as a list
or scalar, and clamp `operations` to a single string when the field
came in via a partial JSON bridge.

The original code did the equivalent of:
    change = data.get("_change", {})
    change.get("description", "")

so when `_change` was a list the inner .get crashed with
`AttributeError: 'list' object has no attribute 'get'`, every ~10
turns the user saw the entire background review collapse.

Three defensive guards in summarize_background_review_actions:

- `call_details.get(tcid, {})` → `call_details.get(tcid) or {}` plus
  `isinstance(detail, dict)` coercion. Catches stale scalar/None
  values when a fork inherits partial state from a stale tool_call_id.
- `operations = detail.get("operations") or []` → `isinstance(ops_raw, list)`
  coerce, then per-entry isinstance check before `.get()`. Skips
  non-dict items without raising; an entire surrounding review no
  longer goes down because one entry was malformed.
- `change = data.get("_change", {})` → `isinstance(change_raw, dict)`
  coerce. The originally-reported crash class for skill_manage with
  list-shaped _change now falls through to the generic summary path.

And the caller in `_run_review_in_thread` is wrapped in a try/except
that maps any residual summarize exception to `actions = []` and
emits a 'partial results' warning, so even an entirely unanticipated
shape won't take down the outer review — the user only sees
'Background memory/skill review failed' instead of the prior hard
crash that lost every successful action the fork had completed.

Tests: tests/test_background_review_list_shapes.py — standalone
pytest-free runner, 7/7 PASS:
  a_change_as_list_does_not_crash       (originally-reported shape)
  a_change_as_int_does_not_crash        (scalar fallback)
  b_operations_as_string_treated_as_empty
  b_operations_as_none_treated_as_empty
  c_operations_contains_non_dict_entries (verbose-mode per-entry filter)
  d_detail_non_dict_replaced_with_empty
  e_call_defends_via_try_except         (structural anchor)

Refs NousResearch/hermes-agent#59437
2026-07-06 03:28:30 -07:00
herbalizer404
4a80e27bba fix telegram explicit private thread routing 2026-07-06 03:18:33 -07:00
giggling-ginger
e53e8a782c fix(mcp): sanitize server names for auth env keys
Server names with non-env-safe characters (dots, slashes, spaces)
produced invalid env-var keys like MCP_MY.SERVER_API_KEY or
MCP_GITHUB/MCP_API_KEY, breaking .env writes and ${VAR} header
substitution. _env_key_for_server now replaces any character outside
[A-Za-z0-9_] with an underscore.

Co-authored-by: Hermes Agent <agent@nousresearch.com>
2026-07-06 03:18:07 -07:00
izumi0uu
ef79ad014d fix(dashboard): accept HA ingress prefix paths
Allow mainstream reverse-proxy path mounts to keep their X-Forwarded-Prefix when Home Assistant Supervisor ingress already consumes nearly the old 64-character budget. Keep validation bounded and keep rejected non-empty prefixes diagnosable with a deduplicated warning.

Constraint: HA Supervisor ingress prefixes are 63 chars before add-on subpaths, so the old 64-char cap dropped valid dashboard deployments.

Rejected: remove the length cap entirely | a bounded header budget is still a conservative validation guard.

Confidence: high

Scope-risk: narrow

Directive: Keep prefix validation centralized in hermes_cli.dashboard_auth.prefix so auth routes, cookies, and SPA asset rewriting agree.

Tested: python probe for the 73-char HA ingress prefix; scripts/run_tests.sh tests/hermes_cli/test_dashboard_auth_prefix.py -q; .venv/bin/python -m pytest tests/hermes_cli/test_web_server.py -k 'spa_assets_are_read_as_utf8' -q; python -m ruff check hermes_cli/dashboard_auth/prefix.py tests/hermes_cli/test_dashboard_auth_prefix.py; git diff --check

Not-tested: full test suite
2026-07-06 03:18:02 -07:00
Teknium
3b5c645433 fix(cron): durable run-claim for one-shots instead of a fixed +60s advance
The +60s next_run_at advance only delayed a duplicate one-shot dispatch by
one tick — a job that outlives the 60s tick interval (the reported 2.5-min
research prompt) still re-fired on the next tick after the window expired,
so the concurrent gateway+desktop double-delivery persisted.

Replace it with a durable run_claim (at+by, mirroring fire_claim) stamped
on the one-shot under the same jobs lock get_due_jobs holds, and checked at
the top of the due-scan: a fresh claim held by an in-flight run makes every
other scheduler process skip the job for its ENTIRE run, not one tick.
mark_job_run() clears the claim on completion; a ONESHOT_RUN_CLAIM_TTL
(30 min) safety valve re-dispatches a claim left by a tick that died mid-run
so a one-shot is never wedged.

E2E: long-running one-shot no longer double-fires at +28/+61/+120/+179s;
completion clears the claim + disables the job; crash recovery re-arms past
the TTL. +3 regression tests.
2026-07-06 03:17:21 -07:00
teknium1
8f849ea365 chore: credit isheng-eqi for #59446 in AUTHOR_MAP 2026-07-06 03:17:21 -07:00
isheng
06cc983b86 fix(cron): prevent double-execution of one-shot jobs across concurrent schedulers
When two scheduler processes (gateway + desktop) run concurrently,
both could pick up the same one-shot job from get_due_jobs() because
its next_run_at was not advanced before execution started — only
recurring jobs were advanced (L3446).  This caused duplicate deliveries
and wasted token spend (#59229).

Now _get_due_jobs_locked advances a one-shot's next_run_at by 60s
before returning it as due, persisted immediately under the same
file lock.  mark_job_run re-anchors next_run_at on completion, so a
tick death between advance and execution only delays the job by one
tick window — it is never lost.

Closes #59229
2026-07-06 03:17:21 -07:00
mbac
f3af7930c2 fix(tui_gateway): honor launch profile terminal.cwd for dashboard chat
Dashboard /chat for the default (launch) profile attaches to the
dashboard process's in-memory TUI gateway. The Node PTY child receives a
bridged TERMINAL_CWD env var, but the in-memory gateway process does not,
so cwd resolution fell through to os.getcwd() (wherever `hermes
dashboard` was launched) and ignored the configured terminal.cwd.

Read the launch profile's config.yaml directly in the in-memory cwd
resolution: a configured terminal.cwd now wins over a stale process env
and the launch directory. Widened to the resume/fallback session-cwd
sites (not just _completion_cwd) via a shared _default_session_cwd()
helper so fresh AND resumed sessions honor the config.

Co-authored-by: ygd58 <buraysandro9@gmail.com>
2026-07-06 03:16:28 -07:00
Tranquil-Flow
83f14b2f21 fix(gateway): relax session_key traversal guard to allow interior '/' (#59322)
The CWE-22 traversal guard in SessionEntry.from_dict rejects any
interior '/' in session_key, but session_key is a logical routing
key (never used as a filesystem path) and Google Chat resource names
legitimately contain '/' (spaces/<id>, spaces/<id>/threads/<id>).

All Google Chat sessions were silently dropped on gateway start.

Split the validation: session_id keeps the strict _is_path_unsafe
guard (it's the value used as a filename); session_key now uses a
relaxed _is_session_key_unsafe helper that only blocks genuine
traversal vectors (parent-dir '..', leading '/', leading '\', leading
Windows drive-letter prefix) and allows interior '/'.
2026-07-06 02:47:40 -07:00
Tranquil-Flow
9d848cc60a fix(cli): pass custom_providers to resolve_display_context_length (#59314)
The CLI model-switch display (both picker and direct-switch paths)
omitted the custom_providers keyword when calling
resolve_display_context_length(). The function already supports it
(and the gateway correctly passes it), but the CLI call sites relied
on the fallthrough to probe-down default (256K) even when a
custom_providers entry specified a per-model context_length.

Fix: pass agent._custom_providers at both resolve_display_context_length
call sites in HermesCLI._apply_model_switch_result(), matching the
pattern already used for config_context_length.
2026-07-06 02:46:24 -07:00
pierrenode
b5158442f0 fix(skills): apply disabled-skill gate to CLI/TUI preloaded skills
build_preloaded_skills_prompt() (hermes -s <skill>, and tui_gateway's
HERMES_TUI_SKILLS deployment env var) loads skills via _load_skill_payload()
with a raw identifier, bypassing get_skill_commands()' scan-time disabled
filter entirely. Result: a skill an operator disabled via skills.disabled
still gets force-loaded and injected into every session — including every
session on a shared tui_gateway deployment where the operator set
HERMES_TUI_SKILLS.

The bundle-invocation path (#59156) already re-checks get_disabled_skill_names()
for exactly this reason; preloaded-skill loading was the other _load_skill_payload
call site still missing it.

Fix: check each resolved skill's name (and raw identifier) against
get_disabled_skill_names() before injecting it. A disabled skill is now
reported the same way an unknown one already is (skipped, listed in the
returned missing_identifiers) — no return-shape or caller changes needed.
No behavior change when no skill is disabled.
2026-07-06 02:43:37 -07:00
Hermes Agent
1a2885535b fix(web): widen config-aware env resolution to exa/parallel/tavily/brave-free providers
Same bug class as #40190: these providers read credentials via bare
os.getenv(), so keys stored in ~/.hermes/.env (hermes config layer)
were invisible in execution paths that never exported them into the
process environment. Add get_provider_env() on the WebSearchProvider
module as the shared config-aware lookup (get_env_value with os.getenv
fallback) and route all credential reads through it. SearXNG already
did this (#34290); Firecrawl fixed in the preceding cherry-picked
commit by @liuhao1024.
2026-07-06 02:42:24 -07:00
liuhao1024
026ab4737d fix(web): use get_env_value for Firecrawl config resolution
The Firecrawl provider used os.getenv() to read FIRECRAWL_API_KEY and
FIRECRAWL_API_URL, which only checks the process environment.  When
values are supplied through Hermes's ~/.hermes/.env config mechanism
(via hermes_cli.config.get_env_value), they are not guaranteed to be
present in os.environ for every gateway/tool execution path.

Switch to get_env_value() which checks both os.environ and the .env
file, matching the pattern used by other providers (nous_subscription,
setup, discord adapter).

Fixes #40190
2026-07-06 02:42:24 -07:00
teknium1
3ba5ba89c2 test(cron): cover cron_list/status/tick/create CLI helpers
Salvaged from #40430; re-verified on main, tightened, tested.

Co-authored-by: xuezhaolan <xuezhaolan@users.noreply.github.com>
2026-07-06 02:21:32 -07:00
teknium1
7e7e3af5b0 chore: map allenliang2022 in AUTHOR_MAP for #56932 test fold-in 2026-07-06 01:56:09 -07:00
allenliang2022
f6d4c1aa60 test(error-classifier): 408 boundary coverage — Copilot user_request_timeout shape, never auto-compress, falsification guard
Folded from PR #56932 (@allenliang2022) — same fix as #56909, submitted 45min later; the test coverage was the richer half.
2026-07-06 01:56:09 -07:00
Frowtek
8457752a3b fix(error-classifier): retry HTTP 408 as timeout instead of aborting as format_error
_classify_by_status() routes every other transient HTTP status to a retryable
reason (500/502 -> server_error, 503/529 -> overloaded, 429 -> rate_limit,
413 -> payload_too_large), but 408 Request Timeout fell through to the generic
`400 <= status < 500` branch and was classified as a non-retryable
format_error -- the same bucket as a 400 Bad Request.

A 408 is a transient timing failure the server itself flags as safe to retry
(RFC 9110 15.5.9), not a malformed request, so the retry loop aborted the turn
when a simple retry would recover. Common trigger: a reverse proxy in front of
a self-hosted backend (llama.cpp / Ollama / vLLM) returns 408 when a long
generation outruns the proxy's request-read window.

Route 408 to the existing FailoverReason.timeout (rebuild client + retry).
Add a regression test plus a boundary test asserting 400 stays non-retryable.
2026-07-06 01:56:09 -07:00
Frowtek
a88e0fd2ab fix(file-sync): re-deliver deferred Ctrl+C via raise_signal, not os.kill (Windows hard-kill)
_sync_back_once defers a SIGINT that lands mid-sync, then re-delivers it once the
sync completes so the user's Ctrl+C isn't lost. It did so with
os.kill(os.getpid(), signal.SIGINT). That is not graceful on Windows: os.kill
only treats CTRL_C_EVENT(0)/CTRL_BREAK_EVENT(1) as console events; any other
value (SIGINT == 2) routes to TerminateProcess(sig), so a Ctrl+C during a
remote-backend (ssh/daytona/modal) sync-back hard-kills the whole CLI session
(exit code 2) on Windows instead of raising KeyboardInterrupt.

Use signal.raise_signal(signal.SIGINT) (3.8+), which invokes the restored
handler through C raise() on every platform. Verified on Windows: raise_signal
runs the handler (graceful) while os.kill(getpid, SIGINT) TerminateProcess-es
the process. Adds a cross-platform regression test that runs on Windows too (it
stubs the locked sync body, so unlike test_file_sync_back.py it needs no fcntl).
2026-07-06 01:55:58 -07:00
kshitijk4poor
c67aab763d chore: map isheng-eqi in AUTHOR_MAP for #59428 salvage
check-attribution CI fails on unmapped bare (non-noreply) contributor
emails. isheng-eqi's commit email (ishengeqi@163.com) has no + so it does
not auto-resolve — add the explicit mapping.
2026-07-06 13:47:18 +05:30
isheng
8def4ccb4f fix(cron): reject past one-shot timestamps in update_job fallback + resume_job (#59395)
Completes the #59395 bug-class fix. create_job and update_job's
schedule-change path already reject past one-shots (via #59410/#59438);
this closes the two remaining doors that stored next_run_at=None for a
'once' schedule and re-created the silent ghost job:

  1. update_job fallback-recompute (the safety-net that re-derives
     next_run_at when it's missing on an enabled, non-paused job)
  2. resume_job (resuming a paused one-shot whose time has already passed
     — empirically confirmed to create a scheduled job that never fires)

The redundant update_job schedule-change hunk from the original PR was
dropped (already on main via #59438). Adds resume-reject + update-reject/
accept regression tests.

Salvaged from #59428 by isheng-eqi.
2026-07-06 13:47:18 +05:30
Teknium
0800af0b8a
perf(cli): TTFT round 2 — live reasoning by default, partial-line streaming, prompt-build cache, stale budget-warning docs (#59389)
Follow-up to #59332 targeting the remaining PERCEIVED first-token latency
(the wire streaming was already per-token; these fix what the user sees):

1. display.show_reasoning default ON. On thinking models the reasoning
   phase streams for tens of seconds; with the display off users stare
   at a spinner the whole time and read it as a stall. Flipped in
   DEFAULT_CONFIG, load_cli_config defaults, tui_gateway raw-YAML
   fallbacks, and the hermes setup status line (all four read sites kept
   in sync). Gateway per-platform defaults intentionally stay off —
   messaging chats shouldn't fill with thinking text. /reasoning hide
   still turns it off and persists.

2. Response box force-flushes long partial lines. _emit_stream_text only
   painted on newline, so a response opening with a long paragraph
   stayed invisible until the first \n — seconds of blank box. Now
   partial lines wrap at terminal width and paint as tokens arrive
   (mirrors the reasoning box's 80-char force-flush that existed since
   day one). Table blocks remain batch-aligned; no content loss at wrap
   boundaries (regression tests added).

3. hermes_time timezone resolution uses read_raw_config (mtime-cached +
   libyaml C loader) instead of a raw yaml.safe_load of config.yaml
   (~110-140ms measured) inside the FIRST system prompt build. First
   build drops 320ms -> ~155ms on a 200-skill install.

4. Stale docs: configuration.md (en+zh) still documented the 70%/90%
   [BUDGET WARNING] tool-result injections. Those were removed in April
   2026 (c8aff7463) precisely because they hurt task completion; current
   behavior is exhaustion-message + one grace call, no mid-loop
   injection, no cache impact. Docs now describe reality.

Verified: token-count compression decisions already use API-reported
last_prompt_tokens (rough estimators are preflight-only and cost ~1.7ms
even on 1.7MB histories — not worth touching).
2026-07-06 00:16:38 -07:00
kshitijk4poor
4976d3c38d fix(cron): guard update_job past-one-shot + enrich rejection message (#59395)
Widen the #59395 fix to the sibling site: update_job's schedule-change path
(cron/jobs.py) had the SAME unguarded compute_next_run -> next_run_at pattern,
so updating a job's schedule to a one-shot >ONESHOT_GRACE_SECONDS in the past
would re-create the ghost job (next_run_at=None, state='scheduled', never fires)
that create_job now rejects. Apply the identical guard on update (raise before
any disk write, so the original job is left intact), with regression tests for
the reject + future-accept cases.

Also surface ONESHOT_GRACE_SECONDS in the raised ValueError (not just the
warning log) so a caller knows how far in the past is too far. Message from the
competing PR #59410 by @isheng-eqi.

Co-authored-by: isheng-eqi <265044697+isheng-eqi@users.noreply.github.com>
2026-07-06 12:11:41 +05:30
Flownium
848089ac93 fix: reject stale one-shot cron jobs 2026-07-06 12:11:41 +05:30
Teknium
845a2d8152
feat(sessions): any prune filter matches all ages; preview shows age span (#59415)
Bare 'hermes sessions prune' keeps the historical 90-day default, but any
filter — now including --source — suppresses the implicit cutoff, so
'prune --source cron' targets ALL cron sessions instead of silently only
those older than 90 days (the surprise a user hit live: 'No sessions
match ... source cron' despite plenty of recent cron runs).

- CLI preview + confirmation now show the match count plus the oldest
  and newest matching session start times before deleting.
- Dashboard /api/sessions/prune mirrors the semantics: attribute filters
  without an explicit older_than_days match all ages (model_fields_set
  distinguishes an explicit 90 from the Pydantic default); dry_run
  responses gain oldest_started_at/newest_started_at.
- Docs + argparse help updated; tests for both surfaces.
2026-07-05 23:01:10 -07:00
Ben
590a19332e fix(skills): don't request Brotli for the centralized skills index
The Skills Hub 'Browse Hub' landing page and index-backed search render
empty on fresh deployments (e.g. Fly.io VPS agents) with no stale cache.

Root cause: the centralized index at /docs/api/skills-index.json is a
large body (~34MB, tens of MB compressed) served with Content-Encoding:
br. httpx's streaming Brotli decoder — backed by brotlicffi 1.2.0.1,
which is pinned so aiohttp can decode Discord attachments — trips over
its own output_buffer_limit on a payload this size and raises:

  DecodingError("brotli: decoder process called with data when
  'can_accept_more_data()' is False")

_load_hermes_index() catches that (DecodingError is an httpx.HTTPError
subclass) and silently falls back to the on-disk cache. On a fresh box
that cache never existed, so HermesIndexSource.is_available is False,
the index contributes 0 skills, and the hub landing page — which is
built solely from an empty-query index search — is blank. Existing
installs only appear to work because they serve a (possibly weeks-)stale
cached index instead.

Fix: request 'gzip, deflate' on the index fetch so httpx never
negotiates the broken Brotli path, and retry once with 'identity' if a
DecodingError still occurs (defends against a proxy that ignores the
header). Falls through to the stale cache only when both attempts fail.

Verified on a live staging VPS agent: index_available flips False->True
and the featured landing list repopulates from 0 to 12.

Also un-freezes already-deployed images: skills added after an image was
built (e.g. the 'unbroker' optional skill) become reachable again via
the index, which is the whole point of the centralized catalog.
2026-07-05 22:21:05 -07:00
davidgut1982
d3602e6308 fix(gateway): read multiplex_profiles from nested gateway section
load_gateway_config() only surfaced the top-level `multiplex_profiles`
key into gw_data before calling GatewayConfig.from_dict(). A config.yaml
that pinned the flag under the nested `gateway:` section -- the form
written by `hermes config set gateway.multiplex_profiles true` -- was
silently ignored, so the gateway loaded with multiplex_profiles=False.

from_dict() already honors the nested fallback, but load_gateway_config()
builds gw_data from top-level keys first, so the nested value never
reached it.

Read gateway.multiplex_profiles into gw_data when the top-level key is
absent, mirroring the existing nested fallback for max_concurrent_sessions.

Adds a load_gateway_config() regression test that writes a config.yaml
with `gateway.multiplex_profiles: true` and asserts the loaded config has
multiplex_profiles=True (fails without the fix).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 22:11:03 -07:00
Teknium
040a5e30dd
feat(sessions): full filter surface for prune + bulk archive subcommand (#59327)
* feat(sessions): full filter surface for prune + new bulk archive subcommand

hermes sessions prune previously only supported --older-than N (integer
days) and --source — no way to target a window like 'the last 5 hours'
(e.g. a batch of CI smoke-test sessions), and no non-destructive option.

- SessionDB.prune_sessions gains keyword filters that AND together:
  started_before/started_after epoch bounds, title_like, end_reason,
  cwd_prefix, min/max_messages, archived tri-state. Default call is
  byte-for-byte compatible (90-day cutoff, ended-only, source).
- New SessionDB.list_prune_candidates (backs --dry-run + confirmation
  previews) and SessionDB.archive_sessions (bulk soft-hide via the
  existing set_session_archived lineage-aware path; nothing deleted).
- CLI: prune gains --newer-than/--before/--after (durations like 5h/2d/1w,
  bare days, or ISO timestamps), --title, --end-reason, --cwd,
  --min/--max-messages, --include-archived, --dry-run. New
  'hermes sessions archive' takes the same filters, requires at least one,
  and is idempotent. Both show a preview before confirming.
- Dashboard /api/sessions/prune accepts the same filters + dry_run.
- Docs: sessions.md + cli-commands.md updated.

Filter parsing lives in hermes_cli/session_filters.py with unit tests;
DB filters covered in tests/test_hermes_state.py.

* feat(sessions): prune/archive filters for model, provider, user, chat, branch, tokens, cost, tool calls

Extends the prune/archive filter surface to everything identifiable in
the sessions table:

- --model (substring on model slug), --provider (exact on
  billing_provider, case-insensitive), --user, --chat-id, --chat-type
  (exact), --branch (substring on git_branch), --min/--max-tokens
  (input+output), --min/--max-cost (USD, actual_cost_usd falling back to
  estimated_cost_usd), --min/--max-tool-calls.
- SessionDB prune/archive/list_prune_candidates now share the filter
  kwargs via **filters into _prune_filter_where (unknown names raise
  TypeError); candidates listing + CLI preview now include the model.
- Any attribute filter (except legacy --source) suppresses the implicit
  90-day default so 'prune --model X' matches all ages.
- Dashboard /api/sessions/prune passes the new fields through.
- Docs + tests updated (7 new DB tests, 3 new parser tests).
2026-07-05 22:04:52 -07:00
izumi0uu
0f154e780e fix(gateway): isolate multiplex profile config env reads
Fixes #50051 by preserving nested gateway.multiplex_profiles and routing gateway config env reads through the active profile secret scope when present.

This keeps secondary profile adapter startup from inheriting default-profile platform tokens or port-binding enables while preserving legacy single-profile behavior outside a scope.

Constraint: latest upstream main f57ff7aef1 still reproduced both nested-config loss and cross-profile env leakage
Rejected: special-casing API_SERVER_* only | left other profile-scoped tokens vulnerable to the same leak
Confidence: high
Scope-risk: moderate
Directive: keep future gateway/config env reads on the scoped helper path unless a variable is explicitly process-global
Tested: pytest -q tests/gateway/test_multiplex_phase0.py tests/gateway/test_multiplex_credential_isolation.py tests/gateway/test_config.py -k 'multiplex or scope or getenv or api_server or relay'
Not-tested: full gateway startup across live platform adapters
2026-07-05 22:00:25 -07:00
Teknium
9169591c50
test(gateway): pin random tip in topic-mode /new test to kill 1-in-380 flake (#59380)
test_group_new_keeps_existing_reset_semantics_when_dm_topic_mode_enabled
asserts 'parallel work' not in the /new reply — but /new appends a
random tip from hermes_cli.tips (380 entries), and one tip's text
contains exactly that phrase (the delegate_task concurrency tip). CI
failed on PR #59331 slice 2 when the dice landed on it. Pin
get_random_tip in the test.
2026-07-05 21:57:55 -07:00
teknium1
f761fb9d6a test(gateway): pin source.profile=None on MagicMock fixtures hitting _adapter_for_source
The routing sweep sends these paths through _adapter_for_source, which
reads source.profile. A bare MagicMock auto-attribute is truthy, so the
fixtures looked like stamped secondary profiles and hit the new
fail-closed branch. Real SessionSource.profile is None or str
(AGENTS.md pitfall #17).
2026-07-05 21:48:59 -07:00
teknium1
f600dfca96 chore(release): map author emails for PR #56854/#57417 salvage 2026-07-05 21:48:59 -07:00
teknium1
ab70551b3d fix(gateway): fail-closed adapter resolution for unregistered secondary profiles
Follow-up to the routing sweep: when a stamped secondary profile has no
_profile_adapters entry (adapter failed to connect / was refused), return
None instead of falling back to the default profile's adapter — the
fallback sends replies out the wrong bot, which is the exact leak class
this cluster fixes. Also restores main's deliberate fail-fast on
port-binding platforms in secondary profiles (the cherry-picked commit
had softened it to silent force-disable).

Co-authored-by: ManniBr <m888.braun@hotmail.com>
2026-07-05 21:48:59 -07:00
Andreas Hiltner
8a9bc38c2e fix(gateway): route multiplex profile responses through correct adapter
Replace 53 instances of self.adapters.get(source.platform) with
self._adapter_for_source(source) in gateway/run.py.

self.adapters is the default profile's adapter map. In multiplex mode,
secondary profiles (lars, kira, jonas, caro) have their adapters in
_profile_adapters[profile]. _adapter_for_source() (from authz_mixin.py)
correctly resolves through _profile_adapters when source.profile is set.

Without this fix, ALL response paths for secondary profiles — streaming,
sending, media delivery, voice, typing indicators, queue operations,
startup restore, and platform notices — route through the default
profile's bot token instead of the profile's own token.

Fixes: Multiplex profiles responding with wrong bot token on Telegram,
Discord, and all other platforms.
2026-07-05 21:48:59 -07:00
teknium1
43a4256320 fix(mcp): wake stale cached servers on session startup + AUTHOR_MAP
register_mcp_servers now nudges cached entries whose session is None
via _signal_reconnect, so a new agent session recovers a parked server
immediately instead of waiting up to _PARKED_RETRY_INTERVAL for the
next self-probe (#50170). Gate-check idea credit: @izumi0uu (#50184),
@LeonSGP43 (#37772), @Tranquil-Flow (#37899).
2026-07-05 21:48:36 -07:00
teknium1
6f5573c524 test(mcp): make circuit-breaker reconnect stub survive a None session
The dead-session half-open test drives _signal_reconnect with
session=None; the salvaged _ReconnectAdapter assumed a live old
session. Also count set() calls explicitly instead of relying on
MagicMock introspection.
2026-07-05 21:48:36 -07:00