main.py 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543
  1. #!/usr/bin/env python3
  2. """Hermes CLI - Main entry point.
  3. Usage:
  4. hermes # Interactive chat (default)
  5. hermes chat / gateway / setup / status / cron / doctor / update / ...
  6. hermes --version # Show version and update status
  7. hermes <cmd> --help # Per-command help
  8. """
  9. # hermes_bootstrap must be the very first import — it sets up UTF-8 stdio on
  10. # Windows (no-op on POSIX). Guarded: after a ``git pull`` / interrupted
  11. # ``hermes update`` the editable install's ``.pth`` may not list it yet; crashing
  12. # here would block ``hermes update``.
  13. try:
  14. import hermes_bootstrap
  15. except ModuleNotFoundError as exc:
  16. if exc.name != "hermes_bootstrap":
  17. raise # the bootstrap exists but cannot load: skipping it would skip PM activation
  18. # A `hermes update` killed while git was writing the new tree leaves a mix of old and new files that
  19. # fails at the next import, whichever it is — put the old tree back before importing anything else
  20. # from the checkout, then rerun the command (this module may itself be one of the new files).
  21. # ``_early_recovery`` is stdlib-only and imported unguarded on purpose: same package
  22. # dir, so if IT can't import nothing in hermes_cli can.
  23. from hermes_cli import _early_recovery as _early_recovery_mod
  24. if _early_recovery_mod.restore_interrupted_pull():
  25. _early_recovery_mod.relaunch_after_restore()
  26. # Windows: neutralize CPython's ``platform._syscmd_ver`` before anything else
  27. # imports — it shells out ``cmd /c ver`` and flashes a console when this
  28. # process is windowless (pythonw gateway, kanban workers). No-op on POSIX.
  29. from hermes_cli._subprocess_compat import suppress_platform_ver_console
  30. suppress_platform_ver_console()
  31. import os
  32. import re
  33. import sys
  34. # Inline path math so ``python hermes_cli/main.py`` (script mode: sys.path[0]
  35. # is hermes_cli/, not the repo root) can import hermes_cli._startup_fast.
  36. _bootstrap_root = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir))
  37. if _bootstrap_root not in sys.path:
  38. sys.path.insert(0, _bootstrap_root)
  39. from hermes_cli import _startup_fast
  40. import itertools
  41. # A literal ``~``/``$VAR`` in HERMES_HOME (fish, or any quoted value) must become absolute
  42. # before the first reader — otherwise it resolves against cwd and scaffolds <cwd>/~/.hermes.
  43. _startup_fast.normalize_hermes_home_env()
  44. # Startup-liveness watchdog: for gateway runs, arm BEFORE the heavy import
  45. # graph below — an import-time deadlock (native-extension init, contended
  46. # import lock) is exactly the "wedged before the event loop, no logs, live
  47. # PID" class it exists for. ``hermes_startup_watchdog`` is stdlib-only so it
  48. # cannot itself wedge. The match requires the ADJACENT pair ``gateway run``
  49. # (wherever global flags like ``-p <profile>`` put it) so unrelated commands
  50. # mentioning both words never arm a 300s hard-exit timer. Foreground runs arm
  51. # too — a pre-loop wedge is just as dead without a supervisor; GatewayRunner
  52. # disarms once the event loop is live.
  53. def _argv_is_gateway_run(argv: list) -> bool:
  54. return any(a == "gateway" and b == "run" for a, b in itertools.pairwise(argv))
  55. if _argv_is_gateway_run(sys.argv[1:]):
  56. try:
  57. from hermes_startup_watchdog import arm_startup_watchdog as _arm_sw
  58. _arm_sw()
  59. del _arm_sw
  60. except Exception:
  61. pass
  62. def _exit_after_oneshot(rc: object) -> None:
  63. """Exit one-shot mode without letting late native finalizers change rc.
  64. The SIGABRT this guards against fires in a native-extension finalizer
  65. during ``Py_FinalizeEx``, *after* the response printed. Flush, shut down
  66. file logging, then ``os._exit`` past finalization. The ``atexit`` chain is
  67. deliberately skipped — several handlers re-enter native code that may be
  68. the abort source; stateful cleanup lives in ``_cleanup_oneshot_runtime``.
  69. See #30387, #43055.
  70. """
  71. for stream in (sys.stdout, sys.stderr):
  72. try:
  73. stream.flush()
  74. except Exception:
  75. pass
  76. from hermes_cli.cpu_profile import write_cpu_profile
  77. write_cpu_profile() # atexit never runs past os._exit
  78. try:
  79. logging.shutdown()
  80. except Exception:
  81. pass
  82. os._exit(rc if isinstance(rc, int) else (0 if rc is None else 1))
  83. _oneshot_cleanup_done = False
  84. # (module, attr, kwargs, exceptions swallowed). MCP shutdown may raise
  85. # BaseException-derived errors from executor teardown; the rest are Exception.
  86. _ONESHOT_CLEANUPS = (
  87. ("tools.terminal_tool", "cleanup_all_environments", {}, Exception),
  88. ("tools.async_delegation", "interrupt_all", {"reason": "oneshot shutdown"}, Exception),
  89. ("tools.browser_session_lifecycle", "emergency_cleanup_all_sessions", {}, Exception),
  90. ("tools.mcp_tool_lifecycle", "shutdown_mcp_servers", {}, BaseException),
  91. ("agent.auxiliary_client", "shutdown_cached_clients", {}, Exception),
  92. # A no-op unless this run booted the managed llama-server (atexit's hook is skipped here).
  93. ("hermes_cli.local_runtime.bootstrap", "shutdown_local_runtime", {}, Exception),
  94. # The atexit hook that closes the metrics session never runs past os._exit.
  95. ("hermes_cli.observability.relay_shared_metrics", "shutdown_runtimes", {}, Exception),
  96. )
  97. def _cleanup_oneshot_runtime() -> None:
  98. """Best-effort process-global cleanup before one-shot hard exit.
  99. ``run_oneshot`` owns the agent-local cleanup (memory provider, agent.close,
  100. session_db.close — all in ``_run_agent``'s finally block). This mirrors the
  101. process-global pieces from ``cli.py:_run_cleanup()`` that would otherwise
  102. be skipped by ``os._exit``.
  103. """
  104. global _oneshot_cleanup_done
  105. if _oneshot_cleanup_done:
  106. return
  107. _oneshot_cleanup_done = True
  108. import importlib
  109. for module, attr, kwargs, swallow in _ONESHOT_CLEANUPS:
  110. try:
  111. getattr(importlib.import_module(module), attr)(**kwargs)
  112. except swallow:
  113. pass
  114. def _run_and_exit_oneshot(
  115. prompt: str,
  116. *,
  117. model: object = None,
  118. provider: object = None,
  119. toolsets: object = None,
  120. skills: object = None,
  121. usage_file: object = None,
  122. resume: object = None,
  123. reasoning: object = None,
  124. ) -> None:
  125. try:
  126. from hermes_cli.oneshot import run_oneshot
  127. rc = run_oneshot(
  128. prompt,
  129. model=model,
  130. provider=provider,
  131. toolsets=toolsets,
  132. skills=skills,
  133. usage_file=usage_file,
  134. resume=resume,
  135. reasoning=reasoning,
  136. )
  137. except KeyboardInterrupt:
  138. rc = 130
  139. except SystemExit as exc:
  140. if exc.code is not None and not isinstance(exc.code, int):
  141. print(exc.code, file=sys.stderr)
  142. rc = 1
  143. else:
  144. rc = exc.code
  145. except BaseException:
  146. # ``run_oneshot`` already maps agent failures to an int rc; anything
  147. # still escaping means it malfunctioned. Print it but never fall
  148. # through to interpreter teardown (the SIGABRT path this routine fixes).
  149. import traceback
  150. try:
  151. traceback.print_exc()
  152. except Exception:
  153. pass
  154. rc = 1
  155. try:
  156. _cleanup_oneshot_runtime()
  157. finally:
  158. # Even an interrupt during cleanup must not fall back into interpreter
  159. # finalization, where the native SIGABRT occurs.
  160. # The hard exit is the safety boundary for #43055.
  161. _exit_after_oneshot(rc)
  162. def _warn_if_unsupervised_pid1(pid: int | None = None) -> None:
  163. """Warn when this process is PID 1 with nothing above it to reap orphans.
  164. The official image's ENTRYPOINT (``docker/entrypoint-dispatch.sh`` -> s6-overlay's
  165. ``/init``) is the reaper for orphaned grandchildren (browser tooling, MCP servers, shell
  166. children). A Compose service that overrides ``entrypoint:`` to invoke hermes directly makes
  167. hermes itself PID 1 — nothing then ``wait()``s on those orphans and they accumulate as
  168. zombies without bound (#111577). Outside a container a user process is never PID 1, so
  169. this is quiet everywhere else; it mirrors the dispatcher's own non-PID-1 warning.
  170. """
  171. if (pid if pid is not None else os.getpid()) != 1:
  172. return
  173. print(
  174. "[hermes] WARNING: this process is PID 1 with no init above it "
  175. "(entrypoint override?). Orphaned child processes will not be "
  176. "reaped and will accumulate as zombies. Use the image's default "
  177. "ENTRYPOINT (docker/entrypoint-dispatch.sh) instead of overriding "
  178. "it, or run with `docker run --init` / `init: true` in Compose.",
  179. file=sys.stderr,
  180. )
  181. def _set_process_title() -> None:
  182. """Cosmetic: show 'hermes' instead of 'python3.xx' in ps/top/htop.
  183. Order: opt-in ``setproctitle`` dep; ctypes ``prctl(PR_SET_NAME)`` (Linux,
  184. 15-char limit); ``pthread_setname_np`` (macOS — lldb/top only, not ``ps
  185. aux``); no-op on Windows (the .exe is already ``hermes.exe``). Never fatal.
  186. """
  187. try:
  188. import setproctitle # type: ignore[import-untyped]
  189. setproctitle.setproctitle("hermes")
  190. return
  191. except ImportError:
  192. pass
  193. import ctypes
  194. import platform
  195. try:
  196. system = platform.system()
  197. if system == "Linux":
  198. libc = ctypes.CDLL("libc.so.6", use_errno=True)
  199. libc.prctl(15, b"hermes", 0, 0, 0) # PR_SET_NAME = 15
  200. elif system == "Darwin":
  201. libc = ctypes.CDLL("libc.dylib", use_errno=True)
  202. libc.pthread_setname_np(b"hermes")
  203. except Exception:
  204. pass
  205. # Cheap read of `display.interface` for the earliest hot-path decisions
  206. # (mouse-residue suppression, Termux fast launch) that run before
  207. # hermes_cli.config is importable. Cached per config path so early callers
  208. # don't re-parse YAML, and so the answer follows the home the process ends up
  209. # in: mouse-residue suppression reads this BEFORE `_apply_profile_override()`
  210. # sets HERMES_HOME, and a cache keyed on nothing pinned every later caller to
  211. # the default home's interface for the whole run (#116902).
  212. _EARLY_INTERFACE_CACHE: tuple[str, str] | None = None
  213. def _early_interface_config_path() -> str:
  214. """config.yaml of the home this process is currently pointed at."""
  215. home = os.environ.get("HERMES_HOME")
  216. if home:
  217. return os.path.join(home, "config.yaml")
  218. return os.path.join(os.path.expanduser("~"), ".hermes", "config.yaml")
  219. def _config_default_interface_early() -> str:
  220. """Return the configured default interface ("cli"/"tui") via a minimal
  221. YAML read. Best-effort: any error falls back to "cli" (legacy behavior)."""
  222. global _EARLY_INTERFACE_CACHE
  223. from hermes_cli.config_backend import config_exists, read_config_doc
  224. cfg_path = _early_interface_config_path()
  225. if _EARLY_INTERFACE_CACHE is not None and _EARLY_INTERFACE_CACHE[0] == cfg_path:
  226. return _EARLY_INTERFACE_CACHE[1]
  227. value = "cli"
  228. try:
  229. if config_exists(cfg_path):
  230. raw = read_config_doc(cfg_path) or {}
  231. disp = raw.get("display", {})
  232. if isinstance(disp, dict):
  233. iface = disp.get("interface")
  234. if isinstance(iface, str) and iface.strip().lower() == "tui":
  235. value = "tui"
  236. except Exception:
  237. value = "cli" # best-effort — default to classic REPL on any error
  238. _EARLY_INTERFACE_CACHE = (cfg_path, value)
  239. return value
  240. def _wants_tui_early(argv: list[str] | None = None) -> bool:
  241. """Earliest TUI decision, usable before argparse/config imports.
  242. Precedence: ``--cli`` wins, then ``--tui``/``HERMES_TUI=1``, then a
  243. real-TTY gate, then ``display.interface``. The TTY gate is load-bearing
  244. for headless spawners (kanban workers, cron, pipes running ``chat -q``):
  245. a ``display.interface: tui`` default used to boot the TUI here, whose
  246. no-TTY bail-out exits 0 without doing the task. An explicit ``--tui``
  247. still reaches that informative bail-out.
  248. """
  249. if argv is None:
  250. argv = sys.argv[1:]
  251. if "--cli" in argv:
  252. return False
  253. if os.environ.get("HERMES_TUI") == "1" or any(flag in argv for flag in ("--tui", "--native", "--tui-native")):
  254. return True
  255. try:
  256. if not (sys.stdin.isatty() and sys.stdout.isatty()):
  257. return False
  258. except Exception:
  259. return False
  260. return _config_default_interface_early() == "tui"
  261. # Mouse-tracking residue suppression — runs BEFORE every other import on the
  262. # TUI hot path: while the launcher is still importing (~100-300ms, cooked+echo
  263. # mode, before the Node TUI takes stdin raw) incoming SGR/X10 mouse reports
  264. # echo into the shell scrollback as ``^[[<…M``. entry.tsx's
  265. # `resetTerminalModes()` is the later cousin. ``HERMES_TUI_NO_EARLY_DISABLE``
  266. # escapes the behaviour for diagnostics.
  267. def _suppress_mouse_residue_early() -> None:
  268. if os.environ.get("HERMES_TUI_NO_EARLY_DISABLE") == "1":
  269. return
  270. if not _wants_tui_early():
  271. return
  272. try:
  273. if not os.isatty(1): # redirected stdout: raw CSI would pollute the log
  274. return
  275. # Every mouse-tracking variant we know about; idempotent.
  276. os.write(
  277. 1,
  278. b"\x1b[?1003l\x1b[?1002l\x1b[?1001l\x1b[?1000l\x1b[?9l"
  279. b"\x1b[?1006l\x1b[?1005l\x1b[?1015l\x1b[?1016l\x1b[?2029l",
  280. )
  281. except OSError:
  282. pass
  283. _suppress_mouse_residue_early()
  284. _startup_fast.ensure_project_root_on_path()
  285. # ``hermes --version`` is answered before config/logging imports.
  286. if _startup_fast.try_fast_version():
  287. raise SystemExit(0)
  288. import argparse
  289. import contextlib
  290. import json
  291. import shutil
  292. import subprocess
  293. from pathlib import Path
  294. from typing import Optional
  295. from hermes_cli.subcommands.cron import build_cron_parser
  296. from hermes_cli.subcommands.gateway import build_gateway_parser
  297. from hermes_cli.subcommands.profile import build_profile_parser
  298. from hermes_cli.subcommands.model import build_model_parser
  299. from hermes_cli.subcommands.setup import build_setup_parser
  300. from hermes_cli.subcommands.whatsapp import build_whatsapp_parser, build_whatsapp_cloud_parser
  301. from hermes_cli.subcommands.slack import build_slack_parser
  302. from hermes_cli.subcommands.login import build_login_parser
  303. from hermes_cli.subcommands.logout import build_logout_parser
  304. from hermes_cli.subcommands.auth import build_auth_parser
  305. from hermes_cli.subcommands.status import build_status_parser
  306. from hermes_cli.subcommands.pause import build_pause_parser
  307. from hermes_cli.subcommands.webhook import build_webhook_parser
  308. from hermes_cli.subcommands.hooks import build_hooks_parser
  309. from hermes_cli.subcommands.doctor import build_doctor_parser
  310. from hermes_cli.subcommands.verify import build_verify_parser
  311. from hermes_cli.subcommands.security import build_security_parser
  312. from hermes_cli.subcommands.approvals import build_approvals_parser
  313. from hermes_cli.subcommands.dump import build_dump_parser
  314. from hermes_cli.subcommands.debug import build_debug_parser
  315. from hermes_cli.subcommands.backup import build_backup_parser
  316. from hermes_cli.subcommands.import_cmd import build_import_cmd_parser
  317. from hermes_cli.subcommands.config import build_config_parser
  318. from hermes_cli.subcommands.skin import build_skin_parser
  319. from hermes_cli.subcommands.console import build_console_parser
  320. from hermes_cli.subcommands.update import build_update_parser
  321. from hermes_cli.subcommands.uninstall import build_uninstall_parser
  322. from hermes_cli.subcommands.dashboard import build_dashboard_parser, build_serve_parser
  323. from hermes_cli.subcommands.webapp import build_webapp_parser
  324. from hermes_cli.subcommands.gui import build_gui_parser
  325. from hermes_cli.subcommands.logs import build_logs_parser
  326. from hermes_cli.subcommands.prompt_size import build_prompt_size_parser
  327. from hermes_cli.subcommands.memory import build_memory_parser
  328. from hermes_cli.subcommands.acp import build_acp_parser
  329. from hermes_cli.subcommands.tools import build_tools_parser
  330. from hermes_cli.subcommands.insights import build_insights_parser
  331. from hermes_cli.subcommands.usage import build_usage_parser
  332. from hermes_cli.subcommands.monitoring import build_monitoring_parser
  333. from hermes_cli.subcommands.skills import build_skills_parser
  334. from hermes_cli.subcommands.pairing import build_pairing_parser
  335. from hermes_cli.subcommands.plugins import build_plugins_parser
  336. from hermes_cli.subcommands.mcp import build_mcp_parser
  337. from hermes_cli.subcommands.connectors import build_connectors_parser
  338. from hermes_cli.subcommands.vault import build_vault_parser
  339. from hermes_cli.subcommands.moa import build_moa_parser
  340. from hermes_cli.subcommands.fallback import build_fallback_parser
  341. from hermes_cli.subcommands.worktree import build_worktree_parser
  342. from hermes_cli.subcommands.browser import build_browser_parser
  343. from hermes_cli.subcommands.secrets import build_secrets_parser
  344. from hermes_cli.subcommands.codex_runtime import build_codex_runtime_parser
  345. from hermes_cli.subcommands.egress import build_egress_parser
  346. from hermes_cli.subcommands.migrate import build_migrate_parser
  347. from hermes_cli.subcommands.checkpoints import build_checkpoints_parser
  348. from hermes_cli.subcommands.bundles import build_bundles_parser
  349. from hermes_cli.subcommands.curator import build_curator_parser
  350. from hermes_cli.subcommands.pets import build_pets_parser
  351. from hermes_cli.subcommands.journey import build_journey_parser
  352. from hermes_cli.subcommands.computer_use import build_computer_use_parser
  353. from hermes_cli.subcommands.sessions import build_sessions_parser, cmd_sessions_lazy
  354. from hermes_cli.subcommands.completion import build_completion_parser
  355. def _require_tty(command_name: str) -> None:
  356. """Exit 1 if stdin is not a terminal: curses/input() prompts spin at 100% CPU on a pipe."""
  357. if not sys.stdin.isatty():
  358. print(
  359. f"Error: 'hermes {command_name}' requires an interactive terminal.\n"
  360. f"It cannot be run through a pipe or non-interactive subprocess.\n"
  361. f"Run it directly in your terminal instead.",
  362. file=sys.stderr,
  363. )
  364. sys.exit(1)
  365. PROJECT_ROOT = Path(_startup_fast.project_root_str())
  366. _startup_fast.ensure_project_root_on_path()
  367. # Profile override — MUST happen before any hermes module import: many modules
  368. # cache HERMES_HOME at import time. --profile/-p is pre-parsed from sys.argv,
  369. # HERMES_HOME set, and the flag stripped so argparse never sees it. Falls back
  370. # to ~/.hermes/active_profile for the sticky default.
  371. _PROFILE_NAME_RE = r"^[a-z0-9][a-z0-9_-]{0,63}$" # mirrors hermes_cli.profiles._PROFILE_ID_RE
  372. # Set only when -p/--profile was on argv. Sticky active_profile must not count:
  373. # `hermes desktop` with no flag must not overwrite Desktop's stored profile.
  374. _explicit_cli_profile: str | None = None
  375. def _inside_mcp_add_args(argv: list, index: int) -> bool:
  376. """True once argv reaches `hermes mcp add ... --args <command argv>`.
  377. ``mcp add --args`` is command-argv passthrough. Flags after that point
  378. belong to the child MCP command (for example Docker MCP Toolkit's
  379. ``--profile``), not to Hermes' own profile selector.
  380. """
  381. try:
  382. mcp_index = argv.index("mcp", 0, index)
  383. argv.index("add", mcp_index + 1, index)
  384. except ValueError:
  385. return False
  386. return True
  387. def _looks_like_hermes_invocation() -> bool:
  388. """False when ``sys.argv`` belongs to a test runner rather than a ``hermes`` run.
  389. pytest's own ``-p no:xdist`` reaches ``_scan_profile_flag`` through ``sys.argv`` at import
  390. time; it must stay a silent skip, while a real ``hermes -p 'Work Bot'`` must fail loudly.
  391. """
  392. return "pytest" not in (sys.argv[0] or "")
  393. def _exit_invalid_profile_name(value: str) -> None:
  394. from hermes_cli.profiles import _invalid_profile_name_error
  395. print(f"Error: {_invalid_profile_name_error(value)}", file=sys.stderr)
  396. print("Run `hermes profile list` to see your profiles.", file=sys.stderr)
  397. sys.exit(2)
  398. def _looks_like_option_value(value: str) -> bool:
  399. """A ``-p`` value that clearly belongs to some other tool (pytest's ``-p no:xdist``, a
  400. third-party ``-p --flag``), never a mistyped profile name."""
  401. return value.startswith("-") or ":" in value
  402. def _scan_profile_flag(argv: list) -> tuple:
  403. """Find -p/--profile/--profile= in argv -> (name, tokens_consumed, index).
  404. Historically the flag worked even after the subcommand (`hermes chat -p
  405. coder`), so scan broadly; stop at ``--`` and at the `mcp add --args`
  406. passthrough region. The value is normalised (strip + casefold, matching
  407. ``profiles.normalize_profile_name``) before validation so ``-p Work`` selects
  408. ``work``. A value that cannot be a profile name is rejected so
  409. resolve_profile_env never sys.exits on it; the rejection is explained (exit 2)
  410. only when the flag comes BEFORE the first subcommand token under a real
  411. ``hermes`` run — after a subcommand, ``-p`` may belong to that subcommand or a
  412. plugin (`hermes kanban ... -p 8080`), and option-looking values (``no:xdist``,
  413. ``--flag``) are always a silent skip.
  414. """
  415. from hermes_cli._parser import top_level_value_flag_sets
  416. value_flags, optional_value_flags = top_level_value_flag_sets()
  417. i = 0
  418. saw_subcommand = False
  419. while i < len(argv):
  420. arg = argv[i]
  421. if arg == "--" or (arg == "--args" and _inside_mcp_add_args(argv, i)):
  422. break
  423. if arg in {"--profile", "-p"} and i + 1 < len(argv):
  424. raw = argv[i + 1]
  425. value = raw.strip().casefold()
  426. if re.match(_PROFILE_NAME_RE, value):
  427. return value, 2, i
  428. if not saw_subcommand and not _looks_like_option_value(raw) and _looks_like_hermes_invocation():
  429. _exit_invalid_profile_name(raw)
  430. break
  431. if arg.startswith("--profile="):
  432. return arg.split("=", 1)[1].strip().casefold(), 1, i
  433. takes_value = "=" not in arg and i + 1 < len(argv) and (
  434. arg in value_flags
  435. or (arg in optional_value_flags and not argv[i + 1].startswith("-"))
  436. )
  437. if not takes_value and not arg.startswith("-"):
  438. saw_subcommand = True
  439. i += 2 if takes_value else 1
  440. return None, 0, None
  441. def _resolve_sudo_user_profile_env(name: str) -> str | None:
  442. """Resolve `sudo hermes -p <name>` against the invoking user's home.
  443. This runs before argparse, so `--run-as-user` is not available yet. For
  444. sudo invocations the best signal is SUDO_USER: root is only doing the
  445. privileged install/start action; the profile store belongs to the user.
  446. """
  447. if name == "default":
  448. return None
  449. from hermes_constants import named_profile_is_live, sudo_invoker_default_home
  450. sudo_home = sudo_invoker_default_home()
  451. if sudo_home is None:
  452. return None
  453. candidate = sudo_home / "profiles" / name
  454. return str(candidate) if named_profile_is_live(candidate) else None
  455. def _under_gateway_supervisor(argv: list) -> bool:
  456. """A supervisor-launched gateway child must NOT follow the sticky active_profile.
  457. Each supervised slot has a fixed profile identity: named slots pass
  458. ``-p <name>`` or pin HERMES_HOME to the profile dir; a bare invocation
  459. means "the root HERMES_HOME profile". If a supervised default-profile
  460. child read active_profile, switching the active profile (dashboard,
  461. ``hermes profile use``) would silently redirect the default gateway into
  462. that profile — adopting its credentials and double-polling a Telegram
  463. token already owned by that profile's own gateway (#74872).
  464. Markers (see gateway/restart.py ``is_gateway_supervisor_process``):
  465. HERMES_SUPERVISED_CHILD (systemd unit / launchd plist / Windows task),
  466. HERMES_S6_SUPERVISED_CHILD (legacy s6 container), INVOCATION_ID (systemd
  467. service children only — consulted ONLY for gateway commands because it is
  468. inherited by every descendant of a systemd-launched process, e.g.
  469. self-hosted CI runners), HERMES_GATEWAY_EXTERNAL_SUPERVISOR (explicit
  470. opt-in) and HERMES_GATEWAY_PROFILE_PIN (its tool children's copy, which is
  471. no supervisor claim). XPC_SERVICE_NAME is deliberately NOT consulted:
  472. interactive macOS terminals set it too.
  473. """
  474. if os.environ.get("HERMES_SUPERVISED_CHILD") or os.environ.get("HERMES_S6_SUPERVISED_CHILD"):
  475. return True
  476. is_gateway_cmd = next((a for a in argv if not a.startswith("-")), None) == "gateway"
  477. if is_gateway_cmd and os.environ.get("INVOCATION_ID"):
  478. return True
  479. return any(os.environ.get(name, "").strip().lower() in {"1", "true", "yes", "on"}
  480. for name in ("HERMES_GATEWAY_EXTERNAL_SUPERVISOR", "HERMES_GATEWAY_PROFILE_PIN"))
  481. def _s6_supervised_gateway_run(argv: list) -> bool:
  482. """A bare ``gateway run`` inside the s6 image names the ``gateway-default`` slot too.
  483. ``_maybe_redirect_run_to_s6_supervision`` turns it into a start of the supervised slot for the
  484. current profile, and it is the image's own CMD. Following the sticky ``active_profile`` there
  485. started that profile's named slot on every container boot: the one the boot reconciler just
  486. registered down, because a started named slot is a second gateway beside the multiplexer.
  487. ``--no-supervise`` keeps the foreground run, which follows ``active_profile`` as before (#22502).
  488. """
  489. words = [a for a in argv if not a.startswith("-")]
  490. if words[:2] != ["gateway", "run"] or "--no-supervise" in argv:
  491. return False
  492. if os.environ.get("HERMES_GATEWAY_NO_SUPERVISE", "").lower() in ("1", "true", "yes"):
  493. return False
  494. from hermes_cli.service_manager import _s6_running
  495. return _s6_running()
  496. def explicit_cli_profile() -> str | None:
  497. """Profile named by a consumed ``-p``/``--profile`` flag, else None.
  498. Sticky ``active_profile`` is not explicit. Desktop launch must not overwrite
  499. its stored profile when the user omitted the flag.
  500. """
  501. return _explicit_cli_profile
  502. def _apply_profile_override() -> None:
  503. """Pre-parse --profile/-p and set HERMES_HOME before imports."""
  504. global _explicit_cli_profile
  505. _explicit_cli_profile = None
  506. argv = sys.argv[1:]
  507. profile_name, consume, profile_index = _scan_profile_flag(argv)
  508. from_sticky_profile = False
  509. # HERMES_HOME already set with no explicit flag: trust it only when it
  510. # points at a specific profile dir ("profiles" as immediate parent). If it
  511. # points at the hermes root (systemd hardcodes HERMES_HOME=/root/.hermes)
  512. # we must still read active_profile — the user may have run
  513. # `hermes profile use` and the gateway should honour it (#22502).
  514. hermes_home_env = os.environ.get("HERMES_HOME", "")
  515. if profile_name is None and hermes_home_env and Path(hermes_home_env).parent.name == "profiles":
  516. return
  517. if (profile_name is None and not _under_gateway_supervisor(argv)
  518. and not _startup_fast.is_desktop_ssh_backend_argv(argv)
  519. and not _s6_supervised_gateway_run(argv)):
  520. try:
  521. from hermes_constants import get_default_hermes_root
  522. active_path = get_default_hermes_root() / "active_profile"
  523. if active_path.exists():
  524. name = active_path.read_text(encoding="utf-8-sig").strip()
  525. if name and name != "default":
  526. profile_name = name # consume stays 0: nothing to strip
  527. from_sticky_profile = True
  528. except (UnicodeDecodeError, OSError):
  529. pass # corrupted file, skip
  530. if profile_name is None:
  531. return
  532. try:
  533. from hermes_cli.profiles import resolve_profile_env
  534. hermes_home = resolve_profile_env(profile_name)
  535. except FileNotFoundError as exc:
  536. hermes_home = _resolve_sudo_user_profile_env(profile_name)
  537. error = str(exc)
  538. if not hermes_home and from_sticky_profile:
  539. from hermes_cli.main_profile_recovery import is_stale_profile_recovery_command
  540. if is_stale_profile_recovery_command(argv):
  541. hermes_home = resolve_profile_env("default")
  542. print(
  543. f"Warning: saved profile '{profile_name}' no longer exists; "
  544. "running this recovery command in the default profile.",
  545. file=sys.stderr,
  546. )
  547. else:
  548. error = f"Saved profile '{profile_name}' no longer exists. Switch back with: hermes profile use default"
  549. if not hermes_home:
  550. print(f"Error: {error}", file=sys.stderr)
  551. sys.exit(1)
  552. except ValueError as exc:
  553. print(f"Error: {exc}", file=sys.stderr)
  554. sys.exit(1)
  555. except Exception as exc:
  556. # A bug in profiles.py must NEVER prevent hermes from starting
  557. print(f"Warning: profile override failed ({exc}), using default", file=sys.stderr)
  558. return
  559. os.environ["HERMES_HOME"] = hermes_home
  560. if consume > 0:
  561. _explicit_cli_profile = profile_name
  562. # Strip the flag from argv so argparse doesn't choke
  563. if consume > 0 and profile_index is not None:
  564. start = profile_index + 1 # +1 because argv is sys.argv[1:]
  565. sys.argv = sys.argv[:start] + sys.argv[start + consume :]
  566. if __name__ == "__main__" and getattr(sys.modules.get("__main__"), "__file__", None) == __file__:
  567. # `python -m`: a later `import hermes_cli.main` reuses THIS module; a second copy would re-run the
  568. # override on the stripped argv, and `--profile default` would fall to the sticky profile.
  569. sys.modules.setdefault("hermes_cli.main", sys.modules["__main__"])
  570. _apply_profile_override()
  571. # ``-p``/active_profile re-homed the process after hermes_bootstrap ran: re-point the temp vars
  572. # at THIS home's scratch dir (a user-set TMPDIR is still left alone).
  573. try:
  574. from hermes_constants import export_scratch_tmp_env as _export_scratch_tmp_env
  575. _export_scratch_tmp_env()
  576. except Exception:
  577. pass # an unwritable home leaves the system temp dir in place; never block startup
  578. # PM runs after profile resolution but before application dependency imports.
  579. if sys.argv[1:2] == ["pm"]:
  580. from pm.cli import main as _pm_main
  581. raise SystemExit(_pm_main(sys.argv[2:]))
  582. # Windows launcher self-heal: the ``hermes`` command is a COPY of the venv console script staged into
  583. # the managed bin dir, outside the checkout because ``hermes update``'s autostash (``git stash push
  584. # --include-untracked``) once swept ``<checkout>\bin`` copies off disk, the desktop updater's
  585. # ``--keep-stash`` never restored them, and ``hermes`` stopped resolving (venv\Scripts must stay off
  586. # PATH: it shadows the user's ``python``, #83797). Re-staging at process start reaches already-broken
  587. # installs via the desktop app's ``python -m hermes_cli.main`` spawn. Sits AFTER the profile override
  588. # on purpose (no hermes module may import before profiles resolve); the helper anchors on the DEFAULT
  589. # root, so profile sessions heal the same shared dir. A few stat calls when healthy; gates fail toward
  590. # inaction so source checkouts are untouched.
  591. if sys.platform == "win32":
  592. try:
  593. from hermes_cli import _install_repair as _install_repair_mod
  594. _install_repair_mod.ensure_windows_bin_launchers(_bootstrap_root)
  595. except Exception:
  596. pass
  597. # Load .env from ~/.hermes/.env first, then project root as dev fallback.
  598. # User-managed env files should override stale shell exports on restart.
  599. from hermes_cli.config import get_hermes_home
  600. from hermes_cli.env_loader import load_hermes_dotenv
  601. # ``update`` must not resolve external secret sources (Windows self-lock via cryptography, slow
  602. # helpers inside the import probe) — ``_early_recovery._should_skip_external_secret_sources``
  603. # owns that argv check for every dotenv load in the process. See #73381.
  604. load_hermes_dotenv(project_env=PROJECT_ROOT / ".env")
  605. # Bridge security.redact_secrets → HERMES_REDACT_SECRETS BEFORE hermes_logging
  606. # imports agent.redact, which snapshots the flag exactly once at import. A
  607. # .env value still wins — this is config.yaml fallback only. network.force_ipv4
  608. # is read from the same parse to avoid a second full load_config() (~17ms).
  609. _FORCE_IPV4_EARLY = False
  610. from hermes_cli.config_backend import config_exists
  611. try:
  612. # The effective-config cache (shared raw parse with read_raw_config()) means this SAME parse
  613. # serves hermes_logging, hermes_time and later raw reads: 3-4 config.yaml parses become one.
  614. # Managed overlay included: administrator-pinned redact_secrets / force_ipv4 win here too.
  615. from hermes_cli.config_effective import load_user_config_effective as _load_effective_early
  616. _cfg_path = get_hermes_home() / "config.yaml"
  617. if config_exists(_cfg_path):
  618. _early_cfg_raw = _load_effective_early(_cfg_path)
  619. if "HERMES_REDACT_SECRETS" not in os.environ:
  620. _early_sec_cfg = _early_cfg_raw.get("security", {})
  621. if isinstance(_early_sec_cfg, dict):
  622. _early_redact = _early_sec_cfg.get("redact_secrets")
  623. if _early_redact is not None:
  624. os.environ["HERMES_REDACT_SECRETS"] = str(_early_redact).lower()
  625. _early_net_cfg = _early_cfg_raw.get("network", {})
  626. if isinstance(_early_net_cfg, dict) and _early_net_cfg.get("force_ipv4"):
  627. _FORCE_IPV4_EARLY = True
  628. del _early_cfg_raw
  629. del _cfg_path
  630. except Exception:
  631. pass # best-effort — redaction stays at default (enabled) on config errors
  632. # Servers cap glibc malloc arenas HERE, before any thread exists: glibc latches its limit later.
  633. from hermes_cli.resource_limits import apply_malloc_arena_max, server_process_argv
  634. if server_process_argv(sys.argv[1:]):
  635. apply_malloc_arena_max()
  636. # Centralized file logging for every subcommand (agent.log + errors.log).
  637. # Dashboard entrypoints use GUI mode so gui.log captures pre-dispatch failures.
  638. try:
  639. from hermes_logging import setup_logging as _setup_logging
  640. _setup_logging(
  641. mode=(
  642. "gui"
  643. if next((arg for arg in sys.argv[1:] if not arg.startswith("-")), "")
  644. in {"dashboard", "serve", "gui", "desktop"}
  645. else "cli"
  646. )
  647. )
  648. except Exception:
  649. pass # best-effort — don't crash the CLI if logging setup fails
  650. # Apply IPv4 preference before any HTTP client is created.
  651. if _FORCE_IPV4_EARLY:
  652. try:
  653. from hermes_constants import apply_ipv4_preference as _apply_ipv4
  654. _apply_ipv4(force=True)
  655. except Exception:
  656. pass # best-effort — don't crash if hermes_constants not importable yet
  657. import logging
  658. import threading
  659. from datetime import datetime
  660. from hermes_cli.model_setup_flows import (
  661. _model_flow_openrouter,
  662. _model_flow_nous,
  663. _model_flow_openai_codex,
  664. _model_flow_xai_oauth,
  665. _model_flow_qwen_oauth,
  666. _model_flow_minimax_oauth,
  667. _model_flow_custom,
  668. _model_flow_azure_foundry,
  669. _model_flow_named_custom,
  670. _model_flow_kimi,
  671. _model_flow_stepfun,
  672. _model_flow_bedrock,
  673. _model_flow_vertex,
  674. _model_flow_api_key_provider,
  675. _model_flow_anthropic,
  676. _model_flow_moa,
  677. _model_flow_ai_gateway,
  678. _model_flow_plugin_provider,
  679. _is_profile_plugin_flow_provider,
  680. _profile_model_setup_flow,
  681. )
  682. from hermes_cli.model_setup_flows_local import _model_flow_local
  683. logger = logging.getLogger(__name__)
  684. from hermes_cli.main_agent_cmds import (
  685. cmd_acp,
  686. cmd_insights,
  687. cmd_memory,
  688. cmd_monitoring,
  689. cmd_skills,
  690. cmd_tools,
  691. )
  692. from hermes_cli.main_platform_setup import (
  693. cmd_slack,
  694. cmd_whatsapp,
  695. cmd_whatsapp_cloud,
  696. )
  697. from hermes_cli.process_identity import is_desktop_owned_backend as _is_desktop_owned_backend
  698. from hermes_cli.main_dashboard import (
  699. _attach_to_host_backend,
  700. _finalize_update_output,
  701. _find_stale_dashboard_pids,
  702. _install_hangup_protection,
  703. _is_electron_packaged_web_dist,
  704. _maybe_setup_dashboard_auth_interactively,
  705. _dashboard_validate_serve_args,
  706. _read_ssh_session_token_file,
  707. _report_dashboard_status,
  708. _resolve_dashboard_web_dist,
  709. _route_named_profile_dashboard,
  710. )
  711. from hermes_cli.main_dashboard import ( # frozen updater surface: update_cmd*.py resolve these via _m()
  712. _respawn_dashboard_processes,
  713. )
  714. from hermes_cli.main_provider_setup import (
  715. _GENERIC_API_KEY_PROVIDERS,
  716. _aux_config_menu,
  717. _build_provider_picker_rows,
  718. _clear_stale_openai_base_url,
  719. _is_profile_api_key_provider,
  720. _model_choice_save_count,
  721. _named_custom_provider_map,
  722. _offer_reasoning_after_pick,
  723. _prompt_main_reasoning_effort,
  724. _prompt_provider_choice,
  725. _remove_custom_provider,
  726. )
  727. # Frozen external updater API: old in-memory siblings still import these names
  728. # after a checkout swap. Keep their inert shims separate from live launch helpers.
  729. from hermes_cli.old_updater_main import (
  730. ShimQuarantineError,
  731. _BYTECODE_FINGERPRINT_FILE,
  732. _desktop_stamp_path,
  733. _detect_broken_lazy_refresh_imports,
  734. _expected_windows_pe_machines,
  735. _hermes_exe_shims,
  736. _insert_python_pin,
  737. _interpreter_scripts_dir,
  738. _load_installable_optional_extras,
  739. _parse_pe_machine,
  740. _quarantine_running_hermes_exe,
  741. _repair_broken_lazy_refresh_imports,
  742. _resolve_install_target_python,
  743. _restore_quarantined_exes,
  744. _run_install_with_heartbeat,
  745. _run_package_only_install,
  746. _run_quarantined_install,
  747. _run_with_idle_timeout,
  748. _self,
  749. _verify_console_scripts_installed,
  750. _verify_core_dependencies_installed,
  751. _web_ui_build_needed,
  752. _windows_native_machine,
  753. _windows_shim_in_process_chain,
  754. _write_web_ui_build_stamp,
  755. )
  756. from hermes_cli.main_install_repair import _cleanup_quarantined_exes, _recover_update_debts_on_startup
  757. from hermes_cli.main_install_repair import ( # frozen updater surface: update_cmd*.py resolve these via _m()
  758. _UPDATE_REEXEC_ENV,
  759. _clear_lazy_refresh_incomplete_marker,
  760. _clear_marker_file,
  761. _clear_update_incomplete_marker,
  762. _is_termux_env,
  763. _is_windows,
  764. _is_windows_npm_path,
  765. _lazy_refresh_marker_path,
  766. _pytest_owns_live_checkout,
  767. _reexec_dependency_sync_off_windows_shim,
  768. _resolve_node_runtime_npm,
  769. _resolve_update_branch,
  770. _update_marker_path,
  771. _venv_scripts_dir,
  772. )
  773. from hermes_cli.main_desktop import (
  774. cmd_gui,
  775. )
  776. from hermes_cli.main_desktop import ( # frozen updater surface: update_cmd*.py resolve these via _m()
  777. _desktop_build_needed,
  778. _desktop_dist_exists,
  779. _desktop_macos_relaunchable_fixup,
  780. _desktop_packaged_executable,
  781. _install_rebuilt_desktop_app,
  782. _installed_desktop_apps,
  783. )
  784. from hermes_cli.main_web_build import (
  785. _sweep_stale_bytecode_if_checkout_changed,
  786. )
  787. from hermes_cli.main_web_build import ( # frozen updater surface: update_cmd*.py resolve these via _m()
  788. _build_web_ui,
  789. _nixos_build_env,
  790. _record_bytecode_fingerprint,
  791. _run_npm_install_deterministic,
  792. )
  793. from hermes_cli.main_tui_launch import (
  794. _bypass_chat_launch,
  795. _launch_tui,
  796. _pin_kanban_board_env,
  797. _refuse_unforwarded_tui_flags,
  798. _resolve_use_tui,
  799. _sync_bundled_skills_quietly,
  800. )
  801. def _is_termux_startup_environment(env: dict[str, str] | None = None) -> bool:
  802. """Import-safe Termux check for cold-start-sensitive CLI paths."""
  803. check = env or os.environ
  804. prefix = str(check.get("PREFIX", ""))
  805. return bool(
  806. check.get("TERMUX_VERSION")
  807. or "com.termux/files/usr" in prefix
  808. or prefix.startswith("/data/data/com.termux/")
  809. )
  810. def _read_packed_ref(common_dir: Path, ref: str) -> str | None:
  811. """Look up a ref in .git/packed-refs without spawning git.
  812. packed-refs lines look like ``<sha> <ref>`` with optional ``^<sha>``
  813. peel lines and ``#``-prefixed comments / ``# pack-refs with:`` header.
  814. """
  815. try:
  816. text = (common_dir / "packed-refs").read_text(encoding="utf-8-sig", errors="replace")
  817. except OSError:
  818. return None
  819. for line in text.splitlines():
  820. if not line or line.startswith("#") or line.startswith("^"):
  821. continue
  822. parts = line.split(" ", 1)
  823. if len(parts) == 2 and parts[1].strip() == ref:
  824. return parts[0].strip()
  825. return None
  826. def _read_git_revision_fingerprint(repo_root: Path) -> str | None:
  827. """Return a cheap checkout fingerprint without spawning git."""
  828. git_dir = repo_root / ".git"
  829. try:
  830. if git_dir.is_file():
  831. for line in git_dir.read_text(encoding="utf-8-sig", errors="replace").splitlines():
  832. key, _, value = line.partition(":")
  833. if key.strip() == "gitdir" and value.strip():
  834. git_dir = (repo_root / value.strip()).resolve()
  835. break
  836. # Worktrees point HEAD at a per-worktree gitdir but pack their refs
  837. # in the main repo's gitdir (referenced via ``commondir``). Resolve
  838. # that up front so packed-refs lookups hit the right file.
  839. common_dir = git_dir
  840. commondir_file = git_dir / "commondir"
  841. if commondir_file.exists():
  842. try:
  843. rel = commondir_file.read_text(encoding="utf-8-sig", errors="replace").strip()
  844. if rel:
  845. common_dir = (git_dir / rel).resolve()
  846. except OSError:
  847. pass
  848. head = (git_dir / "HEAD").read_text(encoding="utf-8-sig", errors="replace").strip()
  849. if head.startswith("ref:"):
  850. ref = head.split(":", 1)[1].strip()
  851. # Loose refs may live in the worktree gitdir OR the common dir
  852. # (branches created via `git worktree add` typically live in the
  853. # common dir's refs/heads/).
  854. for candidate in (git_dir, common_dir):
  855. ref_file = candidate / ref
  856. if ref_file.exists():
  857. return f"git:{ref}:{ref_file.read_text(encoding='utf-8-sig', errors='replace').strip()}"
  858. packed_sha = _read_packed_ref(common_dir, ref)
  859. if packed_sha:
  860. return f"git:{ref}:{packed_sha}"
  861. # Ref name is known but unresolved — still stable across launches,
  862. # and the version/release fallback in the caller will invalidate
  863. # after `hermes update`.
  864. return f"git:{ref}:unresolved"
  865. return f"git:HEAD:{head}"
  866. except OSError:
  867. return None
  868. def _termux_bundled_skills_fingerprint() -> str:
  869. """Cheap invalidation key for Termux bundled-skill startup sync."""
  870. git_fp = _read_git_revision_fingerprint(PROJECT_ROOT)
  871. if git_fp:
  872. return git_fp
  873. from hermes_cli.version_info import get_version_info
  874. version_info = get_version_info()
  875. code_identity = version_info.commit or version_info.derived_version
  876. skills_dir = PROJECT_ROOT / "skills"
  877. try:
  878. stat = skills_dir.stat()
  879. return f"skills:{code_identity}:{stat.st_mtime_ns}:{stat.st_size}"
  880. except OSError:
  881. return f"skills:{code_identity}:missing"
  882. def _termux_bundled_skills_stamp_path() -> Path:
  883. return get_hermes_home() / "skills" / ".termux_bundled_sync_stamp"
  884. def _termux_bundled_skills_sync_needed() -> bool:
  885. if not _is_termux_startup_environment():
  886. return True
  887. if os.environ.get("HERMES_TERMUX_FORCE_SKILLS_SYNC") == "1":
  888. return True
  889. try:
  890. stamp = _termux_bundled_skills_stamp_path()
  891. return stamp.read_text(encoding="utf-8-sig").strip() != _termux_bundled_skills_fingerprint()
  892. except OSError:
  893. return True
  894. def _mark_termux_bundled_skills_synced() -> None:
  895. if not _is_termux_startup_environment():
  896. return
  897. try:
  898. stamp = _termux_bundled_skills_stamp_path()
  899. stamp.parent.mkdir(parents=True, exist_ok=True)
  900. stamp.write_text(_termux_bundled_skills_fingerprint() + "\n", encoding="utf-8")
  901. except OSError:
  902. pass
  903. def _sync_bundled_skills_for_startup() -> bool:
  904. """Sync bundled skills, but skip unchanged Termux checkouts cheaply.
  905. Hashing every bundled skill is safe but expensive on older Android
  906. storage. The git/ref stamp keeps post-update correctness: a changed
  907. checkout revision forces one real sync, then later starts skip it.
  908. """
  909. if _is_termux_startup_environment() and not _termux_bundled_skills_sync_needed():
  910. return False
  911. from tools.skills_sync import sync_skills
  912. sync_skills(quiet=True)
  913. _mark_termux_bundled_skills_synced()
  914. return True
  915. def _termux_should_prefetch_update_check() -> bool:
  916. if not _is_termux_startup_environment():
  917. return True
  918. return os.environ.get("HERMES_TERMUX_PREFETCH_UPDATES") == "1"
  919. def _dotenv_has_provider_key(env_file: Path, provider_env_vars: set) -> bool:
  920. """True if ~/.hermes/.env assigns a non-empty value to any provider key."""
  921. if not env_file.exists():
  922. return False
  923. try:
  924. for line in env_file.read_text(encoding="utf-8-sig").splitlines():
  925. line = line.strip()
  926. if line.startswith("#") or "=" not in line:
  927. continue
  928. line = line.removeprefix("export ")
  929. key, _, val = line.partition("=")
  930. if key.strip() in provider_env_vars and val.strip().strip("'\""):
  931. return True
  932. except Exception:
  933. pass
  934. return False
  935. def _auth_store_logged_in(auth_file: Path, registry, strict_profile_scope: bool) -> bool:
  936. """True if auth.json's active provider is logged in (api_key providers ignored under strict scope)."""
  937. from hermes_cli.auth import get_auth_status
  938. if not auth_file.exists():
  939. return False
  940. try:
  941. auth = json.loads(auth_file.read_text(encoding="utf-8-sig"))
  942. active = auth.get("active_provider")
  943. active_config = registry.get(str(active or "").strip().lower())
  944. if active and not (
  945. strict_profile_scope and active_config and active_config.auth_type == "api_key"
  946. ):
  947. return bool(get_auth_status(active).get("logged_in"))
  948. except Exception:
  949. pass
  950. return False
  951. def _has_any_provider_configured(*, strict_profile_scope: bool = False) -> bool:
  952. """Check if at least one inference provider is usable. Never creates one: the Nous free tier
  953. counts only once its identity exists, and the boot bootstrap (``hermes_cli.free_tier_bootstrap``)
  954. creates it at boot (a first connector use can too); ``cmd_chat`` runs the bootstrap before asking.
  955. ``strict_profile_scope``: the caller has bound a NAMED profile's home and
  956. secret scope and wants an answer for that profile only — launch-process
  957. env and host-wide fallbacks (gh auth, Claude Code credentials) must not
  958. make it appear ready. Unscoped callers keep the legacy behavior.
  959. """
  960. from hermes_cli.config import DEFAULT_CONFIG, get_env_path, get_hermes_home, load_config
  961. from hermes_cli.auth import PROVIDER_REGISTRY, get_auth_status
  962. cfg = load_config()
  963. model_cfg = cfg.get("model")
  964. _model_name = model_cfg if isinstance(model_cfg, str) else ""
  965. if isinstance(model_cfg, dict):
  966. _model_name = model_cfg.get("default") or ""
  967. if isinstance(_model_name, dict):
  968. from hermes_cli.config import split_model_config_default
  969. _model_name, _ = split_model_config_default(_model_name)
  970. _model_name = str(_model_name).strip()
  971. # "Explicitly configured" = model differs from the hardcoded default; gates
  972. # Claude Code credentials so they don't skip setup on a fresh install.
  973. _has_hermes_config = _model_name and _model_name != DEFAULT_CONFIG.get("model", "")
  974. # Env vars (.env or shell). OPENAI_BASE_URL alone counts — local models
  975. # (vLLM, llama.cpp) often need no API key.
  976. provider_env_vars = {
  977. "OPENROUTER_API_KEY",
  978. "OPENAI_API_KEY",
  979. "ANTHROPIC_API_KEY",
  980. "ANTHROPIC_TOKEN",
  981. "OPENAI_BASE_URL",
  982. }
  983. for pconfig in PROVIDER_REGISTRY.values():
  984. if pconfig.auth_type == "api_key":
  985. provider_env_vars.update(pconfig.api_key_env_vars)
  986. if strict_profile_scope:
  987. from agent.secret_scope import current_secret_scope
  988. read_provider_env = (current_secret_scope() or {}).get
  989. else:
  990. read_provider_env = os.getenv
  991. if any(read_provider_env(v) for v in provider_env_vars):
  992. return True
  993. if _dotenv_has_provider_key(get_env_path(), provider_env_vars):
  994. return True
  995. # Cheap on-disk checks (auth.json, config.yaml) first: the PROVIDER_REGISTRY
  996. # sweep below spawns subprocesses (gh) and can take 15-20s — long enough
  997. # that desktop setup.status calls time out.
  998. if _auth_store_logged_in(get_hermes_home() / "auth.json", PROVIDER_REGISTRY, strict_profile_scope):
  999. return True
  1000. # model as a dict with provider/base_url/api_key means setup ran (fresh
  1001. # installs have a plain string); also covers custom endpoints kept in config.
  1002. if isinstance(model_cfg, dict) and any(
  1003. (model_cfg.get(k) or "").strip() for k in ("provider", "base_url", "api_key")
  1004. ):
  1005. return True
  1006. # Provider-specific auth fallbacks (e.g. a token borrowed from a vendor CLI).
  1007. if not strict_profile_scope:
  1008. try:
  1009. if any(
  1010. (status := get_auth_status(pid)).get("logged_in")
  1011. and status.get("key_source") != "keyless"
  1012. for pid, pconfig in PROVIDER_REGISTRY.items()
  1013. if pconfig.auth_type == "api_key"
  1014. ):
  1015. return True
  1016. except Exception:
  1017. pass
  1018. # Claude Code OAuth credentials count only once Hermes is explicitly
  1019. # configured — having Claude Code installed isn't consent to use its tokens.
  1020. if _has_hermes_config and not strict_profile_scope:
  1021. try:
  1022. from agent.anthropic_credentials import read_claude_code_credentials, is_claude_code_token_valid
  1023. creds = read_claude_code_credentials()
  1024. if creds and (
  1025. is_claude_code_token_valid(creds) or creds.get("refreshToken")
  1026. ):
  1027. return True
  1028. except Exception:
  1029. pass
  1030. return False
  1031. def _confirm_startup_expensive_model_override(args) -> None:
  1032. """Guard startup -m/--provider overrides before the first API call."""
  1033. explicit_model = (getattr(args, "model", None) or "").strip()
  1034. explicit_provider = (getattr(args, "provider", None) or "").strip()
  1035. if not explicit_model and not explicit_provider:
  1036. return
  1037. try:
  1038. from hermes_cli.config import load_config
  1039. from hermes_cli.model_selection_guards import (
  1040. combined_message,
  1041. selection_warnings,
  1042. )
  1043. except Exception as exc:
  1044. logger.warning("startup model cost guard unavailable: %s", exc)
  1045. return
  1046. try:
  1047. config = load_config()
  1048. except Exception as exc:
  1049. logger.warning("startup model cost guard could not load config: %s", exc)
  1050. config = {}
  1051. _dict = lambda v: v if isinstance(v, dict) else {}
  1052. config = _dict(config)
  1053. model_cfg = _dict(config.get("model"))
  1054. security_cfg = _dict(config.get("security"))
  1055. model = explicit_model or (model_cfg.get("default") or "").strip()
  1056. if not model:
  1057. return
  1058. provider = (explicit_provider or model_cfg.get("provider") or "").strip()
  1059. try:
  1060. # Unified registry: cost guard + id-keyed guards (e.g. the
  1061. # data-training-tier warning) all fire at startup too.
  1062. warnings = selection_warnings(
  1063. model,
  1064. provider=provider,
  1065. base_url=(model_cfg.get("base_url") or ""),
  1066. api_key=(model_cfg.get("api_key") or ""),
  1067. )
  1068. except Exception as exc:
  1069. logger.warning("startup model cost guard failed for %s/%s: %s", provider, model, exc)
  1070. return
  1071. if not warnings:
  1072. return
  1073. # Intentionally independent of --yolo / --accept-hooks: those approve local
  1074. # command risk, not paid aggregator spend or a surprising provider route.
  1075. is_interactive = sys.stdin.isatty()
  1076. if not is_interactive and security_cfg.get("allow_data_training_tiers_noninteractive") is True:
  1077. acknowledged = [w for w in warnings if w.kind == "data_policy"]
  1078. if acknowledged:
  1079. sys.stderr.write(combined_message(acknowledged) + "\n")
  1080. sys.stderr.write(
  1081. "Proceeding in non-interactive mode because "
  1082. "security.allow_data_training_tiers_noninteractive is true.\n"
  1083. )
  1084. warnings = [w for w in warnings if w.kind != "data_policy"]
  1085. if not warnings:
  1086. return
  1087. message = combined_message(warnings)
  1088. if not is_interactive:
  1089. sys.stderr.write(message + "\n")
  1090. if any(warning.kind == "data_policy" for warning in warnings):
  1091. sys.stderr.write(
  1092. "To acknowledge data-training tiers for unattended runs, set "
  1093. "security.allow_data_training_tiers_noninteractive to true "
  1094. "in config.yaml.\n"
  1095. )
  1096. sys.stderr.write(
  1097. "Refusing this startup model override in non-interactive mode. "
  1098. "Run interactively and confirm if you intend to use it.\n"
  1099. )
  1100. raise SystemExit(1)
  1101. sys.stderr.write(message + "\n")
  1102. try:
  1103. reply = input("Use this model for this invocation? [y/N] ").strip().lower()
  1104. except (EOFError, KeyboardInterrupt):
  1105. reply = ""
  1106. if reply not in {"y", "yes"}:
  1107. sys.stderr.write("Model override cancelled.\n")
  1108. raise SystemExit(1)
  1109. def _resolve_workspace_key() -> Optional[str]:
  1110. """The current workspace identity for cwd-scoped resume.
  1111. Git repo root when CWD is inside a repo (so all sessions across its
  1112. subdirs/worktrees group together), else the CWD itself. Returns None when
  1113. neither can be determined — callers fall back to the global MRU then.
  1114. """
  1115. try:
  1116. result = subprocess.run(
  1117. ["git", "rev-parse", "--show-toplevel"],
  1118. capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5,
  1119. check=False,
  1120. )
  1121. if result.returncode == 0 and result.stdout.strip():
  1122. return os.path.abspath(result.stdout.strip())
  1123. except Exception:
  1124. pass
  1125. try:
  1126. return os.getcwd()
  1127. except Exception:
  1128. return None
  1129. @contextlib.contextmanager
  1130. def _session_db():
  1131. """Yield a read-only ``SessionDB`` (lazy import, so test patches on ``hermes_state``
  1132. intercept). Every caller is a lookup (last session, title → id, recorded cwd), so it
  1133. never opens a writer beside the one the CLI acquires from the registry a moment later.
  1134. Open failures yield None and any error raised by the ``with`` body is swallowed —
  1135. callers fall through to their ``return None``."""
  1136. db = None
  1137. try:
  1138. from hermes_state import SessionDB
  1139. db = SessionDB(db_path=get_hermes_home() / "state.db", read_only=True)
  1140. except Exception:
  1141. pass
  1142. try:
  1143. # Gateway rows the CLI/TUI created are labelled ``local``; source-scoped lookups read main's labels.
  1144. from hermes_cli.gateway_session_store import SurfaceLabelReader
  1145. yield SurfaceLabelReader(db) if db is not None else None # body errors (incl. AttributeError on a None db) are swallowed
  1146. except Exception:
  1147. pass
  1148. finally:
  1149. if db is not None:
  1150. try:
  1151. db.close()
  1152. except Exception:
  1153. pass
  1154. def _latest_session_id(use_tui: bool) -> Optional[str]:
  1155. """MRU session for the active interface; a TUI launch falls back to the CLI MRU."""
  1156. last_id = _resolve_last_session(source="tui" if use_tui else "cli")
  1157. if not last_id and use_tui:
  1158. last_id = _resolve_last_session(source="cli")
  1159. return last_id
  1160. def _resolve_last_session(source: str = "cli") -> Optional[str]:
  1161. """Look up the most recently-used session ID for a source.
  1162. Scoped to the current workspace first (git repo root, else cwd) so
  1163. ``hermes -c`` from repo A continues repo A's last session rather than the
  1164. global MRU. Falls back to the unscoped MRU when no session matches the
  1165. current workspace, preserving the old behaviour for fresh directories.
  1166. """
  1167. # A finite `hermes -z`/`chat -q` run is CLI history too: `hermes -z … --resume latest` chains on it.
  1168. if source == "cli":
  1169. from agent.session_source import CLI_FAMILY_SOURCES
  1170. source = sorted(CLI_FAMILY_SOURCES)
  1171. with _session_db() as db:
  1172. ws_key = _resolve_workspace_key()
  1173. if ws_key:
  1174. sessions = db.search_sessions(source=source, limit=1, workspace_key=ws_key, skip_launch_stubs=True)
  1175. if sessions:
  1176. return sessions[0]["id"]
  1177. # Fallback: global MRU for this source.
  1178. sessions = db.search_sessions(source=source, limit=1, skip_launch_stubs=True)
  1179. return sessions[0]["id"] if sessions else None
  1180. return None
  1181. def _resolve_session_by_name_or_id(name_or_id: str) -> Optional[str]:
  1182. """Resolve a session title or ID to a session ID (None if neither matches).
  1183. A compression root is followed forward to its latest continuation so an
  1184. old root ID (exit summary, notes) resumes at the live tip.
  1185. """
  1186. with _session_db() as db:
  1187. # Exact session ID first, then title (with auto-latest for lineage).
  1188. session = db.get_session(name_or_id)
  1189. resolved_id = session["id"] if session else db.resolve_session_by_title(name_or_id)
  1190. if not resolved_id and name_or_id.startswith("local-"):
  1191. # The TUI epilogue prints a canonical session's unique 22-char prefix.
  1192. resolved_id = db.resolve_session_id(name_or_id)
  1193. if resolved_id:
  1194. # Project forward through compression chain so resumes land on
  1195. # the live tip instead of a dead compressed parent.
  1196. try:
  1197. resolved_id = db.get_compression_tip(resolved_id) or resolved_id
  1198. except Exception:
  1199. pass
  1200. return resolved_id
  1201. return None
  1202. def _create_titled_session(title: str) -> Optional[str]:
  1203. """Create a fresh titled session (``chat -c <title> --create-if-missing``).
  1204. The gateway is the single writer: it creates the session and records the title with user
  1205. provenance, so auto-titling never overwrites it (gateway_session_store.create_titled_session).
  1206. Used by ``chat -c <title> --create-if-missing`` (#86794): programmatic callers (plugins, scripts) that
  1207. want "send to this named thread, making it if needed" get a deterministic outcome instead of a silent
  1208. no-op.
  1209. """
  1210. try:
  1211. from hermes_cli.gateway_session_store import create_titled_session
  1212. return create_titled_session(title)
  1213. except Exception:
  1214. # Programmatic callers rely on --create-if-missing being deterministic;
  1215. # swallow the failure but log the cause so it lands in errors.log
  1216. # (DB lock, I/O error, import error — all otherwise invisible).
  1217. # See #86794.
  1218. logger.exception("Failed to create titled session %r", title)
  1219. return None
  1220. def _resolve_continue_arg(args, *, use_tui: bool) -> None:
  1221. """Resolve ``-c/--continue`` into ``args.resume``.
  1222. ``-c <name>``: resolve by title/ID; on miss fail loudly on **stderr** (exit
  1223. 1) so programmatic callers see it even under quiet mode, or with
  1224. ``--create-if-missing`` create a fresh titled session. Bare ``-c``: this
  1225. terminal's breadcrumb session if valid, else the MRU session.
  1226. Handles both forms: See #86794.
  1227. """
  1228. continue_val = getattr(args, "continue_last", None)
  1229. if continue_val and not getattr(args, "resume", None):
  1230. if isinstance(continue_val, str):
  1231. resolved = _resolve_session_by_name_or_id(continue_val)
  1232. if resolved:
  1233. args.resume = resolved
  1234. elif getattr(args, "create_if_missing", False):
  1235. # "send to this named thread, making it if needed" — without it
  1236. # a quiet send to a not-yet-existing session silently no-ops.
  1237. # --create-if-missing: no session matches the title — create a new session with that title
  1238. # and proceed. See #86794. The classic CLI's gateway writes it (the single writer);
  1239. # the TUI keeps main's local row.
  1240. if use_tui:
  1241. new_sid = _create_titled_session(continue_val)
  1242. else:
  1243. from hermes_cli.gateway_session_store import create_titled_session
  1244. new_sid = create_titled_session(continue_val)
  1245. if new_sid:
  1246. args.resume = new_sid
  1247. else:
  1248. print(
  1249. f"No session found matching '{continue_val}' and "
  1250. "a new titled session could not be created.",
  1251. file=sys.stderr,
  1252. )
  1253. sys.exit(1)
  1254. else:
  1255. print(f"No session found matching '{continue_val}'.", file=sys.stderr)
  1256. print(
  1257. "Use 'hermes sessions list' to see available sessions, or "
  1258. "pass --create-if-missing to start a new session with that title.",
  1259. file=sys.stderr,
  1260. )
  1261. sys.exit(1)
  1262. else:
  1263. # Bare -c: this terminal's breadcrumb (so side-by-side terminals
  1264. # each continue their own conversation), else the MRU session
  1265. # (also when session.terminal_continue is false).
  1266. if getattr(args, "create_if_missing", False):
  1267. # Nothing to create without a name — surface the no-op.
  1268. print(
  1269. "--create-if-missing requires a session name: "
  1270. "`-c <name> --create-if-missing`",
  1271. file=sys.stderr,
  1272. )
  1273. try:
  1274. from hermes_cli.terminal_breadcrumbs import resolve_breadcrumb_session
  1275. _crumb_id = resolve_breadcrumb_session()
  1276. except Exception:
  1277. _crumb_id = None
  1278. if _crumb_id:
  1279. args.resume = _crumb_id
  1280. else:
  1281. # No valid breadcrumb — continue the most recent session
  1282. last_id = _latest_session_id(use_tui)
  1283. if last_id:
  1284. args.resume = last_id
  1285. else:
  1286. kind = "TUI" if use_tui else "CLI"
  1287. print(
  1288. f"No previous {kind} session to continue. Start a new one with "
  1289. "`hermes`, or list sessions with `hermes sessions list`.",
  1290. file=sys.stderr,
  1291. )
  1292. sys.exit(1)
  1293. def _apply_in_dir(args) -> None:
  1294. """--in DIR: chdir first so workspace-scoped lookups key off DIR; pins the session there."""
  1295. in_dir = getattr(args, "in_dir", None)
  1296. if not in_dir:
  1297. return
  1298. # Git Bash / MSYS hands us POSIX-style paths (`--in ~` → `/c/Users/x`);
  1299. # translate drive-root spellings to native Windows form. No-op elsewhere.
  1300. from tools.environments.local import _msys_to_windows_path
  1301. _target_dir = os.path.abspath(os.path.expanduser(_msys_to_windows_path(in_dir)))
  1302. if not os.path.isdir(_target_dir):
  1303. print(f"Error: --in directory not found: {in_dir}")
  1304. sys.exit(1)
  1305. try:
  1306. os.chdir(_target_dir)
  1307. except OSError as e:
  1308. print(f"Error: cannot enter --in directory {in_dir}: {e}")
  1309. sys.exit(1)
  1310. # Every cwd consumer (resolve_agent_cwd -> Codex app-server thread cwd, the
  1311. # terminal tool, context-file discovery) prefers TERMINAL_CWD over the process
  1312. # cwd, so a value inherited from a parent surface, the shell or .env outlives
  1313. # this chdir and re-homes the session in the old directory (#106220). Refresh
  1314. # it. An unset variable stays unset: the backends then derive from the new
  1315. # process cwd (local exports it at cli import, docker mounts it, ssh and
  1316. # container backends keep their own remote/sandbox default).
  1317. if os.environ.get("TERMINAL_CWD", "").strip():
  1318. os.environ["TERMINAL_CWD"] = _target_dir
  1319. args.no_restore_cwd = True
  1320. def _resolve_chat_session_args(args, use_tui: bool) -> None:
  1321. """Normalize --in / --resume / --continue on ``args`` before agent init.
  1322. Order matters: ``--in DIR`` chdirs first so workspace-scoped "latest"/-c
  1323. lookups key off DIR (and pins the session there, skipping cwd restore);
  1324. then ``--resume latest`` → MRU id, ``--continue`` → ``--resume``,
  1325. ``--resume @claude/@codex`` → imported session id, title → id; finally
  1326. cd back into a resumed session's recorded cwd (best-effort, opt-out via
  1327. --no-restore-cwd, skipped under --worktree).
  1328. """
  1329. _apply_in_dir(args)
  1330. # --resume latest: same resolution as bare `-c`. The keyword wins over a
  1331. # session literally titled "latest" (still reachable by ID or `-c latest`).
  1332. _resume_raw = getattr(args, "resume", None)
  1333. if isinstance(_resume_raw, str) and _resume_raw.strip().lower() == "latest":
  1334. _last_id = _latest_session_id(use_tui)
  1335. if _last_id:
  1336. args.resume = _last_id
  1337. else:
  1338. kind = "TUI" if use_tui else "CLI"
  1339. print(f"No previous {kind} session found to resume.")
  1340. print("Use 'hermes sessions list' to see available sessions.")
  1341. sys.exit(1)
  1342. _resolve_continue_arg(args, use_tui=use_tui)
  1343. from hermes_cli.main_resume_args import import_foreign_resume, recreate_resumed_tui_worktree
  1344. import_foreign_resume(args)
  1345. resume_val = getattr(args, "resume", None)
  1346. if resume_val:
  1347. # On miss keep the original so _init_agent reports "Session not found" with it.
  1348. args.resume = _resolve_session_by_name_or_id(resume_val) or resume_val
  1349. recreate_resumed_tui_worktree(args)
  1350. # cd back into a resumed session's recorded cwd (opt out: --no-restore-cwd;
  1351. # --worktree owns its own dir). A missing dir warns and stays put.
  1352. if (
  1353. getattr(args, "resume", None)
  1354. and not getattr(args, "no_restore_cwd", False)
  1355. and not getattr(args, "worktree", False)
  1356. ):
  1357. with _session_db() as db: # never let cwd-restore break a resume
  1358. _saved_cwd = ((db.get_session(args.resume) or {}).get("cwd") or "").strip()
  1359. if _saved_cwd and not os.path.isdir(_saved_cwd):
  1360. print(f"⚠ session's recorded dir is gone ({_saved_cwd}); staying in {os.getcwd()}")
  1361. elif _saved_cwd and os.path.realpath(_saved_cwd) != os.path.realpath(os.getcwd()):
  1362. os.chdir(_saved_cwd)
  1363. print(f"↪ restored workspace dir: {_saved_cwd}")
  1364. def _warn_retired_xai_models() -> None:
  1365. """One-shot xAI retirement warning on stderr; non-blocking, never fails startup."""
  1366. try:
  1367. from hermes_cli.xai_retirement import (
  1368. MIGRATION_GUIDE_URL,
  1369. RETIREMENT_DATE,
  1370. find_retired_xai_refs,
  1371. format_issue,
  1372. )
  1373. from hermes_cli.config import load_config as _load_config_for_xai_check
  1374. _retired_xai_refs = find_retired_xai_refs(_load_config_for_xai_check())
  1375. if _retired_xai_refs:
  1376. sys.stderr.write(
  1377. f"\033[33m⚠ xAI retires {len(_retired_xai_refs)} model(s) "
  1378. f"in your config on {RETIREMENT_DATE}:\033[0m\n"
  1379. )
  1380. for _ref in _retired_xai_refs:
  1381. sys.stderr.write(f" \033[33m⚠\033[0m {format_issue(_ref)}\n")
  1382. sys.stderr.write(f" \033[2mMigration guide: {MIGRATION_GUIDE_URL}\033[0m\n")
  1383. sys.stderr.write(" \033[2mRun 'hermes doctor' for details.\033[0m\n\n")
  1384. except Exception:
  1385. pass
  1386. def _start_chat_background_prefetch() -> None:
  1387. """Kick off the update-check/banner prefetch and the bundled-skills sync.
  1388. Update check is opt-in on Termux (it imports rich/prompt_toolkit in the
  1389. foreground and competes for CPU on single-core devices). The skills sync
  1390. is idempotent and hash-gated (~120-170ms of rglob/hashing) so it normally
  1391. runs in a daemon thread — skill loading happens at agent init, long after.
  1392. The ONE exception is an unseeded ~/.hermes/skills: there the banner
  1393. prefetch races the sync and caches an empty index ("No skills installed"
  1394. on the very first launch), so the first run syncs in the foreground and
  1395. drops the banner's skills cache.
  1396. """
  1397. if _termux_should_prefetch_update_check():
  1398. try:
  1399. from hermes_cli.banner import prefetch_banner_data, prefetch_update_check
  1400. prefetch_update_check()
  1401. prefetch_banner_data() # git banner state + skills index off-thread
  1402. except Exception:
  1403. pass
  1404. def _skills_dir_is_unseeded() -> bool:
  1405. try:
  1406. from hermes_cli.config import get_hermes_home
  1407. skills_dir = Path(get_hermes_home()) / "skills"
  1408. if not skills_dir.is_dir():
  1409. return True
  1410. return next(skills_dir.rglob("SKILL.md"), None) is None
  1411. except Exception:
  1412. return False
  1413. def _skills_sync_bg() -> None:
  1414. try:
  1415. _sync_bundled_skills_for_startup()
  1416. except Exception:
  1417. pass
  1418. if _skills_dir_is_unseeded():
  1419. _skills_sync_bg()
  1420. # Drop the banner's possibly-empty skills cache so it recomputes.
  1421. try:
  1422. import hermes_cli.banner as _banner_mod
  1423. _banner_mod._available_skills_cache = None
  1424. except Exception:
  1425. pass
  1426. else:
  1427. threading.Thread(
  1428. target=_skills_sync_bg, name="bundled-skills-sync", daemon=True
  1429. ).start()
  1430. def _first_run_setup_guard(args) -> None:
  1431. """No provider configured: offer `hermes setup` (TTY) or exit 1 with guidance."""
  1432. print()
  1433. print(
  1434. "It looks like Hermes isn't configured yet -- no API keys or providers found."
  1435. )
  1436. print()
  1437. print(" Run: hermes setup")
  1438. print()
  1439. from hermes_cli.setup import (
  1440. is_interactive_stdin,
  1441. print_noninteractive_setup_guidance,
  1442. )
  1443. if not is_interactive_stdin():
  1444. print_noninteractive_setup_guidance(
  1445. "No interactive TTY detected for the first-run setup prompt."
  1446. )
  1447. sys.exit(1)
  1448. try:
  1449. reply = input("Run setup now? [Y/n] ").strip().lower()
  1450. except (EOFError, KeyboardInterrupt):
  1451. reply = "n"
  1452. if reply in {"", "y", "yes"}:
  1453. cmd_setup(args)
  1454. return
  1455. print()
  1456. print("You can run 'hermes setup' at any time to configure.")
  1457. sys.exit(1)
  1458. # args attr -> (kwarg, default) passed through to _launch_tui / cli.main; only cli.main takes --api-key/--base-url.
  1459. _CHAT_PASSTHROUGH = (
  1460. ("provider", None), ("toolsets", None), ("skills", None), ("verbose", None),
  1461. ("quiet", False), ("query", None), ("image", None), ("resume", None),
  1462. ("worktree", False), ("checkpoints", False), ("pass_session_id", False),
  1463. ("max_turns", None),
  1464. )
  1465. def cmd_chat(args):
  1466. """Run interactive chat CLI."""
  1467. from hermes_cli.stream_json import stream_json_requested
  1468. # stream-json and the --safe-mode / --ignore-user-config bypass keep the transport client; the
  1469. # classic CLI (interactive, -q/-Q) is main's HermesCLI with a gateway-backed agent (gateway_agent.py).
  1470. if stream_json_requested(args) or _bypass_chat_launch(args):
  1471. from hermes_cli.gateway_chat_startup import launch_gateway_chat
  1472. sys.exit(launch_gateway_chat(args))
  1473. _apply_safe_mode(args)
  1474. _apply_user_config_bypass(args)
  1475. _guard_noninteractive_user_config(args)
  1476. use_tui = _resolve_use_tui(args)
  1477. if use_tui:
  1478. _refuse_unforwarded_tui_flags(args)
  1479. _resolve_chat_session_args(args, use_tui)
  1480. _warn_retired_xai_models()
  1481. # The TUI owns its first-run state: it renders "Setup Required" with in-place /setup.
  1482. # The classic prompt only fronts the classic CLI.
  1483. provider_configured = _has_any_provider_configured()
  1484. if not use_tui and not provider_configured:
  1485. _first_run_setup_guard(args)
  1486. return
  1487. _start_chat_background_prefetch()
  1488. # --yolo: bypass all dangerous command approvals. main() also sets this
  1489. # before _prepare_agent_startup() — the authoritative site, since it runs
  1490. # before tool imports freeze _YOLO_MODE_FROZEN. This is a safety net for
  1491. # callers that invoke cmd_chat directly (e.g. subcommand dispatch).
  1492. if getattr(args, "yolo", False):
  1493. os.environ["HERMES_YOLO_MODE"] = "1"
  1494. # --ignore-rules: skip AGENTS.md/SOUL.md/.cursorrules injection, memory
  1495. # entries and preloaded skills (AIAgent(skip_context_files, skip_memory)).
  1496. if getattr(args, "ignore_rules", False):
  1497. os.environ["HERMES_IGNORE_RULES"] = "1"
  1498. # --source: tag session source for filtering (e.g. 'tool' for integrations)
  1499. if getattr(args, "source", None):
  1500. os.environ["HERMES_SESSION_SOURCE"] = args.source
  1501. # Explicit flag, not a label inherited from a parent TUI/Desktop session — one-shot
  1502. # runs must keep it (see agent.session_source.session_source_for).
  1503. os.environ["HERMES_SESSION_SOURCE_EXPLICIT"] = "1"
  1504. _pin_kanban_board_env()
  1505. from hermes_cli.observability.shared_metrics_consent import offer_consent_before_chat
  1506. # Not before setup: a blank install meets "Setup Required" first. The offer stays
  1507. # undecided, so it is asked on the first launch with a provider.
  1508. if provider_configured:
  1509. offer_consent_before_chat(args)
  1510. _confirm_startup_expensive_model_override(args)
  1511. passthrough = {k: getattr(args, k, d) for k, d in _CHAT_PASSTHROUGH}
  1512. if use_tui:
  1513. _launch_tui(
  1514. passthrough.pop("resume"),
  1515. tui_dev=getattr(args, "tui_dev", False),
  1516. native_mode=getattr(args, "tui_native", False) or None,
  1517. model=getattr(args, "model", None),
  1518. accept_hooks=getattr(args, "accept_hooks", False),
  1519. **passthrough,
  1520. )
  1521. from hermes_cli.main_query_file import _read_query_file
  1522. _read_query_file(args)
  1523. safe_mode = getattr(args, "safe_mode", False)
  1524. kwargs = {
  1525. "model": args.model,
  1526. "reasoning": getattr(args, "reasoning", None),
  1527. "toolsets": args.toolsets,
  1528. "query": args.query,
  1529. "oneshot": bool(getattr(args, "oneshot_exit", False)),
  1530. "run_budget": getattr(args, "run_budget", None),
  1531. "output_format": getattr(args, "output_format", "text"),
  1532. "ignore_rules": getattr(args, "ignore_rules", False) or safe_mode,
  1533. "ignore_user_config": getattr(args, "ignore_user_config", False) or safe_mode,
  1534. "compact": getattr(args, "compact", False),
  1535. **{k: getattr(args, k, d) for k, d in _CHAT_PASSTHROUGH + (("api_key", None), ("base_url", None))},
  1536. }
  1537. kwargs = {k: v for k, v in kwargs.items() if v is not None}
  1538. try:
  1539. from cli import main as cli_main
  1540. from hermes_cli.observability.shared_metrics_process import begin_process
  1541. begin_process("cli")
  1542. cli_main(**kwargs)
  1543. except ValueError as e:
  1544. print(f"Error: {e}")
  1545. sys.exit(1)
  1546. except ImportError as e:
  1547. # Mixed-version installs (new cli.py, older hermes_cli.config) crash
  1548. # here — e.g. missing resolve_turn_limit / split_model_config_default
  1549. # (#96900). The agent-setup mixin prints this hint too late: HermesCLI
  1550. # construction already failed. Fast-chat launch also goes through
  1551. # cmd_chat, so this one catch covers `hermes` / `hermes chat`.
  1552. from hermes_constants import emit_partial_update_hint
  1553. if emit_partial_update_hint(e):
  1554. sys.exit(1)
  1555. raise
  1556. def cmd_gateway(args):
  1557. """Gateway management commands."""
  1558. # `gateway run` seeds skills itself (run_bootstrap._start_gateway_configure_logging) inside its
  1559. # own home; a second pass here doubled a cold boot on a fresh home while every attaching client
  1560. # waited on the ensure deadline. Management verbs never need the library.
  1561. from hermes_cli.gateway import gateway_command
  1562. gateway_command(args)
  1563. def cmd_proxy(args):
  1564. """Local OpenAI-compatible proxy to OAuth providers."""
  1565. # aiohttp is an extras install; keep it off the common path.
  1566. from hermes_cli.proxy.cli import cmd_proxy as _cmd_proxy
  1567. rc = _cmd_proxy(args)
  1568. if isinstance(rc, int) and rc != 0:
  1569. raise SystemExit(rc)
  1570. def _forward_command(name: str, module: str, attr: str, *, forward_return: bool = False, doc: str = ""):
  1571. """A ``hermes <cmd>`` handler that hands ``args`` to ``<module>.<attr>``.
  1572. Imports at CALL time so fast paths never pay for it and
  1573. ``patch("<module>.<attr>")`` keeps intercepting. ``forward_return``
  1574. surfaces the return code to ``main()`` (kanban/project/mcp propagate).
  1575. """
  1576. def _cmd(args):
  1577. import importlib
  1578. result = getattr(importlib.import_module(module), attr)(args)
  1579. return result if forward_return else None
  1580. _cmd.__name__ = _cmd.__qualname__ = name
  1581. _cmd.__doc__ = doc or None
  1582. return _cmd
  1583. cmd_setup = _forward_command("cmd_setup", "hermes_cli.setup", "run_setup_wizard", doc='Interactive setup wizard.')
  1584. cmd_login = _forward_command("cmd_login", "hermes_cli.auth", "login_command", doc='Authenticate Hermes CLI with a provider.')
  1585. cmd_logout = _forward_command("cmd_logout", "hermes_cli.auth", "logout_command", doc='Clear provider authentication.')
  1586. cmd_auth = _forward_command("cmd_auth", "hermes_cli.auth_commands", "auth_command", doc='Manage pooled credentials.')
  1587. cmd_status = _forward_command("cmd_status", "hermes_cli.status", "show_status", doc='Show status of all components.')
  1588. cmd_cron = _forward_command("cmd_cron", "hermes_cli.cron", "cron_command", forward_return=True, doc='Cron job management.')
  1589. cmd_webhook = _forward_command("cmd_webhook", "hermes_cli.webhook", "webhook_command", forward_return=True, doc='Webhook subscription management.')
  1590. cmd_kanban = _forward_command("cmd_kanban", "hermes_cli.kanban", "kanban_command", forward_return=True, doc='Multi-profile collaboration board.')
  1591. cmd_project = _forward_command("cmd_project", "hermes_cli.projects_cmd", "projects_command", forward_return=True, doc='Manage projects (named, multi-folder workspaces).')
  1592. cmd_hooks = _forward_command("cmd_hooks", "hermes_cli.hooks", "hooks_command", doc='Shell-hook inspection and management.')
  1593. cmd_doctor = _forward_command("cmd_doctor", "hermes_cli.doctor", "run_doctor", forward_return=True, doc='Check configuration and dependencies.')
  1594. cmd_dump = _forward_command("cmd_dump", "hermes_cli.dump", "run_dump", doc='Dump setup summary for support/debugging.')
  1595. cmd_debug = _forward_command("cmd_debug", "hermes_cli.debug", "run_debug", doc='Debug tools (share report, etc.).')
  1596. cmd_skin = _forward_command("cmd_skin", "hermes_cli.skin_cmd", "skin_command", doc='Skin management (list / use / set).')
  1597. cmd_import = _forward_command("cmd_import", "hermes_cli.backup", "run_import", forward_return=True, doc='Restore a Hermes backup from a zip file.')
  1598. cmd_dashboard_register = _forward_command("cmd_dashboard_register", "hermes_cli.dashboard_register", "cmd_dashboard_register", doc='Register a self-hosted dashboard OAuth client with Nous Portal.')
  1599. cmd_webapp = _forward_command("cmd_webapp", "hermes_cli.webapp_launcher", "cmd_webapp", forward_return=True, doc='Open the browser-hosted Desktop the gateway serves.')
  1600. cmd_gateway_enroll = _forward_command("cmd_gateway_enroll", "hermes_cli.gateway_enroll", "cmd_gateway_enroll", doc='Enroll a self-hosted gateway with a relay connector.')
  1601. cmd_prompt_size = _forward_command("cmd_prompt_size", "hermes_cli.prompt_size", "cmd_prompt_size", doc='Show a byte/char breakdown of the system prompt + tool schemas.')
  1602. cmd_pairing = _forward_command("cmd_pairing", "hermes_cli.pairing", "pairing_command")
  1603. cmd_plugins = _forward_command("cmd_plugins", "hermes_cli.plugins_cmd", "plugins_command")
  1604. cmd_mcp = _forward_command("cmd_mcp", "hermes_cli.mcp_config", "mcp_command", forward_return=True)
  1605. def cmd_model(args):
  1606. """Select default model — starts with provider selection, then model picker."""
  1607. _require_tty("model")
  1608. if getattr(args, "refresh", False):
  1609. try:
  1610. from hermes_cli.models import clear_provider_models_cache
  1611. clear_provider_models_cache()
  1612. print(" Cleared model picker cache.")
  1613. except Exception:
  1614. pass
  1615. from hermes_cli.observability.shared_metrics_setup import provider_setup_surface
  1616. from hermes_cli.setup import run_setup_action_with_navigation
  1617. with provider_setup_surface("cli_model"):
  1618. run_setup_action_with_navigation(
  1619. "Model & Provider", lambda: select_provider_and_model(args=args), cancelled_message="No change.",
  1620. )
  1621. # Provider id -> flow(config, current_model, args). Lambdas resolve the
  1622. # _model_flow_* names at call time so test monkeypatches keep intercepting.
  1623. # ``custom:*``, remove-custom and the generic API-key set are the fallthrough
  1624. # branches in select_provider_and_model.
  1625. _PROVIDER_MODEL_FLOWS = {
  1626. "openrouter": lambda c, m, a: _model_flow_openrouter(c, m),
  1627. "moa": lambda c, m, a: _model_flow_moa(c, m),
  1628. "ai-gateway": lambda c, m, a: _model_flow_ai_gateway(c, m),
  1629. "nous": lambda c, m, a: _model_flow_nous(c, m, args=a),
  1630. "openai-codex": lambda c, m, a: _model_flow_openai_codex(c, m),
  1631. "xai-oauth": lambda c, m, a: _model_flow_xai_oauth(c, m, args=a),
  1632. "qwen-oauth": lambda c, m, a: _model_flow_qwen_oauth(c, m),
  1633. "minimax-oauth": lambda c, m, a: _model_flow_minimax_oauth(c, m, args=a),
  1634. "custom": lambda c, m, a: _model_flow_custom(c),
  1635. "llamacpp": lambda c, m, a: _model_flow_local(c, m),
  1636. "anthropic": lambda c, m, a: _model_flow_anthropic(c, m),
  1637. "kimi-coding": lambda c, m, a: _model_flow_kimi(c, m),
  1638. "stepfun": lambda c, m, a: _model_flow_stepfun(c, m),
  1639. "bedrock": lambda c, m, a: _model_flow_bedrock(c, m),
  1640. "vertex": lambda c, m, a: _model_flow_vertex(c, m),
  1641. "azure-foundry": lambda c, m, a: _model_flow_azure_foundry(c, m),
  1642. }
  1643. def _norm_base_url(url: str) -> str:
  1644. return str(url or "").strip().rstrip("/").lower()
  1645. def _resolve_active_provider(config, model_cfg, effective_provider, custom_provider_map):
  1646. """Provider slug currently in effect (the picker's default row), or None.
  1647. Order: a saved custom provider whose base_url matches model.base_url →
  1648. the configured/env provider (named custom → canonical map key) → auto
  1649. detection. Unknown/unauthenticated providers warn and fall back to auto.
  1650. """
  1651. from hermes_cli.auth import AuthError, format_auth_error, resolve_provider
  1652. from hermes_cli.config import get_compatible_custom_providers, get_env_value
  1653. from hermes_cli.providers import custom_provider_aliases, resolve_provider_full
  1654. active = ""
  1655. if effective_provider == "custom" and isinstance(model_cfg, dict):
  1656. current_base = _norm_base_url(model_cfg.get("base_url", ""))
  1657. if current_base:
  1658. active = next(
  1659. (k for k, info in custom_provider_map.items()
  1660. if _norm_base_url(info.get("base_url", "")) == current_base),
  1661. "",
  1662. )
  1663. if not active and effective_provider != "auto":
  1664. active_def = resolve_provider_full(
  1665. effective_provider,
  1666. config.get("providers"),
  1667. get_compatible_custom_providers(config),
  1668. )
  1669. if active_def is not None:
  1670. active = active_def.id
  1671. if active_def.source == "user-config":
  1672. requested = str(active or "").strip().lower()
  1673. active = next(
  1674. (k for k, info in custom_provider_map.items()
  1675. if requested in custom_provider_aliases(
  1676. info.get("name", ""), info.get("provider_key", ""))),
  1677. active,
  1678. )
  1679. else:
  1680. from hermes_cli.left_core_migration import provider_install_hint
  1681. hint = provider_install_hint(effective_provider) or ("Check 'hermes model' for available providers, or run "
  1682. "'hermes doctor' to diagnose config issues.")
  1683. print(f"Warning: Unknown provider '{effective_provider}'. {hint} Falling back to auto provider detection.")
  1684. if not active:
  1685. try:
  1686. active = resolve_provider("auto")
  1687. except AuthError as exc:
  1688. if exc.code == "no_provider_configured":
  1689. # The picker that is about to open IS the fix; a warning that says
  1690. # "run `hermes model`" from inside `hermes model` is circular.
  1691. print("No provider is set up yet — pick one below. (Nous Portal works without an API key.)")
  1692. elif effective_provider == "auto":
  1693. print(f"Warning: {format_auth_error(exc)} Falling back to auto provider detection.")
  1694. active = None # no provider yet; default to first in list
  1695. # Detect custom endpoint
  1696. if active == "openrouter" and get_env_value("OPENAI_BASE_URL"):
  1697. active = "custom"
  1698. return active
  1699. def _pick_provider(config, active, provider_labels, custom_provider_map):
  1700. """Provider picker (+ group member sub-picker) -> concrete slug, or None on cancel."""
  1701. # Group rows drill into a member sub-picker that resolves back to a
  1702. # concrete slug, so the flow dispatch is unchanged.
  1703. ordered, default_idx = _build_provider_picker_rows(
  1704. config, active, provider_labels, custom_provider_map
  1705. )
  1706. provider_idx = _prompt_provider_choice(
  1707. [label for _, label, _ in ordered],
  1708. default=default_idx,
  1709. )
  1710. if provider_idx is None or ordered[provider_idx][0] == "cancel":
  1711. return None
  1712. selected_key, group_label, selected_members = ordered[provider_idx]
  1713. if not selected_members:
  1714. return selected_key
  1715. # Default to the active member when it lives in this group. The group row
  1716. # carries the descriptive text, so member rows show only their short label.
  1717. member_idx = _prompt_provider_choice(
  1718. [provider_labels.get(m, m) for m in selected_members],
  1719. default=selected_members.index(active) if active in selected_members else 0,
  1720. title=f"Select {group_label.split(' ▸', 1)[0]} provider:",
  1721. )
  1722. return None if member_idx is None else selected_members[member_idx]
  1723. def select_provider_and_model(args=None):
  1724. """Core provider selection + model picking logic.
  1725. Shared by ``cmd_model`` (``hermes model``) and the setup wizard
  1726. (``setup_model_provider`` in setup.py). Handles the full flow:
  1727. provider picker, credential prompting, model selection, and config
  1728. persistence.
  1729. """
  1730. from hermes_cli.config import load_config
  1731. config = load_config()
  1732. model_cfg = config.get("model")
  1733. current_model = model_cfg.get("default", "") if isinstance(model_cfg, dict) else model_cfg
  1734. current_model = current_model or "(not set)"
  1735. # Effective provider the same way the CLI resolves it at startup:
  1736. # config.yaml model.provider > env var > auto-detect
  1737. config_provider = model_cfg.get("provider") if isinstance(model_cfg, dict) else None
  1738. effective_provider = config_provider or os.getenv("HERMES_INFERENCE_PROVIDER") or "auto"
  1739. # User-defined custom providers from config.yaml: key → {name, base_url, api_key}
  1740. _custom_provider_map = _named_custom_provider_map(config)
  1741. active = _resolve_active_provider(config, model_cfg, effective_provider, _custom_provider_map)
  1742. from hermes_cli.models import _PROVIDER_LABELS
  1743. provider_labels = dict(_PROVIDER_LABELS) # derive from canonical list
  1744. if active and active in _custom_provider_map:
  1745. active_label = _custom_provider_map[active]["name"]
  1746. else:
  1747. active_label = provider_labels.get(active, active) if active else "none"
  1748. print()
  1749. print(f" Current model: {current_model}")
  1750. print(f" Active provider: {active_label}")
  1751. print()
  1752. selected_provider = _pick_provider(config, active, provider_labels, _custom_provider_map)
  1753. if selected_provider is None:
  1754. print("No change.")
  1755. return
  1756. if selected_provider == "aux-config":
  1757. _aux_config_menu()
  1758. return
  1759. if selected_provider == "reasoning":
  1760. # Effort for the CURRENT default model, no model change.
  1761. _prompt_main_reasoning_effort(current_model, active or "")
  1762. return
  1763. # Provider-specific setup + model selection. Flows resolve the
  1764. # _model_flow_* names at call time so test monkeypatches on
  1765. # hermes_cli.main keep intercepting.
  1766. saves_before = _model_choice_save_count()
  1767. from hermes_cli.observability.shared_metrics_setup import cli_provider_setup
  1768. with cli_provider_setup(selected_provider):
  1769. # Bespoke core flow, else the profile's own (``model_setup_flow``), else the generic one.
  1770. flow = _PROVIDER_MODEL_FLOWS.get(selected_provider) or _profile_model_setup_flow(selected_provider)
  1771. if flow is None and _is_profile_plugin_flow_provider(selected_provider):
  1772. # Registered plugin profile with no bespoke flow: the generic one, keyed by its auth_type.
  1773. flow = lambda c, m, a: _model_flow_plugin_provider(c, selected_provider, m)
  1774. if flow is not None:
  1775. flow(config, current_model, args)
  1776. elif (
  1777. selected_provider.startswith("custom:")
  1778. or selected_provider in _custom_provider_map
  1779. ):
  1780. provider_info = _named_custom_provider_map(load_config()).get(selected_provider)
  1781. if provider_info is None:
  1782. print(
  1783. "Warning: the selected saved custom provider is no longer available. "
  1784. "It may have been removed from config.yaml. No change."
  1785. )
  1786. return
  1787. _model_flow_named_custom(config, provider_info)
  1788. elif selected_provider == "remove-custom":
  1789. _remove_custom_provider(config)
  1790. elif (
  1791. selected_provider in _GENERIC_API_KEY_PROVIDERS
  1792. or _is_profile_api_key_provider(selected_provider)
  1793. ):
  1794. _model_flow_api_key_provider(config, selected_provider, current_model)
  1795. _offer_reasoning_after_pick(current_model, saves_before)
  1796. # Post-switch cleanup: switching to a named provider (anything except
  1797. # "custom") leaves a stale OPENAI_BASE_URL in ~/.hermes/.env that poisons
  1798. # auxiliary clients using provider:auto — clear it proactively. (#5161)
  1799. if selected_provider not in {
  1800. "custom",
  1801. "cancel",
  1802. "remove-custom",
  1803. } and not selected_provider.startswith("custom:"):
  1804. _clear_stale_openai_base_url()
  1805. def _detect_venv_python_processes(*, exclude_pids: set[int] | None = None) -> list[tuple[int, str, str]]:
  1806. # Shim to stop the old updater doing work until relaunch. Do not scan or kill.
  1807. # Current Windows checks use the real detector in update_cmd_windows instead.
  1808. return []
  1809. # Retired hooks must bypass update_cmd: its current dispatcher captures PM helpers
  1810. # before swapping code, but a historical caller may first resolve these afterward.
  1811. # Frozen updater surface (PEP 562 ``__getattr__`` below): the frozen
  1812. # ``hermes_cli/update_cmd*.py`` files resolve these names via ``_m().<name>``
  1813. # on hermes_cli.main; importing update_cmd eagerly would cost every ``hermes``
  1814. # invocation ~50-100ms, so they resolve on first read. Nothing else may be
  1815. # added here — internal import paths are not a stable API.
  1816. _FROZEN_UPDATER_SURFACE: dict[str, tuple[str, ...]] = {
  1817. "hermes_cli.update_cmd": (
  1818. "_assess_parked_branch_switch",
  1819. "_cold_start_windows_gateway_after_update", "_discard_stashed_changes",
  1820. "_filter_non_gateway_concurrent_instances", "_fleet_probe_expected_runtimes",
  1821. "_get_origin_url", "_park_stashed_changes",
  1822. "_pause_windows_gateways_for_update", "_print_parked_branch_kept_notice",
  1823. "_print_parked_branch_skip_warning",
  1824. "_refresh_bootstrap_cache_scripts", "_refresh_windows_gateway_launchers",
  1825. "_restore_stashed_changes",
  1826. "_resume_windows_gateways_after_update", "_run_logged_subprocess", "_run_pre_update_backup",
  1827. "_stash_local_changes_if_needed", "_sync_with_upstream_if_needed",
  1828. "_venv_launcher_ancestors",
  1829. "_wait_for_windows_update_gateway_exit", "_warn_orphaned_update_autostashes",
  1830. ),
  1831. "hermes_cli.old_updater_deps": (
  1832. "_capture_active_lazy_features", "_handoff_reapable_backend_pids",
  1833. "_ledger_manual_serve_holders", "_ledger_reapable_backend_pids",
  1834. "_leftover_pausable_gateway_pids", "_npm_lockfile_changed",
  1835. "_orphaned_desktop_backend_pids", "_refresh_active_lazy_features",
  1836. "_refresh_active_memory_provider_dependencies", "_relaunch_stopped_serves",
  1837. "_stop_process_trees",
  1838. ),
  1839. "hermes_cli.update_cmd_maint": (
  1840. "_purge_stale_hermes_modules", "_reload_updated_runtime_modules",
  1841. ),
  1842. "hermes_cli.dashboard_procs": (
  1843. "_detect_concurrent_hermes_instances", "_kill_stale_dashboard_processes",
  1844. ),
  1845. }
  1846. _FROZEN_ATTR_SOURCES: dict[str, str] = {
  1847. attr: module for module, attrs in _FROZEN_UPDATER_SURFACE.items() for attr in attrs
  1848. }
  1849. def __getattr__(name):
  1850. """Resolve the frozen updater surface on first read (see _FROZEN_UPDATER_SURFACE)."""
  1851. if name == "_write_update_incomplete_marker":
  1852. from hermes_cli._old_updater import stop_for_relaunch as value
  1853. else:
  1854. module = _FROZEN_ATTR_SOURCES.get(name)
  1855. if module is None:
  1856. raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
  1857. import importlib
  1858. value = getattr(importlib.import_module(module), name)
  1859. globals()[name] = value # cache: later accesses skip __getattr__
  1860. return value
  1861. def cmd_verify(args):
  1862. """Detect a project's run recipe and smoke-test it."""
  1863. from hermes_cli.verify_cmd import run_verify_command
  1864. sys.exit(run_verify_command(args))
  1865. def cmd_security(args):
  1866. """Dispatch `hermes security <subcmd>`."""
  1867. sub = getattr(args, "security_command", None)
  1868. if sub in ("audit", None):
  1869. from hermes_cli.security_audit import cmd_security_audit
  1870. # Default subcommand is `audit` when no subcmd is given.
  1871. code = cmd_security_audit(args)
  1872. sys.exit(int(code or 0))
  1873. print(f"unknown security subcommand: {sub}", file=sys.stderr)
  1874. sys.exit(2)
  1875. def cmd_approvals(args):
  1876. """Dispatch `hermes approvals <subcmd>`."""
  1877. from hermes_cli.approvals_suggest import approvals_command
  1878. status = approvals_command(args)
  1879. if status:
  1880. sys.exit(status)
  1881. return status
  1882. def cmd_config(args):
  1883. """Configuration management."""
  1884. from hermes_cli.config import config_command
  1885. try:
  1886. config_command(args)
  1887. except RuntimeError as exc:
  1888. # Fail-closed config write guard (require_readable_config_before_write);
  1889. # covers migrate and future write subcommands so none end in a traceback.
  1890. print(f"✗ {exc}", file=sys.stderr)
  1891. sys.exit(1)
  1892. def cmd_backup(args):
  1893. """Back up Hermes home directory to a zip file."""
  1894. from hermes_cli import backup
  1895. if getattr(args, "quick", False):
  1896. backup.run_quick_backup(args)
  1897. elif not backup.run_backup(args):
  1898. raise SystemExit(1) # archive written but incomplete: never shell-success for a timer
  1899. def _print_version_info(*, check_updates: bool = True) -> None:
  1900. # Shared with the `hermes --version` pre-import fast path.
  1901. _startup_fast.print_fast_version_info(check_updates=check_updates)
  1902. def cmd_version(args):
  1903. """Show version (--version/-V flag)."""
  1904. _print_version_info(check_updates=True)
  1905. def cmd_uninstall(args):
  1906. """Uninstall Hermes Agent (or just the Chat GUI with --gui).
  1907. ``--yes`` paths run from the desktop app's non-interactive cleanup scripts,
  1908. so the TTY gate applies only when we actually need to prompt.
  1909. """
  1910. # Machine-readable snapshot for the desktop uninstall UI; before any TTY gate.
  1911. if getattr(args, "gui_summary", False):
  1912. from hermes_cli.gui_uninstall import gui_install_summary
  1913. print(json.dumps(gui_install_summary()))
  1914. return
  1915. if getattr(args, "data", False):
  1916. if not getattr(args, "yes", False) and not getattr(args, "dry_run", False):
  1917. _require_tty("uninstall --data")
  1918. from hermes_cli.uninstall import run_data_uninstall
  1919. run_data_uninstall(args)
  1920. return
  1921. if getattr(args, "gui", False):
  1922. if not getattr(args, "yes", False) and not getattr(args, "dry_run", False):
  1923. _require_tty("uninstall --gui")
  1924. from hermes_cli.uninstall import run_gui_uninstall
  1925. run_gui_uninstall(args)
  1926. return
  1927. if not getattr(args, "yes", False) and not getattr(args, "dry_run", False):
  1928. _require_tty("uninstall")
  1929. from hermes_cli.uninstall import run_uninstall
  1930. run_uninstall(args)
  1931. def _clear_bytecode_cache(root: Path) -> int:
  1932. """Remove all __pycache__ dirs under *root* (stale .pyc → ImportError after updates).
  1933. Returns the number of directories removed.
  1934. """
  1935. removed = 0
  1936. for dirpath, dirnames, _ in os.walk(root):
  1937. dirnames[:] = [
  1938. d
  1939. for d in dirnames
  1940. if d not in {"venv", ".venv", "node_modules", ".git", ".worktrees"}
  1941. ]
  1942. if os.path.basename(dirpath) == "__pycache__":
  1943. try:
  1944. shutil.rmtree(dirpath)
  1945. removed += 1
  1946. except OSError:
  1947. pass
  1948. dirnames.clear() # nothing left to recurse into
  1949. return removed
  1950. def _finalize_update_receipt(code: int, reason: str) -> None:
  1951. """Best-effort receipt close at the command boundary; no-op if already finalized."""
  1952. try:
  1953. # Receipt boundary (#91283 review): the impl has many early sys.exit paths (concurrent-instance
  1954. # preflight, venv-holder refusal, head-pinned no-op, fetch failure) that never reach an inner
  1955. # finalize. Persist any still-open receipt with the real exit code, then let the exit proceed
  1956. # unchanged. No-op when an inner path already finalized (exactly-once by construction).
  1957. from hermes_cli.update_receipt import finalize_pending_update_receipt
  1958. finalize_pending_update_receipt(code, reason)
  1959. except Exception:
  1960. pass
  1961. def _update_preflight_handled(args) -> bool:
  1962. """Managed-install refusal, --plan, admission gate, --check. True = nothing more to do."""
  1963. from hermes_cli.config import is_managed, managed_error
  1964. from hermes_cli.update_channel import handle_metadata_args
  1965. from hermes_cli.update_cmd_common import _record_stop
  1966. if handle_metadata_args(args, PROJECT_ROOT):
  1967. sys.exit(0)
  1968. if is_managed():
  1969. managed_error("update Hermes Agent")
  1970. if not any(getattr(args, flag, False) for flag in ("plan", "check", "list_venv_holders")):
  1971. _record_stop("managed_install", without_receipt="refused") # an update attempt: a metrics row only
  1972. return True
  1973. # --plan is read-only and deployment-kind aware, so it runs BEFORE the
  1974. # docker/nix/apt refusal gates: on an image/package-managed install the
  1975. # plan itself reports "not updatable in place" plus the right mechanism.
  1976. if getattr(args, "plan", False):
  1977. # Read-only plan phase (#91277 Phase 2): inventory every running Hermes runtime across profiles, its
  1978. # supervisor, and its running code version — without mutating anything. Safe on a live fleet.
  1979. from hermes_cli.update_inventory import (
  1980. collect_runtime_inventory,
  1981. print_update_plan,
  1982. )
  1983. print_update_plan(collect_runtime_inventory())
  1984. return True
  1985. if getattr(args, "list_venv_holders", False):
  1986. # Read-only twin of the Windows venv-holder refusal (#117246): same scan and classifiers,
  1987. # machine-readable, exit 3 when holders remain so automation can stop those PIDs and retry.
  1988. import json
  1989. from hermes_cli.update_cmd_windows import VENV_HOLDERS_EXIT, list_venv_holders
  1990. holders = list_venv_holders()
  1991. print(json.dumps(holders, indent=2))
  1992. if holders:
  1993. sys.exit(VENV_HOLDERS_EXIT)
  1994. return True
  1995. # Image/package-managed admission gate (#91277 Phase 3): baked provenance marker first (fail-closed
  1996. # on malformed), then docker/nix/apt heuristics; one shared decision for every mutation surface, so
  1997. # --check never reports git state for an image-managed install. Prints the real update command,
  1998. # records a `refused` receipt and exits 2 (refused-by-contract, distinct from exit 1 errors).
  1999. from hermes_cli.update_contract import (
  2000. evaluate_update_admission,
  2001. record_refusal_receipt,
  2002. )
  2003. refusal = evaluate_update_admission(PROJECT_ROOT)
  2004. if refusal is not None:
  2005. print(refusal.message)
  2006. record_refusal_receipt(refusal)
  2007. sys.exit(2)
  2008. if getattr(args, "check", False):
  2009. # --check honors --branch so its answer matches what update would pull.
  2010. branch = _resolve_update_branch(args)
  2011. from hermes_cli.update_cmd import _cmd_update_check
  2012. _cmd_update_check(
  2013. branch=branch,
  2014. branch_explicit=bool(getattr(args, "branch", None)),
  2015. **({"channel": args.channel} if getattr(args, "channel", None) else {}),
  2016. )
  2017. return True
  2018. return False
  2019. from hermes_cli.update_receipt import update_receipt_scope
  2020. @update_receipt_scope()
  2021. def cmd_update(args):
  2022. """Update Hermes Agent: hangup protection + update lock around ``_cmd_update_impl``."""
  2023. # Marks this frame as the CURRENT updater for
  2024. # _old_updater.in_historical_update(); historical on-disk updaters do not
  2025. # declare this local, so only they hand off through retired shims.
  2026. _hermes_current_updater_frame = True
  2027. from hermes_cli.update_owning_install import retarget_to_owning_install
  2028. retarget_to_owning_install(PROJECT_ROOT)
  2029. if _update_preflight_handled(args):
  2030. return
  2031. gateway_mode = getattr(args, "gateway", False)
  2032. _update_io_state = _install_hangup_protection(gateway_mode=gateway_mode)
  2033. # Cross-process mutual exclusion: dashboard Update button, Tauri updater
  2034. # and this command all mutate one checkout; two at once strand it
  2035. # half-updated. Shares the marker the Tauri/Electron updaters already use.
  2036. from hermes_cli.update_lock import (
  2037. UPDATE_EXIT_CONCURRENT,
  2038. UpdateLock,
  2039. describe_holder,
  2040. )
  2041. _update_lock = UpdateLock(install_root=PROJECT_ROOT)
  2042. if not _update_lock.acquire():
  2043. print(describe_holder(_update_lock.holder))
  2044. _finalize_update_output(_update_io_state)
  2045. from hermes_cli.update_cmd_common import _record_stop
  2046. _record_stop("lock_held", without_receipt="refused") # no receipt: latest.json is the holder's
  2047. sys.exit(UPDATE_EXIT_CONCURRENT)
  2048. from hermes_cli.update_cmd import _cmd_update_impl
  2049. from pm import InstallError
  2050. def _custody_refusal() -> str | None:
  2051. # m2: readers swallow an OSError, so a refused update child can end the run as a misleading
  2052. # downstream error; the refusal is what stopped it. Never on POSIX (nothing refuses there).
  2053. custody = sys.modules.get("hermes_cli.update_custody")
  2054. return custody.refusal_notice() if custody is not None else None
  2055. try:
  2056. _cmd_update_impl(args, gateway_mode=gateway_mode)
  2057. except (InstallError, OSError, subprocess.SubprocessError) as exc:
  2058. refusal = _custody_refusal()
  2059. print(refusal or f"✗ Update failed: {exc}")
  2060. _finalize_update_receipt(1, f"{type(exc).__name__}: {exc}")
  2061. if gateway_mode:
  2062. from hermes_cli.update_cmd_fleet import _write_gateway_update_exit_code
  2063. _write_gateway_update_exit_code(False)
  2064. raise SystemExit(1) from exc
  2065. except SystemExit as _update_exit:
  2066. # Receipt boundary: the impl has many early sys.exit paths that never
  2067. # reach an inner finalize. Persist any still-open receipt with the real
  2068. # exit code (no-op if already finalized), then let the exit proceed.
  2069. _code = _update_exit.code if isinstance(_update_exit.code, int) else 1
  2070. if _code and (refusal := _custody_refusal()):
  2071. print(refusal)
  2072. _finalize_update_receipt(_code, f"sys.exit({_code})")
  2073. if gateway_mode and _code:
  2074. from hermes_cli.update_cmd_fleet import _write_gateway_update_exit_code
  2075. _write_gateway_update_exit_code(False)
  2076. raise
  2077. except BaseException as _update_exc:
  2078. if gateway_mode:
  2079. from hermes_cli.update_cmd_fleet import _write_gateway_update_exit_code
  2080. _write_gateway_update_exit_code(False)
  2081. _finalize_update_receipt(1, f"{type(_update_exc).__name__}: {_update_exc}")
  2082. raise
  2083. else:
  2084. from hermes_cli.update_receipt import COMMAND_BOUNDARY_STOP_REASON
  2085. _finalize_update_receipt(0, COMMAND_BOUNDARY_STOP_REASON)
  2086. finally:
  2087. _update_lock.release()
  2088. _finalize_update_output(_update_io_state)
  2089. def _coalesce_session_name_args(argv: list) -> list:
  2090. """Join unquoted multi-word session names after -c/--continue and -r/--resume.
  2091. ``hermes -c Pokemon Agent Dev`` → ``['-c', 'Pokemon Agent Dev']``; tokens
  2092. are collected until the next flag (``-*``) or known top-level subcommand.
  2093. """
  2094. _SUBCOMMANDS = {
  2095. "chat", "model", "gateway", "setup", "whatsapp", "whatsapp-cloud", "login", "logout",
  2096. "auth", "status", "cron", "doctor", "config", "pairing", "skills", "tools", "mcp",
  2097. "sessions", "insights", "update", "uninstall", "profile", "dashboard", "serve", "webapp",
  2098. "desktop", "gui", "honcho", "claw", "plugins", "security", "acp", "webhook", "peer",
  2099. "memory", "dump", "debug", "backup", "import", "completion", "logs", "usage",
  2100. }
  2101. _SESSION_FLAGS = {"-c", "--continue", "-r", "--resume"}
  2102. result = []
  2103. i = 0
  2104. while i < len(argv):
  2105. token = argv[i]
  2106. if token in _SESSION_FLAGS:
  2107. result.append(token)
  2108. i += 1
  2109. # Collect subsequent non-flag, non-subcommand tokens as one name
  2110. parts: list = []
  2111. while (
  2112. i < len(argv)
  2113. and not argv[i].startswith("-")
  2114. and argv[i] not in _SUBCOMMANDS
  2115. ):
  2116. parts.append(argv[i])
  2117. i += 1
  2118. if parts:
  2119. result.append(" ".join(parts))
  2120. else:
  2121. result.append(token)
  2122. i += 1
  2123. return result
  2124. from hermes_cli.profile_cmd import cmd_profile
  2125. def _dashboard_lifecycle_flags(args, token_file) -> None:
  2126. """--status / --stop: report or kill running dashboards and exit (no deps needed)."""
  2127. if token_file and (getattr(args, "status", False) or getattr(args, "stop", False)):
  2128. raise SystemExit("--ssh-session-token-file cannot be used with --status or --stop")
  2129. if getattr(args, "status", False):
  2130. _report_dashboard_status()
  2131. sys.exit(0) # status is informational, always 0
  2132. if getattr(args, "stop", False):
  2133. # Scoped to the invoking home (`-p` applied by _apply_profile_override): another
  2134. # install's or profile's backend on this machine is never a target (#113978).
  2135. from hermes_constants import get_hermes_home
  2136. own_home = str(get_hermes_home())
  2137. if not _find_stale_dashboard_pids(scope_home=own_home):
  2138. print("No hermes dashboard processes running for this profile.")
  2139. sys.exit(0)
  2140. # Reuse the same SIGTERM-grace-SIGKILL path used after `hermes update`;
  2141. # it prints outcomes itself. Exit 1 only if a pid was unkillable — judged
  2142. # from the kill result, not a re-scan: a launchd KeepAlive job respawns
  2143. # its backend on a fresh PID, which is not a failed stop.
  2144. from hermes_cli.dashboard_procs import _kill_stale_dashboard_processes
  2145. result = _kill_stale_dashboard_processes(reason="requested via --stop", scope_home=own_home)
  2146. sys.exit(1 if result["failed"] else 0)
  2147. def _dashboard_sanitize_desktop_env(headless_backend) -> None:
  2148. """Strip Desktop-inherited env that hijacks a standalone launch.
  2149. Desktop Electron spawns its backend with HERMES_DESKTOP=1 plus
  2150. HERMES_WEB_DIST=<packaged app.asar[/unpacked]/dist> (and often
  2151. HERMES_SERVE_HEADLESS=1). A shell inheriting those then running
  2152. `hermes dashboard` would serve the desktop renderer ("Desktop IPC bridge
  2153. is unavailable", #52945) or disable the SPA. Only Electron-packaged
  2154. WEB_DIST contamination is stripped from browser dashboards — caller-managed
  2155. overrides (dev / custom builds) must still work, while headless `serve`
  2156. keeps the packaged path used by the Desktop backend. Headless `serve`
  2157. re-sets HERMES_SERVE_HEADLESS itself.
  2158. The Desktop's legacy fallback spawn (`dashboard --no-open`, taken when the
  2159. `serve --help` probe times out on a cold host) is not headless yet must keep
  2160. its packaged dist: it is told apart by the per-spawn
  2161. HERMES_DASHBOARD_SESSION_TOKEN, which the terminal pane never receives and
  2162. the terminal tool's env policy strips from agent children.
  2163. """
  2164. desktop_owned_child = _is_desktop_owned_backend()
  2165. if (
  2166. not headless_backend
  2167. and not desktop_owned_child
  2168. and _is_electron_packaged_web_dist(os.environ.get("HERMES_WEB_DIST", ""))
  2169. ):
  2170. os.environ.pop("HERMES_WEB_DIST", None)
  2171. if not headless_backend:
  2172. os.environ.pop("HERMES_SERVE_HEADLESS", None)
  2173. def _require_dashboard_web_deps() -> None:
  2174. """Exit with the right message when the dashboard's web-server packages can't import.
  2175. A plain missing-package ImportError gets the standard repair guidance; the
  2176. ``DLL load failed ... _ssl`` signature of Windows Smart App Control blocking the
  2177. embedded runtime gets the policy guidance instead, so users stop looping on
  2178. repair for a block repair can never lift (#63796)."""
  2179. try:
  2180. import fastapi
  2181. import uvicorn
  2182. except ImportError as e:
  2183. from hermes_cli.main_dep_hints import (
  2184. missing_optional_deps_message,
  2185. smart_app_control_block_message,
  2186. )
  2187. print(smart_app_control_block_message(e) or missing_optional_deps_message(
  2188. "dashboard", "its web-server packages (fastapi, uvicorn)", "all"))
  2189. print(f"Details: {e}")
  2190. sys.exit(1)
  2191. def _dashboard_prepare_runtime(args, headless_backend) -> bool:
  2192. """Deps check, skills seed, terminal env bridge, plugins, MCP discovery.
  2193. Returns ``start_mcp_discovery_after_bind`` for start_server.
  2194. """
  2195. # Attach gui.log early so dashboard startup/build failures are captured in
  2196. # the same logs directory as every other Hermes surface.
  2197. try:
  2198. from hermes_logging import setup_logging as _setup_logging_gui
  2199. _setup_logging_gui(mode="gui")
  2200. except Exception:
  2201. pass
  2202. _require_dashboard_web_deps()
  2203. # Seed bundled skills on first dashboard launch so the desktop GUI's
  2204. # skills picker / agent skill discovery sees the bundled library.
  2205. _sync_bundled_skills_quietly()
  2206. # Bridge terminal.* config into TERMINAL_* env for THIS process, like the
  2207. # CLI (cli.py env_mappings) and gateway (_terminal_env_map) do. The
  2208. # dashboard/serve backend runs agents in-process (tui_gateway.ws →
  2209. # server._make_agent) and ticks cron itself when desktop-spawned; without
  2210. # this those consumers saw an unset TERMINAL_ENV and ran every command on
  2211. # the host even under `terminal.backend: docker` (#63141, #54449).
  2212. try:
  2213. # PTY chat spawns already bridge their child env copy; this covers the in-process consumers. See
  2214. # #61115, #65696.
  2215. from hermes_cli.config import apply_terminal_config_to_env
  2216. apply_terminal_config_to_env()
  2217. except Exception:
  2218. logger.debug("terminal config → env bridge failed for dashboard/serve",
  2219. exc_info=True)
  2220. _resolve_dashboard_web_dist(args, headless_backend)
  2221. # Load plugins so any DashboardAuthProvider plugin registers BEFORE
  2222. # start_server's fail-closed gate check. Argparse setup skips discovery
  2223. # for built-in subcommands (~500ms), but the dashboard's server-side
  2224. # runtime depends on plugin-registered providers (image_gen, web,
  2225. # dashboard_auth, …).
  2226. try:
  2227. from hermes_cli.plugins import discover_plugins
  2228. discover_plugins()
  2229. except Exception as exc:
  2230. # Must not block startup; the gate's fail-closed branch surfaces a
  2231. # missing provider if it matters.
  2232. print(f"⚠ Plugin discovery failed: {exc}", file=sys.stderr)
  2233. # Desktop chat uses the in-process /api/ws gateway (tui_gateway.server
  2234. # ._make_agent), which only snapshots the tool registry and never starts
  2235. # MCP discovery — so configured MCP servers would never connect. Spawn
  2236. # discovery in the background here so a slow/dead server can't block
  2237. # startup. Desktop-spawned headless backends start it AFTER the socket
  2238. # binds instead (start_server's ready path): the thread's first act is the
  2239. # ~350ms `mcp` SDK import, which holds the GIL against the web_server
  2240. # import and delays the READY sentinel; _make_agent's bounded
  2241. # wait_for_mcp_discovery covers a server still connecting at first turn.
  2242. # A standalone (non-Desktop) dashboard may sit idle and unvisited for days
  2243. # (#58733): it arms discovery instead and the first /api/ws client fires it.
  2244. desktop = _is_desktop_owned_backend()
  2245. if headless_backend and desktop:
  2246. return True
  2247. try:
  2248. from hermes_cli.mcp_startup import (
  2249. defer_background_mcp_discovery,
  2250. start_background_mcp_discovery,
  2251. )
  2252. if desktop:
  2253. start_background_mcp_discovery(logger=logger, thread_name="dashboard-mcp-discovery")
  2254. else:
  2255. defer_background_mcp_discovery(logger=logger, thread_name="dashboard-mcp-discovery", delay=None)
  2256. except Exception:
  2257. logger.debug(
  2258. "Background MCP tool discovery failed at dashboard startup",
  2259. exc_info=True,
  2260. )
  2261. return False
  2262. def cmd_dashboard(args):
  2263. """Start the web UI server, or (with --stop/--status) manage running ones."""
  2264. _token_file = getattr(args, "ssh_session_token_file", None)
  2265. _dashboard_lifecycle_flags(args, _token_file)
  2266. # `serve` is the headless backend: no UI build, no SPA mount, neutral
  2267. # ready sentinel. Resolved once and threaded through the re-exec, the
  2268. # build gate, and start_server.
  2269. _headless_backend = getattr(args, "headless_backend", False)
  2270. _ssh_owner_nonce = _dashboard_validate_serve_args(args, _headless_backend, _token_file)
  2271. _dashboard_sanitize_desktop_env(_headless_backend)
  2272. _attach_to_host_backend(args, _headless_backend)
  2273. _route_named_profile_dashboard(args, _headless_backend, _ssh_owner_nonce, _token_file)
  2274. # Apply the final process/profile policy after dashboard routing, but before
  2275. # importing the web server or opening dashboard state. Applying it before a
  2276. # named-profile re-exec could leak that profile's higher limit into the
  2277. # machine/default dashboard, whose lower policy intentionally cannot undo it.
  2278. # This also covers Desktop SSH's isolated `serve` child, which does not route.
  2279. from hermes_cli.resource_limits import apply_nofile_soft_limit
  2280. apply_nofile_soft_limit()
  2281. _ssh_session_token = _read_ssh_session_token_file(_token_file) if _token_file else None
  2282. _mcp_discovery_after_bind = _dashboard_prepare_runtime(args, _headless_backend)
  2283. from hermes_cli.dashboard_procs import BACKEND_LOCK_NAME
  2284. from hermes_cli.web_server import start_server
  2285. # Interactive auth setup: if this bind will engage the auth gate but no
  2286. # provider is registered yet, offer to configure one here (TTY only)
  2287. # instead of hard-failing inside start_server. Non-interactive callers
  2288. # (Docker/s6, CI, --no-open pipelines) fall through to start_server's
  2289. # fail-closed SystemExit unchanged.
  2290. _maybe_setup_dashboard_auth_interactively(args)
  2291. if _headless_backend:
  2292. from hermes_cli.observability.shared_metrics_process import begin_process
  2293. begin_process("serve")
  2294. # The in-browser Chat tab (embedded TUI over PTY/WebSocket) is always
  2295. # available — desktop and dashboard both rely on `/api/ws` + `/api/pty`.
  2296. start_server(
  2297. host=args.host,
  2298. port=args.port,
  2299. open_browser=not args.no_open,
  2300. allow_public=getattr(args, "insecure", False),
  2301. initial_profile=getattr(args, "open_profile", "") or "",
  2302. headless=_headless_backend,
  2303. isolated=getattr(args, "isolated", False),
  2304. ssh_session_token=_ssh_session_token,
  2305. ssh_owner_nonce=_ssh_owner_nonce,
  2306. start_mcp_discovery_after_bind=_mcp_discovery_after_bind,
  2307. # The validated token file lives in desktop-ssh/<ownershipId>/, next to the Desktop's lock.
  2308. ssh_lock_path=Path(_token_file).parent / BACKEND_LOCK_NAME if _token_file else None,
  2309. )
  2310. def cmd_completion(args, parser=None):
  2311. """Print shell completion script."""
  2312. from hermes_cli import completion
  2313. shell = getattr(args, "shell", "bash")
  2314. generate = {"zsh": completion.generate_zsh, "fish": completion.generate_fish}.get(
  2315. shell, completion.generate_bash
  2316. )
  2317. print(generate(parser))
  2318. def cmd_logs(args):
  2319. """View and filter Hermes log files."""
  2320. from hermes_cli.logs import tail_log, list_logs
  2321. log_name = getattr(args, "log_name", "agent") or "agent"
  2322. if log_name == "list":
  2323. list_logs()
  2324. return
  2325. tail_log(
  2326. log_name,
  2327. num_lines=getattr(args, "lines", 50),
  2328. follow=getattr(args, "follow", False),
  2329. level=getattr(args, "level", None),
  2330. session=getattr(args, "session", None),
  2331. since=getattr(args, "since", None),
  2332. component=getattr(args, "component", None),
  2333. )
  2334. def cmd_console(args):
  2335. """Open the safe Hermes command console."""
  2336. from hermes_cli.console_engine import run_console_repl
  2337. return run_console_repl()
  2338. # Top-level subcommands known WITHOUT plugin discovery (which costs 500ms+ of
  2339. # eager plugin imports). Keep in sync with the add_parser calls in
  2340. # _build_cli_parser: a missing entry only costs a one-time discovery; an extra
  2341. # entry would let a plugin command silently fail to parse.
  2342. _BUILTIN_SUBCOMMANDS = frozenset(
  2343. {
  2344. "acp", "approvals", "auth", "backup", "bundles", "checkpoints", "codex-runtime", "completion",
  2345. "computer-use", "connectors",
  2346. "config", "console", "cron", "curator", "dashboard", "serve", "debug", "doctor",
  2347. "dump", "egress", "fallback", "gateway", "hooks", "import", "insights",
  2348. "gui", "desktop", "kanban", "login", "logout", "logs", "lsp", "mcp", "memory", "migrate", "moa",
  2349. "journey", "memory-graph", "learning",
  2350. "model", "monitoring", "pairing", "pause", "peer", "pets", "plugins", "portal", "profile",
  2351. "project", "proxy",
  2352. "prompt-size",
  2353. "resume",
  2354. "send", "sessions", "setup",
  2355. "skin", "skills", "slack", "status", "tools", "uninstall", "update",
  2356. "usage", "vault",
  2357. "webhook", "whatsapp", "whatsapp-cloud", "worktree", "chat", "secrets", "security",
  2358. "browser",
  2359. "verify",
  2360. # Plugin commands missing from top-level --help is an accepted trade-off.
  2361. "help",
  2362. }
  2363. )
  2364. def _first_positional_argv() -> str | None:
  2365. """First non-flag, non-flag-value token in ``sys.argv[1:]`` (skips values of known flags).
  2366. Not a full argparse simulation: an unknown ``--foo bar`` may classify
  2367. ``bar`` as positional, which at worst forces a one-time plugin discovery.
  2368. """
  2369. from hermes_cli._parser import command_argv
  2370. args = command_argv(sys.argv[1:])
  2371. return args[0] if args else None
  2372. def _plugin_cli_discovery_needed() -> bool:
  2373. """True when the CLI might be invoking a plugin-registered subcommand.
  2374. False skips plugin discovery at argparse setup (~500-650ms). An unknown
  2375. first token could be a plugin command OR a chat prompt — either way
  2376. discovery is needed; for a prompt its cost amortizes over the agent run.
  2377. """
  2378. first = _first_positional_argv() # None = bare ``hermes`` → chat
  2379. return first is not None and first not in _BUILTIN_SUBCOMMANDS
  2380. def _resolve_deferred_platform_cli_command(command_name: str | None) -> None:
  2381. """Materialize the deferred platform whose top-level CLI command matches.
  2382. Bundled platforms are *deferred* entries (no gateway SDK imports at
  2383. startup), so a platform's ``register_cli_command`` side effect only runs
  2384. on import; ``discover_plugins()`` alone leaves ``hermes photon`` failing
  2385. with ``invalid choice``. Importing just the matching platform keeps
  2386. startup cheap.
  2387. On the unknown-top-level-command slow path, ``discover_plugins()`` records the deferred loader but does
  2388. not import it, so the CLI registration never happens and ``hermes photon`` fails with argparse ``invalid
  2389. choice`` (issue #54678).
  2390. """
  2391. if not command_name:
  2392. return
  2393. try:
  2394. from gateway.platform_registry import platform_registry
  2395. platform_registry.get(command_name)
  2396. except Exception as exc:
  2397. logging.getLogger(__name__).debug(
  2398. "Deferred platform CLI resolution failed for %s: %s",
  2399. command_name,
  2400. exc,
  2401. )
  2402. _AGENT_COMMANDS = {None, "chat", "acp", "rl"}
  2403. _AGENT_SUBCOMMANDS = {
  2404. "cron": ("cron_command", {"run", "tick"}),
  2405. "gateway": ("gateway_command", {"run"}),
  2406. }
  2407. def _is_tui_chat_launch(args) -> bool:
  2408. if _bypass_chat_launch(args):
  2409. return False
  2410. if getattr(args, "tui", False) or os.environ.get("HERMES_TUI") == "1":
  2411. return True
  2412. # The chat path decides TUI-vs-classic via _resolve_use_tui (--cli/--tui
  2413. # flags, TTY gate, HERMES_TUI env, display.interface config). Bare
  2414. # `hermes`/`hermes chat` with a TUI display config was previously missed
  2415. # here, so the wrapper pre-warmed its own MCP discovery while the TUI
  2416. # gateway (spawned moments later) ran a second one — an idle stdio MCP
  2417. # server copy held dead for the whole session. Only chat commands can
  2418. # launch the TUI; other commands (gateway, acp, cron) keep
  2419. # their own discovery behavior untouched.
  2420. if getattr(args, "command", None) not in {None, "chat"}:
  2421. return False
  2422. return _resolve_use_tui(args)
  2423. def _agent_subcommand_selected(args) -> bool:
  2424. """True for ``cron run/tick``, ``gateway run`` (see _AGENT_SUBCOMMANDS)."""
  2425. _sub_attr, _sub_set = _AGENT_SUBCOMMANDS.get(args.command, (None, None))
  2426. return bool(_sub_attr and getattr(args, _sub_attr, None) in _sub_set)
  2427. def _should_background_mcp_startup(args) -> bool:
  2428. return not _is_tui_chat_launch(args) and args.command in {None, "chat", "rl"}
  2429. def _chat_runs_at_gateway(args) -> bool:
  2430. """Every ``hermes`` / ``hermes chat`` turn (classic view, ``-q``, ``-z``, TUI) executes in the
  2431. gateway, which discovers and owns MCP servers itself. Discovery in this client only spawns a
  2432. second copy of every server and holds the cross-process discovery lock the cold-starting gateway
  2433. then waits on (measured 2.0 s with one stdio server) for tools nothing here ever calls."""
  2434. return args.command in {None, "chat"}
  2435. def _prepare_agent_startup(args) -> None:
  2436. """Discover plugins/MCP/hooks for commands that can run an agent turn."""
  2437. # --yolo chokepoint: HERMES_YOLO_MODE must be set before any discovery
  2438. # below imports tools.approval, which freezes _YOLO_MODE_FROZEN at import.
  2439. # main() sets it earlier too, but other launchers (Termux fast-CLI) reach
  2440. # here directly, so the guarantee lives where the import is triggered.
  2441. # See #7994.
  2442. if getattr(args, "yolo", False):
  2443. os.environ["HERMES_YOLO_MODE"] = "1"
  2444. if args.command in {None, "chat"} and _bypass_chat_launch(args):
  2445. # Bypass launches are frozen by the gateway owner and executed out of process. This
  2446. # client is a transport: no env mutation (it would ride into an authority spawn),
  2447. # no plugin/MCP/hook discovery, and no profile read of the config under suspicion.
  2448. return
  2449. _apply_safe_mode(args)
  2450. _apply_user_config_bypass(args)
  2451. _guard_noninteractive_user_config(args)
  2452. if not (args.command in _AGENT_COMMANDS or _agent_subcommand_selected(args)):
  2453. return
  2454. _accept_hooks = bool(getattr(args, "accept_hooks", False))
  2455. if not (_is_tui_chat_launch(args) or _chat_runs_at_gateway(args)):
  2456. # The TUI backend and the gateway (chat turns, plugin commands, pre_command) discover their own.
  2457. try:
  2458. from hermes_cli.plugins import start_background_plugin_discovery
  2459. # Daemon thread: ~150ms of manifest scanning overlaps the rest of
  2460. # startup. Every synchronous reader goes through discover_plugins(),
  2461. # which joins this thread first (incl. model_tools at import time).
  2462. start_background_plugin_discovery()
  2463. except Exception:
  2464. logger.warning(
  2465. "plugin discovery failed at CLI startup",
  2466. exc_info=True,
  2467. )
  2468. # -t/--toolsets narrows which configured MCP servers get spawned, on
  2469. # every discovery path (background thread, TUI/desktop
  2470. # deferred start). Built-in toolset names never match a server key, so
  2471. # `-t terminal` simply spawns nothing; `-t all` keeps the full set.
  2472. try:
  2473. from hermes_cli.mcp_startup import set_mcp_server_filter
  2474. set_mcp_server_filter(getattr(args, "toolsets", None))
  2475. except Exception:
  2476. logger.debug("MCP server filter setup failed", exc_info=True)
  2477. # TUI launches background MCP discovery with a bounded join; acp/gateway/cron do their own.
  2478. if _chat_runs_at_gateway(args): # chat turns run in the gateway: it owns MCP, hooks, webhooks
  2479. if _accept_hooks: # rides session.create (env_launch_flags) and the classic CLI's consent check
  2480. os.environ["HERMES_ACCEPT_HOOKS"] = "1"
  2481. return
  2482. if _should_background_mcp_startup(args):
  2483. try:
  2484. from hermes_cli.mcp_startup import start_background_mcp_discovery
  2485. start_background_mcp_discovery(
  2486. logger=logger,
  2487. thread_name="cli-mcp-discovery",
  2488. )
  2489. except Exception:
  2490. logger.debug(
  2491. "Background MCP tool discovery failed at CLI startup",
  2492. exc_info=True,
  2493. )
  2494. try:
  2495. from hermes_cli.config import load_config
  2496. from agent.shell_hooks import register_from_config
  2497. from agent.outbound_webhooks import register_from_config as register_outbound_webhooks
  2498. _hooks_cfg = load_config()
  2499. register_from_config(_hooks_cfg, accept_hooks=_accept_hooks, interactive=args.command in {None, "chat", "rl"})
  2500. if _accept_hooks and args.command == "gateway": # every session-open re-sync keeps honouring it
  2501. from agent.shell_hooks import accept_for_process
  2502. accept_for_process()
  2503. register_outbound_webhooks(_hooks_cfg)
  2504. except Exception:
  2505. logger.debug(
  2506. "shell-hook registration failed at CLI startup",
  2507. exc_info=True,
  2508. )
  2509. def _apply_safe_mode(args) -> None:
  2510. if not getattr(args, "safe_mode", False):
  2511. return
  2512. os.environ["HERMES_SAFE_MODE"] = "1"
  2513. os.environ["HERMES_IGNORE_USER_CONFIG"] = "1"
  2514. os.environ["HERMES_IGNORE_RULES"] = "1"
  2515. def _apply_user_config_bypass(args) -> None:
  2516. """Apply the explicit config bypass before any startup config reads."""
  2517. if getattr(args, "ignore_user_config", False):
  2518. os.environ["HERMES_IGNORE_USER_CONFIG"] = "1"
  2519. def _guard_noninteractive_user_config(args) -> None:
  2520. """Fail closed before a non-interactive invocation initializes providers."""
  2521. if getattr(args, "_noninteractive_config_validated", False):
  2522. return
  2523. is_noninteractive = (
  2524. bool(getattr(args, "oneshot", None))
  2525. or bool(getattr(args, "query", None))
  2526. )
  2527. if not is_noninteractive:
  2528. return
  2529. from hermes_cli.config import (
  2530. InvalidUserConfigError,
  2531. require_parseable_user_config,
  2532. )
  2533. try:
  2534. require_parseable_user_config(
  2535. ignore_user_config=bool(
  2536. getattr(args, "ignore_user_config", False)
  2537. or getattr(args, "safe_mode", False)
  2538. )
  2539. )
  2540. except InvalidUserConfigError as exc:
  2541. print(f"Error: {exc}", file=sys.stderr)
  2542. raise SystemExit(2) from exc
  2543. args._noninteractive_config_validated = True
  2544. def _set_chat_arg_defaults(args) -> None:
  2545. """Fill the chat-parser attrs cmd_chat reads when chat was not parsed."""
  2546. for attr, default in [
  2547. ("query", None),
  2548. ("model", None),
  2549. ("provider", None),
  2550. ("toolsets", None),
  2551. ("verbose", False),
  2552. ("resume", None),
  2553. ("continue_last", None),
  2554. ("worktree", False),
  2555. ]:
  2556. if not hasattr(args, attr):
  2557. setattr(args, attr, default)
  2558. def _run_oneshot_from_args(args) -> None:
  2559. """Top-level --oneshot / -z: single-shot mode, stdout = final response only.
  2560. Bypasses cli.py entirely; the transport launcher never returns.
  2561. """
  2562. from hermes_cli.gateway_chat_startup import launch_gateway_chat
  2563. sys.exit(launch_gateway_chat(args))
  2564. def _enable_cpu_profile(args) -> None:
  2565. """Honour ``--cpu-profile`` right after a launch path parses argv, before it branches."""
  2566. from hermes_cli.cpu_profile import enable_cpu_profile_from_args
  2567. enable_cpu_profile_from_args(args)
  2568. def _light_chat_parser():
  2569. """Top-level + chat parser only (no subcommand tree); chat dispatches to cmd_chat."""
  2570. from hermes_cli._parser import build_top_level_parser
  2571. parser, _subparsers, chat_parser = build_top_level_parser()
  2572. chat_parser.set_defaults(func=cmd_chat)
  2573. return parser
  2574. def _promote_top_level_resume(args) -> None:
  2575. """Top-level --resume/--continue with no subcommand is a chat shortcut."""
  2576. if (args.resume or args.continue_last) and args.command is None:
  2577. args.command = "chat"
  2578. def _try_fast_serve_launch() -> bool:
  2579. """Dispatch an unambiguous built-in ``serve`` without the full CLI tree.
  2580. Desktop runs this on every cold start; building every other parser costs
  2581. thousands of filesystem-backed lookups on Windows. Unknown or global
  2582. arguments fall back to normal parsing so error reporting is unchanged.
  2583. """
  2584. if os.environ.get("HERMES_DISABLE_FAST_SERVE_LAUNCH") == "1":
  2585. return False
  2586. argv = sys.argv[1:]
  2587. if not argv or argv[0] != "serve" or "-h" in argv or "--help" in argv:
  2588. return False
  2589. # Container routing is top-level policy and must run before host dispatch.
  2590. try:
  2591. from hermes_cli.config import get_container_exec_info
  2592. if get_container_exec_info():
  2593. return False
  2594. except Exception:
  2595. return False
  2596. parser = build_serve_parser(
  2597. cmd_dashboard=cmd_dashboard,
  2598. add_help=False,
  2599. exit_on_error=False,
  2600. )
  2601. try:
  2602. args, unknown = parser.parse_known_args(argv[1:])
  2603. except (argparse.ArgumentError, ValueError):
  2604. return False
  2605. if unknown:
  2606. return False
  2607. cmd_dashboard(args)
  2608. return True
  2609. def _try_fast_chat_launch() -> bool:
  2610. """Fast path for unambiguous interactive chat launches (all hosts).
  2611. Building all ~40 subcommand parsers costs ~140ms the chat path never
  2612. uses. Bails out (False) whenever the invocation is not certainly a chat
  2613. launch — subcommand positional, ``--help``, unknown flags. Mirrors
  2614. ``_try_termux_fast_cli_launch`` minus the Termux deferred startup; kept
  2615. separate so phone-tuned behavior doesn't leak to desktops.
  2616. """
  2617. if os.environ.get("HERMES_DISABLE_FAST_CHAT_LAUNCH") == "1":
  2618. return False
  2619. argv = sys.argv[1:]
  2620. if "-h" in argv or "--help" in argv:
  2621. return False
  2622. # Container routing must win: NixOS container mode forwards EVERY invocation.
  2623. try:
  2624. from hermes_cli.config import get_container_exec_info
  2625. if get_container_exec_info():
  2626. return False
  2627. except Exception:
  2628. return False
  2629. # TUI launches keep full dispatch outside Termux (own startup path).
  2630. if _wants_tui_early(argv):
  2631. return False
  2632. if _first_positional_argv() not in {None, "chat"}:
  2633. return False
  2634. parser = _light_chat_parser()
  2635. try:
  2636. args, unknown = parser.parse_known_args(_coalesce_session_name_args(argv))
  2637. except SystemExit:
  2638. return False
  2639. if unknown: # plugin subcommand or full-parser-only flag → full dispatch
  2640. return False
  2641. if getattr(args, "version", False):
  2642. return False
  2643. if getattr(args, "command", None) not in {None, "chat"}:
  2644. return False
  2645. _enable_cpu_profile(args)
  2646. if getattr(args, "yolo", False):
  2647. os.environ["HERMES_YOLO_MODE"] = "1"
  2648. _prepare_agent_startup(args)
  2649. if getattr(args, "oneshot", None):
  2650. _run_oneshot_from_args(args)
  2651. _promote_top_level_resume(args)
  2652. _set_chat_arg_defaults(args)
  2653. cmd_chat(args)
  2654. return True
  2655. def _try_termux_fast_cli_launch() -> bool:
  2656. """Run obvious Termux non-TUI chat/oneshot/version paths on a light parser."""
  2657. if not _is_termux_startup_environment():
  2658. return False
  2659. if os.environ.get("HERMES_TERMUX_DISABLE_FAST_CLI") == "1":
  2660. return False
  2661. argv = sys.argv[1:]
  2662. if "-h" in argv or "--help" in argv:
  2663. return False
  2664. if _wants_tui_early(argv): # TUI fast path / full dispatch owns those
  2665. return False
  2666. if _startup_fast.is_global_fast_version_argv(argv):
  2667. _print_version_info(check_updates=True)
  2668. return True
  2669. first = _first_positional_argv()
  2670. has_oneshot = any(
  2671. arg == "-z" or arg == "--oneshot" or arg.startswith("--oneshot=")
  2672. for arg in argv
  2673. )
  2674. if not has_oneshot and first not in {None, "chat"}:
  2675. return False
  2676. parser = _light_chat_parser()
  2677. args = parser.parse_args(_coalesce_session_name_args(argv))
  2678. _enable_cpu_profile(args) # before any branch: the interactive one defers agent startup
  2679. if getattr(args, "version", False):
  2680. _print_version_info(check_updates=True)
  2681. return True
  2682. if getattr(args, "oneshot", None):
  2683. _prepare_agent_startup(args)
  2684. _run_oneshot_from_args(args)
  2685. _promote_top_level_resume(args)
  2686. if args.command in {None, "chat"}:
  2687. _set_chat_arg_defaults(args)
  2688. if not getattr(args, "query", None) and not getattr(args, "image", None): # interactive prompt
  2689. # Reach the prompt first; agent-only discovery on the first turn.
  2690. args.compact = True
  2691. os.environ["HERMES_DEFER_AGENT_STARTUP"] = "1"
  2692. os.environ["HERMES_FAST_STARTUP_BANNER"] = "1"
  2693. if getattr(args, "accept_hooks", False):
  2694. os.environ["HERMES_ACCEPT_HOOKS"] = "1"
  2695. else:
  2696. _prepare_agent_startup(args)
  2697. cmd_chat(args)
  2698. return True
  2699. return False
  2700. def _try_termux_fast_tui_launch() -> bool:
  2701. """Launch obvious Termux TUI invocations before building every subparser.
  2702. `hermes --tui` is the hot path on phones and the TUI immediately execs
  2703. Node, so the full parser's command-module imports are pure waste there.
  2704. """
  2705. if not _is_termux_startup_environment():
  2706. return False
  2707. if "-h" in sys.argv[1:] or "--help" in sys.argv[1:]:
  2708. return False
  2709. wants_tui = _wants_tui_early(sys.argv[1:])
  2710. if not wants_tui:
  2711. return False
  2712. first = _first_positional_argv()
  2713. if first not in {None, "chat"}:
  2714. return False
  2715. parser = _light_chat_parser()
  2716. args = parser.parse_args(_coalesce_session_name_args(sys.argv[1:]))
  2717. # Preserve top-level behaviours whose semantics are not "launch chat/TUI".
  2718. if getattr(args, "version", False) or getattr(args, "oneshot", None):
  2719. return False
  2720. if getattr(args, "command", None) not in {None, "chat"}:
  2721. return False
  2722. if not _resolve_use_tui(args):
  2723. return False
  2724. _enable_cpu_profile(args)
  2725. cmd_chat(args)
  2726. return True
  2727. def _advertise_agent_env() -> None:
  2728. """Advertise the agent harness to child processes.
  2729. ``AI_AGENT`` is the cross-agent standard (huggingface_hub reads it); the
  2730. value must be our id in the public agent-harness registry
  2731. (``hermes-agent``) — matching is exact. ``HERMES_AGENT`` is the
  2732. Hermes-specific marker. setdefault: never clobber an outer harness.
  2733. ``AI_AGENT`` is the emerging cross-agent standard (huggingface_hub's agent detection reads it; pi and
  2734. other agents set it — earendil-works/pi#7493) so generic tooling can attribute subprocesses to the
  2735. harness that spawned them. Hermes running inside another agent's terminal).
  2736. """
  2737. os.environ.setdefault("AI_AGENT", "hermes-agent")
  2738. os.environ.setdefault("HERMES_AGENT", "true")
  2739. def _attach_plugin_cli_command(subparsers, cmd_info) -> None:
  2740. """Register one plugin-provided top-level command from its descriptor."""
  2741. plugin_parser = subparsers.add_parser(
  2742. cmd_info["name"],
  2743. help=cmd_info["help"],
  2744. description=cmd_info.get("description", ""),
  2745. formatter_class=__import__("argparse").RawDescriptionHelpFormatter,
  2746. )
  2747. cmd_info["setup_fn"](plugin_parser)
  2748. if cmd_info.get("handler_fn") is not None:
  2749. plugin_parser.set_defaults(func=cmd_info["handler_fn"])
  2750. def _register_plugin_cli_commands(subparsers) -> None:
  2751. """Register plugin-provided top-level commands (each plugin builds its own argparse tree).
  2752. Skipped when the invocation targets a known built-in — eagerly importing
  2753. every bundled plugin module costs 500-650ms.
  2754. """
  2755. if not _plugin_cli_discovery_needed():
  2756. return
  2757. try:
  2758. from plugins.memory import discover_plugin_cli_commands
  2759. from hermes_cli.plugins import discover_plugins, get_plugin_manager
  2760. from hermes_cli.left_core_migration import recover_for_command
  2761. recover_for_command(_first_positional_argv())
  2762. seen_plugin_commands = set()
  2763. for cmd_info in discover_plugin_cli_commands():
  2764. _attach_plugin_cli_command(subparsers, cmd_info)
  2765. seen_plugin_commands.add(cmd_info["name"])
  2766. discover_plugins()
  2767. # The invoked platform may still be a deferred entry; import it so its
  2768. # register_cli_command side effect runs before we read _cli_commands.
  2769. # See #54678.
  2770. _resolve_deferred_platform_cli_command(_first_positional_argv())
  2771. for cmd_info in get_plugin_manager()._cli_commands.values():
  2772. if cmd_info["name"] not in seen_plugin_commands:
  2773. _attach_plugin_cli_command(subparsers, cmd_info)
  2774. except Exception as _exc:
  2775. logging.getLogger(__name__).debug("Plugin CLI discovery failed: %s", _exc)
  2776. def _build_cli_parser():
  2777. """Build the full ``hermes`` argparse tree -> ``(parser, subparsers)``.
  2778. Registration ORDER is the ``hermes --help`` order; keep it stable. Groups
  2779. live in ``hermes_cli/subcommands/<group>.py`` with handlers injected so
  2780. those modules never import main.
  2781. """
  2782. from hermes_cli._parser import build_top_level_parser
  2783. parser, subparsers, chat_parser = build_top_level_parser()
  2784. chat_parser.set_defaults(func=cmd_chat)
  2785. build_model_parser(subparsers, cmd_model=cmd_model)
  2786. build_moa_parser(subparsers)
  2787. build_fallback_parser(subparsers)
  2788. build_worktree_parser(subparsers)
  2789. build_browser_parser(subparsers)
  2790. build_secrets_parser(subparsers)
  2791. # OUTBOUND egress firewall; ``hermes proxy`` (gateway group) is the INBOUND one.
  2792. build_egress_parser(subparsers)
  2793. build_migrate_parser(subparsers)
  2794. build_codex_runtime_parser(subparsers)
  2795. build_gateway_parser(
  2796. subparsers, cmd_gateway=cmd_gateway, cmd_proxy=cmd_proxy, cmd_gateway_enroll=cmd_gateway_enroll
  2797. )
  2798. # LSP is optional — a registration failure must not break the CLI.
  2799. try:
  2800. from agent.lsp.cli import register_subparser as _lsp_register
  2801. _lsp_register(subparsers)
  2802. except Exception as _lsp_err:
  2803. logger.debug("LSP CLI registration failed: %s", _lsp_err)
  2804. build_setup_parser(subparsers, cmd_setup=cmd_setup)
  2805. build_whatsapp_parser(subparsers, cmd_whatsapp=cmd_whatsapp)
  2806. build_whatsapp_cloud_parser(subparsers, cmd_whatsapp_cloud=cmd_whatsapp_cloud)
  2807. build_slack_parser(subparsers, cmd_slack=cmd_slack)
  2808. from hermes_cli.send_cmd import register_send_subparser
  2809. register_send_subparser(subparsers)
  2810. build_login_parser(subparsers, cmd_login=cmd_login)
  2811. build_logout_parser(subparsers, cmd_logout=cmd_logout)
  2812. build_auth_parser(subparsers, cmd_auth=cmd_auth)
  2813. build_status_parser(subparsers, cmd_status=cmd_status)
  2814. build_pause_parser(subparsers)
  2815. build_cron_parser(subparsers, cmd_cron=cmd_cron)
  2816. build_webhook_parser(subparsers, cmd_webhook=cmd_webhook)
  2817. from hermes_cli.subcommands.peer import build_peer_parser
  2818. build_peer_parser(subparsers)
  2819. from hermes_cli.portal_cli import add_parser as _add_portal_parser
  2820. _add_portal_parser(subparsers)
  2821. from hermes_cli.kanban import build_parser as _build_kanban_parser
  2822. _build_kanban_parser(subparsers).set_defaults(func=cmd_kanban)
  2823. from hermes_cli.projects_cmd import build_parser as _build_project_parser
  2824. _build_project_parser(subparsers).set_defaults(func=cmd_project)
  2825. build_hooks_parser(subparsers, cmd_hooks=cmd_hooks)
  2826. build_doctor_parser(subparsers, cmd_doctor=cmd_doctor)
  2827. build_verify_parser(subparsers, cmd_verify=cmd_verify)
  2828. build_security_parser(subparsers, cmd_security=cmd_security)
  2829. build_approvals_parser(subparsers, cmd_approvals=cmd_approvals)
  2830. build_dump_parser(subparsers, cmd_dump=cmd_dump)
  2831. build_debug_parser(subparsers, cmd_debug=cmd_debug)
  2832. build_backup_parser(subparsers, cmd_backup=cmd_backup)
  2833. build_checkpoints_parser(subparsers)
  2834. build_import_cmd_parser(subparsers, cmd_import=cmd_import)
  2835. build_config_parser(subparsers, cmd_config=cmd_config)
  2836. build_skin_parser(subparsers, cmd_skin=cmd_skin)
  2837. build_console_parser(subparsers, cmd_console=cmd_console)
  2838. build_pairing_parser(subparsers, cmd_pairing=cmd_pairing)
  2839. build_skills_parser(subparsers, cmd_skills=cmd_skills)
  2840. build_bundles_parser(subparsers)
  2841. build_plugins_parser(subparsers, cmd_plugins=cmd_plugins)
  2842. _register_plugin_cli_commands(subparsers)
  2843. build_curator_parser(subparsers)
  2844. build_pets_parser(subparsers)
  2845. build_journey_parser(subparsers)
  2846. build_memory_parser(subparsers, cmd_memory=cmd_memory)
  2847. build_tools_parser(subparsers, cmd_tools=cmd_tools)
  2848. build_computer_use_parser(subparsers)
  2849. build_mcp_parser(subparsers, cmd_mcp=cmd_mcp)
  2850. build_connectors_parser(subparsers)
  2851. build_sessions_parser(subparsers, cmd_sessions=cmd_sessions_lazy)
  2852. build_insights_parser(subparsers, cmd_insights=cmd_insights)
  2853. build_usage_parser(subparsers)
  2854. build_monitoring_parser(subparsers, cmd_monitoring=cmd_monitoring)
  2855. build_vault_parser(subparsers)
  2856. build_update_parser(subparsers, cmd_update=cmd_update)
  2857. build_uninstall_parser(subparsers, cmd_uninstall=cmd_uninstall)
  2858. build_acp_parser(subparsers, cmd_acp=cmd_acp)
  2859. build_profile_parser(subparsers, cmd_profile=cmd_profile)
  2860. build_completion_parser(subparsers, cmd_completion=cmd_completion, parser=parser)
  2861. build_dashboard_parser(
  2862. subparsers, cmd_dashboard=cmd_dashboard, cmd_dashboard_register=cmd_dashboard_register)
  2863. build_webapp_parser(subparsers, cmd_webapp=cmd_webapp)
  2864. # "desktop" is canonical (Hermes-Setup.exe tells users to run it, so it
  2865. # must be the name --help shows); "gui" is a deprecated alias.
  2866. build_gui_parser(subparsers, cmd_gui=cmd_gui)
  2867. build_logs_parser(subparsers, cmd_logs=cmd_logs)
  2868. build_prompt_size_parser(subparsers, cmd_prompt_size=cmd_prompt_size)
  2869. return parser, subparsers
  2870. def _parse_cli_args(parser, subparsers, argv):
  2871. """Parse ``argv`` with the bpo-9338 subparser-routing workaround.
  2872. On Python <3.11 argparse fails to route subcommand tokens when the parent
  2873. has nargs='?' optionals (--continue): "unrecognized arguments: model". When
  2874. argv holds a known subcommand token, set subparsers.required=True to force
  2875. routing; if that fails (``hermes -c model`` — 'model' is the session name)
  2876. fall back to the default behaviour.
  2877. """
  2878. import io as _io
  2879. _processed_argv = _coalesce_session_name_args(argv)
  2880. _known_cmds = (
  2881. set(subparsers.choices.keys()) if hasattr(subparsers, "choices") else set()
  2882. )
  2883. _has_cmd_token = any(
  2884. t in _known_cmds for t in _processed_argv if not t.startswith("-")
  2885. )
  2886. if not _has_cmd_token:
  2887. subparsers.required = False
  2888. return parser.parse_args(_processed_argv)
  2889. from contextlib import redirect_stderr, redirect_stdout
  2890. subparsers.required = True
  2891. speculative_stdout = _io.StringIO()
  2892. try:
  2893. with redirect_stderr(_io.StringIO()), redirect_stdout(speculative_stdout):
  2894. args = parser.parse_args(_processed_argv)
  2895. except SystemExit as exc:
  2896. if exc.code == 0:
  2897. print(speculative_stdout.getvalue(), end="")
  2898. raise
  2899. # Discard speculative diagnostics, including structured errors on stdout.
  2900. subparsers.required = False
  2901. return parser.parse_args(_processed_argv)
  2902. print(speculative_stdout.getvalue(), end="")
  2903. return args
  2904. def _default_to_chat(args) -> None:
  2905. """No subcommand given: run chat."""
  2906. _promote_top_level_resume(args)
  2907. _set_chat_arg_defaults(args)
  2908. cmd_chat(args)
  2909. def main():
  2910. """Main entry point for hermes CLI."""
  2911. _set_process_title()
  2912. _warn_if_unsupervised_pid1()
  2913. _advertise_agent_env()
  2914. # Force UTF-8 stdio on Windows before anything prints. No-op elsewhere.
  2915. try:
  2916. from hermes_cli.stdio import configure_windows_stdio
  2917. configure_windows_stdio()
  2918. except Exception:
  2919. pass
  2920. # A non-UTF-8 locale that the package import had to repair would crash Python children the
  2921. # same way. Only on that host, so a healthy UTF-8 locale keeps its children untouched.
  2922. from hermes_cli import _stdio_repaired
  2923. if _stdio_repaired:
  2924. os.environ.setdefault("PYTHONUTF8", "1")
  2925. os.environ.setdefault("PYTHONIOENCODING", "utf-8")
  2926. # One TLS authority: trust the OS store before any outbound call resolves a
  2927. # CA bundle (agent/ssl_verify.py). Never raises; False just means OpenSSL's paths.
  2928. from agent.ssl_verify import install_truststore
  2929. install_truststore()
  2930. # Sweep stale ``hermes.exe.old.*`` quarantine files from previous Windows
  2931. # updates. No-op elsewhere.
  2932. try:
  2933. _cleanup_quarantined_exes()
  2934. except Exception:
  2935. pass
  2936. # Checkout changed since last launch → sweep stale __pycache__ once so no
  2937. # process resolves fresh source against old bytecode. Never raises.
  2938. _sweep_stale_bytecode_if_checkout_changed()
  2939. _recover_update_debts_on_startup() # owed fleet restarts, gateways a killed update paused
  2940. if _first_positional_argv() != "update":
  2941. from hermes_cli.boot_bootstrap import maybe_run_boot_bootstrap
  2942. from pm.paths import install_root
  2943. maybe_run_boot_bootstrap(install_root())
  2944. # Every dispatch, including fast chat/serve, gets one passive PM verdict.
  2945. try:
  2946. from hermes_cli.venv_sync import check_runtime
  2947. from pm.paths import install_root
  2948. problem = check_runtime(install_root())
  2949. if problem:
  2950. print(f"⚠ {problem}", file=sys.stderr)
  2951. except Exception:
  2952. import logging
  2953. logging.getLogger(__name__).debug("pm startup check failed", exc_info=True)
  2954. if _try_termux_fast_tui_launch():
  2955. return
  2956. if _try_termux_fast_cli_launch():
  2957. return
  2958. if _try_fast_serve_launch():
  2959. return
  2960. if _try_fast_chat_launch():
  2961. return
  2962. parser, subparsers = _build_cli_parser()
  2963. # NixOS container mode routes ALL invocations into the managed container.
  2964. # MUST run before parse_args() so --help, unrecognised flags and every
  2965. # subcommand are forwarded instead of intercepted by argparse on the host.
  2966. from hermes_cli.config import get_container_exec_info
  2967. container_info = get_container_exec_info()
  2968. if container_info:
  2969. from hermes_cli.main_container import exec_in_container
  2970. exec_in_container(container_info, sys.argv[1:])
  2971. sys.exit(1) # unreachable: execvp replaces the process or raises
  2972. args = _parse_cli_args(parser, subparsers, sys.argv[1:])
  2973. _enable_cpu_profile(args)
  2974. if args.version:
  2975. cmd_version(args)
  2976. return
  2977. # --yolo must be set *before* plugin discovery: tools.approval freezes
  2978. # _YOLO_MODE_FROZEN at import; set later (inside cmd_chat) it does nothing.
  2979. if getattr(args, "yolo", False):
  2980. os.environ["HERMES_YOLO_MODE"] = "1"
  2981. # Plugin discovery + shell hooks once, gated so introspection commands
  2982. # (hooks list, cron list, gateway status, ...) pay no discovery cost and
  2983. # trigger no consent prompts for hooks the user is still inspecting.
  2984. _prepare_agent_startup(args)
  2985. if getattr(args, "oneshot", None):
  2986. _run_oneshot_from_args(args)
  2987. from hermes_cli.observability.shared_metrics_disabled import set_process_surface
  2988. set_process_surface(args.command)
  2989. # No subcommand (optionally with top-level --resume / --continue) → chat.
  2990. if args.command is None:
  2991. _default_to_chat(args)
  2992. return
  2993. # A handler's int return code becomes the exit code (None = success).
  2994. if hasattr(args, "func"):
  2995. rc = args.func(args)
  2996. if isinstance(rc, int) and rc != 0:
  2997. sys.exit(rc)
  2998. else:
  2999. parser.print_help()
  3000. if __name__ == "__main__":
  3001. main()