hermes-agent/hermes_cli/cli_chat_turn_mixin.py
Teknium 9bcbe7b5df
feat(i18n): pluggable, layered language packs across core, Desktop and TUI (#126296)
* feat(i18n): layered catalogs — plugin packs and user overlay over bundled locales

* feat(tui): i18n layer — en catalog, nanostore runtime, RPC pack loader, _keys.tui.json emitter

ui-tui/src/i18n/: en.ts (facade over topical siblings under en/), types.ts
(Translations + dotted TranslationKey derived from en), runtime.ts ($locale/
$catalog atoms, translateFrom active→en→key, pack merge with string→fn
wrapping for {0}/{1} placeholders), loader.ts (display.language →
i18n.catalog {lang, surface:'tui'}, English when the method is missing),
useT()/useLocale() hooks, t() for non-React code. useConfigSync feeds the
loader from the existing config.get full hydration. `npm run i18n:keys`
writes locales/_keys.tui.json (sorted flat key list) and runs before build.

* feat(plugins): provides_locales manifest field, ctx.register_locale/register_locale_dir, manifest-only language packs

* chore(tui): split en catalog siblings by lane (slash sibling)

* feat(plugins): validate language packs — parse, text-only, key-subset WARN against en / _keys exports

* feat(tui_gateway): i18n.languages / i18n.catalog RPC + regenerated contracts

* feat(config): display.language accepts any supported_languages() id, refuses unknown ids with the list

* docs(i18n): language packs user guide, pluggable display.language, plugin developer section, AGENTS notes

* feat(plugins): report language-pack layers in the mid-run activation summary

* feat(tui): wire status bar, composer placeholders, hotkey help and approval/clarify/confirm prompts through i18n

StatusRule maps compared state values (ready/running…/summoning) to catalog
text at render via displayStatus(); hotkeys()/placeholder() resolve lazily so
a pack that arrives after boot applies. Catalog grows to 81 keys.

* feat(desktop): pluggable app locales — registry, host.i18n.registerAppLocale, backend packs, keys emitter

- Locale widens to string (BundledLocale keeps the union); TRANSLATIONS stays
  the bundled record and every consumer resolves through the registry.
- src/i18n/registry.ts: registerAppLocale(id, {endonym, rtl, translations})
  layers partial packs (nested or flat dotted) over bundled/en via
  mergeTranslations; a string over a function-valued en entry becomes a
  positional {0}/{1} formatter; $appLocaleVersion bumps so translators
  re-render; per-source disposers + replaceAppLocaleSource for atomic swaps.
- Backend packs: i18n.languages + i18n.catalog {surface:'desktop'} feed the
  registry as source 'backend' (method-not-found is silent); re-synced on
  socket open, display.language change and profile switch. A saved pack-only
  language is promoted once its pack registers.
- SDK: host.i18n.registerAppLocale / languageOptions; ctx.i18n.registerAppLocale
  tracked for unload. Docs in the desktop plugin SDK guide + skill reference.
- Language switcher lists bundled ∪ registered ∪ backend, endonym-only; RTL
  from the registry (applyDocumentLocale takes rtl).
- npm run i18n:keys emits locales/_keys.desktop.json (wired into build).

* i18n(cli): route /topup + /subscription copy through t() (cli.billing.*, cli.subscription.*)

Module-level copy tables and modal choice tuples in cli_billing_mixin.py froze
English at import, before display.language was known. They are now key tables /
builder functions evaluated at call time; every user-facing line in the /usage
balance block, /subscription and the five /topup screens reads the catalog.
Choice VALUES stay English identifiers. Fragment-assembled status lines
(Plan: … → cancels · $x left · renews …) become full templates.

* i18n(gateway): exec-approval card contract + base/run/run_busy/run_inbound replies through t()

- base_exec_approval: EA_* English constants stay; add ea_header_text()/ea_reason_label_text()/
  ea_smart_deny_line_text()/ea_default_reason_text()/ea_action_labels()/approval_timed_out_notice()
  accessors; deadline + timed-out notice resolve via gateway.exec_approval.*
- BasePlatformAdapter._EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/_EA_ACTION_LABELS become
  properties (adapters still shadow them with markup class attrs)
- run.py: provider error replies table holds catalog keys; _CONTEXT_OVERFLOW_REPLY -> _context_overflow_reply()
- run_busy/run_inbound: typed approval + slash-confirm matchers accept English ∪ approval.inputs.* (t())
- locales/en.yaml: gateway.exec_approval/busy/errors/... namespaces

* i18n(cli): wire modal, loops, agent-setup mixins through t() (cli.* keys)

* i18n(platforms): route Slack, Matrix and Feishu user-facing text through t()

Exec-approval markup overrides (_EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/
_EA_ACTION_LABELS) become per-call properties over the shared
gateway.exec_approval.* contract keys, so Slack's 3000-char section budget
measures the resolved template. Slack _APPROVAL_DECISIONS/_CONFIRM_DECISIONS,
Feishu _APPROVAL_LABEL_MAP and Matrix _EA_LEGEND/_EA_TYPED_HINT turn into
key tables resolved at click time; the Matrix typed hints become whole
sentences per offered tier instead of spliced fragments. Slack button labels
are cut to 75 chars and select placeholders to 150 after translation; the
model-facing clarify fallback answer ('choice N') stays English while the
card copy localizes.

locales/en.yaml gains the gateway.exec_approval.* contract keys plus the
platform.shared.* / platform.slack.* / platform.matrix.* / platform.feishu.*
namespaces (and the keys for the other adapters wired in follow-up commits).

* i18n(gateway): run_turn / run_turn_runner / approval-settle copy through t()

- status hints, proxy errors, background task notices, progress heartbeats, session info lines
- tool progress chrome (tool_head/tool_pending/tool_preview/tool_verbose) shared by base.format_tool_event
- run_turn_runner:1406 Chinese clarify placeholder -> gateway.clarify.native_stream_placeholder (zh text kept in zh.yaml)
- _UNEXPECTED_SILENCE_REPLY/_CLARIFY_EXPIRED_NOTICE -> accessor functions

* i18n(platforms): route Google Chat and Teams user-facing text through t()

Google Chat clarify card, typing placeholder, orphan-card labels and the whole
/setup-files reply set (module constants become platform.google_chat.setup_files.*
keys resolved at reply time). The attachment-fallback notice that shipped
hardcoded in Spanish is keyed with an English en value; es.yaml carries the
original Spanish text for those four keys.

Teams approval card header/reason use the gateway.exec_approval.* contract,
_APPROVAL_LABELS becomes a key table resolved at click time, and the meeting
summary writer resolves its section headings/fallbacks per render.

* i18n(platforms): route LINE, WeCom, email, DingTalk, IRC and Home Assistant text through t()

LINE default copy constants become catalog keys resolved in __init__ (the
LINE_*_TEXT / extra.* operator overrides still win); the busy-ack bypass
matcher keys on the leading emoji marker only, so it keeps firing once the
gateway busy heads are localized. WeCom media size/format notices that shipped
hardcoded in Chinese are keyed with English en values and zh.yaml carries the
original Chinese text. DingTalk emotion bubbles resolve per send.

* i18n(cli): route /model switch output and -q status lines through t() (cli.model.*, cli.single_query.*)

Switch-summary labels shared with the gateway reuse gateway.model.* keys
(provider/context/max-output/capabilities/prompt-caching); CLI-only variants
(glyph or no-backtick forms) live under cli.model.*. The hand-padded /model usage
block becomes a (form, description-key) table padded at render time so the
command syntax stays fixed while descriptions translate. -q 'Error:' reuses
gateway.model.error_prefix.

* i18n(cli): route TUI panel/hint/placeholder copy through t() (cli.tui.*)

_APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS become key tables resolved at
render time; vault/sudo panel bodies are one catalog value per panel split on
newline; inline plurals use <key>_one/<key>_other. Adds the cli.* namespace
(shared/tui/voice/render/subagents/dock) to locales/en.yaml.

* i18n(cli): voice/wake-word CLI copy through t() (cli.voice.*)

RuntimeError texts raised in _voice_start_recording are human copy (callers
print {e}) and are keyed; the Termux requirement-check match stays English.
Wake state ids stay internal, only their labels localize.

* i18n(cli): live-work dock, subagent monitor and render copy through t()

cli.subagents.* / cli.dock.* / cli.render.*; count fragments pluralize via
_one/_other keys, verdict table holds keys resolved at paint time so width
clipping measures the translated text.

* i18n(gateway): unauthorized/pairing, voice, topics, shutdown, startup, notifications, kanban pings through t()

* i18n(cli): move tips + composer placeholders into the catalog (tips.tNNN / tips.placeholder.pNN)

get_random_tip()/get_random_composer_placeholder() pick a key from the English catalog
(the parity baseline, probed once per process) and resolve it through t() for the active
language, so language packs translate tips like any other string. Also lands the cli.*
en.yaml namespace consumed by the CLI info/help/error-copy wiring in the next commit.

* i18n(cli): wire chat-turn + session mixins through t(); kanban log trimmer matches t() output

* test(cli): assert TUI/dock/voice copy via t(key); prove labels resolve at render time

Pinned-English assertions in the approval-UI, live-work dock and voice tests now
go through the catalog. New test swaps the catalog after import and checks the
approval panel + hint row follow it (the reason _APPROVAL_CHOICE_LABELS and
_TUI_MODAL_HINTS became key tables).

* i18n(cli): route CLI info/help/error copy through t() (cli.* namespace)

cli_info_mixin: /help consumes CommandDef.describe() (added to commands.py: slash.<name>.description
with fallback to .description), section titles/skill/quick-command headers, /tools, /toolsets,
/usage labels, /context, /whoami, /insights, /gateway status, tool-progress labels, bang-shell
denials, MCP config-watch + /reload-mcp confirm/reload lines, /reload-skills, and the session-store
warning all read the catalog at call time (module-level label tables became functions so the
active language is honoured after startup). cli.py: worktree cleanup, tirith warning, show_config
(labels re-padded at print time), quick/plugin/skill slash-command errors, ambiguous-command hint,
stdin error, gateway start, profile warning. cli_chat_error_copy / cli_unknown_command /
cli_output / cli_init_mixin: chat error panel copy, did-you-mean lines, n-more / yes-no prompt
(localized affirmative initial alongside 'y'), unknown-toolsets warning.

* i18n(w1a): wire agent display/explainers/approval + slash registry/help through t()

- hermes_cli/commands.py: CommandDef.describe() resolves slash.<name>.description
  at call time; category labels via slash.category.*; help/alias/usage suffixes
  via slash.shared.*; gateway_help_lines and commands_platforms/slash_exec use them.
- agent/display.py: display.verb.* resolved at call time via get_tool_verb();
  bridge/spinner/thinking-verb/cute-row/failure/preview/diff text via display.*.
- agent/turn_explainers.py: exit-reason / persistence-cause tables become call-time
  lookups (explainer.exit.*, explainer.persistence.*, explainer.file_mutation.*).
- agent/background_review.py, session_activity.py, context_breakdown.py,
  status_output.py: review summaries, iteration progress, context notices.
- tools/approval.py, approval_context.py: approval.summary.*, approval.noun.*,
  approval.window.* pluralized keys.
- gateway/slash_commands*.py: remaining raw strings (busy, whoami, platform,
  bundles, memory, skills, approvals, set_home, diff, update, debug, profile,
  heartbeat, refine, review, subgoal, loop, retry, compress codex path, save,
  sessions, model guard/errors, agents rows, topup, login). HISTORY_UNREADABLE
  keeps its English constant; callers use history_unreadable() ->
  gateway.shared.history_unreadable.
- locales/en.yaml: new approval/display/explainer/slash blocks + gateway leftovers.

* i18n(telegram): route adapter chat copy through t()

Approval card (header/reason/smart-deny as HTML-escaped properties), inline
button labels, callback toasts (cut at Telegram's 200-char cap), model/choice
pickers, clarify/update/slash-confirm prompts, gmail-triage labels and the
inbound-media failure notice now come from the catalog. _UNAUTHORIZED is a
lazy _unauthorized() so the import no longer binds a language. The command
menu carries a language+payload fingerprint (forum scopes re-register on
change) and BotCommand descriptions are cut at 256.

Adds gateway.exec_approval.* (WAVE2 contract), platform.telegram.*,
platform.discord.* and the slash.*.description keys the Discord table shares
with the CLI registry to locales/en.yaml.

* i18n(gateway/platforms): whatsapp_cloud, yuanbao, weixin, signal, api_server copy through t()

- whatsapp_cloud: clarify list/buttons, approve/deny + slash-confirm labels via platform.whatsapp.* (t()-then-truncate at 20/24/72 caps); _EA_HEADER becomes a property wrapping ea_header_text()
- yuanbao: SLOW_RESPONSE_MESSAGE -> slow_response_message() (platform.yuanbao.slow_response_notice; zh keeps the original text); cron-wrapper markers centralized as module constants for strip_cron_wrapper
- api_server: PROVIDER_AUTH_FAILED_LABEL/PROVIDER_RATE_LIMITED_LABEL stay English for run.py matchers; user_text() renders via t()
- signal/_format_wait, weixin voice caption, openai_routes transformed notice
- run_turn: second _UNEXPECTED_SILENCE_REPLY consumer -> accessor

* i18n(discord): route adapter chat copy through t()

Native slash-command table becomes _NATIVE_SLASH_COMMAND_SPECS holding catalog
keys; _native_slash_commands() resolves descriptions, parameter descriptions
and Choice names for the active language, each cut at Discord's 100-char cap,
and the app-command sync fingerprint now includes get_language() so a
display.language change re-syncs. Exec-approval card (gateway.exec_approval.*
contract), slash-confirm / clarify / update views, model+choice pickers,
thread creation, forum titles, voice acks, the response-truncation notice,
the unauthorized-slash security alert and the media upload-size notices all
read from platform.discord.*. Decorator-declared button labels are relabelled
in __init__ (80-char cap); embed titles cut at 256, select placeholders at
150, option label/description at 100. _UNAUTHORIZED is a lazy _unauthorized().

* i18n(cli): wire status-bar, stream, terminal mixins + terminal_input through t(); rename kwargs that shadow t(key)

* i18n: wire hermes_cli/cli_commands_mixin.py slash-command copy through t()

- 431 new leaves under cli.commands.<cmd>.* in locales/en.yaml; 12 rows reuse
  existing gateway.* keys (rollback, diff, resume, branch, btw, model, reasoning)
  via a _gt() helper so CLI and gateway replies stay identical.
- Module-level English tables (_BUSY_MODE_*, _REASONING_TOGGLES, _HATCH_PROGRESS,
  _DIFF_LABELS, _LOCAL_ENGINE_LINES) become call-time catalog lookups keyed by id.
- Verb tables (Enabling/Disabling, Paused/Resumed/Triggered, planned/done,
  Updating/Generating) are one full template per variant; plurals use
  <key>_one/<key>_other via _tn(); hand-padded column labels (/snapshot list)
  translate the value and re-pad at the call site.
- Multi-line usage blocks are single catalog values split with _lines().
- Model-facing system notes and DB-stored reasons stay English (EXCLUDED).

* tests: assert /handoff, /worktree, /login CLI copy via t(key) instead of pinned English

* test(i18n): pin Telegram/Discord adapter catalog wiring

Lazy unauthorized notice, exec-approval contract keys, HTML escaping before
Telegram <b> wrapping, 200-char toast / 256-char BotCommand caps, Discord
100-char app-command text and 80-char button caps, and language-bearing
command-menu fingerprints on both platforms.

* i18n: reconcile cli.shared on/off vs enabled/disabled after lane merge

* i18n: describe() in TUI-gateway slash listings; localize TUI exit resume hint

* i18n(tr): translate bundled catalog + tui pack

* i18n(ja): translate bundled catalog + tui pack

* i18n(ko): translate bundled catalog + tui pack

* i18n(zh): translate bundled catalog + tui pack

* i18n(fr): translate bundled catalog + tui pack

* i18n(af): translate bundled catalog + tui pack

* i18n(uk): translate bundled catalog + tui pack

* i18n(ar): translate bundled catalog + tui pack

* i18n(pt): translate bundled catalog + tui pack

* i18n(it): translate bundled catalog + tui pack

* i18n(es): translate bundled catalog + tui pack

* i18n(zh-hant): translate bundled catalog + tui pack

* i18n(ru): translate bundled catalog + tui pack

* i18n(hu): translate bundled catalog + tui pack

* i18n(hu): translate pre-existing English-valued leftovers (kanban wake, /context, /status, fast labels)

* i18n(de): translate bundled catalog + tui pack

* i18n(ga): translate bundled catalog + tui pack

* test(i18n): fixture matches _normalize_lang(lang, home) signature

* i18n(tui): scaffold userMessages/slashCmd en siblings

* i18n(tui): wire secure prompts + content tables

* feat(tui): i18n — wire billing, subscription, connection-setup and journey overlays

Adds en siblings billing.ts / subscription.ts / connection.ts (namespaces
billing, subscription, connection, journey) and routes every user-facing
literal in billingOverlay, subscriptionOverlay, connectionSetupOverlay and
journey through useT()/messages(). Module-level label tables became lazy
(scopeStillDeniedResult(), verbOf(T, action)); auto-reload rows dispatch on
stable ids instead of label text. Regenerates locales/_keys.tui.json.

* i18n(tui): wire slash ops/wake replies

* i18n(tui): wire pickers (modelPicker, activeSessionSwitcher, petPicker)

* i18n(tui): wire slash core/debug/setup replies

* i18n(tui): wire hubs (agents overlay/panel/controls, skills, plugins)

* i18n(tui): wire slash session/topup/subscription replies

* i18n(tui): wire chat bits (branding, thinking, messageLine, loaders, todo, queued, banner, entry)

* i18n(tui): register t3 siblings (pickers, hubs, secure, content, chatBits) and regenerate keys

* i18n(tui): wire userMessages copy through the userMessages namespace

* i18n(tui): lazy-copy test for userMessages, regenerate _keys.tui.json

* i18n(tui): wire session/gateway/lib text through the TUI catalog (lane t2)

Adds en siblings session.ts, gatewayMsg.ts, libText.ts (namespaces session,
gatewayMsg, libText) and routes user-facing literals in app/{useMainApp,
useSessionLifecycle,useInputHandlers,turnController,createServerRequestHandler,
setupHandoff,createGatewayEventHandler}.ts, gatewayClient displayed reasons,
lib/*, domain/*, hooks/* through t()/messages(). Status-bar state values that
code compares against, backend-matched strings, log lines, model-bound text,
and machine 'error:' prefixes stay literal. Regenerates locales/_keys.tui.json
(232 keys).

* i18n: serve bundled locales/<lang>.tui.yaml under overlay/packs; TUI pack parity test; regen _keys.tui.json (1250)

* i18n: translate pre-existing English stubs in bundled locales (424 leaves, 14 locales)

* tui: i18n-export-en script (English templates for pack translators)

* docs(i18n): bundled TUI packs are the bottom layer of the tui surface

* i18n(ru): translate TUI pack

* i18n(ar): translate TUI pack

* i18n(es): translate TUI pack

* i18n(pt): translate TUI pack

* i18n(ko): translate TUI pack

* i18n(de): translate TUI pack

* i18n(ja): translate TUI pack

* i18n(fr): translate TUI pack

* i18n(tr): translate TUI pack

* i18n(it): translate TUI pack

* i18n(zh): translate TUI pack

* i18n(zh-hant): translate TUI pack

* i18n(hu): translate TUI pack

* i18n(uk): translate TUI pack

1,169 missing keys translated; 81 pre-existing kept byte-identical. Parity OK missing=0 extra=0 placeholder_mismatch=0 empty=0.

Deliberately identical to en: chatBits.branding.mcpSummary ({0} MCP), chatBits.thinking.agentsHint ((/agents)), session.main.voiceStt (◉ STT), session.main.voiceTtsSuffix ( [tts]), slashCmd.core.help.tuiSection (TUI), slashCmd.core.history.hermesTag (Hermes #{0}), slashCmd.debug.heapdump.heapPath (heapdump: {0}), slashCmd.debug.mem.rss (rss), subscription.stepUp.title (Remote Spending — product feature name, as in core catalog), content.faces.* (glyph-only kaomoji).

* i18n(ga): translate TUI pack

* i18n(af): translate TUI pack

* plugin_guard: locale catalogs in language packs step down the agent-config family

A translated status line such as "Updating AGENTS.md" in locales/<lang>.yaml is UI text the loader
reads as a string leaf; it cannot edit a file. The bundled en.yaml itself tripped agent_config_mod
at critical, making any faithful language pack uninstallable. Injection shapes keep full severity.

* plugin_validate_locales: read key exports with utf-8-sig (Windows footgun lint)

* i18n(relay): route relay adapter prompt copy through t(); drop dead import-bound approval header

Adds platform.relay.* (5 keys) to en and all 16 bundled locales, reusing the sibling platform
translations for the confirm buttons and the Other option.

* ci: fix TUI import order, MDX table pipe, main's overflow-warning wording in all locales; fresh-install fixture carries the i18n kernel

- ui-tui/src/i18n/en.ts: perfectionist/sort-imports (slash before slashCmd)
- docs plugins/index.md: escape the | inside the provides_locales table cell (MDX parsed <id> as JSX)
- display.notice.uncompressed_context_overflow: adopt main's wording (names compression.enabled: false
  and /compact) in en + 16 locales; the guardrail test pins that phrase
- tests/scripts/test_fresh_source_install.py: the installer tail now resolves CLI text through
  agent.i18n, so the fixture tree carries the i18n kernel + en.yaml (not the agent runtime)

* docs(desktop-plugin-sdk): double-backtick the template-literal example (MDX evaluated ${n})

* test(e2e): display.language is validated against the live language set; exclude it from the arbitrary-string set property

* commands: keep the localized COMMANDS/COMMANDS_BY_CATEGORY module __getattr__ after the compat block removal

* build: never write locales/_keys.*.json from the desktop/TUI builds; regenerate the committed desktop key export

The desktop build regenerated locales/_keys.desktop.json in the checkout, so a
hermes update that rebuilt the app left the tree dirty (Desktop update E2E:
'M locales/_keys.desktop.json'). The key exports are committed artifacts pinned
to en.ts by apps/desktop/scripts/i18n-keys.test.mjs and ui-tui i18n:keys:check;
builds read them, never write them. Regenerated after main's new desktop strings.

* test: unbreak two main-red timing tests the PR merge-ref inherits

- test_local_runtime racing fake publishes the modern state record (legacy pid-only
  records are rejected since 65ff3ad353; main has been red on this test since)
- test_run_progress_topics ManyProgressLinesAgent waits for the first bubble instead of
  a fixed 0.35s, which a loaded CI runner does not always meet

* chore(i18n): regenerate desktop key catalog for main's new strings (model pricing, copy changelog)

* test(e2e): torture-chamber fd monitor confirms a deleted sidecar is still held before calling it a leak

SQLite's WAL last-close unlinks -shm before closing its descriptor (unixShmUnmap, then
unixShmPurge), so a healthy close shows a (deleted) -shm for microseconds; the 20ms poll
occasionally caught that window on the short-lived opener and failed the episode.

* chore(i18n): regenerate desktop key catalog for main's telemetry/consent strings

* chore(i18n): regenerate desktop key catalog after main sync

---------

Co-authored-by: Teknium <[email protected]>
2026-09-28 14:16:18 -07:00

729 lines
40 KiB
Python

"""chat() and its per-turn phases: image routing, staging, agent thread, interrupt monitor, rendering.
Mixin bound onto ``HermesCLI`` via the MRO. cli.py-internal symbols are imported LAZILY
inside each method — importing ``cli`` at module load time would be a cycle.
"""
from __future__ import annotations
import logging
import os
import queue
import sys
import threading
import time
from pathlib import Path
from rich import box as rich_box
from rich.panel import Panel
from typing import Optional
from agent.i18n import t
from hermes_cli.cli_agent_setup_mixin import _retire_agent
class CLIChatTurnMixin:
"""chat() and its per-turn phase helpers."""
# Last completed turn's raw agent result. chat() returns only the rendered
# response string, so one-shot callers that must map an outcome onto a
# process exit code (see cli._run_single_query_mode) read this instead.
_last_turn_result = None
def _sync_fallback_chain_with_config(self, agent) -> None:
"""Adopt ``fallback_providers`` edits made while this chat is open (#95066) — the same
per-turn, fail-closed contract as the Desktop/TUI and messaging gateways: a torn config.yaml
keeps the last known-good chain instead of reading as "chain removed"."""
from cli import logger
try:
from gateway.run import GatewayRunner
from hermes_cli.config_effective import load_user_config_effective
from hermes_cli.fallback_config import get_fallback_chain
self._fallback_model = get_fallback_chain(load_user_config_effective(fail_closed=True))
except Exception as e:
logger.debug("fallback chain sync skipped (keeping current chain): %s", e)
return
GatewayRunner._apply_fallback_chain_to_agent(agent, self._fallback_model)
def chat(self, message, images: list = None, voice_input: bool = False) -> Optional[str]:
"""Run one user turn; returns the agent's response, or None on error.
Input typed while the agent runs goes to ``_interrupt_queue`` (separate from
``_pending_input`` so process_loop and the interrupt monitor never compete); an
interrupting message is re-queued as the next turn. ``voice_input`` gates the
concise voice-response prefix.
Args: message: The user's message (str or multimodal content list) images: Optional list of Path
objects for attached images voice_input: True when the message came from voice transcription (gates
the concise voice-response prefix, #65827)
"""
from cli import ChatConsole, _ChatTurn, _DIM, _RST, _accent_hex, _cprint, set_secret_capture_callback
from tools.process_registry_notifications import TimelineNotification
# Single-query and direct chat callers do not go through run().
set_secret_capture_callback(self._secret_capture_callback)
# Reset per turn; only a real interrupt flips it, so early returns leave it False.
self._last_turn_interrupted = False
if not self._ensure_runtime_credentials():
return None
turn_route = self._resolve_turn_agent_config(message)
if turn_route["signature"] != self._active_agent_route_signature:
_retire_agent(self)
if self.agent is None:
_cprint(f"{_DIM}{t('cli.chat.initializing_agent')}{_RST}")
if not self._init_agent(model_override=turn_route["model"], runtime_override=turn_route["runtime"],
request_overrides=turn_route.get("request_overrides")):
return None
agent = self.agent
if agent is None:
return None
self._sync_fallback_chain_with_config(agent) # chain added after this chat opened reaches this turn
message = self._chat_route_images(message, images)
if isinstance(message, str) and not isinstance(message, TimelineNotification):
message, blocked = self._chat_expand_context_references(message)
if blocked is not None:
return blocked
# Lone surrogates (rich-text clipboard paste) crash the OpenAI SDK's JSON serialization.
from agent.message_sanitization import _sanitize_surrogates
message = _sanitize_surrogates(message)
self._chat_stage_user_message(agent, message)
if isinstance(message, TimelineNotification):
message = str(message) # UI metadata is on the staged row, never in model content.
ChatConsole().print(f"[{_accent_hex()}]{'─' * 40}[/]")
_cprint("")
from agent.notification_presentation import notification_config_snapshot, notification_policy_snapshot
with notification_policy_snapshot(agent, "cli", notification_config_snapshot()):
turn = _ChatTurn()
from gateway.warning_notifications import diagnostic_turn_muted
turn.mute_notification_reply = diagnostic_turn_muted(
agent._pending_cli_user_message.get("display_metadata"), "cli", agent._notification_config)
try:
self._reset_stream_state()
# Not part of _reset_stream_state: must persist across intermediate turn
# boundaries (tool-calling loops), reset once per user turn.
self._reasoning_shown_this_turn = False
self._streamed_text_this_turn = ""
self._chat_setup_turn_audio(turn, message, voice_input)
# Per-prompt elapsed timer — frozen when the agent thread finishes.
self._prompt_start_time = time.time()
self._prompt_duration = 0.0
# Daemon: closing the terminal tab (SIGHUP) must not be kept alive by it.
agent_thread = threading.Thread(target=self._chat_run_agent, args=(turn, message), daemon=True)
agent_thread.start()
interrupt_msg = self._chat_monitor_agent_thread(turn, agent_thread)
self._chat_settle_turn(turn)
return self._chat_render_turn(turn, agent_thread, interrupt_msg)
except Exception as e:
_cprint(t("gateway.model.error_prefix", error=e))
return None
finally:
self._chat_release_turn_audio(turn)
def _chat_release_turn_audio(self, turn):
"""Every exit path: stop the thinking sound, send the TTS sentinel, cut TTS only if abnormal."""
from cli import logger
if turn.thinking_started:
try:
from tools.voice_mode import stop_thinking_sound
stop_thinking_sound()
except Exception:
pass
# Safety-net sentinel for exception paths that skipped _chat_settle_turn's; a
# duplicate is harmless (stream_tts_to_speaker exits on the first None).
# stop_event only on abnormal exit: after a normal drain it would race the
# playback worker and cut the final sentence mid-audio.
if turn.text_queue is not None:
try:
turn.text_queue.put_nowait(None)
except Exception:
pass
if turn.stop_event is not None and not turn.tts_normal_exit:
logger.info("TTS CUT: exception finally block setting stop_event")
turn.stop_event.set()
if turn.tts_thread is not None and turn.tts_thread.is_alive():
turn.tts_thread.join(timeout=5)
def _chat_expand_context_references(self, message: str):
"""Expand ``@file:``/``@diff``/``@folder:`` references.
Returns ``(message, blocked)``; ``blocked`` is the refusal text to return instead
of running the turn when injection was refused, else None.
"""
from cli import _DIM, _RST, _cprint
if "@" not in message:
return message, None
try:
from agent.context_references import preprocess_context_references
from agent.model_metadata import get_model_context_length
_ctx_len = get_model_context_length(
self.model, base_url=self.base_url or "", api_key=self.api_key or "",
provider=self.provider or "",
config_context_length=getattr(self.agent, "_config_context_length", None) if self.agent else None)
_ctx_result = preprocess_context_references(message, cwd=os.getcwd(), context_length=_ctx_len)
if _ctx_result.expanded or _ctx_result.blocked:
if _ctx_result.references:
_cprint(f" {_DIM}{t('cli.chat.context_refs', count=len(_ctx_result.references), tokens=_ctx_result.injected_tokens)}{_RST}")
for w in _ctx_result.warnings:
_cprint(f" {_DIM}⚠ {w}{_RST}")
if _ctx_result.blocked:
return message, ("\n".join(_ctx_result.warnings) or t("cli.chat.context_injection_refused"))
message = _ctx_result.message
except Exception as e:
logging.debug("@ context reference expansion failed: %s", e)
return message, None
def _chat_route_images(self, message, images):
"""Attach images natively (vision model) or pre-describe them as text; returns the message to send.
"native" → OpenAI-style content parts (adapters translate per provider); "text" →
vision_analyze each image and prepend the description. Decision: agent/image_routing.py.
"""
from cli import _DIM, _RST, _cprint, _split_model_config_default
if not images:
return message
text = message if isinstance(message, str) else ""
try:
from agent.image_routing import build_native_content_parts, decide_image_input_mode
from hermes_cli.config import load_config
_img_model = (_split_model_config_default(self.model)[0]
if isinstance(self.model, dict) else str(self.model or ""))
_img_provider = (_split_model_config_default(self.provider)[1]
if isinstance(self.provider, dict) else str(self.provider or ""))
_img_mode = decide_image_input_mode(
_img_provider.strip(), _img_model.strip(), load_config(),
requested_provider=(self.requested_provider or "").strip(),
)
except Exception as _img_exc:
logging.debug("image_routing decision failed, defaulting to text: %s", _img_exc)
_img_mode = "text"
if _img_mode == "native":
try:
_img_str_paths = [str(p) for p in images]
_parts, _skipped = build_native_content_parts(text, _img_str_paths)
if _skipped:
_cprint(f" {_DIM}{t('cli.chat.skipped_unreadable_images', count=len(_skipped))}{_RST}")
if any(p.get("type") == "image_url" for p in _parts):
_img_names = ", ".join(Path(p).name for p in _img_str_paths)
_cprint(f" {_DIM}{t('cli.chat.attaching_images_natively', count=len(images), names=_img_names)}{_RST}")
return _parts
# All images unreadable — fall back to text enrichment.
except Exception as _img_exc:
logging.warning("native image attach failed, falling back to text: %s", _img_exc)
return self._preprocess_images_with_vision(text, images)
def _chat_stage_user_message(self, agent, message):
"""Append the staged user dict to the transcript under the agent's persist lock."""
# Copy before appending: mutating ``agent._session_messages`` in this UI-only step
# would expose a duplicate-prone snapshot to terminal-close persistence.
if self.conversation_history is getattr(agent, "_session_messages", None):
self.conversation_history = list(self.conversation_history)
# Clear the prior turn's override before exposing the new staged input: a shutdown
# before the worker prologue would otherwise persist old API-local text as this message.
import contextlib
from agent.message_metadata import stamp_message_timestamp
persist_lock = getattr(agent, "_session_persist_lock", None)
with persist_lock if persist_lock is not None else contextlib.nullcontext():
agent._persist_user_message_idx = None
agent._persist_user_message_override = None
agent._persist_user_message_timestamp = None
staged_user_message = stamp_message_timestamp({"role": "user", "content": message})
from tools.process_registry_notifications import TimelineNotification
if isinstance(message, TimelineNotification):
staged_user_message.update(content=str(message), display_kind=message.display_kind,
display_metadata={"display_text": message.display_text,
"notification_category": message.notification_category})
agent._pending_cli_user_message = staged_user_message
self.conversation_history.append(staged_user_message)
def _chat_setup_turn_audio(self, turn, message, voice_input):
"""Arm the full-duplex listener and the streaming-TTS pipeline for this turn (voice mode only)."""
from cli import _ACCENT, _RST, _STREAM_PAD, _cprint, datetime
if getattr(turn, "mute_notification_reply", False):
return
# Continuous voice mode: arm the mic NOW (utterance-submit), not at TTS playback —
# it spans generation (speech interrupts the turn) and playback (speech cuts TTS)
# and disarms itself when the turn is done. See _voice_full_duplex_listener.
if self._voice_mode and self._voice_continuous:
self._voice_last_tts_text = ""
threading.Thread(target=self._voice_full_duplex_listener, daemon=True).start()
# Streaming TTS: any working provider speaks sentence-by-sentence as tokens arrive.
if self._voice_tts:
try:
from tools.tts_tool import _import_sounddevice, check_tts_requirements
from tools.tts_tool_speaker import stream_tts_to_speaker
_import_sounddevice()
turn.use_streaming_tts = check_tts_requirements()
except Exception:
pass
if turn.use_streaming_tts:
turn.text_queue = queue.Queue()
turn.stop_event = threading.Event()
# display_callback only when token streaming is off: with streaming on,
# _stream_delta already renders the text and this would print it twice.
def display_callback(sentence: str):
if not turn.box_opened:
turn.box_opened = True
label = " ☤ Hermes "
if self.show_timestamps:
label = f"{label}{datetime.now().strftime(self.timestamp_format)} "
w = self._scrollback_box_width(getattr(self.console, "width", 80))
fill = w - 2 - self._status_bar_display_width(label)
_cprint(f"\n{_ACCENT}╭─{label}{'─' * max(fill - 1, 0)}╮{_RST}")
_cprint(f"{_STREAM_PAD}{sentence.rstrip()}")
turn.tts_thread = threading.Thread(
target=stream_tts_to_speaker, args=(turn.text_queue, turn.stop_event, self._voice_tts_done),
kwargs={"display_callback": None if self.streaming_enabled else display_callback},
daemon=True,
)
turn.tts_thread.start()
# Barge-in paths (voice key, full-duplex listener) cut playback via this event.
self._voice_tts_stop = turn.stop_event
def stream_callback(delta: str):
turn.text_queue.put(delta)
# Track what is being spoken so a playback-phase barge capture can be
# checked against it (echo guard).
self._voice_last_tts_text = (self._voice_last_tts_text or "") + delta
turn.stream_callback = stream_callback
# API-call-local only — run_conversation persists the original clean user message.
if voice_input and isinstance(message, str):
turn.voice_prefix = ("[Voice input — respond concisely and conversationally, "
"2-3 sentences max. No code blocks or markdown.] ")
def _chat_run_agent(self, turn, message):
"""Agent-thread body: bind per-thread callbacks/approval key, prepend one-shot notes, run the turn."""
from cli import (
_prepend_note_to_message, set_approval_callback, set_secret_capture_callback,
set_sudo_password_callback,
)
from agent.vault_backends.unlock import set_code_prompt_callback, set_save_login_prompt_callback, set_unlock_prompt_callback
# terminal_tool callbacks are thread-local: run()'s registration is invisible here.
set_sudo_password_callback(self._sudo_password_callback)
set_approval_callback(self._approval_callback)
set_secret_capture_callback(self._secret_capture_callback)
set_unlock_prompt_callback(self._vault_unlock_callback)
set_save_login_prompt_callback(self._vault_save_login_callback)
set_code_prompt_callback(self._vault_code_callback)
# Bind the approval session key so ``is_current_session_yolo_enabled()`` resolves
# against the same key ``/yolo`` toggles under (``enable_session_yolo(self.session_id)``).
try:
from tools.approval_context import reset_current_session_key, set_current_session_key
_approval_session_token = set_current_session_key(self.session_id or "default")
except Exception:
reset_current_session_key = None # type: ignore[assignment]
_approval_session_token = None
agent_message = turn.voice_prefix + message if turn.voice_prefix else message
# One-shot /model and /reload-skills notes; _prepend_note_to_message also handles
# multimodal content-part lists (string concat raised TypeError with an image).
for _note_attr in ("_pending_model_switch_note", "_pending_skills_reload_note"):
_note = getattr(self, _note_attr, None)
if _note:
agent_message = _prepend_note_to_message(agent_message, _note)
setattr(self, _note_attr, None)
# Barged mid-speech (VAD or record key)? Tell the model it was cut off.
from tools.tts_streaming import SPEECH_INTERRUPTED_NOTE, take_speech_interrupted
if take_speech_interrupted():
agent_message = _prepend_note_to_message(agent_message, SPEECH_INTERRUPTED_NOTE)
_moa_cfg = getattr(self, "_pending_moa_config", None)
self._pending_moa_config = None
# Notes and voice prefix are API-local: the staged input stays the durable transcript
# value so a close-path marker follows the same dict instead of a second user row.
_persist_clean_user_message = message if (turn.voice_prefix or agent_message != message) else None
_one_turn_model_restore = getattr(self, "_pending_one_turn_model_restore", None)
self._pending_one_turn_model_restore = None
try:
from agent.notification_presentation import notification_turn
muted = getattr(turn, "mute_notification_reply", False)
with notification_turn(self.agent, muted=muted, session_id=self.session_id):
turn.result = self.agent.run_conversation(
user_message=agent_message,
conversation_history=self.conversation_history[:-1],
stream_callback=None if muted else turn.stream_callback, task_id=self.session_id,
persist_user_message=_persist_clean_user_message, moa_config=_moa_cfg,
)
if getattr(self, "_pending_moa_disable_after_turn", False):
_restore = getattr(self, "_pending_moa_restore_model", None) or {}
for _key, _value in _restore.items():
if _value is not None:
setattr(self, _key, _value)
_retire_agent(self)
self._pending_moa_restore_model = None
self._pending_moa_disable_after_turn = False
except Exception as exc:
logging.error("run_conversation raised: %s", exc, exc_info=True)
_summary = getattr(self.agent, '_summarize_api_error', lambda e: str(e)[:300])(exc)
from hermes_cli.cli_chat_error_copy import chat_error_response
turn.result = {
"final_response": chat_error_response(
exc, provider=str(getattr(self.agent, "provider", "") or self.provider or ""),
model=str(getattr(self.agent, "model", "") or self.model or "")),
"messages": [], "api_calls": 0,
"completed": False, "failed": True, "error": _summary,
}
finally:
if _one_turn_model_restore:
self._restore_model_runtime_snapshot(_one_turn_model_restore)
# Credit notices paint cleanly above the prompt here, not behind streamed output.
self._flush_credit_notices()
# A reused thread must never hold stale references to a disposed CLI instance.
try:
set_sudo_password_callback(None)
set_approval_callback(None)
set_secret_capture_callback(None)
set_unlock_prompt_callback(None)
set_save_login_prompt_callback(None)
set_code_prompt_callback(None)
except Exception:
pass
# Unbind the per-turn key; ``_session_yolo`` state itself persists across turns.
if _approval_session_token is not None and reset_current_session_key is not None:
try:
reset_current_session_key(_approval_session_token)
except Exception:
pass
def _chat_monitor_agent_thread(self, turn, agent_thread):
"""Poll the interrupt queue while the agent thread runs; returns the interrupting message (or None)."""
from cli import _cprint, _hermes_home, logger
# Ambient "thinking" blips in voice mode; skipped per-blip while TTS speaks, the mic
# records or a barge capture is live. voice.thinking_sound gates it (default on).
if self._voice_mode:
try:
from tools.voice_mode import start_thinking_sound
turn.thinking_started = start_thinking_sound(should_play=lambda: (
self._voice_tts_done.is_set() and not self._voice_recording
and not self._voice_barge_capture.is_set()))
except Exception:
turn.thinking_started = False
interrupt_msg = None
while agent_thread.is_alive():
try:
interrupt_msg = self._interrupt_queue.get(timeout=0.1)
except queue.Empty:
# Flush the StdoutProxy buffer: it otherwise only flushes on input-triggered
# renderer passes, so on macOS the CLI looks frozen until the user types.
# Force prompt_toolkit to flush any pending stdout output from the agent thread. (#1624)
self._invalidate(min_interval=0.15)
continue
if not interrupt_msg:
continue
# With a clarify question active, Enter routes to the clarify queue; anything
# landing here is a race — don't interrupt, park it as the next turn.
if self._clarify_state or self._clarify_freetext:
try:
self._pending_input.put(interrupt_msg)
except Exception:
pass
interrupt_msg = None
continue
_cprint(f"\n{t('cli.chat.new_message_interrupting')}")
if turn.stop_event is not None:
turn.stop_event.set()
self.agent.interrupt(interrupt_msg)
# Modal prompts gate input until reset — otherwise the CLI freezes after an
# interrupt until the prompt's own timeout.
self._clear_active_overlays_for_interrupt()
# Debug log to file (stdout may be devnull under redirect_stdout).
try:
with open(_hermes_home / "interrupt_debug.log", "a", encoding="utf-8") as _f:
_f.write(f"{time.strftime('%H:%M:%S')} interrupt fired: msg={str(interrupt_msg)[:60]!r}, "
f"children={len(self.agent._active_children)}, "
f"parent._interrupt={self.agent._interrupt_requested}\n")
for _ci, _ch in enumerate(self.agent._active_children):
_f.write(f" child[{_ci}]._interrupt={_ch._interrupt_requested}\n")
except Exception:
pass
break
if interrupt_msg is not None:
# After an interrupt the agent may take seconds to clean up (kill
# subprocess, persist). Poll instead of a blocking join so another
# interrupt (Ctrl+C sets _should_exit) or a stuck agent can't freeze
# us; the thread is daemon and dies on process exit regardless.
for _ in range(50): # 50 * 0.2s = 10s max
agent_thread.join(timeout=0.2)
if not agent_thread.is_alive() or self._should_exit:
break
if agent_thread.is_alive():
logger.warning(
"Agent thread still alive after interrupt "
"(thread %s). Daemon thread will be cleaned up "
"on exit.",
agent_thread.ident,
)
else:
agent_thread.join(timeout=30) # should be done already; guard edge cases
return interrupt_msg
def _chat_settle_turn(self, turn):
"""After the agent thread ends: freeze timers, flush streams, drain TTS, sync history/session id."""
if self._prompt_start_time is not None:
self._prompt_duration = max(0.0, time.time() - self._prompt_start_time)
self._prompt_start_time = None
self._last_turn_finished_at = time.time() # status bar idle time
self._last_turn_result = turn.result
# AsyncOpenAI clients bound to the worker's now-closed loop would crash
# prompt_toolkit's loop from __del__ on GC.
try:
from agent.auxiliary_client import cleanup_stale_async_clients
cleanup_stale_async_clients()
except Exception:
pass
self._flush_stream()
if turn.use_streaming_tts and turn.text_queue is not None:
turn.text_queue.put(None) # end-of-text sentinel
if turn.tts_thread is not None:
turn.tts_thread.join(timeout=120)
# A timed-out join leaves tts_normal_exit False so the release path's
# stop_event kills the runaway worker.
turn.tts_normal_exit = not turn.tts_thread.is_alive()
# Drain the StdoutProxy buffer so tool/status lines render ABOVE the response
# box; the sleep lets the renderer paint before we draw.
sys.stdout.flush()
time.sleep(0.15)
if turn.result:
self.conversation_history = turn.result.get("messages", self.conversation_history)
# Mid-turn auto-compression continues in a child session: sync so /status, /resume,
# titling and the exit summary target the live child, not the ended parent.
if (self.agent and getattr(self.agent, "session_id", None)
and self.agent.session_id != self.session_id):
self._transfer_session_yolo(self.session_id, self.agent.session_id)
self.session_id = self.agent.session_id
self._write_terminal_breadcrumb()
self._pending_title = None
def _chat_render_turn(self, turn, agent_thread, interrupt_msg):
"""Post-turn display: errors, interrupt marker, reasoning/response panels, bell, re-queues.
Returns the response text.
"""
from cli import _DIM, _RST, _cprint, _suspend_output_history
response = turn.result.get("final_response", "") if turn.result else ""
if getattr(turn, "mute_notification_reply", False):
pending, _ = self._chat_resolve_interrupt(turn, agent_thread, interrupt_msg, response)
if pending:
self._pending_input.put(pending)
return None
# "failed"/"partial" with an empty final_response: no usable answer.
if turn.result and (turn.result.get("failed") or turn.result.get("partial")) and not response:
from hermes_cli.cli_chat_error_copy import chat_error_response
response = chat_error_response(
str(turn.result.get("error") or t("cli.chat.unknown_error")),
provider=str(getattr(self.agent, "provider", "") or self.provider or ""),
model=str(getattr(self.agent, "model", "") or self.model or ""),
failure_reason=turn.result.get("failure_reason"))
# Stop continuous voice on persistent errors (e.g. 429) — else error→record→error loops.
if self._voice_continuous:
self._voice_continuous = False
_cprint(f"\n{_DIM}{t('cli.chat.continuous_voice_stopped')}{_RST}")
pending_message, _show_interrupt_marker = self._chat_resolve_interrupt(
turn, agent_thread, interrupt_msg, response)
self._chat_print_reasoning_box(turn)
self._chat_print_response_panel(turn, response)
# History suppressed so the marker is never recorded in _OUTPUT_HISTORY
# (appending it to `response` duplicated it on redraw).
if _show_interrupt_marker:
with _suspend_output_history():
_cprint(f"\n{_DIM}{t('cli.chat.interrupted_marker')}{_RST}")
# Focus view: "⋯ N tool lines hidden" after the answer; resets the counter.
try:
self._emit_focus_recovery_line()
except Exception:
pass
self._ring_bell(context=t("cli.modal.bell_turn_complete")) # propagates over SSH
if turn.result and not turn.result.get("completed") and not turn.result.get("interrupted"):
_api_calls = turn.result.get("api_calls", 0)
_max_iter = getattr(self.agent, "max_iterations", 500)
if _api_calls >= _max_iter:
from gateway.warning_notifications import render_notification
render_notification(
lambda: _cprint(
f"\n{_DIM}{t('cli.chat.iteration_budget_reached', used=_api_calls, max=_max_iter)}{_RST}"
),
platform="cli", user_config=getattr(self.agent, "_notification_config", None))
# Batch TTS unless streaming TTS already spoke the response.
if self._voice_tts and response and not turn.use_streaming_tts:
self._voice_speak_response_async(response)
# Re-queue the interrupt message (plus any that arrived meanwhile) as the next
# prompt. Only reached in busy_input_mode == "interrupt"; "queue" mode routes
# Enter straight to _pending_input.
if pending_message:
all_parts = [pending_message]
while not self._interrupt_queue.empty():
try:
extra = self._interrupt_queue.get_nowait()
if extra:
all_parts.append(extra)
except queue.Empty:
break
# Payloads may be (text, images) tuples when the message carried image
# attachments (bundled at cli_tui_mixin._tui_on_enter); unpack them here —
# "\n".join(all_parts) raises TypeError on a tuple and the outer
# handler swallows it, silently dropping the interrupt (#110737).
text_parts: list[str] = []
image_parts: list = []
for part in all_parts:
if isinstance(part, tuple):
part_text, part_images = part
text_parts.append(part_text)
image_parts.extend(part_images or [])
else:
text_parts.append(part)
combined = "\n".join(text_parts)
payload = (combined, image_parts) if image_parts else combined
preview = combined[:50] + ("..." if len(combined) > 50 else "")
if len(all_parts) > 1:
_cprint(f"\n{t('cli.chat.sending_after_interrupt_multi', count=len(all_parts), preview=preview)}")
else:
_cprint(f"\n{t('cli.chat.sending_after_interrupt', preview=preview)}")
self._pending_input.put(payload)
# A /steer the agent finished before absorbing becomes the next user turn.
_leftover_steer = turn.result.get("pending_steer") if turn.result else None
if _leftover_steer:
preview = _leftover_steer[:60] + ("..." if len(_leftover_steer) > 60 else "")
_cprint(f"\n{t('cli.chat.delivering_leftover_steer', preview=preview)}")
self._pending_input.put(_leftover_steer)
return response
def _chat_resolve_interrupt(self, turn, agent_thread, interrupt_msg, response):
"""Return ``(pending_message, show_marker)``; clears a stale agent interrupt flag.
The marker is printed separately after the response Panel (history suppressed)
so a terminal redraw never duplicates it.
"""
pending_message = None
_show_interrupt_marker = False
_interrupted_this_turn = bool(turn.result and turn.result.get("interrupted"))
# Post-turn hooks (e.g. goal continuation) skip themselves on a user-cancelled turn.
self._last_turn_interrupted = _interrupted_this_turn
if _interrupted_this_turn:
pending_message = turn.result.get("interrupt_message") or interrupt_msg
_show_interrupt_marker = bool(response and pending_message)
elif interrupt_msg:
# agent.interrupt() fired but the result doesn't acknowledge it (racy): either
# the thread had passed its last interrupt check so finalize_turn() never saw
# the flag, or the 10s post-interrupt wait expired and `result` is None. The
# user's message must NOT be dropped — re-queue it as the next turn.
pending_message = interrupt_msg
# An interrupt landing after finalize_turn()'s clear_interrupt() leaves a stale
# flag that would abort the NEXT turn at its first check. Clear it — but ONLY if
# the thread exited: on an abandoned thread the flag is what eventually unwinds
# the wedged tool.
try:
if (not agent_thread.is_alive() and self.agent
and getattr(self.agent, "_interrupt_requested", False)):
self.agent.clear_interrupt()
except Exception:
pass
return pending_message, _show_interrupt_marker
def _chat_print_reasoning_box(self, turn):
"""Collapsed reasoning box when show_reasoning is on and streaming did not already show it."""
from cli import _DIM, _RST, _cprint
# _reasoning_shown_this_turn, not _reasoning_stream_started: the latter resets at
# intermediate turn boundaries (tool loops) and re-rendered the box after the answer.
if self.show_reasoning and turn.result and not self._reasoning_shown_this_turn:
reasoning = turn.result.get("last_reasoning")
if reasoning:
w = self._scrollback_box_width()
r_label = f" {t('cli.chat.reasoning_label')} "
r_top = f"{_DIM}┌─{r_label}{'─' * max(w - 3 - len(r_label), 0)}┐{_RST}"
r_bot = f"{_DIM}└{'─' * (w - 2)}┘{_RST}"
# First 10 lines unless the user opted into /reasoning full.
lines = reasoning.strip().splitlines()
if len(lines) > 10 and not self.reasoning_full:
display_reasoning = "\n".join(lines[:10])
display_reasoning += f"\n{_DIM} {t('cli.chat.reasoning_more_lines', count=len(lines) - 10)}{_RST}"
else:
display_reasoning = reasoning.strip()
_cprint(f"\n{r_top}\n{_DIM}{display_reasoning}{_RST}\n{r_bot}")
def _chat_print_response_panel(self, turn, response):
"""Response box (close TTS-drawn box / post-stream transform / Rich Panel), then billing CTA."""
from cli import (
ChatConsole, _ACCENT, _RST, _cprint, _maybe_remap_for_light_mode, _post_stream_transform_output,
_render_final_assistant_content,
)
if response and not (turn.result and turn.result.get("response_previewed", False)):
try:
from hermes_cli.skin_engine import get_active_skin
_skin = get_active_skin()
label = _skin.get_branding("response_label", "☤ Hermes")
_resp_color = _maybe_remap_for_light_mode(_skin.get_color("response_border", "#CD7F32"))
_resp_text = _maybe_remap_for_light_mode(_skin.get_color("banner_text", "#FFF8DC"))
except Exception:
label = "☤ Hermes"
_resp_color = _maybe_remap_for_light_mode("#CD7F32")
_resp_text = _maybe_remap_for_light_mode("#FFF8DC")
is_error_response = turn.result and (turn.result.get("failed") or turn.result.get("partial"))
# An interrupted reply that streamed before a tool-call boundary reset the segment
# state is already on screen (#65666). Only suppress when the response IS that text:
# unstreamed interrupt/status messages and completed replies still get their Panel.
_interrupted_streamed = bool(
self._last_turn_interrupted and response.strip()
and " ".join(response.split()) in " ".join(self._streamed_text_this_turn.split())
)
already_streamed = (
(self._stream_started and self._stream_box_opened) or _interrupted_streamed
) and not is_error_response
if turn.use_streaming_tts and turn.box_opened and not is_error_response:
# Text already printed sentence-by-sentence; just close the box.
_cprint(f"\n{_ACCENT}╰{'─' * (self._scrollback_box_width() - 2)}╯{_RST}")
elif already_streamed:
# _flush_stream() already closed the streamed box; a post-stream transform
# hook shows a suffix for append-only changes, else the full replacement.
_post_stream_text = _post_stream_transform_output(response, turn.result)
if _post_stream_text.strip():
_cprint(_post_stream_text)
else:
ChatConsole().print(Panel(
_render_final_assistant_content(response, mode=self.final_response_markdown),
title=f"[{_resp_color} bold]{label}[/]", title_align="left", border_style=_resp_color,
style=_resp_text, box=rich_box.HORIZONTALS, padding=(1, 0),
width=self._scrollback_box_width(),
))
# Billing CTA pins the single action (Nous → /topup, others → billing page) so it
# stays visible instead of scrolling away inside the response prose.
if turn.result and turn.result.get("failure_reason") == "billing":
_bb = turn.result.get("billing_block") or {}
if _bb.get("is_nous"):
_cta_lines = [t("cli.chat.billing_cta_nous")]
else:
_url = _bb.get("billing_url")
_cta_lines = [t("cli.chat.billing_cta_provider",
provider=_bb.get("provider_label") or t("cli.chat.your_provider"))
+ (f": [bold]{_url}[/]" if _url else ".")]
_cta_lines.append(t("cli.chat.billing_cta_switch"))
try:
ChatConsole().print(Panel(
"\n".join(_cta_lines), title=f"[#CD7F32 bold]{t('cli.chat.out_of_credits_title')}[/]",
title_align="left", border_style="#CD7F32", box=rich_box.HORIZONTALS,
padding=(1, 4), width=self._scrollback_box_width(),
))
except Exception:
pass