forked from NousResearch/hermes-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
1820 lines (1568 loc) · 78.9 KB
/
Copy pathcli.py
File metadata and controls
1820 lines (1568 loc) · 78.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Hermes Agent CLI — interactive terminal interface (``python cli.py --help`` for usage)."""
# Must be the very first import (UTF-8 stdio on Windows). Missing only mid-``hermes update``.
try:
import hermes_bootstrap # noqa: F401
except ModuleNotFoundError:
pass
import logging
import os
import functools
import shutil # noqa: F401 — tests patch shutil/time through the cli facade
import sys
import re
import atexit
import errno
import time # noqa: F401 — see shutil
from collections import deque
from dataclasses import dataclass
from contextlib import contextmanager, suppress
from pathlib import Path
from datetime import datetime # noqa: F401 — siblings import it lazily through cli
from typing import List, Dict, Any, Optional
logger = logging.getLogger(__name__)
os.environ["HERMES_QUIET"] = "1" # suppress our modules' startup chatter
from hermes_cli.cli_agent_setup_mixin import CLIAgentSetupMixin
from hermes_cli.cli_commands_mixin import CLICommandsMixin
from hermes_cli.cli_billing_mixin import CLIBillingMixin
from hermes_cli.cli_loops_mixin import CLILoopsMixin
from hermes_cli.cli_info_mixin import CLIInfoMixin
from hermes_cli.cli_terminal_mixin import CLITerminalMixin
from hermes_cli.cli_modal_mixin import CLIModalMixin
from hermes_cli.cli_stream_mixin import CLIStreamMixin
from hermes_cli.cli_session_mixin import CLISessionMixin
from hermes_cli.cli_model_switch_mixin import CLIModelSwitchMixin
from hermes_cli.cli_voice_mixin import CLIVoiceMixin
from hermes_cli.cli_status_bar_mixin import CLIStatusBarMixin
from hermes_cli.cli_tui_mixin import CLITuiMixin
from hermes_cli.cli_process_notifications import CLIProcessNotificationsMixin
from hermes_cli.cli_init_mixin import CLIInitMixin
from hermes_cli.cli_tui_runtime_mixin import CLITuiRuntimeMixin
# Extracted clusters (mechanical split, #116911); re-exported here so `cli.<name>` stays the seam.
from hermes_cli.cli_shutdown import ( # noqa: F401,E402
_CLEANUP_STEPS,
_arm_exit_watchdog,
_emit_interrupted_session_end,
_exit_watchdog_timeout,
_finalize_single_query,
_float_env,
_flush_logging_and_stdio,
_flush_one_shot_session_store,
_interrupt_async_delegations,
_invoke_interrupted_session_end,
_notify_session_finalize,
_notify_single_query_session_finalize,
_oneshot_agent_and_session,
_should_emit_cleanup_session_finalize,
_shutdown_agent_memory_provider,
_shutdown_cached_aux_clients,
_shutdown_mcp_servers,
_stop_cli_wake_word,
_sync_process_session_id,
_wait_for_oneshot_background_completions,
)
from hermes_cli.cli_auto_maintenance import ( # noqa: F401,E402
_run_checkpoint_auto_maintenance,
_run_state_db_auto_maintenance,
)
from hermes_cli.cli_render import ( # noqa: F401,E402
ChatConsole,
_ACCENT,
_ACCENT_ANSI_DEFAULT,
_BOLD,
_DA1_REPLY_RE,
_DIM,
_FALSE_RE,
_LIGHT_DEFAULT_TERM_PROGRAMS,
_LIGHT_MODE_REMAP,
_LIGHT_MODE_REMAP_UPPER,
_REASONING_TAGS,
_RST,
_STREAM_PAD,
_STREAM_PARTIAL_PREVIEW_LEN,
_SkinAwareAnsi,
_TOOL_CALL_TAGS,
_TRUE_RE,
_WINDOWS_PATH_WITH_DOT_SEGMENT_RE,
_accent_hex,
_append_blank_panel_line,
_append_panel_line,
_assistant_content_as_text,
_assistant_copy_text,
_b,
_build_compact_banner,
_clear_output_history,
_cli_visible_print,
_coerce_output_history_limit,
_cprint,
_d,
_detect_light_mode_uncached,
_heal_cooked_mode_drift,
_hex_to_ansi,
_install_skin_light_mode_hook,
_luminance_from_hex,
_maybe_remap_for_light_mode,
_output_history_recording,
_panel_box_width,
_post_stream_transform_output,
_prepend_note_to_message,
_preserve_windows_dot_segments_for_markdown,
_pt_app_is_running,
_pt_print_ansi,
_query_osc11_background,
_record_output_history,
_record_output_history_entry,
_render_final_assistant_content,
_rich_text_from_ansi,
_strip_markdown_syntax,
_strip_reasoning_tags,
_terminal_columns,
_terminal_width_for_streaming,
_tty_wrap,
_wrap_panel_text,
_wrap_panel_text_keep_ws,
)
from hermes_cli.cli_config_load import ( # noqa: F401,E402
_AUXILIARY_TASK_ENV,
_CWD_PLACEHOLDERS,
_TERMINAL_ENV_MAPPINGS,
_cli_config_defaults,
_init_logging_and_display_from_config,
_load_prefill_messages,
_merge_file_config,
_mirror_config_to_env,
_parse_reasoning_config,
_parse_service_tier_config,
_resolve_prefill_messages_file,
load_cli_config,
)
from hermes_cli.cli_terminal_input import ( # noqa: F401,E402
_BACKSLASH_LINE_CONTINUATION_RE,
_DSR_CPR_ESC_RE,
_DSR_CPR_VISIBLE_RE,
_EXTENDED_ENTER_KEYS_SEQ,
_IMAGE_EXTENSIONS,
_KITTY_KEYBOARD_PUSH_SEQ,
_MODIFY_OTHER_KEYS_SEQ,
_SGR_MOUSE_BARE_RE,
_SGR_MOUSE_ESC_RE,
_SGR_MOUSE_VISIBLE_RE,
_TERMINAL_INPUT_MODE_RESET_SEQ,
_apply_backslash_line_continuation,
_apply_bracketed_paste_timeout_patch,
_bind_prompt_submit_keys,
_build_cpr_disabled_output,
_cli_multiline_shortcuts_enabled,
_collect_query_images,
_detect_file_drop,
_disable_prompt_toolkit_cpr_warning,
_enable_extended_enter_keys,
_estimate_tui_input_height,
_file_drop_result,
_format_image_attachment_badges,
_hermes_call_output_screen_diff,
_is_backslash_line_continuation,
_is_ghostty_terminal,
_preserve_ctrl_enter_newline,
_resolve_attachment_path,
_select_classic_cli_pt_output,
_should_auto_attach_clipboard_image_on_paste,
_split_path_input,
_status_bar_visible_from_display_config,
_strip_leaked_terminal_responses_with_meta,
_terminal_may_leak_cpr,
_terminal_supports_extended_enter_keys,
_termux_example_image_path,
)
from hermes_cli.cli_single_query import ( # noqa: F401,E402
_TERMINAL_PROVIDER_REASONS,
_TRANSIENT_PROVIDER_REASONS,
_collect_kanban_task_images,
_configure_quiet_agent,
_install_single_query_signal_handlers,
_int_or,
_interrupt_agent_for_signal,
_route_single_query_images,
_run_kanban_goal_loop_chat,
_run_kanban_goal_loop_q,
_run_quiet_single_query,
_run_single_query_mode,
_single_query_exit_code,
_sync_cli_session_id_from_agent,
)
from prompt_toolkit.patch_stdout import patch_stdout
try:
from prompt_toolkit.enums import EditingMode
except ImportError: # partial prompt_toolkit stubs in tests
EditingMode = None
from prompt_toolkit import print_formatted_text as _pt_print
from prompt_toolkit.formatted_text import ANSI as _PT_ANSI
try:
from prompt_toolkit.cursor_shapes import CursorShape
_STEADY_CURSOR = CursorShape.BLOCK
except (ImportError, AttributeError):
_STEADY_CURSOR = None
try:
from hermes_cli import pt_input_extras as _pt_extras
_pt_extras.install_shift_enter_alias()
_pt_extras.install_ctrl_enter_alias()
_pt_extras.install_cmd_backspace_alias()
_pt_extras.install_modify_other_keys_aliases()
_pt_extras.install_keypress_data_normalization()
_pt_extras.install_ignored_terminal_sequences()
del _pt_extras
except Exception:
pass
import threading
import queue
def _lazy_shim(module: str, name: str, alias: str | None = None):
"""Import ``module.name`` on first call; keeps heavy imports off startup while ``cli.<name>`` stays patchable."""
import importlib
def shim(*args, **kwargs):
return getattr(importlib.import_module(module), name)(*args, **kwargs)
shim.__name__ = shim.__qualname__ = alias or name
return shim
def format_duration_compact(*args, **kwargs):
seconds = float(args[0] if args else kwargs.get("seconds", 0.0))
if seconds < 60:
return f"{seconds:.0f}s"
minutes = seconds / 60
if minutes < 60:
return f"{minutes:.0f}m"
hours = minutes / 60
if hours < 24:
remaining_min = int(minutes % 60)
return f"{int(hours)}h {remaining_min}m" if remaining_min else f"{int(hours)}h"
days = hours / 24
return f"{days:.1f}d"
# model id -> shortest configured alias (process-lifetime cache; config is read once).
_REVERSE_ALIAS_CACHE: dict[str, str] | None = None
def _reverse_alias_for_display(model_name: str) -> str:
"""Shortest alias for ``model_name`` from ``model_aliases:`` or ``model.aliases:``, else ``model_name``."""
global _REVERSE_ALIAS_CACHE
if not model_name:
return model_name
if _REVERSE_ALIAS_CACHE is None:
rmap: dict[str, str] = {}
def _put(m: str, alias: str) -> None:
if m and (m not in rmap or len(alias) < len(rmap[m])):
rmap[m] = alias
try:
from hermes_cli.config import load_config
cfg = load_config() or {}
ma = cfg.get("model_aliases")
if isinstance(ma, dict):
for alias, entry in ma.items():
if isinstance(entry, dict):
_put(str(entry.get("model", "") or "").strip(), alias)
mdl = cfg.get("model", {}) or {}
if isinstance(mdl, dict):
simple = mdl.get("aliases")
if isinstance(simple, dict):
for alias, val in simple.items():
if isinstance(val, str) and val.strip():
v = val.strip()
_put(v.split("/", 1)[1] if "/" in v else v, alias)
except Exception:
pass
_REVERSE_ALIAS_CACHE = rmap
return _REVERSE_ALIAS_CACHE.get(model_name, model_name)
def format_token_count_compact(*args, **kwargs):
value = int(args[0] if args else kwargs.get("value", 0))
abs_value = abs(value)
if abs_value < 1_000:
return str(value)
sign = "-" if value < 0 else ""
units = ((1_000_000_000, "B"), (1_000_000, "M"), (1_000, "K"))
for threshold, suffix in units:
if abs_value >= threshold:
scaled = abs_value / threshold
text = f"{scaled:.{2 if scaled < 10 else 1 if scaled < 100 else 0}f}"
if "." in text:
text = text.rstrip("0").rstrip(".")
return f"{sign}{text}{suffix}"
return f"{value:,}"
realign_markdown_tables = _lazy_shim("agent.markdown_tables", "realign_markdown_tables")
_COMMAND_SPINNER_FRAMES = ("⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏")
# ~/.hermes/.env first, project .env as dev fallback; user env files override stale shell exports.
from hermes_constants import get_hermes_home
from hermes_cli.env_loader import load_hermes_dotenv
_hermes_home = get_hermes_home()
_project_env = Path(__file__).parent / '.env'
load_hermes_dotenv(hermes_home=_hermes_home, project_env=_project_env)
CLI_CONFIG = load_cli_config()
_init_logging_and_display_from_config()
# Neuter AsyncHttpxClientWrapper.__del__ before any AsyncOpenAI client exists: it
# schedules aclose() on the running loop (prompt_toolkit's, during idle), closing
# transports bound to dead worker loops ("Event loop is closed" / "Press ENTER to
# continue..."). A meta_path finder patches ``openai._base_client`` at first import —
# eager import costs ~166ms/30MB cold, and the patch is guaranteed to land before
# instantiation. See ``agent.auxiliary_client.neuter_async_httpx_del``.
try:
import sys as _httpx_neuter_sys
import importlib.util as _httpx_neuter_imp_util
class _AsyncHttpxDelNeuter:
"""Patch ``AsyncHttpxClientWrapper.__del__`` to a no-op when ``openai._base_client`` loads."""
_armed = True
def find_spec(self, fullname, path=None, target=None):
if not self._armed or fullname != "openai._base_client":
return None
# Disarm before delegating so the recursive find_spec doesn't loop through us.
self._armed = False
try:
_httpx_neuter_sys.meta_path.remove(self)
except ValueError:
pass
spec = _httpx_neuter_imp_util.find_spec(fullname)
if spec is None or spec.loader is None:
return None
_orig_exec = spec.loader.exec_module
def _patched_exec(module):
_orig_exec(module)
try:
cls = getattr(module, "AsyncHttpxClientWrapper", None)
if cls is not None:
cls.__del__ = lambda self: None # type: ignore[assignment]
except Exception:
pass
spec.loader.exec_module = _patched_exec # type: ignore[method-assign]
return spec
_httpx_neuter_sys.meta_path.insert(0, _AsyncHttpxDelNeuter())
except Exception:
pass
# Agent/tool systems load lazily: bare startup only needs the prompt.
def get_tool_definitions(*args, **kwargs):
from hermes_cli.mcp_startup import wait_for_mcp_discovery
from model_tools import get_tool_definitions as _get_tool_definitions
wait_for_mcp_discovery()
return _get_tool_definitions(*args, **kwargs)
validate_toolset = _lazy_shim("toolsets", "validate_toolset")
_cleanup_all_terminals = _lazy_shim("tools.terminal_tool", "cleanup_all_environments", "_cleanup_all_terminals")
set_sudo_password_callback = _lazy_shim("tools.terminal_tool", "set_sudo_password_callback")
set_approval_callback = _lazy_shim("tools.terminal_tool", "set_approval_callback")
set_secret_capture_callback = _lazy_shim("tools.skills_tool", "set_secret_capture_callback")
_cleanup_all_browsers = _lazy_shim("tools.browser_tool_lifecycle", "_emergency_cleanup_all_sessions", "_cleanup_all_browsers")
_cleanup_done = False # _run_cleanup runs exactly once
_cleanup_in_progress = False
_cli_wake_owner = None
# One-shot finalization runs before process cleanup (plugins see the boundary while the
# agent is attached); atexit cleanup must not finalize those sessions again.
_single_query_finalize_attempted_session_ids: set[str | None] = set()
# /handoff sessions belong to the gateway: finalizing them here would stamp end_reason on
# a row the gateway just reopened, making the handoff leg vanish from history.
# Session IDs that were handed off to the gateway via /handoff. The CLI process exits after a successful
# handoff, but the gateway now owns the session lifecycle — _run_cleanup must NOT call finalize_session on
# these, because doing so sets end_reason on a row the gateway just reopened and is actively writing to
# (#88234). The race made the handoff leg vanish from session history and broke session_search recall for
# the handed-off session.
_handed_off_session_ids: set[str | None] = set()
_active_agent_ref = None # active AIAgent, for memory-provider shutdown at exit
_deferred_agent_startup_done = False
# Set once the TUI app starts (focus reporting + mouse tracking on); gates the on-exit
# terminal reset so non-TUI one-shot runs never emit codes for modes they never enabled.
_tui_input_modes_active = False
# Set True once the TUI's prompt_toolkit app starts (which enables focus reporting + mouse tracking). Gates
# the on-exit terminal reset so non-TUI one-shot CLI runs — which also register _run_cleanup via atexit —
# don't emit escape codes for modes they never enabled (#36823).
def _mark_tui_input_modes_active() -> None:
"""Record that the TUI app started, so _run_cleanup resets input modes."""
global _tui_input_modes_active
_tui_input_modes_active = True
def _prepare_deferred_agent_startup() -> None:
"""Run Termux-deferred agent discovery before the first real agent turn."""
global _deferred_agent_startup_done
if _deferred_agent_startup_done:
return
if os.environ.get("HERMES_DEFER_AGENT_STARTUP") != "1":
return
_deferred_agent_startup_done = True
_accept_hooks = os.environ.get("HERMES_ACCEPT_HOOKS", "").lower() in {"1", "true", "yes", "on"}
try:
from hermes_cli.plugins import discover_plugins
discover_plugins()
except Exception:
logger.warning("plugin discovery failed at deferred CLI startup", exc_info=True)
try:
from hermes_cli.mcp_startup import start_background_mcp_discovery
start_background_mcp_discovery(logger=logger, thread_name="termux-cli-mcp-discovery")
except Exception:
logger.debug("MCP tool discovery failed at deferred CLI startup", exc_info=True)
try:
from agent.shell_hooks import register_from_config
from agent.outbound_webhooks import register_from_config as register_outbound_webhooks
from hermes_cli.config import load_config
_hooks_cfg = load_config()
register_from_config(_hooks_cfg, accept_hooks=_accept_hooks)
register_outbound_webhooks(_hooks_cfg)
except Exception:
logger.debug("shell-hook registration failed at deferred CLI startup", exc_info=True)
_signal_watchdog_armed = False
def _arm_exit_watchdog_on_shutdown_signal() -> None:
"""Arm the exit backstop the moment a termination signal arrives (idempotent; never raises).
The graceful unwind has wedge points BEFORE ``_run_cleanup`` arms its own watchdog
(main thread in a syscall, prompt_toolkit teardown never returning). Leash is 2x
the cleanup timeout so a progressing cleanup is never cut short. Never arm at
startup: the timer exits unconditionally.
SIGTERM/SIGHUP establish unambiguous shutdown intent, but the graceful path from signal →
``agent.interrupt()`` → ``app.exit()`` / ``KeyboardInterrupt`` → ``finally`` → ``_run_cleanup`` has
several wedge points BEFORE ``_run_cleanup`` arms the normal watchdog: a main thread parked in a syscall
that never observes the unwind, a prompt_toolkit teardown that never returns, or an agent worker
blocking the ``finally``. When that happens the process has NO backstop and a "dead" CLI lingers
(observed: ``hermes --tui`` alive ~47 min at 4% CPU after terminal close — the #65998 class).
"""
global _signal_watchdog_armed
if _signal_watchdog_armed:
return
_signal_watchdog_armed = True
base = _exit_watchdog_timeout()
if base <= 0:
return # explicitly disabled
with suppress(Exception): # never let the backstop break signal handling
_arm_exit_watchdog(timeout_s=base * 2, from_signal=True)
def _run_cleanup(*, notify_session_finalize: bool = True):
"""Run resource cleanup exactly once."""
global _cleanup_done, _cleanup_in_progress
if _cleanup_done:
return
_cleanup_done = True
_cleanup_in_progress = True
try:
_arm_exit_watchdog()
# Reset terminal input modes FIRST: teardown below can take seconds and a later
# step raising must not skip the reset. No-op unless the TUI ran.
# See #36823.
_reset_terminal_input_modes_on_exit()
for step, swallow in _CLEANUP_STEPS:
with suppress(swallow):
globals()[step]()
if notify_session_finalize:
cleanup_session_id = _active_agent_ref.session_id if _active_agent_ref else None
if _should_emit_cleanup_session_finalize(cleanup_session_id):
_notify_session_finalize(session_id=cleanup_session_id, platform="cli", reason="shutdown")
try:
_shutdown_agent_memory_provider(_active_agent_ref)
except Exception as e:
logger.warning("CLI cleanup memory shutdown failed: %s", e, exc_info=True)
finally:
_cleanup_in_progress = False
def _reset_terminal_input_modes_on_exit() -> None:
"""Disable focus reporting + mouse tracking on TUI exit (best-effort).
Ctrl+C / SIGTERM / crashes bypass prompt_toolkit's unwind, leaving focus events and
mouse reports as visible text in the next shell. Writes to stdout when it is the
terminal, else /dev/tty (the TUI may have run with stdout redirected).
Called from ``_run_cleanup`` (atexit-registered + invoked on the normal / EOF / interrupt exit paths)
this covers normal quit, Ctrl+C and SIGTERM/SIGHUP. ``kill -9`` is uncatchable, and the kanban worker's
``os._exit(0)`` path bypasses ``atexit``; neither runs this — but both are non-TTY / non-TUI, so there
is nothing to reset there. See #36823.
"""
global _tui_input_modes_active
if not _tui_input_modes_active:
return
# Clear first so a re-armed _run_cleanup doesn't re-emit.
_tui_input_modes_active = False
try:
stream = sys.stdout
if stream is not None and stream.isatty():
stream.write(_TERMINAL_INPUT_MODE_RESET_SEQ)
stream.flush()
return
except Exception:
pass
with suppress(Exception), open("/dev/tty", "w", encoding="ascii") as tty:
tty.write(_TERMINAL_INPUT_MODE_RESET_SEQ)
tty.flush()
from hermes_cli.worktree_ops import (
_git_quiet,
_git_repo_root,
_maintain_pack_health,
_prune_stale_worktrees,
_repo_is_shallow,
_setup_worktree,
_worktree_has_unpushed_commits,
release_lsp_clients,
)
# ============================================================================= Git Worktree Isolation
# (#652) =============================================================================
_active_worktree: Optional[Dict[str, str]] = None
def _cleanup_worktree(info: Dict[str, str] = None) -> None:
"""Remove a worktree and its branch on exit; kept only when it has unpushed commits."""
global _active_worktree
info = info or _active_worktree
if not info:
return
wt_path, branch, repo_root = info["path"], info["branch"], info["repo_root"]
if not Path(wt_path).exists():
return
if _worktree_has_unpushed_commits(wt_path, timeout=10):
if _repo_is_shallow(repo_root):
# Shallow boundary makes the unpushed verdict unreliable; the startup pruner reaps later.
_cprint(f"\n\033[33m⚠ Shallow clone — cannot verify push state, keeping: {wt_path}\033[0m")
print(" The next `hermes -w` session deepens the clone and prunes merged worktrees automatically.")
else:
_cprint(f"\n\033[33m⚠ Worktree has unpushed commits, keeping: {wt_path}\033[0m")
print(f" To clean up manually: git worktree remove --force {wt_path}")
_active_worktree = None
return
# Release the tree's language servers while the path still exists, then unlock so `remove`
# isn't blocked by the lock placed at creation. Fail-soft.
release_lsp_clients(wt_path)
_git_quiet(["worktree", "unlock", wt_path], repo_root, log="git worktree unlock failed (non-fatal)")
_git_quiet(["worktree", "remove", wt_path, "--force"], repo_root, timeout=15, log="Failed to remove worktree")
_git_quiet(["branch", "-D", branch], repo_root, log=f"Failed to delete branch {branch}")
_active_worktree = None
_cprint(f"\033[32m✓ Worktree cleaned up: {wt_path}\033[0m")
# Light/dark terminal detection (mirrors ui-tui/src/theme.ts detectLightMode()). Priority:
# HERMES_LIGHT/HERMES_TUI_LIGHT env, HERMES_TUI_THEME, HERMES_TUI_BACKGROUND, COLORFGBG
# (bg slot 7/15 = light), OSC 11 query, default dark. Cached so the terminal is queried once.
_LIGHT_MODE_CACHE: bool | None = None
def _detect_light_mode() -> bool:
global _LIGHT_MODE_CACHE
if _LIGHT_MODE_CACHE is not None:
return _LIGHT_MODE_CACHE
try:
result = _detect_light_mode_uncached()
except Exception:
result = False
_LIGHT_MODE_CACHE = result
return result
_install_skin_light_mode_hook()
# Prime the light-mode cache when interactive so OSC 11 happens before prompt_toolkit owns the tty.
with suppress(Exception):
if sys.stdin.isatty() and sys.stdout.isatty():
_detect_light_mode()
_OUTPUT_HISTORY_ENABLED = True
_OUTPUT_HISTORY_REPLAYING = False
_OUTPUT_HISTORY_SUPPRESSED = False
_OUTPUT_HISTORY_MAX_LINES = 200
_OUTPUT_HISTORY = deque(maxlen=_OUTPUT_HISTORY_MAX_LINES)
def _configure_output_history(enabled: bool, max_lines=200) -> None:
"""Configure recent CLI output replayed after terminal redraws."""
global _OUTPUT_HISTORY_ENABLED, _OUTPUT_HISTORY_MAX_LINES, _OUTPUT_HISTORY
_OUTPUT_HISTORY_ENABLED = bool(enabled)
_OUTPUT_HISTORY_MAX_LINES = _coerce_output_history_limit(max_lines)
_OUTPUT_HISTORY = deque(maxlen=_OUTPUT_HISTORY_MAX_LINES)
@contextmanager
def _suspend_output_history():
global _OUTPUT_HISTORY_SUPPRESSED
old_value = _OUTPUT_HISTORY_SUPPRESSED
_OUTPUT_HISTORY_SUPPRESSED = True
try:
yield
finally:
_OUTPUT_HISTORY_SUPPRESSED = old_value
def _replay_output_history() -> None:
"""Repaint recent output above the prompt after a full screen clear."""
global _OUTPUT_HISTORY_REPLAYING
if not _OUTPUT_HISTORY_ENABLED or not _OUTPUT_HISTORY:
return
_OUTPUT_HISTORY_REPLAYING = True
try:
rendered_lines = []
for entry in tuple(_OUTPUT_HISTORY):
lines = [entry]
if callable(entry):
try:
lines = entry()
except Exception:
continue
if isinstance(lines, str):
lines = lines.splitlines()
rendered_lines.extend(str(line) for line in lines)
if rendered_lines:
# One payload: per-line pt prints each force a sync redraw (a waterfall of old output).
_pt_print(_PT_ANSI("\n".join(rendered_lines)))
except Exception:
pass
finally:
_OUTPUT_HISTORY_REPLAYING = False
_strip_leaked_bracketed_paste_wrappers = _lazy_shim(
"hermes_cli.input_sanitize", "strip_leaked_bracketed_paste_wrappers", "_strip_leaked_bracketed_paste_wrappers"
)
# OSC sequences (e.g. OSC-8 links): pt's ANSI parser strips the ESC but leaks the payload as text.
_OSC_ESCAPE_RE = re.compile(r"\x1b\][\s\S]*?(?:\x07|\x1b\\)")
def _looks_like_slash_command(text: str) -> bool:
"""``/help`` yes, ``/Users/x/file.md`` no: a command's first word has no further ``/``."""
if not text or not text.startswith("/"):
return False
return "/" not in text.split()[0][1:]
_skill_commands = None
_skill_bundles = None
def _slash_args(cmd: str) -> str:
"""Text after the slash-command word, stripped ("" when absent)."""
parts = cmd.split(None, 1)
return parts[1].strip() if len(parts) > 1 else ""
def _ensure_skill_commands() -> dict:
global _skill_commands
if _skill_commands is None:
from agent.skill_commands import scan_skill_commands
_skill_commands = scan_skill_commands()
return _skill_commands
def get_skill_commands() -> dict:
return _ensure_skill_commands()
build_skill_invocation_message = _lazy_shim("agent.skill_commands", "build_skill_invocation_message")
build_preloaded_skills_prompt = _lazy_shim("agent.skill_commands", "build_preloaded_skills_prompt")
def get_skill_bundles() -> dict:
global _skill_bundles
if _skill_bundles is None:
from agent.skill_bundles import get_skill_bundles as _impl
_skill_bundles = _impl()
return _skill_bundles
build_bundle_invocation_message = _lazy_shim("agent.skill_bundles", "build_bundle_invocation_message")
def _get_plugin_cmd_handler_names() -> set:
"""Return plugin command names (without slash prefix) for dispatch matching."""
try:
from hermes_cli.plugins import get_plugin_commands
return set(get_plugin_commands().keys())
except Exception:
return set()
def _parse_skills_argument(skills: str | list[str] | tuple[str, ...] | None) -> list[str]:
"""Normalize a CLI skills flag into a deduplicated list of skill identifiers."""
if not skills:
return []
raw_values = [str(item) for item in skills if item is not None] if isinstance(skills, (list, tuple)) else [str(skills)]
parts = (p.strip() for raw in raw_values for p in raw.split(","))
return list(dict.fromkeys(p for p in parts if p))
def save_config_value(key_path: str, value: any) -> bool:
"""Persist dot-separated ``key_path`` = value into HERMES_HOME/config.yaml; True on success.
Never the repo's cli-config.yaml: no config reader loads it, so the value would vanish.
"""
config_path = get_hermes_home() / 'config.yaml'
try:
from hermes_constants import mkdir_under_hermes_home
mkdir_under_hermes_home(config_path.parent)
from utils import atomic_roundtrip_yaml_update
atomic_roundtrip_yaml_update(config_path, key_path, value)
try: # owner-only: config files contain API keys
os.chmod(config_path, 0o600)
except (OSError, NotImplementedError):
pass
return True
except Exception as e:
logger.error("Failed to save config: %s", e)
return False
def _normalize_moa_model(model: Optional[str]) -> tuple[Optional[str], Optional[str]]:
"""``moa:<preset>`` -> ``("moa", preset)`` (same routing as ``/moa``); anything else -> ``(None, model)``.
Returns ``("moa", "<preset>")`` when *model* selects the MoA virtual provider, otherwise ``(None,
model)`` unchanged. This gives non-interactive ``hermes chat -Q -m moa:<preset>`` the same routing the
interactive ``/moa`` command and the model picker already use: ``resolve_runtime_provider`` handles
``requested_provider == "moa"`` and ``agent_init`` builds the MoAClient off ``provider == "moa"``.
Without this the raw ``moa:<preset>`` string is sent to the real provider and rejected with a 401/400
"model not supported" (#56828).
"""
if isinstance(model, str) and model.strip().lower().startswith("moa:"):
preset = model.strip().split(":", 1)[1].strip()
if preset:
return "moa", preset
return None, model
_split_model_config_default = _lazy_shim("hermes_cli.config", "split_model_config_default", "_split_model_config_default")
class _VoiceInputMessage:
"""Sentinel for voice-transcribed input so the concise voice prefix never applies to typed text.
Distinguishes STT output from manually typed text while voice mode is active, so the
concise-voice-response prefix is applied only to messages that actually came from the microphone
(#65827).
"""
__slots__ = ("text",)
def __init__(self, text: str):
self.text = text
def __str__(self) -> str:
return self.text
class _SeededQueryMessage:
"""Sentinel for a ``-q`` prompt seeded into an interactive session; treated LITERALLY (no slash/!/file-drop)."""
__slots__ = ("text", "images")
def __init__(self, text: str, images=None):
self.text = text or ""
self.images = list(images or [])
def __str__(self) -> str:
return self.text
def _should_seed_interactive(query, image, quiet: bool, oneshot: bool) -> bool:
"""``-q`` seeds an interactive session only on a real TTY without ``--oneshot``/``-Q`` (automation answers and exits)."""
if not (query or image) or oneshot or quiet:
return False
try:
return bool(sys.stdin.isatty() and sys.stdout.isatty())
except Exception:
return False
@dataclass
class _ChatTurn:
"""Per-turn state shared by the ``chat()`` phases and the agent worker thread.
``result`` is written by the worker and read after the join; ``tts_normal_exit`` is
set only when the TTS worker drained on its own so the last sentence is never cut.
"""
result: Optional[dict] = None
mute_notification_reply: bool = False
use_streaming_tts: bool = False
box_opened: bool = False
thinking_started: bool = False
text_queue: Optional[queue.Queue] = None
tts_thread: Optional[threading.Thread] = None
stream_callback: Optional[Any] = None
stop_event: Optional[threading.Event] = None
tts_normal_exit: bool = False
voice_prefix: str = ""
from hermes_cli.cli_chat_turn_mixin import CLIChatTurnMixin
_PASTE_REF_RE = re.compile(r'\[Pasted text #\d+: \d+ lines \u2192 (.+?)\]')
class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin, CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin, CLITuiMixin, CLIStatusBarMixin, CLIVoiceMixin, CLIModelSwitchMixin, CLISessionMixin, CLIStreamMixin, CLIModalMixin, CLITerminalMixin, CLIInfoMixin, CLILoopsMixin, CLIChatTurnMixin):
"""Interactive REPL for the Hermes Agent."""
# Seeded -q first message (see _should_seed_interactive); run() re-creates
# _pending_input, so it is enqueued only after the fresh queue exists.
_seeded_first_message: Optional["_SeededQueryMessage"] = None
# Inspection surfaces (banner, /tools, status line) read this on partially built instances too.
disabled_toolsets: Optional[List[str]] = None
def __init__(
self,
model: str = None,
toolsets: List[str] = None,
provider: str = None,
reasoning: str = None,
api_key: str = None,
base_url: str = None,
max_turns: int = None,
run_budget: float = None,
verbose: Optional[bool] = None,
compact: bool = False,
resume: str = None,
checkpoints: bool = False,
pass_session_id: bool = False,
ignore_rules: bool = False,
):
"""CLI args win over config; ``reasoning`` is per-run only; ``resume`` restores history from SQLite."""
self._init_display_options(verbose, compact)
self._init_model_routing(model, toolsets, provider, reasoning, api_key, base_url, max_turns, run_budget,
checkpoints, pass_session_id, ignore_rules)
self._init_runtime_state(resume)
def _claim_active_session(self, surface: str = "cli", *, stderr: bool = False) -> bool:
"""Claim a global active-session slot for this CLI process."""
if self._active_session_lease is not None:
return True
try:
from hermes_cli.active_sessions import format_refusal_stderr, try_acquire_active_session
lease, message = try_acquire_active_session(
session_id=self.session_id,
surface=surface,
config=self.config,
# Writer identity: a re-claim by this process replaces its own entry.
# See #94595.
metadata={"live_session_id": str(self.session_id)},
)
except Exception as exc:
logger.warning("Failed to claim active session slot: %s", exc)
return True
if message:
print(format_refusal_stderr(message), file=sys.stderr) if stderr else self._console_print(f"[bold red]{message}[/]")
return False
self._active_session_lease = lease
with suppress(Exception):
atexit.register(self._release_active_session)
return True
def _release_active_session(self) -> None:
lease = getattr(self, "_active_session_lease", None)
if lease is None:
return
try:
lease.release()
except Exception:
logger.debug("Failed to release active session slot", exc_info=True)
finally:
self._active_session_lease = None
_PET_FRAME_INTERVAL = 0.16
_PET_CFG_INTERVAL = 2.5
def _install_tool_callbacks(self) -> None:
"""Install tool callbacks that need the live prompt UI."""
if self._tool_callbacks_installed:
return
set_sudo_password_callback(self._sudo_password_callback)
set_approval_callback(self._approval_callback)
set_secret_capture_callback(self._secret_capture_callback)
from agent.vault_backends.unlock import set_code_prompt_callback, set_save_login_prompt_callback, set_unlock_prompt_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)
self._tool_callbacks_installed = True
def _ensure_tirith_security(self) -> None:
"""Check tirith availability once before tools can run terminal commands."""
if self._tirith_security_checked:
return
self._tirith_security_checked = True
try:
from tools.tirith_security import ensure_installed, is_platform_supported
if (
ensure_installed(log_failures=False) is None and is_platform_supported()
and (self.config.get("security", {}) or {}).get("tirith_enabled", True)
):
_cprint(
f" {_DIM}⚠ tirith security scanner enabled but not available "
f"— command scanning will use pattern matching only{_RST}"
)
except Exception:
pass
def _show_security_advisories(self):
"""Startup banner for unacked security advisories, on stderr (piped stdout stays clean); 24h rate-limited."""
try:
from hermes_cli.security_advisories import detect_compromised, startup_banner
banner = startup_banner(detect_compromised())
if banner:
print(banner, file=sys.stderr, flush=True)
except Exception:
pass # never block startup
def _show_browser_backend_notice(self):
"""Once-per-24h hint when the default Browser Use backend silently fell back to built-in tools."""
try:
from tools.browser_use_cli import default_downgrade_notice
notice = default_downgrade_notice()
if notice:
from gateway.warning_notifications import render_notification
render_notification(lambda: self._console_print(f"[yellow]⚠ {notice}[/yellow]"), platform="cli")
except Exception:
logger.debug("browser backend notice failed", exc_info=True)
def finalize_preloaded_skills(self) -> None:
"""Join the background --skills preload and fold it into the prompt (idempotent).
Raises ``ValueError`` only when EVERY requested skill was unknown.
"""
if getattr(self, "_preload_skills_finalized", False):
return
thread = getattr(self, "_preload_skills_thread", None)
if thread is None:
self._preload_skills_finalized = True
return
thread.join(timeout=120)
self._preload_skills_finalized = True
err = getattr(self, "_preload_skills_error", None)
if err is not None:
raise err
auto_result = getattr(self, "_auto_load_skills_result", None)
if auto_result and auto_result[2]: