Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions agent/chat_completion_helpers_relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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(
Expand All @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions agent/client_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions agent/model_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 24 additions & 4 deletions agent/transports/chat_completions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`` /
Expand All @@ -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 ``<provider>.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)):
Expand Down Expand Up @@ -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]
Expand All @@ -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)

Expand Down
6 changes: 6 additions & 0 deletions agent/usage_pricing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
)


Expand All @@ -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(
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/src/app/shell/model-catalog-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down
13 changes: 10 additions & 3 deletions apps/desktop/src/lib/model-status-label.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
14 changes: 13 additions & 1 deletion apps/desktop/src/lib/model-status-label.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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}$/, '')

Expand Down
13 changes: 8 additions & 5 deletions hermes_cli/auth_model_picker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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))
Expand All @@ -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.

Expand Down Expand Up @@ -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"

Expand Down
56 changes: 52 additions & 4 deletions hermes_cli/model_setup_flows.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 ""), ""


Expand Down Expand Up @@ -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."""
Expand All @@ -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)

Expand Down
Loading
Loading