diff --git a/agent/chat_completion_helpers_relay.py b/agent/chat_completion_helpers_relay.py index ef5923c8193f4..f853045822775 100644 --- a/agent/chat_completion_helpers_relay.py +++ b/agent/chat_completion_helpers_relay.py @@ -35,6 +35,7 @@ def __init__(self) -> None: self._content: list[str] = [] self._reasoning: list[str] = [] self._refusal: list[str] = [] # OpenAI ``delta.refusal`` — a refusal is content, not an empty stream + self._reasoning_details: list[Any] = [] # opaque provider records (signed blocks); order preserved verbatim self._tool_calls = _ToolCallAccumulator() self._model = self._usage = self._finish_reason = None self._role = "assistant" @@ -58,6 +59,7 @@ def observe(self, chunk: Any) -> None: text = flatten_message_text(delta.get("content"), sep="") if text: self._content.append(text) + self._reasoning_details.extend(delta.get("reasoning_details") or []) reasoning = delta.get("reasoning_content") or delta.get("reasoning") if reasoning: self._reasoning.append(separate_glued_reasoning_blocks( @@ -73,6 +75,7 @@ def finalize(self) -> dict[str, Any]: message = {"role": self._role, "content": "".join(self._content) or None, "reasoning_content": "".join(self._reasoning) or None, "refusal": "".join(self._refusal) or None, + "reasoning_details": self._reasoning_details or None, "tool_calls": [acc[i] for i in sorted(acc)] or None} # "stop" also covers Nous Portal ``lastOne`` usage frames, which carry no finish_reason. return {"model": self._model, "usage": self._usage, diff --git a/agent/client_lifecycle.py b/agent/client_lifecycle.py index 753af3bd84b23..cfe6a5cd06e56 100644 --- a/agent/client_lifecycle.py +++ b/agent/client_lifecycle.py @@ -416,6 +416,10 @@ def _abort_request_slot_client(self, slot_attr: str, client: Any, *, reason: str if cache["client"] is client: cache["poisoned"] = True try: + # Non-HTTP providers cancel without closing owner-thread file descriptors. + if callable(getattr(type(client), "cancel", None)): + client.cancel() + return shutdown_count = self._force_close_tcp_sockets(client) # Zero sockets shut down means the worker stays blocked — WARN, not success. # tcp_force_closed=0 means the stranger-thread abort found no sockets to shut down — the worker diff --git a/agent/model_metadata.py b/agent/model_metadata.py index fe7e46018f9d2..4f38ec1c07b44 100644 --- a/agent/model_metadata.py +++ b/agent/model_metadata.py @@ -2209,6 +2209,13 @@ def get_model_context_length( endpoint_context = _endpoint_scoped_context_length(model, base_url) if endpoint_context is not None: return endpoint_context + # A profile that qualifies its own bound (external processes have no /models probe) wins + # over the generic caches below; explicit user/endpoint overrides above still take precedence. + from providers import get_provider_profile + profile = get_provider_profile(provider) + context = profile.get_model_context_length(model) if profile else None + if type(context) is int and context > 0: + return context is_bedrock_context = _is_bedrock_context(base_url, provider) # A Codex Responses route is keyed on its transport, not its host: behind a proxy # (HERMES_CODEX_BASE_URL, model.base_url, custom api_mode: codex_responses) the URL looks diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.py index ee11801b3824d..8f3ae6671287a 100644 --- a/agent/transports/chat_completions.py +++ b/agent/transports/chat_completions.py @@ -372,7 +372,10 @@ def _finish_kwargs(api_kwargs: dict[str, Any], sanitized: list, params: dict, *, return api_kwargs -def _sanitize_message(msg: Any, strip_extra_content: bool, strip_reasoning_details: bool = False) -> dict | None: +def _sanitize_message( + msg: Any, strip_extra_content: bool, strip_reasoning_details: bool = False, + native_reasoning_details_type: str | None = None, +) -> dict | None: """Sanitized copy of ``msg``, or None when nothing needs stripping. Drops persistence sidecars, ``_``-prefixed scaffolding markers, tool-call ``call_id`` / @@ -381,18 +384,32 @@ def _sanitize_message(msg: Any, strip_extra_content: bool, strip_reasoning_detai on tool results (schema-valid only on user/assistant messages; strict providers reject it with ``contains item with unknown key name``), and ``reasoning_details`` unless the route replays it (``_route_replays_reasoning_details``). + On a replaying route, private ``.native_assistant`` carriers still go only to the + profile that declared that exact type: another provider's signed replay is meaningless (or + rejected) elsewhere, and stored history keeps it for a return to the original provider. """ if not isinstance(msg, dict): return None strip_keys = [k for k in msg if k in _STRIP_MSG_KEYS or (isinstance(k, str) and k.startswith("_"))] + kept_details = None if strip_reasoning_details and "reasoning_details" in msg: strip_keys.append("reasoning_details") + elif isinstance(msg.get("reasoning_details"), list): + details = msg["reasoning_details"] + kept = [d for d in details if not ( + isinstance(d, dict) and isinstance(d.get("type"), str) + and d["type"].endswith(".native_assistant") and d["type"] != native_reasoning_details_type)] + if len(kept) != len(details): + strip_keys.append("reasoning_details") + kept_details = kept # ``name`` is schema-valid on user/assistant messages, so the removal is # role-qualified: only tool results carry it illegally (strict providers # reject with "contains item with unknown key name"). if msg.get("role") == "tool" and "name" in msg: strip_keys.append("name") out_msg = {k: v for k, v in msg.items() if k not in strip_keys} + if kept_details: + out_msg["reasoning_details"] = kept_details tool_calls = msg.get("tool_calls") copied_tool_calls = None if msg.get("role") == "assistant" and "tool_calls" in msg and (tool_calls is None or (isinstance(tool_calls, list) and not tool_calls)): @@ -433,8 +450,11 @@ def convert_messages(self, messages: list[dict[str, Any]], **kwargs) -> list[dic Returns the input list unchanged when nothing needs sanitizing. """ strip_extra_content = not _model_consumes_thought_signature(kwargs.get("model")) - strip_reasoning_details = not _route_replays_reasoning_details(kwargs.get("base_url")) - sanitized_pairs = [(m, _sanitize_message(m, strip_extra_content, strip_reasoning_details)) for m in messages] + # A profile declaring a native carrier type consumes replayed details by contract. + native_type = getattr(kwargs.get("provider_profile"), "native_reasoning_details_type", None) or None + strip_reasoning_details = not (native_type or _route_replays_reasoning_details(kwargs.get("base_url"))) + sanitized_pairs = [(m, _sanitize_message(m, strip_extra_content, strip_reasoning_details, native_type)) + for m in messages] if all(s is None for _, s in sanitized_pairs): return messages return [m if s is None else s for m, s in sanitized_pairs] @@ -451,8 +471,8 @@ def build_kwargs( With ``provider_profile`` every quirk comes from the profile; the legacy flag path below (is_kimi, is_openrouter, ...) is only reached for unregistered providers. """ - sanitized = self.convert_messages(messages, model=model, base_url=params.get("base_url")) _profile = params.get("provider_profile") + sanitized = self.convert_messages(messages, model=model, base_url=params.get("base_url"), provider_profile=_profile) if _profile: return self._build_kwargs_from_profile(_profile, model, sanitized, tools, params) diff --git a/agent/usage_pricing.py b/agent/usage_pricing.py index 172374bf6bc03..d356fd42a5d16 100644 --- a/agent/usage_pricing.py +++ b/agent/usage_pricing.py @@ -542,6 +542,7 @@ def normalize_usage( return CanonicalUsage( input_tokens=input_tokens, output_tokens=output_tokens, cache_read_tokens=cache_read_tokens, cache_write_tokens=cache_write_tokens, reasoning_tokens=reasoning_tokens, + raw_usage=dict(u) if isinstance(u, dict) else (u.model_dump() if callable(getattr(u, 'model_dump', None)) else None), ) @@ -553,6 +554,11 @@ def estimate_usage_cost( model_name: str, usage: CanonicalUsage, *, provider: Optional[str] = None, base_url: Optional[str] = None, api_key: Optional[str] = None, ) -> CostResult: + from providers import get_provider_profile + profile = get_provider_profile(provider or '') + reported = profile.get_usage_cost(model_name, usage) if profile else None + if reported is not None: + return reported route = resolve_billing_route(model_name, provider=provider, base_url=base_url) if route.billing_mode == "subscription_included": return CostResult( diff --git a/apps/desktop/src/app/shell/model-catalog-menu.tsx b/apps/desktop/src/app/shell/model-catalog-menu.tsx index 2dcdcf2c8e3d9..c3e4dff50d543 100644 --- a/apps/desktop/src/app/shell/model-catalog-menu.tsx +++ b/apps/desktop/src/app/shell/model-catalog-menu.tsx @@ -493,7 +493,7 @@ export function ModelCatalogMenu({ : null const isCurrent = activeId !== null - const name = modelDisplayParts(family.id).name + const { name, tag } = modelDisplayParts(family.id) const caps = group.provider.capabilities?.[family.id] // Managed local model loading into memory right now: @@ -517,6 +517,7 @@ export function ModelCatalogMenu({ ) const meta = [ + tag || null, fastControl.kind !== 'none' && fastControl.on ? copy.fast : null, (caps?.reasoning ?? true) ? reasoningEffortLabel(effEffort || defaultEffort, isCurrent ? current.effortWire : undefined) diff --git a/apps/desktop/src/lib/model-status-label.test.ts b/apps/desktop/src/lib/model-status-label.test.ts index bf2b4a875eec2..6fe1f8fa92ece 100644 --- a/apps/desktop/src/lib/model-status-label.test.ts +++ b/apps/desktop/src/lib/model-status-label.test.ts @@ -11,9 +11,16 @@ describe('model-status-label', () => { expect(displayModelName('openai/gpt-5.5')).toBe('GPT-5.5') }) - it('strips trailing date-pin snapshots from the display name', () => { - expect(displayModelName('claude-opus-4-5-20251101')).toBe('Opus 4 5') - expect(displayModelName('anthropic/claude-haiku-4-5-20251001')).toBe('Haiku 4 5') + it('strips trailing date-pin snapshots and dots hyphenated Anthropic versions', () => { + expect(displayModelName('claude-opus-4-5-20251101')).toBe('Opus 4.5') + expect(displayModelName('anthropic/claude-haiku-4-5-20251001')).toBe('Haiku 4.5') + expect(displayModelName('claude-fable-5-1')).toBe('Fable 5.1') + }) + + it('renders the Anthropic 1M-context route suffix as a tag, never raw brackets', () => { + expect(modelDisplayParts('claude-sonnet-5[1m]')).toEqual({ name: 'Sonnet 5', tag: '1M' }) + expect(modelDisplayParts('claude-fable-5-1[1m]')).toEqual({ name: 'Fable 5.1', tag: '1M' }) + expect(displayModelName('claude-opus-5[1m]')).not.toContain('[') }) it('renders local GGUF ids as a clean name with a quant tag', () => { diff --git a/apps/desktop/src/lib/model-status-label.ts b/apps/desktop/src/lib/model-status-label.ts index e2b2749120473..8bd73213672b8 100644 --- a/apps/desktop/src/lib/model-status-label.ts +++ b/apps/desktop/src/lib/model-status-label.ts @@ -53,7 +53,9 @@ const titleCase = (text: string): string => text.replace(/\b\w/g, char => char.t function prettifyBase(base: string): string { if (/^claude-/i.test(base)) { - return titleCase(base.replace(/^claude-/i, '').replace(/-/g, ' ')) + // Anthropic ids spell the version with hyphens (`haiku-4-5`, `fable-5-1`); + // the human name is dotted ("Haiku 4.5"), not "Haiku 4 5". + return titleCase(base.replace(/^claude-/i, '').replace(/(\d)-(?=\d)/g, '$1.').replace(/-/g, ' ')) } if (/^gpt-/i.test(base)) { @@ -96,6 +98,16 @@ export function modelDisplayParts(model: string): { name: string; tag: string } } } + // Anthropic's `[1m]` route suffix selects the 1M-context window. It is a + // variant of the same model, so it renders as a tag ("Sonnet 5 · 1M") rather + // than raw brackets that read like an ANSI escape ("Sonnet 5[1m]"). + const contextWindow = base.match(/\[(\d+[mk])\]$/i) + + if (contextWindow) { + tag = tag ? `${tag} ${contextWindow[1].toUpperCase()}` : contextWindow[1].toUpperCase() + base = base.slice(0, -contextWindow[0].length) + } + // Drop a trailing date-pin (`…-20251101`) — snapshot noise, not a name. base = base.replace(/-\d{8}$/, '') diff --git a/hermes_cli/auth_model_picker.py b/hermes_cli/auth_model_picker.py index 1eda39aad0081..acfddbddec063 100644 --- a/hermes_cli/auth_model_picker.py +++ b/hermes_cli/auth_model_picker.py @@ -57,10 +57,12 @@ class _ModelPickerRows: def __init__( self, all_models: List[str], pricing: Optional[Dict[str, Dict[str, str]]], *, - current_model: str, sale_chrome: bool, + current_model: str, sale_chrome: bool, notes: Optional[Dict[str, str]] = None, ) -> None: from hermes_cli.models_pricing import _format_price_per_mtok, compute_sale_discount self.current_model = current_model + # Per-model dim annotation (e.g. "usage credits"); the row stays selectable. + self.notes = notes or {} self.has_pricing = bool(pricing and any(pricing.get(m) for m in all_models)) # Leave room for a leading "★ " on sale rows (Nous only). name_pad = 3 if sale_chrome else 2 @@ -106,8 +108,9 @@ def _was(raw: str) -> str: def segments(self, mid: str) -> list[tuple[str, str | None]]: """Build a rich radiolist row: yellow ★/% , dim was, plain prices.""" current = [(_CURRENT_SUFFIX, None)] if mid == self.current_model else [] + note = [(f" · {self.notes[mid]}", "dim")] if self.notes.get(mid) else [] if not self.has_pricing: - return [(mid, None), *current] + return [(mid, None), *note, *current] inp, out, cache, pct, was_inp, was_out = self._price_cache.get(mid, ("", "", "", None, "", "")) on_sale = pct is not None @@ -125,7 +128,7 @@ def segments(self, mid: str) -> list[tuple[str, str | None]]: segs.append((f" -{pct}%", "yellow")) if was_inp or was_out: segs.append((f" was {was_inp}/{was_out}", "dim")) - return segs + current + return segs + note + current def label(self, mid: str) -> str: return "".join(text for text, _style in self.segments(mid)) @@ -152,7 +155,7 @@ def _prompt_model_selection( pricing: Optional[Dict[str, Dict[str, str]]] = None, unavailable_models: Optional[List[str]] = None, portal_url: str = "", unavailable_message: str = "", confirm_provider: str = "", confirm_base_url: str = "", - confirm_api_key: str = "", + confirm_api_key: str = "", notes: Optional[Dict[str, str]] = None, ) -> Optional[str]: """Interactive model picker; current_model listed first. Returns the chosen model ID or None. @@ -187,7 +190,7 @@ def _custom_selection() -> Optional[str]: )) # All models for column-width computation (selectable + unavailable) - rows = _ModelPickerRows(ordered + list(_unavailable), pricing, current_model=current_model, sale_chrome=sale_chrome) + rows = _ModelPickerRows(ordered + list(_unavailable), pricing, current_model=current_model, sale_chrome=sale_chrome, notes=notes) _DIM = "\033[2m" _RESET = "\033[0m" diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.py index 8f39d8d6f1a44..f461eed1723f0 100644 --- a/hermes_cli/model_setup_flows.py +++ b/hermes_cli/model_setup_flows.py @@ -1066,6 +1066,34 @@ def _model_flow_anthropic(config, current_model=""): # ``_model_flow_api_key_provider``; ``hermes_cli.main`` routes every registered profile missing # from ``_PROVIDER_MODEL_FLOWS`` here, so an admitted plugin is never a silent no-op. +def _external_process_login_gate(profile, status) -> bool: + """Logged in → say so (with plan). Logged out → run the CLI's own login on a TTY (it is + browser/device based, so it must own the terminal), else print the instruction and stop.""" + import shlex + import subprocess + import sys + + if status["logged_in"]: + plan = f" ({status['plan']})" if status.get("plan") else "" + _say(f" {profile.display_name} credentials: ✓{plan}", "") + return True + login = status.get("login_command") + if not login or not sys.stdin.isatty(): + _say(f" ✗ {status['detail']}") + return False + _say(f" {status['detail'].split('.')[0]}.", f" Starting `{shlex.join(login[-2:])}` (press Ctrl-C to cancel)...", "") + try: + subprocess.run(login, check=False) + except (KeyboardInterrupt, OSError): + print("Login cancelled or failed.") + return False + if not profile.setup_status()["logged_in"]: + print("Login failed.") + return False + _say("", f" {profile.display_name} credentials: ✓", "") + return True + + def _plugin_flow_external_process(provider_id: str, profile) -> tuple[str, str] | None: from hermes_cli.auth import get_external_process_provider_status, resolve_external_process_provider_credentials status = get_external_process_provider_status(provider_id) @@ -1077,6 +1105,14 @@ def _plugin_flow_external_process(provider_id: str, profile) -> tuple[str, str] except Exception as exc: _say(f" ⚠ {exc}") return None + # A profile that can ask its CLI (``setup_status``) gates on login before anything is saved. + probe = profile.setup_status() + if probe is not None: + if not probe["available"]: + _say(f" ✗ {probe['detail']}") + return None + if not _external_process_login_gate(profile, probe): + return None return str(creds.get("base_url") or profile.base_url or ""), "" @@ -1109,6 +1145,20 @@ def _is_profile_plugin_flow_provider(provider_id: str) -> bool: return profile is not None and profile.auth_type in _PLUGIN_FLOW_CREDENTIALS +def _plugin_flow_live_rows(profile, api_key: str, base_url: str) -> tuple[list[str] | None, dict[str, str]]: + """``(live ids, {id: note})``. ``discover_models()`` (the account's own annotated picker, e.g. + ``usage credits``) wins when the profile implements it; otherwise the plain ``fetch_models()``.""" + with contextlib.suppress(Exception): + rows = profile.discover_models() + if rows: + _say(f" Models below come from your {profile.display_name or profile.name} account.", "") + return [r["id"] for r in rows], {r["id"]: r["note"] for r in rows if r.get("note")} + live = None + with contextlib.suppress(Exception): + live = profile.fetch_models(api_key=api_key or None, base_url=base_url or None) + return live, {} + + def _model_flow_plugin_provider(config, provider_id, current_model=""): """Generic ``hermes model`` flow for a registered plugin profile: credential step by auth_type, catalog via ``merge_profile_catalog`` (live ``fetch_models()`` ⊕ ``fallback_models``), persist.""" @@ -1120,13 +1170,11 @@ def _model_flow_plugin_provider(config, provider_id, current_model=""): if creds is None: return base_url, api_key = creds - live = None - with contextlib.suppress(Exception): - live = profile.fetch_models(api_key=api_key or None, base_url=base_url or None) + live, notes = _plugin_flow_live_rows(profile, api_key, base_url) model_list = merge_profile_catalog(provider_id, profile, live) or [] selected = _pick_model_or_prompt( model_list, "Model name: ", current_model=current_model, confirm_provider=provider_id, - confirm_base_url=base_url, confirm_api_key=api_key) + confirm_base_url=base_url, confirm_api_key=api_key, notes=notes) _finish_model(selected, provider_id, f"Default model set to: {selected} (via {profile.display_name or provider_id})", base_url=base_url or None, api_mode=profile.api_mode or None) diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py index 54fc500071628..07fd0162d9b10 100644 --- a/hermes_cli/model_switch.py +++ b/hermes_cli/model_switch.py @@ -756,12 +756,24 @@ def resolve_alias(raw_input: str, current_provider: str) -> Optional[tuple[str, if da.model.lower() == key: return (da.provider, da.model, alias_name) + process_catalog, process_aliases = _external_process_catalog(current_provider) + if process_catalog: + # Process providers own their model IDs and aliases (models.dev knows nothing about + # them); a typed id or family alias that they declare must not leave the provider. + declared = _external_process_match(process_catalog, process_aliases, key, provider=current_provider) + if declared is not None: + return (current_provider, declared, key) + identity = MODEL_ALIASES.get(key) if identity is None: return None vendor, family = identity + if process_catalog: + declared = _external_process_match(process_catalog, process_aliases, family, provider=current_provider) + return (current_provider, declared, key) if declared else None + # models.dev catalog merged with static _PROVIDER_MODELS entries it may be missing. catalog = list_provider_models(current_provider) try: @@ -785,6 +797,30 @@ def resolve_alias(raw_input: str, current_provider: str) -> Optional[tuple[str, return (current_provider, matches[0], key) +def _external_process_catalog(provider: str) -> tuple[list[str], dict[str, str]]: + """``(declared model ids, own aliases)`` of an ``external_process`` profile, else empty.""" + from providers import get_provider_profile + profile = get_provider_profile(provider) + if profile is None or profile.auth_type != "external_process": + return [], {} + return list(profile.fallback_models), {k.lower(): v for k, v in profile.model_aliases.items()} + + +def _external_process_match(catalog: list[str], aliases: dict[str, str], typed: str, *, provider: str) -> str | None: + """Provider alias, exact id, else the single declared id that extends it (``claude-opus-5`` + -> ``claude-opus-5[1m]``); several candidates raise so nothing is picked silently.""" + wanted = typed.strip().lower() + if wanted in aliases: + return aliases[wanted] + exact = next((m for m in catalog if m.lower() == wanted), None) + if exact is not None: + return exact + matches = [m for m in catalog if m.lower().startswith(wanted)] + if len(matches) > 1: + raise AmbiguousAliasError(wanted, provider, matches) + return matches[0] if matches else None + + def get_authenticated_provider_slugs( current_provider: str = "", user_providers: dict = None, custom_providers: list | None = None ) -> list[str]: diff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.py index ff766cbdb1c84..565932522c0f0 100644 --- a/hermes_cli/model_switch_providers.py +++ b/hermes_cli/model_switch_providers.py @@ -1132,6 +1132,12 @@ def _build_curated_lists(current_provider: str, current_base_url: str, current_m from hermes_cli.models import OPENROUTER_MODELS, _PROVIDER_MODELS, get_curated_nous_model_ids curated: dict[str, list[str]] = dict(_PROVIDER_MODELS) curated["openrouter"] = [mid for mid, _ in OPENROUTER_MODELS] + # Plugin profiles without a static row: their fallback_models are the curated floor, so the + # non-blocking GUI read (cold catalog cache) lists them instead of an empty provider row. + from providers import list_providers + for _pp in list_providers(): + if _pp.fallback_models and not curated.get(_pp.name): + curated[_pp.name] = list(_pp.fallback_models) # Remote manifest so new Portal models surface without a release; in-repo snapshot fallback. curated["nous"] = get_curated_nous_model_ids() if "ollama-cloud" not in curated: diff --git a/hermes_cli/models.py b/hermes_cli/models.py index 6fa3ca2076492..b31397f6489bc 100644 --- a/hermes_cli/models.py +++ b/hermes_cli/models.py @@ -1550,7 +1550,9 @@ def _profile_live_catalog(normalized: str) -> Optional[list[str]]: except Exception as exc: # a failed subprocess launch degrades to the curated list, like api_key below logger.debug("external_process catalog fetch failed for %s: %s", normalized, exc) live = None - return list(live) if live else (list(profile.fallback_models) or None) + # Same merge as setup (`_model_flow_plugin_provider`) so /model, the Desktop picker and + # `hermes model` offer one list: live ids plus any pinned id the probe omitted. + return merge_profile_catalog(normalized, profile, list(live) if live else None) if not (profile.auth_type == "api_key" and profile.base_url): return list(profile.fallback_models) or None api_key, base_url = _api_key_credentials(normalized) diff --git a/hermes_cli/models_validate.py b/hermes_cli/models_validate.py index 0deaaff31531f..6290775e7c635 100644 --- a/hermes_cli/models_validate.py +++ b/hermes_cli/models_validate.py @@ -539,6 +539,27 @@ def _validate_bedrock(req: _Request) -> Optional[dict[str, Any]]: return None +def _validate_external_process(req: _Request) -> Optional[dict[str, Any]]: + """Process providers have no HTTP listing: the picker's list (``provider_model_ids`` — the + CLI's live catalog merged with the declared one) plus the profile's short aliases is the whole + truth, so a listed id is accepted outright and an unlisted one gets the catalog verdict without + the misleading "endpoint was unreachable" note.""" + from providers import get_provider_profile + + profile = get_provider_profile(req.normalized) + if profile is None or profile.auth_type != "external_process": + return None + if req.lookup.lower() in {k.lower() for k in profile.model_aliases}: + return _accept() + catalog = _static_catalog(req.normalized) or list(profile.fallback_models) + match = _match_in_catalog(req.lookup, catalog, case_insensitive=True) + if match.exact: + return _accept() + return match.verdict(req) or _soft_accept( + f"Note: `{req.requested}` is not declared by {profile.display_name or profile.name}." + f"{match.suggestion_text}\n The model may still work if the local client accepts it.") + + def _validate_catalog_fallback(req: _Request) -> dict[str, Any]: """/models unreachable: validate against the curated ``provider_model_ids()`` list so gateway /model switches keep working while a provider's endpoint is down (otherwise switch_model() would @@ -578,7 +599,7 @@ def _for(*providers: str) -> Callable[[_Request], bool]: # (gate, branch): the branch runs when the gate passes; the first non-None verdict wins. ORDER IS # BEHAVIOR: moa → whitespace → OpenRouter preset parse → LM Studio → Ollama native → custom → # codex/xai static → MiniMax → managed local (staged library) → Anthropic native → -# Anthropic Messages → live listing → Bedrock → curated-catalog fallback (always decides). +# Anthropic Messages → external process → live listing → Bedrock → curated-catalog fallback (always decides). _LADDER: tuple[tuple[Callable[[_Request], bool], Callable[[_Request], Optional[dict[str, Any]]]], ...] = ( (_for("moa"), _validate_moa), (lambda req: True, _reject_whitespace), @@ -591,6 +612,7 @@ def _for(*providers: str) -> Callable[[_Request], bool]: (_for("llamacpp", "llama.cpp", "llama-cpp"), _validate_managed_local), (_for("anthropic"), _validate_anthropic), (lambda req: req.api_mode == "anthropic_messages", _validate_anthropic_messages), + (lambda req: True, _validate_external_process), (lambda req: True, _validate_live_listing), # API unreachable — accept and persist, but warn so typos don't silently break things. (_for("bedrock"), _validate_bedrock), diff --git a/hermes_cli/plugin_dev.py b/hermes_cli/plugin_dev.py index 3718c7b6314d9..ed03cea55dc66 100644 --- a/hermes_cli/plugin_dev.py +++ b/hermes_cli/plugin_dev.py @@ -73,6 +73,11 @@ def _doctor_runtime(plugin_path: Path): raise _DoctorLoadError( f"Expected one plugin manifest, discovered {len(manifests)} under {copied}") manifest = manifests[0] + if manifest.kind == "model-provider": + with _load_model_provider(copied, manifest) as registered: + yield SimpleNamespace(manifest=manifest, manager=manager, registered_tools=(), + registered_hooks=(), registered_providers=registered) + return manager._load_plugin(manifest) loaded = manager._plugins.get(manifest.key or manifest.name) if loaded is None: @@ -83,7 +88,7 @@ def _doctor_runtime(plugin_path: Path): raise _DoctorLoadError("Plugin registration did not enable the runtime record") yield SimpleNamespace( manifest=manifest, manager=manager, registered_tools=tuple(sorted(loaded.tools_registered)), - registered_hooks=tuple(loaded.hooks_registered)) + registered_hooks=tuple(loaded.hooks_registered), registered_providers=()) finally: entries_after = {entry.name: entry for entry in registry._snapshot_entries()} changed_names = { @@ -112,6 +117,40 @@ def _is_plugin_module(name: str) -> bool: return name == "hermes_plugins" or name.startswith("hermes_plugins.") +@contextmanager +def _load_model_provider(copied: Path, manifest): + """Doctor path for ``kind: model-provider``: those register a ProviderProfile at import through + providers/ discovery (PluginManager skips the kind), so demanding ``register(ctx)`` would fail + every valid provider plugin. Registry additions are undone on exit.""" + import providers + + # The live install may already have imported this very plugin (same directory name) during + # startup discovery; import the copy fresh and put the live module/profiles back afterwards. + module_name = f"_hermes_user_provider_{copied.name.replace('-', '_')}" + prior_module = sys.modules.pop(module_name, None) + before = dict(providers._REGISTRY) + before_aliases = dict(providers._ALIASES) + try: + providers._import_plugin_dir(copied, "user") + registered = tuple(sorted( + name for name, profile in providers._REGISTRY.items() if before.get(name) is not profile)) + if not registered: + raise _DoctorLoadError( + "model-provider plugin registered no ProviderProfile at import (see the warning above)") + yield registered + finally: + for name in [n for n, p in providers._REGISTRY.items() if before.get(n) is not p]: + providers._REGISTRY.pop(name) + providers._SOURCES.pop(name, None) + providers._REGISTRY.update(before) + providers._ALIASES.clear() + providers._ALIASES.update(before_aliases) + providers._PROVIDER_LIST_CACHE = None + sys.modules.pop(module_name, None) + if prior_module is not None: + sys.modules[module_name] = prior_module + + @dataclass(frozen=True) class DoctorFinding: level: Literal["error", "warning"] @@ -125,6 +164,7 @@ class DoctorReport: findings: list[DoctorFinding] = field(default_factory=list) registered_tools: tuple[str, ...] = () registered_hooks: tuple[str, ...] = () + registered_providers: tuple[str, ...] = () @property def ok(self) -> bool: @@ -147,7 +187,8 @@ def format_text(self) -> str: if self.ok: lines.append(" OK: runtime discovery, manifest parsing, import, and registration passed") lines.append( - f" registrations: {len(self.registered_tools)} tool(s), {len(self.registered_hooks)} hook(s)") + f" registrations: {len(self.registered_tools)} tool(s), {len(self.registered_hooks)} hook(s)" + + (f", provider(s): {', '.join(self.registered_providers)}" if self.registered_providers else "")) return "\n".join(lines) @@ -294,6 +335,7 @@ def doctor_plugin(target: str | os.PathLike[str] | None = None) -> DoctorReport: report.manifest = host.manifest report.registered_tools = host.registered_tools report.registered_hooks = host.registered_hooks + report.registered_providers = host.registered_providers from hermes_cli.plugins import VALID_HOOKS diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py index a16a7af3d667f..a234264c446a5 100644 --- a/hermes_cli/plugins_cmd.py +++ b/hermes_cli/plugins_cmd.py @@ -165,10 +165,6 @@ def _scan_plugin_tree(plugin_dir: Path, identifier: str, *, force: bool, scan_de return result -# Highest ``manifest_version`` this installer understands; breaking schema changes bump it. -_SUPPORTED_MANIFEST_VERSION = 1 - - def _plugins_dir() -> Path: """Return the user plugins directory, creating it if needed.""" plugins = get_hermes_home() / "plugins" @@ -595,11 +591,14 @@ def _check_manifest_version(manifest: dict, plugin_name: str) -> None: raise PluginOperationError( f"Plugin '{plugin_name}' has invalid manifest_version '{mv}' (expected an integer).", ) from None - if mv_int > _SUPPORTED_MANIFEST_VERSION: + # Shared with the runtime loader so the installer can never drift behind what the loader + # accepts (#85879): a private cap here refused v2 manifests the runtime happily loads. + from hermes_cli.plugins_manifest import SUPPORTED_MANIFEST_VERSION + if mv_int > SUPPORTED_MANIFEST_VERSION: from hermes_cli.config import recommended_update_command raise PluginOperationError( f"Plugin '{plugin_name}' requires manifest_version {mv}, " - f"but this installer only supports up to {_SUPPORTED_MANIFEST_VERSION}. " + f"but this Hermes supports up to {SUPPORTED_MANIFEST_VERSION}. " f"Run {recommended_update_command()} to update Hermes.", ) from None diff --git a/providers/base.py b/providers/base.py index ec754709c7a71..caba1ca9ddc8a 100644 --- a/providers/base.py +++ b/providers/base.py @@ -97,6 +97,11 @@ class ProviderProfile: # top-level fields rather than ignoring them. supports_prompt_cache_key: bool = False + # Private replay carriers use a namespaced '.native_assistant' type + # in reasoning_details. Only this profile may receive its matching carrier; + # other providers (including an unregistered fallback) get ordinary details only. + native_reasoning_details_type: str | None = None + # ── External-process providers (auth_type="external_process") ── # An agent CLI driven over stdio (ACP) rather than an HTTP endpoint. These # describe how to launch it; hermes_cli/auth.py's @@ -112,6 +117,9 @@ class ProviderProfile: # fallback_models: curated list shown in /model picker when live fetch fails. # Only agentic models that support tool calling should appear here. fallback_models: tuple = () + # model_aliases: short name -> id in fallback_models, for providers whose catalog is not + # in models.dev (external processes); `/model ` resolves here before core guessing. + model_aliases: dict = field(default_factory=dict) # hostname: base hostname for URL→provider reverse-mapping in model_metadata.py # e.g. "api.gmi-serving.com". Derived from base_url when empty. @@ -236,6 +244,14 @@ def default_vision_model(self) -> str | None: """ return None + def get_model_context_length(self, model: str) -> int | None: + """Provider-qualified context bound; explicit user overrides take precedence.""" + return None + + def get_usage_cost(self, model: str, usage: Any) -> Any | None: + """Optional CostResult from canonical usage; distinguish estimates from invoices.""" + return None + def get_max_tokens(self, model: str | None) -> int | None: """Return the default max_tokens cap for *model*. @@ -304,6 +320,16 @@ def create_client(self, **client_kwargs: Any) -> Any | None: """ return None + def setup_status(self, **kwargs: Any) -> dict[str, Any] | None: + """External-process providers: ``{available, logged_in, plan, detail, login_command}`` from the + CLI itself so setup can gate on login. ``None`` = nothing to report beyond executable presence.""" + return None + + def discover_models(self, **kwargs: Any) -> list[dict[str, Any]] | None: + """External-process providers: the account's live picker as ``[{id, label, note}]`` without + any inference request; ``None`` falls back to ``fallback_models``.""" + return None + def fetch_models( self, *, diff --git a/tests/agent/test_provider_client_cancel.py b/tests/agent/test_provider_client_cancel.py new file mode 100644 index 0000000000000..33fd632eec789 --- /dev/null +++ b/tests/agent/test_provider_client_cancel.py @@ -0,0 +1,62 @@ +"""Request-owned non-HTTP transports must participate in interruption.""" + +import subprocess +import sys +import threading + +from agent.client_lifecycle import ClientLifecycleMixin + + +class Agent(ClientLifecycleMixin): + socket_sweeps = 0 + + def _client_log_context(self): + return "provider=test" + + def _force_close_tcp_sockets(self, client): + self.socket_sweeps += 1 + return 0 + + +def test_cross_thread_cancel_stops_real_provider_process(): + proc = subprocess.Popen( + [sys.executable, "-c", "import time; time.sleep(60)"], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + class Client: + def cancel(self): + proc.terminate() + + agent = Agent() + client = Client() + try: + thread = threading.Thread( + target=agent._abort_request_openai_client, + args=(client,), + kwargs={"reason": "interrupt_abort"}, + ) + thread.start() + thread.join(timeout=2) + assert not thread.is_alive() + assert proc.wait(timeout=2) is not None + assert agent.socket_sweeps == 0 + finally: + if proc.poll() is None: + proc.kill() + proc.wait(timeout=5) + + +def test_dynamic_attributes_do_not_opt_http_clients_into_cancel(): + calls = [] + + class Client: + def __getattr__(self, name): + return lambda: calls.append(name) + + agent = Agent() + agent._abort_request_openai_client(Client(), reason="interrupt_abort") + assert agent.socket_sweeps == 1 + assert calls == [] diff --git a/tests/agent/test_provider_history_parity.py b/tests/agent/test_provider_history_parity.py new file mode 100644 index 0000000000000..cf7f9b5b03427 --- /dev/null +++ b/tests/agent/test_provider_history_parity.py @@ -0,0 +1,36 @@ +"""Provider-native replay carriers stay private to their owning provider.""" +from copy import deepcopy + +from agent.transports.chat_completions import ChatCompletionsTransport +from providers.base import ProviderProfile + +OPENROUTER = "https://openrouter.ai/api/v1" + + +def test_native_carriers_follow_only_their_owner_on_each_request(): + owner = ProviderProfile(name="native-owner", base_url="process://native-owner") + owner.native_reasoning_details_type = "native-owner.native_assistant" + carrier = {"type": owner.native_reasoning_details_type, "messages": [{"text": "private"}]} + standard = {"type": "reasoning.encrypted", "data": "opaque-signature"} + history = [{"role": "assistant", "content": "answer", "reasoning_details": [carrier, standard]}] + original = deepcopy(history) + transport = ChatCompletionsTransport() + + # The declaring profile gets its carrier on its own (non-HTTP) route, on every request, + # including after another provider served a turn in between; the other provider on a + # replaying route sees standard records only. + for profile in (owner, ProviderProfile(name="other"), owner): + base_url = owner.base_url if profile is owner else OPENROUTER + wire = transport.build_kwargs("test", history, provider_profile=profile, base_url=base_url)["messages"] + expected = [carrier, standard] if profile is owner else [standard] + assert wire[0]["reasoning_details"] == expected + assert history == original + + # No declaring profile: a replaying route keeps standard records, a strict route drops the + # field wholesale (#70233) — never the stored history. + assert transport.build_kwargs("test", history, base_url=OPENROUTER)["messages"][0]["reasoning_details"] == [standard] + assert "reasoning_details" not in transport.build_kwargs("test", history, base_url="https://api.groq.com/openai/v1")["messages"][0] + assert history == original + + only_native = [{"role": "assistant", "content": "answer", "reasoning_details": [carrier]}] + assert "reasoning_details" not in transport.convert_messages(only_native, base_url=OPENROUTER)[0] diff --git a/tests/agent/test_stream_reasoning_details.py b/tests/agent/test_stream_reasoning_details.py new file mode 100644 index 0000000000000..906f6415c5c95 --- /dev/null +++ b/tests/agent/test_stream_reasoning_details.py @@ -0,0 +1,98 @@ +"""Opaque reasoning records survive both collectors and durable replay.""" + +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest +from openai import OpenAI +from openai.types.chat import ChatCompletion + +from agent.chat_completion_helpers import build_assistant_message, interruptible_streaming_api_call +from agent.chat_completion_helpers_relay import RelayChatAccumulator +from agent.transports.chat_completions import ChatCompletionsTransport +from hermes_state import SessionDB +from run_agent import AIAgent + + +@pytest.mark.parametrize("collector", ["main", "relay"]) +@pytest.mark.parametrize("delivery", ["final", "multiple", "absent"]) +def test_stream_reasoning_details_survive_replay(tmp_path, collector, delivery): + details = [ + {"type": "opaque.native", "version": 1, "messages": [ + {"type": "thinking", "signature": " signed+/=\n", "thinking": "α"}, + {"type": "text", "text": "hello"}, + {"type": "redacted_thinking", "data": "AA+/=="}], + "projection": {"content": "hello world", "tool_calls": []}}, + {"type": "opaque.future", "index": 7, "unknown": [None, False, {"signature": "\r\n"}]}, + ] if delivery != "absent" else [] + deltas = [{"role": "assistant", "content": "hello"}, {"content": " world"}] + if delivery == "multiple": + deltas[0]["reasoning_details"] = details[:1] + deltas.append({"reasoning_details": []}) + deltas.append({"reasoning_details": details[1:]}) + elif delivery == "final": + deltas.append({"reasoning_details": details}) + requests = [] + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_args): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)))) + if not self.path.endswith("/chat/completions"): + self.send_response(404) + self.end_headers() + return + requests.append(body) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + for index, delta in enumerate(deltas): + chunk = {"id": "local-proof", "object": "chat.completion.chunk", "created": 1, + "model": "test-model", "choices": [{"index": 0, "delta": delta, + "finish_reason": "stop" if index == len(deltas) - 1 else None}]} + self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode()) + self.wfile.flush() + self.wfile.write(b"data: [DONE]\n\n") + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + base_url = f"http://127.0.0.1:{server.server_port}/v1" + agent = AIAgent(api_key="local-test", base_url=base_url, provider="custom", model="test-model", + platform="subagent", quiet_mode=True, skip_memory=True, skip_context_files=True, + enabled_toolsets=[], save_trajectories=False) + kwargs = {"model": "test-model", "messages": [{"role": "user", "content": "hi"}]} + try: + if collector == "main": + response = interruptible_streaming_api_call(agent, kwargs) + else: + acc = RelayChatAccumulator() + with OpenAI(api_key="local-test", base_url=base_url) as client: + with client.chat.completions.create(**kwargs, stream=True) as stream: + for chunk in stream: + acc.observe(chunk.model_dump(mode="json")) + recorded = acc.finalize() + recorded["choices"][0]["index"] = 0 + response = ChatCompletion.model_validate({"id": "local-proof", "created": 1, + "object": "chat.completion", **recorded}) + assert requests and all(request["stream"] is True for request in requests) + assert response.choices[0].message.content == "hello world" + assert getattr(response.choices[0].message, "reasoning_details", None) == (details or None) + normalized = ChatCompletionsTransport().normalize_response(response) + assert normalized.reasoning_details == (details or None) + message = build_assistant_message(agent, normalized, normalized.finish_reason) + assert message.get("reasoning_details") == (details or None) + db_path = tmp_path / "replay.db" + with SessionDB(db_path=db_path) as db: + db.create_session("reasoning-proof", source="cli") + db.append_messages_batch("reasoning-proof", [message]) + with SessionDB(db_path=db_path) as db: + replay = db.get_messages_as_conversation("reasoning-proof") + assert replay[0].get("reasoning_details") == (details or None) + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) diff --git a/tests/hermes_cli/test_model_flow_external_process_setup.py b/tests/hermes_cli/test_model_flow_external_process_setup.py new file mode 100644 index 0000000000000..408cca212280c --- /dev/null +++ b/tests/hermes_cli/test_model_flow_external_process_setup.py @@ -0,0 +1,76 @@ +"""`hermes model` for a process provider gates on the CLI's login and lists its live picker. + +The generic plugin flow (``_model_flow_plugin_provider``) drives a registered ``external_process`` +profile end to end: credential resolution, the optional ``setup_status`` login gate, and the +optional ``discover_models`` rows (ids + per-row notes) merged with the pinned catalog. +""" +import sys +from unittest.mock import patch + +import pytest + +from hermes_cli import model_setup_flows as flows +from providers import register_provider +from providers.base import ProviderProfile + + +class _Profile(ProviderProfile): + def __init__(self, status, live): + super().__init__(name="proc-provider", display_name="Proc Provider", auth_type="external_process", + base_url="process://proc-provider", process_command=sys.executable, + fallback_models=("pinned-a", "pinned-b")) + self._status, self._live = status, live + + def setup_status(self, **_): + return self._status + + def discover_models(self, **_): + return self._live + + +def _run(profile, capsys): + register_provider(profile) + picked = {} + + def fake_pick(model_list, prompt, **kwargs): + picked.update(models=model_list, notes=kwargs.get("notes")) + return model_list[0] if model_list else None + + with patch.object(flows, "_pick_model_or_prompt", fake_pick), \ + patch.object(flows, "_finish_model", lambda *a, **k: picked.update(finished=a[0])): + flows._model_flow_plugin_provider({}, profile.name) + return picked, capsys.readouterr().out + + +def test_logged_out_without_tty_stops_with_login_instruction(capsys): + status = {"available": True, "logged_in": False, "plan": "", "login_command": ["claude", "auth", "login"], + "detail": "Claude Code is installed but not logged in. Run `claude auth login`, then select this provider again."} + with patch("sys.stdin.isatty", return_value=False): + picked, out = _run(_Profile(status, None), capsys) + assert not picked and "not logged in" in out and "claude auth login" in out + + +def test_logged_in_lists_live_picker_with_notes(capsys): + status = {"available": True, "logged_in": True, "plan": "Claude Pro", "login_command": ["claude", "auth", "login"], "detail": ""} + live = [{"id": "claude-sonnet-5[1m]", "label": "Sonnet 5", "note": ""}, + {"id": "claude-fable-5-1[1m]", "label": "Fable 5.1", "note": "usage credits"}] + picked, out = _run(_Profile(status, live), capsys) + assert "Claude Pro" in out + # Live rows are offered together with the pinned catalog so no declared id disappears. + assert set(picked["models"]) >= {"claude-sonnet-5[1m]", "claude-fable-5-1[1m]", "pinned-a", "pinned-b"} + assert picked["notes"] == {"claude-fable-5-1[1m]": "usage credits"} + assert picked["finished"] == picked["models"][0] + + +@pytest.mark.parametrize("via_status", [True, False]) +def test_missing_cli_stops_before_any_pick(capsys, via_status): + """Missing binary: the generic credential step refuses (core check) and, when the profile also + reports it, its own ``detail`` is what the user reads. Either way nothing is picked or saved.""" + detail = "Claude Code is not installed (no `claude` on PATH). Install it with `npm install -g @anthropic-ai/claude-code`." + status = {"available": False, "logged_in": False, "plan": "", "login_command": None, "detail": detail} + profile = _Profile(status if via_status else None, None) + if not via_status: + profile.process_command = "definitely-not-a-real-cli-binary" + picked, out = _run(profile, capsys) + assert not picked + assert (detail in out) if via_status else ("Could not find" in out and "definitely-not-a-real-cli-binary" in out) diff --git a/tests/hermes_cli/test_model_switch_external_process_alias.py b/tests/hermes_cli/test_model_switch_external_process_alias.py new file mode 100644 index 0000000000000..078444ea6da45 --- /dev/null +++ b/tests/hermes_cli/test_model_switch_external_process_alias.py @@ -0,0 +1,53 @@ +"""`/model ` stays on an external-process provider that declares the alias. + +Process providers are not in models.dev, so ``list_provider_models`` returns ``[]`` and +the alias fallback used to route ``haiku`` to whichever authenticated HTTP provider was +handy (live repro: Copilot, then HTTP 400 on the next turn). +""" +from unittest.mock import patch + +from hermes_cli.model_switch import switch_model +from providers.base import ProviderProfile + +_ACCEPTED = {"accepted": True, "persist": True, "recognized": True, "message": None} + + +def _switch(raw_input, profile): + with patch("hermes_cli.model_switch.list_provider_models", return_value=[]), \ + patch("providers.get_provider_profile", return_value=profile), \ + patch("hermes_cli.model_switch.get_authenticated_provider_slugs", return_value=["copilot", "anthropic"]), \ + patch("hermes_cli.models_validate.validate_requested_model", return_value=_ACCEPTED), \ + patch("hermes_cli.models.detect_provider_for_model", return_value=("copilot", "claude-haiku-4.5")), \ + patch("hermes_cli.model_switch.get_model_info", return_value=None), \ + patch("hermes_cli.model_switch.get_model_capabilities", return_value=None), \ + patch("hermes_cli.runtime_provider.resolve_runtime_provider", + return_value={"api_key": "external-process", "base_url": profile.base_url, "api_mode": "chat_completions"}): + return switch_model(raw_input=raw_input, current_provider=profile.name, + current_model="claude-sonnet-5[1m]", current_base_url=profile.base_url, + user_providers={}, custom_providers=[]) + + +def test_alias_and_model_id_stay_on_external_process_provider(): + profile = ProviderProfile( + name="proc-provider", auth_type="external_process", base_url="process://proc-provider", + fallback_models=("claude-sonnet-5[1m]", "claude-haiku-4-5-20251001", "claude-opus-5[1m]", "claude-opus-4-8[1m]"), + model_aliases={"opus": "claude-opus-5[1m]", "fable": "claude-fable-5-1[1m]"}) + for typed, expected in (("haiku", "claude-haiku-4-5-20251001"), ("claude-opus-5[1m]", "claude-opus-5[1m]"), + ("Claude-Opus-5", "claude-opus-5[1m]"), ("opus", "claude-opus-5[1m]"), + ("fable", "claude-fable-5-1[1m]")): + result = _switch(typed, profile) + assert result.success, result.error_message + assert (result.target_provider, result.new_model) == (profile.name, expected), typed + + +def test_declared_process_model_validates_without_endpoint_warning(): + from hermes_cli.models_validate import validate_requested_model + profile = ProviderProfile( + name="proc-provider", auth_type="external_process", base_url="process://proc-provider", + fallback_models=("claude-sonnet-5[1m]", "claude-haiku-4-5-20251001")) + with patch("providers.get_provider_profile", return_value=profile), \ + patch("hermes_cli.models.fetch_api_models", side_effect=AssertionError("no HTTP probe for process://")): + verdict = validate_requested_model("claude-haiku-4-5-20251001", profile.name, base_url=profile.base_url) + assert verdict["accepted"] and verdict["recognized"] and not verdict.get("message") + unknown = validate_requested_model("claude-haiku-9", profile.name, base_url=profile.base_url) + assert "unreachable" not in (unknown.get("message") or "") diff --git a/tests/hermes_cli/test_plugin_dev.py b/tests/hermes_cli/test_plugin_dev.py index 253ed27274d67..094200ea1c0d0 100644 --- a/tests/hermes_cli/test_plugin_dev.py +++ b/tests/hermes_cli/test_plugin_dev.py @@ -259,3 +259,32 @@ def _enospc(*_args, **_kwargs): # exact window where a stranded hermes-plugin-doctor-* dir was observed. leftovers = list(scratch.glob("hermes-plugin-doctor-*")) assert leftovers == [], f"stranded doctor temp dirs: {leftovers}" + + +def test_doctor_loads_model_provider_plugins_through_provider_discovery(tmp_path: Path) -> None: + """`kind: model-provider` registers a ProviderProfile at import and has no register(ctx); + doctor must judge it by that contract and leave the live registry untouched.""" + import providers + from hermes_cli.plugin_dev import doctor_plugin + + plugin = tmp_path / "acme-provider" + plugin.mkdir() + (plugin / "plugin.yaml").write_text("name: acme-provider\nkind: model-provider\n", encoding="utf-8") + (plugin / "__init__.py").write_text( + "from providers import register_provider\nfrom providers.base import ProviderProfile\n" + "register_provider(ProviderProfile(name='acme-doctor-probe', auth_type='external_process',\n" + " process_command='acme', aliases=('acme-alias',)))\n", + encoding="utf-8") + registry_before = dict(providers._REGISTRY) + + report = doctor_plugin(plugin) + assert report.ok, report.format_text() + assert report.registered_providers == ("acme-doctor-probe",) + assert "provider(s): acme-doctor-probe" in report.format_text() + assert providers._REGISTRY == registry_before + assert "acme-alias" not in providers._ALIASES + + (plugin / "__init__.py").write_text("x = 1\n", encoding="utf-8") + report = doctor_plugin(plugin) + assert not report.ok + assert any("registered no ProviderProfile" in f.message for f in report.findings) diff --git a/tests/hermes_cli/test_plugin_install_manifest_version.py b/tests/hermes_cli/test_plugin_install_manifest_version.py new file mode 100644 index 0000000000000..938762f406cfa --- /dev/null +++ b/tests/hermes_cli/test_plugin_install_manifest_version.py @@ -0,0 +1,84 @@ +"""Installer accepts every manifest_version the runtime loader supports (#85879). + +The installer used to carry its own private manifest-version cap, which +drifted behind the loader's ``SUPPORTED_MANIFEST_VERSION`` and refused v2 +plugins the runtime happily loads. These tests install through the real +clone path so the two can never split again on the next bump. +""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest +import yaml + +from hermes_cli.plugins import SUPPORTED_MANIFEST_VERSION + + +def _git(repo: Path, *args: str) -> str: + result = subprocess.run( + ["git", *args], cwd=repo, check=True, capture_output=True, text=True + ) + return result.stdout.strip() + + +def _plugin_repo(root: Path, manifest: dict) -> Path: + repo = root / "repo" + repo.mkdir() + _git(repo, "init", "-q") + _git(repo, "config", "user.email", "fixture@example.com") + _git(repo, "config", "user.name", "Fixture") + (repo / "plugin.yaml").write_text(yaml.safe_dump(manifest), encoding="utf-8") + _git(repo, "add", ".") + _git(repo, "commit", "-qm", "init") + return repo + + +@pytest.mark.parametrize( + "manifest_version", list(range(1, SUPPORTED_MANIFEST_VERSION + 1)) +) +def test_install_accepts_every_loader_supported_manifest_version( + monkeypatch, tmp_path, manifest_version +): + from hermes_cli.plugins_cmd import _install_plugin_core + + repo = _plugin_repo( + tmp_path, + {"name": "demo", "version": "1.0.0", "manifest_version": manifest_version}, + ) + home = tmp_path / "home" + monkeypatch.setenv("HERMES_HOME", str(home)) + + target, manifest, name = _install_plugin_core(repo.as_uri(), force=False) + + assert name == "demo" + assert target.exists() + assert int(manifest["manifest_version"]) == manifest_version + + +def test_manifest_version_above_shared_support_is_refused_cleanly( + monkeypatch, tmp_path +): + from hermes_cli.plugins_cmd import PluginOperationError, _install_plugin_core + + repo = _plugin_repo( + tmp_path, + { + "name": "demo", + "version": "1.0.0", + "manifest_version": SUPPORTED_MANIFEST_VERSION + 1, + }, + ) + home = tmp_path / "home" + monkeypatch.setenv("HERMES_HOME", str(home)) + + with pytest.raises( + PluginOperationError, + match=rf"supports up to {SUPPORTED_MANIFEST_VERSION}\b", + ): + _install_plugin_core(repo.as_uri(), force=False) + + assert not (home / "plugins" / "demo").exists() + assert not (home / "plugins" / ".install-metadata.json").exists() diff --git a/tests/tools/test_delegate_external_provider.py b/tests/tools/test_delegate_external_provider.py new file mode 100644 index 0000000000000..6b48b242fc371 --- /dev/null +++ b/tests/tools/test_delegate_external_provider.py @@ -0,0 +1,23 @@ +"""A selected external-process provider must survive child command resolution.""" +import sys +from types import SimpleNamespace + +import pytest + +from providers import register_provider +from providers.base import ProviderProfile +from tools.delegate_tool_config import _resolve_child_runtime + + +@pytest.mark.parametrize("external", [True, False]) +def test_pinned_command_retains_selected_external_provider(external): + profile = ProviderProfile(name="test-process-provider", display_name="Test", auth_type="external_process" if external else "api_key") + register_provider(profile) + parent = SimpleNamespace(model="test-model", provider=profile.name, base_url="process://test", api_mode="chat_completions", acp_args=[]) + result = _resolve_child_runtime( + parent, {}, "external-process", model=None, override_provider=profile.name, + override_base_url=None, override_api_key=None, override_api_mode=None, + override_acp_command=sys.executable, override_acp_args=[], + ) + assert result["provider"] == (profile.name if external else "copilot-acp") + assert result["acp_command"] == sys.executable diff --git a/tests/tui_gateway/test_external_process_picker.py b/tests/tui_gateway/test_external_process_picker.py new file mode 100644 index 0000000000000..bbe75d365caa9 --- /dev/null +++ b/tests/tui_gateway/test_external_process_picker.py @@ -0,0 +1,142 @@ +"""A user-installed ``external_process`` provider must survive shared picker discovery and native selection. + +Drives a fake process profile (registered like a ``$HERMES_HOME/plugins/`` model-provider plugin +would) through ``list_available_providers``, ``provider_model_ids``, the TUI/Desktop ``model.options`` +RPC, the ``hermes model`` setup picker and a session-scoped ``config.set model`` switch. +""" +import shutil +import sys +from pathlib import Path + +import pytest + +from providers import register_provider +from providers.base import ProviderProfile + +LIVE = ["fake-large[1m]", "fake-credit[1m]", "fake-small"] + + +class _FakeProcessProfile(ProviderProfile): + def fetch_models(self, **_): + return list(LIVE) + + def discover_models(self, **_): + return [{"id": m, "label": m, "note": "usage credits" if "credit" in m else ""} for m in LIVE] + + def setup_status(self, **_): + return {"available": True, "logged_in": True, "plan": "Fake Pro", "detail": "", "login_command": None} + + +@pytest.fixture +def picker_env(monkeypatch, tmp_path): + # Real registries/config/runtime resolution, isolated from the user's home. + monkeypatch.setattr(Path, "home", lambda: tmp_path) + home = tmp_path / "hermes" + home.mkdir() + monkeypatch.setenv("HERMES_HOME", str(home)) + profile = _FakeProcessProfile( + name="fake-process-provider", display_name="Fake Process Provider", auth_type="external_process", + api_mode="chat_completions", base_url="process://fake-process-provider", process_command="fake-process-cli", + default_aux_model="fake-small", fallback_models=("fake-large[1m]", "fake-small", "fake-pinned-only"), + model_aliases={"large": "fake-large[1m]"}) + register_provider(profile) + real_which = shutil.which + monkeypatch.setattr(shutil, "which", + lambda cmd, *a, **kw: sys.executable if cmd == profile.process_command else real_which(cmd, *a, **kw)) + import agent.models_dev as models_dev + monkeypatch.setattr(models_dev, "fetch_models_dev", lambda *a, **kw: {}) + import hermes_cli.inventory as inventory + monkeypatch.setattr(inventory, "_prewarm_pricing_async", lambda *a, **kw: None) + return home, profile + + +def test_process_provider_reaches_every_shared_picker(picker_env, monkeypatch): + home, profile = picker_env + from hermes_cli.config import save_config + from hermes_cli.main_provider_setup import _build_provider_picker_rows + from hermes_cli.models import _PROVIDER_LABELS, list_available_providers, provider_model_ids + from tui_gateway import server + + assert any(row["id"] == profile.name for row in list_available_providers()) + rows, _ = _build_provider_picker_rows({}, "", _PROVIDER_LABELS, {}) + assert any(row[0] == profile.name for row in rows) + # The account's live picker (the profile's own probe) is what the shared pickers list, + # merged with the pinned catalog so a declared id the probe omits is still selectable. + ids = provider_model_ids(profile.name) + assert set(LIVE) <= set(ids) and "fake-pinned-only" in ids + + # GUI read path: a cold catalog cache must still list the pinned floor (never an empty row); + # an explicit refresh blocks on the profile's probe and adds the live ids. + response = server._methods["model.options"](1, {}) + assert "error" not in response, response + row = next(r for r in response["result"]["providers"] if r["slug"] == profile.name) + assert set(profile.fallback_models) <= set(row["models"]) + assert row["authenticated"] + response = server._methods["model.options"](1, {"refresh": True}) + row = next(r for r in response["result"]["providers"] if r["slug"] == profile.name) + assert set(LIVE) <= set(row["models"]) + + # Both native clients use model.options. The desktop explicit-only view + # must keep a configured process provider without borrowing API credentials. + save_config({"model": {"provider": profile.name, "default": profile.default_aux_model}}) + for explicit_only in (False, True): + response = server._methods["model.options"](1, {"explicit_only": explicit_only, "refresh": True}) + assert "error" not in response, response + row = next(r for r in response["result"]["providers"] if r["slug"] == profile.name) + assert set(LIVE) <= set(row["models"]) + assert row["is_current"] + assert row["authenticated"] + + # The setup picker dispatches the process row through the generic plugin flow and persists it. + from hermes_cli import main, model_setup_flows + from hermes_cli.config import load_config + selected = "fake-credit[1m]" + seen = {} + monkeypatch.setattr(main, "_pick_provider", lambda *a: profile.name) + + def fake_pick(model_list, prompt, **kwargs): + seen.update(models=model_list, notes=kwargs.get("notes")) + return selected + + monkeypatch.setattr(model_setup_flows, "_pick_model_or_prompt", fake_pick) + main.select_provider_and_model() + assert seen["notes"] == {"fake-credit[1m]": "usage credits"} + saved = load_config()["model"] + assert saved["provider"] == profile.name + assert saved["default"] == selected + assert saved["api_mode"] == profile.api_mode + assert saved["base_url"] == profile.base_url + + # An unavailable process must not overwrite an existing saved selection. + before = (home / "config.yaml").read_bytes() + monkeypatch.setattr(shutil, "which", lambda cmd, *a, **kw: None) + main.select_provider_and_model() + assert (home / "config.yaml").read_bytes() == before + + +def test_native_picker_selection_preserves_process_runtime(picker_env, monkeypatch): + home, profile = picker_env + from hermes_cli.config import load_config, save_config + from hermes_cli.models import provider_model_ids + from tui_gateway import server + + save_config(load_config()) # materialize defaults before checking session-only writes + config_before = (home / "config.yaml").read_bytes() + session = {"agent": None, "running": False} + monkeypatch.setitem(server._sessions, "process-picker", session) + models = provider_model_ids(profile.name) + assert models, "A registered process provider must expose selectable models" + for model in models: + response = server._methods["config.set"](2, { + "session_id": "process-picker", "key": "model", + "value": f"{model} --provider {profile.name} --session", + "confirm_expensive_model": True, + }) + assert "error" not in response, response + assert response["result"]["value"] == model + runtime = session["model_override"] + assert runtime["model"] == model + assert runtime["provider"] == profile.name + assert runtime["api_mode"] == profile.api_mode + assert runtime["base_url"] == profile.base_url + assert (home / "config.yaml").read_bytes() == config_before diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.py index 2b1390fa5314d..d85a04db0408b 100644 --- a/tools/delegate_tool_config.py +++ b/tools/delegate_tool_config.py @@ -542,8 +542,11 @@ def _resolve_child_runtime( # transport would run the child somewhere the user explicitly routed it away from. Normally unreachable # via delegate_task, which pre-validates the command in _resolve_delegation_credentials. if override_acp_command: - # Forced ACP transport requires provider copilot-acp for run_agent to init the client. - effective_provider, effective_api_mode = "copilot-acp", "chat_completions" + from providers import get_provider_profile + profile = get_provider_profile(effective_provider or "") + # A generic process command does not imply the legacy ACP protocol. + if profile is None or profile.auth_type != "external_process": + effective_provider, effective_api_mode = "copilot-acp", "chat_completions" # Reasoning: delegation.reasoning_effort > parent. Keep the raw value — a # YAML ``false`` must disable thinking, not coerce to "" and inherit. diff --git a/website/docs/developer-guide/model-provider-plugin.md b/website/docs/developer-guide/model-provider-plugin.md index 19a2e7f78cea9..777e5285ab9b3 100644 --- a/website/docs/developer-guide/model-provider-plugin.md +++ b/website/docs/developer-guide/model-provider-plugin.md @@ -270,6 +270,22 @@ The catalog cache is keyed on the profile's `process_command_env_vars` / `proces Selecting the row in `hermes model` (and the setup wizard) runs one generic flow keyed by the profile's `auth_type`: external-process profiles are launch-checked (`resolve_external_process_provider_credentials`), OAuth profiles need a live pool row (otherwise the flow prints `hermes auth add ` and stops), then the merged catalog is offered and `config.model` is persisted with the profile's `base_url`/`api_mode`. No `_model_flow_*` entry in core is needed. +#### Optional external-process hooks + +External-process profiles may implement `setup_status(**kwargs)` returning `{available, logged_in, plan, detail, login_command}` and `discover_models(**kwargs)` returning `[{id, label, note}]`. The generic flow gates on `logged_in` (running `login_command` inline on a TTY, printing `detail` otherwise) and, when `discover_models()` returns rows, offers them merged with `fallback_models`; `note` renders as a dim per-row annotation (`· usage credits`) and never hides a model. Keep `fetch_models()` returning the same ids so `/model` and the Desktop picker agree with setup. Both hooks must be cheap and must never perform inference; return `None` to fall back to `fallback_models`. + +For interruptible non-HTTP requests, implement a class-declared `cancel(self)` method. Hermes calls it from the interrupting thread after marking the request client unusable. It must return promptly and safely stop its own transport, including cancellation racing process startup; it must not close file descriptors owned by the request thread. The request owner still calls `close()` for cleanup. Clients without this method retain the existing socket-shutdown cancellation path. + +Declare `model_aliases` (`{"sonnet": "claude-sonnet-5[1m]"}`) for a catalog models.dev does not know: bare `/model ` and `/model ` resolve inside the process provider first, and `validate_requested_model` accepts a declared id without probing `process://`. + +Explicit external-process delegation retains the selected provider and its protocol when resolving the child command; an executable override alone does not change an external-process provider into ACP. + +Native clients may persist private assistant replay in `reasoning_details` with a namespaced `.native_assistant` type. Declare the identical string in `ProviderProfile.native_reasoning_details_type` (default `None`). Chat Completions request sanitization forwards that carrier only to its declaring profile, including after fallback or model switching; it removes other private carriers even if their source plugin is no longer installed. Standard reasoning details such as OpenRouter's `reasoning.encrypted` remain unchanged. Filtering is request-only: durable history remains intact for returning to the original provider. + +Providers may override `get_model_context_length(model)` with a qualified positive token bound, or return `None` for the existing lookup chain. Explicit configuration and endpoint-scoped overrides take precedence; the provider bound is consulted before generic caches and HTTP probes. Do not confuse a catalog maximum with an account entitlement. + +For a nonstandard cost surface, `get_usage_cost(model, usage)` may return an `agent.usage_pricing.CostResult`, or `None` for normal pricing. `usage` is a `CanonicalUsage` whose `raw_usage` retains response metadata when available. Classify native list-price totals as `estimated`, never `actual` or `included`; missing invoice information is not proof of zero charges. The default hooks return `None`, preserving existing providers. + ## Hook reference examples Look at these bundled plugins for idioms: diff --git a/website/docs/developer-guide/provider-runtime.md b/website/docs/developer-guide/provider-runtime.md index 38f4970223246..a1718fd343583 100644 --- a/website/docs/developer-guide/provider-runtime.md +++ b/website/docs/developer-guide/provider-runtime.md @@ -37,6 +37,13 @@ Fragments retain their explicit whitespace; normalization adds no intra-field se Main-stream and Relay recording retain the existing paragraph breaks between complete bold reasoning headings. Reasoning stays separate from the visible answer. +`delta.reasoning_details` is a list of opaque provider records. Both the main +stream and Relay recording append these records in arrival order without +flattening, merging, or rewriting their contents. Providers can emit complete +records on the final delta or across multiple deltas; omit the field on chunks +without new records. The collected records pass through response normalization +and assistant-message storage into session replay, including nested signed payloads. + ## Resolution precedence At a high level, provider resolution uses: