Add hermes_cli/config_backend.py (config-config design §4.1, D10/D11): a
ConfigBackend protocol, the FileBackend (today's behaviour), selection by
HERMES_CONFIG_BACKEND only (default file; 'remote' and unknown values fail
closed with ConfigBackendUnavailable), and path-level helpers
(read_config_doc, read_config_doc_readonly, config_version, config_exists,
write_config_key, write_config_document, supports_file_tooling).
Migrate every direct reader/stat/exists/bypass writer of a user config.yaml
to the helpers (config.py loaders + caches, config_effective, env_loader,
gateway, TUI, CLI watchers, cron, tools, profiles, logging, time). File
tooling (config edit, backups, xAI migration rewrite, raw dashboard editor)
checks supports_file_tooling() first; migrations skip write-back without it.
Add scripts/check_config_yaml_readers.py (CI lint next to the writers gate)
that rejects a direct read of a config path outside the backend.
A session on Anthropic behind a proxy, or rotating a credential pool, ran
/model haiku --once, and that one turn went to the provider's default
host with its default key, without the pool or the session's request
overrides. So did an endpointless model_aliases entry, a plain model id
that reverse-matches one, and an external_process provider's own alias
or declared id, which also lost the session's command. With the previous
commit, /model M --once through an alias named M with no endpoint now
reaches the owner too.
The owner ran a pick whole whenever resolved_via_alias was set. But
switch_model gives a pick its own endpoint and key only for a direct
alias with a base_url (_apply_direct_alias_endpoint); for every other
alias kind it resolves the provider's default route, and the owner ran
that in place of the session's.
switch_model now says on its result whether it applied a direct alias's
own endpoint (alias_endpoint_applied, False by default), and the owner
runs a same-provider pick whole only then. The owner decides from the
route switch_model resolved and validated, not from a second read of the
alias table, which a config.yaml edit in between or another profile's
reload of the shared table could change. Every other alias keeps the
session's pool, endpoint, key, command and overrides, and the wire still
follows a provider that picks it per model. An alias with its own
endpoint, and a different provider, still run whole; the CLI still sends
the alias name.
Refs #134889, #140719
(cherry picked from commit eeac2f5b5fdd7d9b5e863a154bdaf654ea99202a)
(cherry picked from commit 752350eb3dd60e18c0c94e4fbed4382c6dfc79fc)
A single-profile owner binds no secret scope and never reloads .env for
local turns, so session.create expanded config.yaml ${VAR} refs (MCP
headers, provider base_url, ...) against the os.environ the daemon
started with; a rotated value only reached new sessions after a
restart. Tool env already refreshes from the profile .env.
stage_local_session now reads config through load_profile_config: it
binds the profile's secret scope (build_profile_secret_scope, the same
.env + secret-source + managed composition the owner scope uses) around
the read when none is bound. A served profile's owner scope is kept as
is; on the launch profile a scope miss still falls to the process env,
so systemd / op run injection keeps resolving. Frozen sessions are
untouched (their stored config is not re-expanded).
Refs #134889 (CFG-4)
Refs #139523
When `model:` carries an anchor reused elsewhere (`auxiliary.vision: *route`),
the safe loader returns one shared dict for both keys. persist_model_selection
assigned a fresh merged copy to config["model"], leaving the alias holding the
old route; the round-trip writer merges onto the shared ruamel node, so the
later auxiliary.vision merge wrote the old values back and /model save reported
success while persisting old-model.
Edit the loaded model mapping in place instead, so every alias carries the new
route — the same file main's per-key writer produces (alias kept, both keys
resolve to the new route). Still one publication.
persist_model_selection read the raw config, then ran
should_clear_context_pin (cold-start disk I/O) and the rest of the
selection logic, then published the whole document with
atomic_config_replace, which deletes keys missing from the snapshot.
Any setting another process saved in that window was silently erased
(e.g. display.theme written via atomic_roundtrip_yaml_update).
Compute the model updates from a pre-read first, then do read -> merge
-> replace as one in-memory section under _CONFIG_LOCK. If model:
changed between the pre-read and the snapshot, recompute against the
fresh block so the route rules still see the current state.
Adds a test where a real subprocess saves a setting during the route
decision; it fails on the previous head and passes here.
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); no other main commit touches a conflicted file. Resolution: the branch side
of each file plus main's exact autofix (ruff 0.15.10, main's ruff.strict.toml, --fix
--unsafe-fixes). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
8 conflicts, all from main's lint sweep (#135281 "Harder linter fixes" + the RUF series:
implicit-Optional, unused-unpacked-variable, next(...) for [...][0]). No other main commit touches
a conflicted file. Resolution: the branch side of each file plus main's exact autofix
(ruff 0.15.10, main's ruff.strict.toml, --fix --unsafe-fixes) on it. ruff.strict.toml takes main's
copy (the newly enabled rules). tests/cron/test_bot_chat_delivery_child_env.py stays deleted
(1cc9cb9199 retired its lane).
prepare_model() wrote only model.default/provider/base_url into the frozen
policy and cleared the launch key only when the provider *name* changed. A
probe on r6-base (custom -> custom, new origin) committed base_url B while:
- api_mode, a context_length pin and key_env from endpoint A survived;
- the explicit launch key bound to endpoint A stayed bound (provider_changed
is a name comparison);
- _resolve_policy_agent_runtime still read the creation request's base_url
as explicit_base_url, so the next turn went to A, with A's key.
Root fix, two halves:
- prepare_model applies the shared apply_model_selection() contract
(model_selection_config_updates: api_mode synced, context pin dropped when
its route changed, inline key / key_env / api_key_env dropped on a route
change), and decides launch-key reuse with the same route-identity test
(now public as selection_route_changed: provider OR normalized base_url),
so custom -> custom on another origin drops the endpoint-bound key.
Private config values whose model.* field was cleared are not re-hydrated.
- _resolve_policy_agent_runtime honours the creation request's base_url only
while it still is the policy's endpoint; the creation request itself stays
immutable (retry identity unchanged).
A same-route re-pick keeps the launch key and key_env (pinned by the test).
Review: https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6067585232
resolve_persist_behavior() hard-coded the provider-scoped path as exploratory
(return False before the config default was read), so
model.persist_switch_by_default: true was silently ignored whenever --provider
was passed - which is the exact shape the Desktop picker sends.
For twin provider pairs (two custom_providers entries sharing one base_url with
different keys) that is not exploration of a different backend: it is tenant or
account selection on the same backend. The session-scoped pick is dropped, and
the next chat re-derives the provider from the shared base_url, which
deterministically returns one fixed twin - the request is then served with the
other tenant's key, silently: wrong credentials, quotas and billing, no error.
Read the flag before the explicit_provider bail-out so an opt-in to persistence
covers provider picks too. --session and --once stay the explicit opt-outs and
--global still persists; without the flag provider picks remain exploratory, so
the existing behavior is unchanged for everyone who never set the key.
Fixes#123150
A providers.<slug> block with no base_url/url/api of its own is settings,
not a user-defined endpoint. Only remap to the custom: validation branch
when the user-config entry declares a base_url; otherwise openai-codex and
other listing-less built-ins keep their normal catalog path.
Closes#120020
Every /model surface parses through parse_model_switch_args. The legacy
5-tuple wrapper had no production caller; its remaining references were two
tests of the tuple shape, an unused import, and two tui_gateway patch()
calls on a function tui_gateway no longer calls.
The en-dash --session normalization those tests covered moves into the
parse_model_switch_args keeper. test_model_switch_once_flags and
test_model_switch_context_offload are removed: the first re-tests the
private parser the keeper already drives, the second the one-line to_thread
wrapper that tests/gateway/test_model_command_context_offload.py proves off
the event loop through the real /model handler.
* refactor(plugins): remove the Sep 2026 decomposition compat layer on schedule
The PLUGIN-COMPAT layer (2776813df3 + d63e380324 + 0a5164cebe) kept pre-#102117 import paths
alive for external plugins until 2026-09-14. That window closed two weeks ago; since then the loader
has already been skipping plugins that use the old paths. This removes the layer itself:
- 328 appended `PLUGIN-COMPAT` blocks (lazy `__getattr__` pointer tables, re-exported third-party
names, restored dead definitions) and the three re-export stub modules
(gateway/startup_watchdog, hermes_cli/observability/relay_runtime, tools/environments/modal_utils)
- COMPAT_MANIFEST.md, compat_manifest.json, scripts/check_compat_pointers.py and its lint step
- the reporting surfaces: CLI banner notice, `hermes plugins compat`, the `hermes doctor` section,
the post-update notice, the Desktop one-time dialog, the loader's pre-import skip and the
`plugins.allow_deprecated_imports` escape hatch
An external plugin that still imports an old path now fails to load with its ImportError as the
reason in `hermes plugins list`, the same path as any broken plugin.
hermes_cli/plugin_compat.py stays as three inert stubs (compat_report, removal_in_effect,
summary_lines): an already-running pre-removal `hermes update` lazy-imports them after the checkout
swap (tests/compat/old_updater_surface.json).
In-tree fallout, both already dead: hermes_cli/setup.py::_check_espeak_ng (no callers; its
`shutil` came from a compat block) and gateway/config.py::SessionResetPolicy ("retained solely for
the scheduled plugin-compat window"). Two test_run_agent patches targeted the removed
`run_agent.handle_function_call` pointer; they now patch `model_tools.handle_function_call`, the
seam production reads, like every sibling test in that file.
* chore: retrigger CI (zero-job startup_failure phantom)
* test: drop resolution allowlist rows for the two deleted which() sites
hermes_cli/setup.py::_check_espeak_ng (dead) and tools/skillevaluator_scan.py::scanner_available
(a restored definition inside a PLUGIN-COMPAT block) no longer exist; the stale-row gate requires
their allowlist entries go with them.
Chat catalogs and the session switch treated image and video generation
models as chat. Exclude them by the capability type and name shape the
catalog already publishes, reject selecting one as the session model, and
do not restore a primary already known to be non-chat. Desktop shows the
fallback switch in the transcript.
Only the --provider path handed user_providers/custom_providers to
resolve_alias, so the provider-identity comparison behind the
current-provider preference could not see legacy custom_providers
entries on the implicit path (/model <id>) or the authenticated-provider
fallback. On custom:corp-llm, /model shared-model picked another
provider's alias for the same model id and switched to its base_url.
Pass both provider maps on every resolve_alias call site. The two
existing resolve_alias stubs in test_ollama_cloud_auth.py accept the
extra positional args; their assertions are unchanged.
The --provider ownership check compared normalize_provider() spellings, but a
legacy custom_providers entry resolves to id "custom:<name>". An alias with
"provider: corp-llm" under "--provider corp-llm" was therefore dropped and the
switch fell back to the provider's own base_url/key instead of the alias's.
Compare resolve_provider_full(...).id on both sides (normalize_provider when
unresolvable), in the ownership check and in resolve_alias's reverse-lookup
preference loop, which now receives the user/custom provider config.
An explicit `/model <id> --provider X` switch could report target_provider=X
while base_url still pointed at the previous provider's endpoint: resolve_alias
finds a direct alias by reverse model-ID lookup, and the base_url override
applied that alias unconditionally even when the alias belonged to a different
provider. Requests would then be sent to the old provider's URL under the new
provider's identity.
Two narrow changes:
- resolve_alias's reverse lookup now prefers an alias whose provider matches
current_provider, falling back to first-match only when none does. Insertion
order is not a routing decision.
- The direct-alias base_url override now ignores (and stops reporting) an alias
whose provider differs from target_provider.
Exact alias-name lookup stays provider-agnostic, and the first-match fallback is
preserved, both pinned by tests.
[salvaged onto the refactored switch pipeline: the ownership guard now sits in
_route_explicit_provider, where resolved_alias is settled, so both the runtime
resolve (explicit_base_url) and the direct-alias override see the filtered alias]
OpenAI shipped gpt-6-sol / gpt-6-terra / gpt-6-luna as the successors of the
gpt-5.6 tier line (Sol and Luna live on OpenRouter + the Nous Portal today).
The curated aggregator catalogs (OPENROUTER_MODELS and the derived nous list,
plus the published website model-catalog.json) now carry the gpt-6 tiers and
their -pro variants instead of the 5.6 ones; the openai-api curated fallback
lists them ahead of 5.6.
Codex OAuth support mirrors the 5.6 + Astra contract for every gpt-6 tier:
curated fallback + forward-compat synthesis (from the 5.6 twin or 5.5),
272K advertised fallback, the opt-in -900k picker variants with the
live-verified 900K bump (still capped by the catalog's max_context_window),
dated-snapshot eligibility, wire-suffix stripping, the compaction auto-raise
on the base slug, and the gpt-5.6 effort ladder (max allowed, minimal
rejected). Pricing rows for gpt-6-sol / gpt-6-luna come from OpenAI's model
pages (272K whole-request tier like Astra); Terra has no published page yet
so it deliberately has none.
/model gpt keeps resolving to the flagship: "astra" joins the rank-0 suffix
set so gpt-6-astra sorts above gpt-6-sol.
The provider-agnostic half of PR #105863, so a CLI-driven subscription provider can ship as a
standalone `kind: model-provider` plugin instead of a bundled one:
- ProviderProfile: `native_reasoning_details_type`, `model_aliases`, `get_model_context_length`,
`get_usage_cost`, `setup_status`, `discover_models` hooks (all default None / no-op).
- Chat Completions transport: provider-native `reasoning_details` carriers follow only their
declaring profile; standard records still replay on OpenRouter-style routes, strict routes
drop the field wholesale (#70233). Relay/stream accumulate `delta.reasoning_details` verbatim.
- `hermes model`: the generic plugin flow gates an external-process row on the CLI's own login
status (inline `login_command` on a TTY), offers `discover_models()` rows with per-row notes,
and never writes config when the executable is missing.
- `/model` and the pickers: process providers list their live catalog merged with the pinned
one, declared aliases/ids resolve inside the provider, and validation accepts a listed id
without probing `process://`.
- Delegation keeps the selected external-process provider and protocol for the child.
- Model metadata / usage pricing consult the profile's bound and cost hooks first.
- Desktop: `[1m]` renders as a "1M" tag and hyphenated Anthropic versions read "Haiku 4.5".
The bespoke `_model_flow_external_process` and hard-coded `hermes_cli/main.py` paths from the
PR were dropped in favour of main's `_model_flow_plugin_provider`.
Co-authored-by: unsupportedpastels <unsupportedpastels@users.noreply.github.com>
The /model -> local/ flow offers the 'llamacpp' row from staged GGUFs alone,
but resolve_provider_full only admitted that id behind a live endpoint, so
selecting a staged model died with "Unknown provider 'llamacpp'" before the
runtime seam could start or attach a server.
- providers.py: LLAMACPP_PROVIDER_ID/ALIASES are the single definition; the
llamacpp rung resolves when a server is reachable OR a model is staged.
- inventory.py: the picker row's slug comes from that definition.
- endpoint.py: honour local_runtime.detect_ports (every provider caller
invoked the resolver bare, leaving the documented knob dead).
- model_switch.py: a local-runtime alias failure surfaces the seam's own
message instead of an API-key hint.
An unpinned cron job used to snapshot the global provider/model at creation and treat that
snapshot as its effective pin (#44585), so `hermes model` / `/model` never moved the fleet and
`hermes cron resnap` existed to catch jobs up. New ruling: jobs run on whatever the main agent
model is when they fire. Resolution is per-job pin > cron.model / cron.model_provider (the cron
fleet default) > model.default.
`pinned` replaces the implicit snapshot with an explicit lock: create/update with pinned=true
writes the CURRENT main provider+model onto the job as an ordinary per-job pin; pinned=false
releases both. The cronjob tool exposes it (schema: only when the user asks; it can only lock
the main model, never point spend at a different one) and reports `pinned` per job; the CLI
gets `--pin` / `--unpin`. Legacy records that still carry *_snapshot keys follow the main model.
Removed with the snapshot: `hermes cron resnap`, the tool's resnap action + `all` param, the
"N unpinned jobs keep running on ..." notice in `hermes model` / `hermes config set` / the
dashboard model assignment, and the Desktop cron-model-impact card (setMainModelAssignment
keeps the expensive-model confirm flow in store/model-assignment.ts).
Live A/B (real store + run_job against a temp HERMES_HOME): main-model X -> Y, unpinned job
fires on X before, Y after; pinned job stays on X; unpin -> Y; legacy snapshot record -> Y.
get_authenticated_provider_slugs only needs slugs but ran the full listing,
which force-refreshed every stale catalog (6 probes on a cold cache with 6
keys) during alias-fallback routing of a model switch. Pass
non_blocking_catalogs=True: same slug set, 0 forced probes.
#116138 taught the bare-`custom` switched arm to keep the session endpoint when the credential
ladder answered with the `OPENROUTER_BASE_URL` mirror. That test was host/URL-only, so it also
fired when the ladder's answer came from an endpoint configured *ahead* of the OpenRouter rung —
`CUSTOM_BASE_URL`, or a trusted `model.base_url` holding the same URL as the mirror (two env vars
aimed at one proxy). In that configuration the switch paired the new model with the previous
provider's host and key again, i.e. the #73680 shape this arm exists to prevent.
The guard now asks the ladder's own question: the mirror counts as a fallback only when
`CUSTOM_BASE_URL` and a trusted `model.base_url` are both absent, so a URL that equals the mirror
because the user configured it there still wins.
Second act of `test_switch_to_bare_custom_ignores_an_openrouter_mirror` pins it: with both env
vars pointed at the same proxy the switch adopts that endpoint; without the precision check the
test fails (`api.anthropic.com` kept instead of the configured proxy).
The switched-provider bare-`custom` arm adopts the resolved endpoint unless it is the
OpenRouter default. `_fell_back_to_openrouter_default` only knew the built-in
`openrouter.ai` host, so an `OPENROUTER_BASE_URL` mirror — the credential ladder's last
rung, reached whenever no trusted `model.base_url`/`CUSTOM_BASE_URL` exists — looked like a
configured custom endpoint: a session on another provider switching to bare `custom` landed
on the mirror with the `no-key-required` placeholder, dropping the key it was using.
The helper now also recognizes that mirror (read the way the resolver reads it, through the
profile's secret scope), so the arm keeps the session's endpoint and key instead. Sharing the
helper also covers the same-provider #74143 path: a `custom`/`local` session on a session-only
endpoint no longer adopts the mirror either — the same "resolution landed on OpenRouter"
case that guard exists for.
The mirror read is a GUARD read, not a credential fetch: a scope failure (unscoped under
multiplexing) leaves the mirror undetected so the caller keeps the session endpoint, instead
of raising out of `switch_model` where the resolver's own read of the same name is suppressed.
`CUSTOM_BASE_URL` and a trusted `model.base_url` still win: those are endpoints configured for
`custom`, which is the point of the arm.
- model_switch: the host-mandated wire mode (codex_responses on api.openai.com)
corrects STALE modes; it must not overwrite the resolver's codex_app_server opt-in.
- runtime_provider: docstring ladder gains step 9 (the overlay); one logger.info when
the overlay replaces a rung's api_mode, since that rung's credential/endpoint is not used.
- gateway/run_agent_cache.py::_rehydrate_session_model_override re-resolved api_mode from the
target model but kept the persisted base_url verbatim, so a /v1-stripped or other-family
relay URL written by an older build stayed on a chat_completions model. Run
normalize_opencode_base_url after re-resolution for opencode-family providers (test drives
the production rehydration entry: red before, green after).
- hermes_cli/model_switch.py::_build_switch_result now uses model_derived_api_mode() instead
of its own exact-key table lookup, so a custom provider extending a family slug
(opencode-go-bridge) gets the same per-model wire on live /model as on resume.
- tui_gateway/server.py::_resolve_agent_model_runtime: the re-derivation guard is
any(overrides.values()) — a model_override dict always carries the three keys, so
'if overrides' was always true.
Part of #96066
Two independent gaps hit a user on provider opencode-go with
deepseek-v4-flash-vision-exp (#96066):
- Vision: the model is absent from models.dev, so get_model_capabilities()
returned None and image_input_mode: auto detoured images through the lossy
text describe path. OpenCode Zen/Go resell vendor previews before the catalog
indexes them; the id's `-vision` token is the vendor's own capability marker,
so _apply_overrides() now fills the catalog gap with a vision-only base for
any OpenCode-family provider (built-in or family-slug custom). Catalog entries,
explicit and _default overrides stay authoritative; reasoning stays unknown.
- Route: _resolve_agent_model_runtime() applied a resumed row's persisted
api_mode/base_url verbatim. A row written while the session ran an
anthropic_messages model (MiniMax on Go, or an older build's /zen/v1 relay)
pinned that wire onto a chat_completions model, surfacing as 401s from the
Anthropic transport or the Zen relay. Providers that pick the wire per model
(OpenCode families, Copilot, Nous — the existing _PROVIDER_API_MODE_OVERRIDES
table, now reachable via model_derived_api_mode()) re-derive api_mode from the
target model on resume and heal the relay URL; fixed-wire providers keep
honoring their row.
Salvages #96116 (@Finn763): same two atoms, redone slim (data-driven table
instead of an opencode-only hostname guard in the tui_gateway facade).
The switched-provider comment implied the guard catches the resolver raise;
it is suppress() leaving st.* at the session values that does. The
stay-on-provider comment now states the one semantic widening of moving to
the shared helper: an empty resolver result keeps the session endpoint on
any host, not only off openrouter.ai.
Gate finding: resolve_runtime_provider(requested="custom") never returns an
empty base_url — with no model.base_url but an OpenRouter key present it
lands on OpenRouter's default host, so the "keep the current endpoint"
fallback was dead and an Anthropic session adopting `provider: custom`
hopped to openrouter.ai. The guard _creds_for_current_provider already
carries for this (#74143) is now a shared helper used by both branches;
the branch assigns once instead of assign-then-undo; the import sits with
the other from-imports; the new test's write_text carries an encoding.
Second invariant test pins the no-endpoint case.
The bare-custom credential branch kept the session's current base_url and
key whenever the target was `custom`, regardless of where the session was.
That is right for a bare-custom session picking another model on its own
endpoint, but when the TUI's per-turn config sync adopts `provider: custom`
from an OpenRouter (or any other) session, the new model was paired with
OpenRouter's URL and key and every request 400/404'd (Bug 2 in issue 73680).
Arriving from another provider now resolves the configured custom endpoint
through resolve_runtime_provider; with none configured the current endpoint
is kept, so direct aliases still supply their own URL afterwards and the
bare-custom same-endpoint case is unchanged.
Review findings folded: (1) `parse_model_input` resolved the configured
`custom:<name>` ids through its own `load_config()`, so the `user_providers`/
`custom_providers` the three startup callers pass were ignored for this branch
— two config sources for one decision. It now takes `custom_ids` and the route
builds them from its arguments with `custom_provider_slug`, the same identity
`providers:` entries carry everywhere else. (2) The "typo" guard was wrong: it
fired on legitimate bare-custom tags (`custom:qwen3.5:4b`) and its `None` fell
straight back into the default-provider egress the fix exists to prevent. A
bare `custom` route with an unknown id now 404s on the user's own endpoint,
matching `/model`. Docstring lists the `provider:model` form.
Third entry path with the same egress: `_resolve_startup_runtime` seeded the model
from HERMES_INFERENCE_MODEL and went straight to static provider detection, so the
qualified string reached the configured default. Route through
`resolve_startup_model_route` first, as HermesCLI and oneshot now do.
Also: an unconfigured `custom:<typo>:<model>` now logs a warning and leaves the
route undecided instead of steering a garbage model id at the bare custom endpoint,
and the redundant `qualified_model != raw` guard is gone.
`hermes -m custom:jetson-vllm:nemotron-nano-30b` (and `-z`) kept the configured default
provider and sent the UNSPLIT string as the model name, so the whole prompt reached
api.anthropic.com before a 404 — a local endpoint the user picked never saw the request.
`parse_model_input` already decodes the form; nothing on the startup path called it.
`resolve_startup_model_route`, the owner of startup provider/model decoding, now consumes
the colon-qualified form through `parse_model_input` ahead of the `provider/model` branch,
so HermesCLI picks it up unchanged. The oneshot resolver routes through the same owner
before provider auto-detection instead of only after a direct-alias miss.
Live, config `providers.jetson-vllm` at 127.0.0.1:8000 and `model.provider: anthropic`:
before — HTTP 401 from Anthropic, local sink idle; after — sink receives
POST /v1/chat/completions model=nemotron-nano-30b, Anthropic untouched.
Closes#73943. First reported fix: PR #74082 by @Drexuxux (HermesCLI.__init__ decode); the
seam moved to the startup route owner during the Sep-2026 cli.py decomposition.
Co-authored-by: Drexuxux <drexux0@gmail.com>
The explicit_base_url hunk in _creds_for_switched_provider passed every
URL-bearing direct alias's endpoint to resolve_runtime_provider, so a
built-in label (anthropic, openai) resolved its vendor key AGAINST the
alias's foreign host; _apply_direct_alias_endpoint then saw a same-origin
credential and kept it. Gate on _resolves_to_custom: only ollama/vllm-style
labels, the ones the missing-endpoint guard refuses, get the alias URL.
CI: tests/hermes_cli/test_model_alias_credentials.py
::test_builtin_label_does_not_pull_that_providers_key_to_a_foreign_host
[anthropic] red on ce4e9d580ac, green here; direct-ollama-alias /model
tests stay green.
Follow-up on the picked #113768 commit so it clears the constraint that got
e9a54c48f2 reverted (a9fabe43c4): `/model <direct-alias>` resolves the alias
LABEL first and applied the alias endpoint only afterwards, so any guard that
fires on the label alone turns a working switch into "ollama is not connected"
(tests/hermes_cli/test_models.py::TestLocalOllamaModelDiscovery went red again
with the PR as-is).
- hermes_cli/runtime_provider.py::_raise_if_local_alias_missing_endpoint keys
on the class (anything auth.resolve_provider maps to `custom` without a rung
of its own; llamacpp keeps its managed-server fail-fast) instead of a second
hardcoded alias set, requires the providers.<alias> block to actually carry a
base_url (an entry without one falls through to OpenRouter too), and names
the alias plus where to set its endpoint. OPENROUTER_BASE_URL never counts as
the alias endpoint; an explicit api_key does not lift the guard.
- hermes_cli/model_switch.py::_creds_for_switched_provider hands a URL-bearing
direct alias's base_url to the resolver as explicit_base_url, so the alias
has an endpoint at the moment the guard runs (the same URL
_apply_direct_alias_endpoint installs later).
- Tests trimmed to two invariants (raise-and-name incl. the OPENROUTER_BASE_URL
/ explicit-api_key non-lifts + bare-custom control; every endpoint source
resolves to its URL). Docs: troubleshooting entry in the local Ollama guide.
Cron replay snapshots that store the resolved `custom` instead of the alias
are #109765's atom and untouched here.
Top-level `model_aliases:` entries carried credentials into DirectAlias but
the nested `model.aliases:` dict form built it without `api_key`/`key_env`,
so an alias with its own base_url got no credential (401) even though the
URL resolved correctly. Pass both fields through, as the top-level path does.
Source hunk from PR #109834 (earliest filer); invariant tests from the
identical later PR #114472. Nested-alias credential atom of #114471.
Co-authored-by: Yagna Vudathu <yagnavudathu@gmail.com>
Dropping an identity-equal legacy `custom_providers` entry from the candidate list also dropped the
models only that entry declared: `/model gpt-5.4-mini` (declared by the legacy row but not by
providers.relay) fell through to the current provider (openrouter) instead of routing to the shared
endpoint — a fail-open flip versus the pre-#112788 behaviour, which routed it to custom:relay.
Keep every entry as a candidate and credit a duplicate's hits to the providers row it duplicates, so
the collapse loses no declaration. `_duplicates_configured_row` now returns the owning slug.
Also require credential equality (not just endpoint) in the raw-list `provider_key` shortcut: a
hand-written entry stamped `provider_key: relay` on the same URL but a different key_env is a
distinct route and stays ambiguous, matching the issue's "preserve ambiguity when credential differs"
criterion.
`_configured_provider_matches` now drops a `custom_providers` entry when it is a second view of a
`providers.<slug>` row: either that row's compat projection (provider_key names the slug AND the
endpoint matches) or a legacy duplicate with the same provider identity (normalized name, endpoint,
credential identity, api_mode — read through the same normalizer that builds the compat view).
Any difference in endpoint, credential or wire protocol keeps two rows distinct.
Why: the first pass (#113103) only filtered entries whose provider_key equalled a providers slug.
A hand-migrated config that kept the same endpoint in both sections was still reported as
"declared by multiple configured providers (custom:relay, relay)", and on the raw-list fallback
(gateway/agent_init pass cfg['custom_providers'] verbatim when the compat view fails) a hand-written
provider_key pointing at a different endpoint was silently hidden instead of ambiguous.
`_route_configured_provider` treats `custom:<name>` of a projected row as an alias of its slug when
checking whether the session is already on the matched provider, so a session running on
`custom:relay` that types a model providers.relay declares stays on `custom:relay` instead of
flipping target_provider/explicit_provider to `relay`.
Closes the remaining atoms of #112788. Identity-tuple approach ported from the
`_configured_provider_identity` hunk of #112794.
Co-authored-by: KoNit-K <124019182+KoNit-K@users.noreply.github.com>
The gateway, Ink TUI and classic CLI hand switch_model() both the modern
``providers:`` map and ``get_compatible_custom_providers(cfg)``, which
re-lists every ``providers.<slug>`` row a second time as a ``custom:<name>``
entry stamped with ``provider_key: <slug>``. ``_configured_provider_matches``
only collapsed identical slugs, so a model declared by exactly one configured
endpoint matched twice (``relay`` and ``custom:relay``) and
``_route_configured_provider`` rejected the switch as "declared by multiple
configured providers" instead of routing it (#112788).
Skip a custom entry whose ``provider_key`` is already a ``providers`` slug in
the candidate list: it is the projection of that very row, not a second
declaration. Hand-written ``custom_providers:`` rows carry no provider_key and
remain independent candidates, so two genuinely distinct endpoints declaring
the same model still stop the switch with the ambiguity message.
Slim redo of #112794 (identity-tuple dedup helper) using the marker the
projection already carries.
Co-authored-by: KoNit-K <124019182+KoNit-K@users.noreply.github.com>
The cherry-picked commit extends the config/profile/MCP/managed-scope/completer/
OAuth/skills-manifest signatures. This commit finishes the class and trims it:
- `file_signature()` lives in `utils.py` next to the other stat/metadata helpers
instead of `hermes_cli.managed_scope` (gateway/ and agent/ callers no longer
reach into the managed-scope module for a generic stat helper).
- `hermes_cli/config_effective.py` was left comparing 2-/4-wide prefixes against
the widened `_RAW_CONFIG_CACHE` / `_load_config_cache_sig` records, so
`load_user_config_effective()` re-parsed on every call (3 parses for 3 calls on
an unchanged file, 1 before); index by the new widths.
- Sibling caches keyed on the same (mtime, size) shape and reading the SAME files
now use the helper: `load_env()` memo, `agent/skill_utils` raw-config and
external-dirs caches, `hermes_cli/model_switch` alias identity, `agent/moa_loop`
preset stamp, `hermes_cli/auth` global auth-store memo.
- Tests trimmed to one invariant each (pinned-mtime replacement invalidates; an
unchanged file still hits), both red on origin/main.
Left alone on purpose: `tools/registry.py`, `tools/skills_tool_dedup.py`,
`gateway/status.py`, `hermes_cli/banner.py`, `hermes_cli/main.py`,
`hermes_cli/session_recovery.py` — those fingerprint source files, PID/lock files
or write to persisted on-disk caches shared across processes, where an inode/ctime
key would churn on every checkout/copy rather than catch a replaced config.
Squashed integration of the user-facing message audit for this surface set.
Full per-finding receipts: /tmp/ux-audit/lanes/*-receipt.md (campaign artifacts).
`model.key_env` is not custom-only: the Desktop settings UI stores REGISTRY
provider keys there (e.g. HERMES_CUSTOM_LMSTUDIO_API_KEY with provider
lmstudio, #106336) and auth._model_level_key_env honours it. The previous
predicate (`not custom or route_changed`) therefore wiped that pointer on a
same-provider same-base_url model re-pick and silently broke the user's
credential. The pointer now clears ONLY when provider or base_url changed;
the inline api_key/api rule is unchanged.
Custom-endpoint activation (model_setup_flows_custom) popped base_url /
api_key but never key_env, so a stale pointer from a previous endpoint
outranked the credential it had just written — pop it alongside.
Tests: the same-route re-pick case now covers a registry provider (red on
the old predicate), and the two clear_model_endpoint_credentials tests are
folded into one invariant.
Main no longer clears credentials in web_server's _apply_main_model_assignment;
every /model surface (CLI, gateway, TUI, dashboard) persists through
model_selection_config_updates(), which only dropped api_key/api on a route
change. Custom-endpoint activation writes model.key_env with NO inline key, so
a pointer-only model block survived every provider switch and routed the new
provider's requests to the old endpoint's env var (the PR's Bug 5) — live
repro on main: activate custom_myep -> /api/model/set openrouter left
key_env: CUSTOM_MYEP_API_KEY on disk.
Port the PR's web_server hunk to the one shape function: key_env/api_key_env
clear under the same route-changed rule as api_key (same-route re-pick keeps
them). The dashboard's _resolve_assignment_credentials re-adds the TARGET
provider's own pointer after this, so custom->custom still ends with the new
endpoint's key_env. One invariant test in the one-shape suite.