cli_single_query.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. """Single-query (``-q`` / one-shot) helpers: kanban goal loops, exit-code mapping, quiet single-query runner, image routing, signal handlers and the single-query mode orchestrator.
  2. Split out of ``cli.py``; ``cli`` re-exports every public name and moved bodies late-bind
  3. cli-level names through ``from cli import ...`` at call time so facade monkeypatch seams hold.
  4. """
  5. from __future__ import annotations
  6. from typing import TYPE_CHECKING
  7. import logging
  8. import os
  9. import sys
  10. import time
  11. from agent.i18n import t
  12. from agent.interrupt_compat import request_hard_interrupt
  13. from contextlib import suppress
  14. from pathlib import Path
  15. from typing import Any
  16. # Log-record parity with the origin module.
  17. logger = logging.getLogger("cli")
  18. if TYPE_CHECKING:
  19. from cli import HermesCLI
  20. def _int_or(value, default: int) -> int:
  21. """``int(value)``, or ``default`` when it does not parse."""
  22. try:
  23. return int(value)
  24. except (TypeError, ValueError):
  25. return default
  26. def _interrupt_agent_for_signal(agent, signum) -> None:
  27. """Hard-interrupt ``agent`` for a shutdown signal, then sleep ``HERMES_SIGTERM_GRACE`` (1.5 s).
  28. The grace lets the agent thread kill the tool's setsid subprocess group before the
  29. main thread unwinds (else an orphan child). Never raises.
  30. """
  31. from cli import _float_env
  32. try:
  33. if agent is not None:
  34. request_hard_interrupt(agent, f"received signal {signum}")
  35. _grace = _float_env("HERMES_SIGTERM_GRACE", 1.5)
  36. if _grace > 0:
  37. time.sleep(_grace)
  38. except Exception:
  39. pass # never block signal handling
  40. def _run_kanban_goal_loop_q(cli: HermesCLI, first_response: str, run_turn=None, log=None) -> None:
  41. """Drive a kanban goal_mode worker through ``goals.run_kanban_goal_loop`` after its first turn.
  42. ``run_turn`` defaults to the bare ``-Q`` turn (final answer only). The ``-q`` worker path
  43. passes ``cli.chat`` so every follow-up turn keeps the tool activity feed that the Kanban
  44. worker log is made of. The caller swallows all errors: a broken loop must never wedge a worker.
  45. """
  46. from cli import _int_or, _sync_cli_session_id_from_agent
  47. task_id = (os.environ.get("HERMES_KANBAN_TASK") or "").strip()
  48. if not task_id:
  49. return
  50. raw_run_id = (os.environ.get("HERMES_KANBAN_RUN_ID") or "").strip()
  51. worker_run_id = _int_or(raw_run_id, None) if raw_run_id else None
  52. if raw_run_id and worker_run_id is None:
  53. logger.warning("invalid HERMES_KANBAN_RUN_ID=%r", raw_run_id)
  54. from hermes_cli import kanban_db as _kb
  55. from hermes_cli import kanban_db_connect as _kbc
  56. from hermes_cli.goals import run_kanban_goal_loop as _run_loop, DEFAULT_MAX_TURNS as _DEF_TURNS
  57. # Goal text = title + body (the acceptance criteria the judge evaluates against).
  58. with _kbc.connect_closing() as conn:
  59. task = _kb.get_task(conn, task_id)
  60. if task is None:
  61. return
  62. goal_text = "\n\n".join(p for p in (task.title or "", task.body) if p).strip()
  63. if not goal_text:
  64. return
  65. def _quiet_turn(prompt: str) -> dict:
  66. result = cli.agent.run_conversation(user_message=prompt, conversation_history=cli.conversation_history)
  67. _sync_cli_session_id_from_agent(cli)
  68. resp = result.get("final_response", "") if isinstance(result, dict) else str(result)
  69. if resp:
  70. print(resp)
  71. # Carry failed/failure_reason so run_kanban_goal_loop can stop on a failed
  72. # worker turn instead of grinding out empty continuation turns (#91264).
  73. return {
  74. "response": resp or "",
  75. "failed": result.get("failed", False) if isinstance(result, dict) else False,
  76. "failure_reason": result.get("failure_reason") if isinstance(result, dict) else None,
  77. }
  78. def _task_status() -> str | None:
  79. with _kbc.connect_closing() as c:
  80. return _kb.goal_run_status(c, task_id, worker_run_id)
  81. def _block(reason: str) -> None:
  82. with _kbc.connect_closing() as c:
  83. _kb.block_task(c, task_id, reason=reason, expected_run_id=worker_run_id)
  84. _run_loop(
  85. task_id=task_id, goal_text=goal_text, run_turn=run_turn or _quiet_turn,
  86. task_status_fn=_task_status, block_fn=_block,
  87. max_turns=task.goal_max_turns or _DEF_TURNS, first_response=first_response or "",
  88. log=log or (lambda m: logger.info("%s", m)),
  89. )
  90. def _run_kanban_goal_loop_chat(cli: HermesCLI, first_response: str) -> None:
  91. """``-q`` worker variant: follow-up turns go through ``cli.chat`` (tool feed stays on stdout,
  92. which is the Kanban worker log) and judge verdicts are printed there too, so a goal_mode card's
  93. log reads like any other worker's instead of staying blank until the final answer."""
  94. from cli import _run_kanban_goal_loop_q
  95. def _log(msg: str) -> None:
  96. logger.info("%s", msg)
  97. print(msg, flush=True)
  98. _run_kanban_goal_loop_q(cli, first_response, run_turn=lambda p: cli.chat(p) or "", log=_log)
  99. def _sync_cli_session_id_from_agent(cli) -> None:
  100. """Keep ``cli.session_id`` in sync when mid-run compression rotated the agent's session."""
  101. if getattr(cli.agent, "session_id", None) and cli.agent.session_id != cli.session_id:
  102. cli.session_id = cli.agent.session_id
  103. # ``failure_reason`` values that say nothing about the task itself: the provider is walled,
  104. # down or unreachable, or the account is out of credit, so a Kanban worker signals "try
  105. # later" instead of "I failed" and the dispatcher does not spend the task's retry budget on it.
  106. from hermes_cli.turn_exit import TRANSIENT_PROVIDER_REASONS as _TRANSIENT_PROVIDER_REASONS
  107. # ``failure_reason`` values a retry can never heal: the credential was rejected, the model does
  108. # not exist for this account, or the TLS chain is broken. A Kanban worker exits
  109. # ``KANBAN_TERMINAL_PROVIDER_EXIT_CODE`` so the dispatcher parks the card after ONE spawn with
  110. # the provider's words as the reason, instead of re-spawning into the same wall until
  111. # ``kanban.failure_limit`` is spent. ``billing`` stays transient: credit comes back.
  112. # ``upstream_blocked`` (a WAF/CDN refusing the SDK's User-Agent) is terminal too: only a
  113. # header change heals it, never a retry.
  114. from hermes_cli.turn_exit import TERMINAL_PROVIDER_REASONS as _TERMINAL_PROVIDER_REASONS
  115. def _single_query_exit_code(result, *, credentials_rate_limited: bool = False,
  116. credentials_terminal: bool = False) -> int:
  117. """Map a one-shot turn result onto a process exit code, for both `-q` and `-Q`.
  118. 0 only when the turn completed; 130 when it was interrupted; 1 when it failed, stopped
  119. partway (`partial`, `completed: False`) or never ran at all (credentials / agent init
  120. failed, so ``result`` is not a dict). A Kanban worker (``HERMES_KANBAN_TASK`` set) that
  121. failed purely on a provider rate-limit / billing wall exits ``KANBAN_RATE_LIMIT_EXIT_CODE``
  122. (EX_TEMPFAIL): the dispatcher books that run ``rate_limited`` and requeues the task
  123. WITHOUT counting a failure, so a quota window or a provider outage cannot trip the breaker.
  124. The same sentinel applies when credential resolution itself is a quota/rate-limit
  125. AuthError (no turn result object is produced). One that failed on a terminal provider
  126. error (credential revoked, model gone) exits ``KANBAN_TERMINAL_PROVIDER_EXIT_CODE``
  127. (EX_CONFIG): the dispatcher blocks the card at once. The same code applies
  128. before a turn when credential resolution explicitly requires re-authentication;
  129. unknown startup failures retain exit 1.
  130. The worker predicate is the STRIPPED ``kanban_task_id()`` (from
  131. ``agent.kanban_turn_recovery``) so a whitespace-only value is not a worker here
  132. either — the exit mapping and the recovery gate must agree on what a worker is.
  133. """
  134. # Late-bound through the ``cli`` facade so a patched ``cli._*_PROVIDER_REASONS`` holds.
  135. from cli import _TERMINAL_PROVIDER_REASONS as terminal_reasons
  136. from cli import _TRANSIENT_PROVIDER_REASONS as transient_reasons
  137. from agent.kanban_turn_recovery import kanban_task_id
  138. from hermes_cli.turn_exit import turn_exit_code
  139. return turn_exit_code(
  140. result, kanban_worker=kanban_task_id() is not None,
  141. credentials_rate_limited=credentials_rate_limited,
  142. credentials_terminal=credentials_terminal,
  143. transient_reasons=transient_reasons,
  144. terminal_reasons=terminal_reasons,
  145. )
  146. def _run_quiet_single_query(cli, effective_query, emitter=None):
  147. """Quiet (-Q) one-shot turn: run, print the response (stderr for errors/session_id), then sys.exit with the automation exit code.
  148. With a ``StreamJsonEmitter`` the final answer and the exit line become the terminal ``result`` JSONL record instead.
  149. HERMES_TURN_AUTHOR (set only by a bot-to-bot dispatcher) is consumed here so tool subprocesses do not inherit it.
  150. Nested Bot Mode notifies bind this session's key (not the dispatcher's) and resume in-process
  151. before stdout is printed, so a teammate reply is the quiet run's final answer rather than a
  152. stranded receipt."""
  153. from cli import _emit_interrupted_session_end, _run_kanban_goal_loop_q, _single_query_exit_code, _sync_cli_session_id_from_agent
  154. from agent.interrupt_compat import _accepts_keyword
  155. from agent.turn_author import take_turn_author_from_env
  156. from hermes_cli.quiet_single_query import (
  157. bind_quiet_session_key, continue_quiet_notify_completions, exit_single_query, quiet_notify_linger_seconds, take_turn_report_path, write_turn_report,
  158. )
  159. author = take_turn_author_from_env()
  160. # A spawner that bounds only the turn (cron Bot Chat lane) learns the outcome from this
  161. # report, written before the linger below; popped so tool subprocesses do not inherit it.
  162. turn_report_path = take_turn_report_path()
  163. author_kwargs = {"turn_author": author} if author is not None and _accepts_keyword(cli.agent.run_conversation, "turn_author") else {}
  164. with bind_quiet_session_key(getattr(cli, "session_id", "") or "default"):
  165. try:
  166. result = cli.agent.run_conversation(
  167. user_message=effective_query, conversation_history=cli.conversation_history, **author_kwargs,
  168. )
  169. except KeyboardInterrupt:
  170. _emit_interrupted_session_end(cli, reason="keyboard_interrupt")
  171. if emitter is not None:
  172. exit_single_query(emitter.emit_result({"failed": True, "error": "Interrupted"}, session_id=cli.session_id or "", exit_code=130))
  173. print(f"\nsession_id: {cli.session_id}", file=sys.stderr)
  174. exit_single_query(130)
  175. # The exit line below reports session_id to stderr for automation wrappers;
  176. # without this sync it would point at the ended parent after compression.
  177. _sync_cli_session_id_from_agent(cli)
  178. # Kanban worker: a turn that died on a retryable provider failure is retried
  179. # IN PLACE (same session, context preserved) instead of ending the run silently.
  180. # Authority (typed retryable failure, no interrupt / terminal settlement) and the
  181. # live run/claim proof live in agent/kanban_turn_recovery.py. Runs BEFORE the turn
  182. # report so everything downstream — report, follow-ups, response, goal gate, exit —
  183. # sees the post-recovery disposition.
  184. from agent.kanban_turn_recovery import recover_failed_kanban_turns as _recover_turns
  185. def _quiet_recover_turn(nudge):
  186. nonlocal result
  187. _history = result.get("messages") if isinstance(result, dict) else None
  188. result = cli.agent.run_conversation(
  189. user_message=nudge,
  190. conversation_history=_history or cli.conversation_history,
  191. **author_kwargs,
  192. )
  193. _sync_cli_session_id_from_agent(cli)
  194. _recover_turns(
  195. _quiet_recover_turn,
  196. lambda: result,
  197. emit=lambda msg: print(msg, file=sys.stderr, flush=True),
  198. )
  199. # The turn is over and persisted: the one-shot exit linger that follows protects nested
  200. # notify_on_complete replies and is NOT part of the spawner's delivery (#113608). The
  201. # report carries what this run will print, so a spawner booking a child still lingering
  202. # at its cap relays the answer instead of a timeout (#114980).
  203. def _report_turn(res) -> None:
  204. write_turn_report(
  205. turn_report_path, exit_code=_single_query_exit_code(res),
  206. error=str(res.get("error") or "") if isinstance(res, dict) else "agent turn did not run",
  207. reply=res.get("final_response", "") if isinstance(res, dict) else str(res),
  208. )
  209. _report_turn(result)
  210. if isinstance(result, dict) and not result.get("failed"):
  211. history = result.get("messages") or cli.conversation_history
  212. def _follow_up(text):
  213. nonlocal history
  214. follow = cli.agent.run_conversation(
  215. user_message=text, conversation_history=history, **author_kwargs,
  216. )
  217. if isinstance(follow, dict) and follow.get("messages"):
  218. history = follow["messages"]
  219. # Same sync contract as the main turn: a compression rotation during a
  220. # follow-up must not leave a stale id on the exit line / drain key.
  221. _sync_cli_session_id_from_agent(cli)
  222. return follow
  223. # One shared linger budget for the whole run: the loop below and the later
  224. # _wait_for_oneshot_background_completions pass must not each wait the full
  225. # oneshot_completion_wait_seconds on the same stuck notify_on_complete child.
  226. # Flagged after the loop (finally-equivalent): the wait is the loop's first
  227. # statement, so anything raising past that point has consumed budget the
  228. # finalize pass must not re-wait.
  229. try:
  230. continued = continue_quiet_notify_completions(
  231. getattr(cli, "session_id", "") or "",
  232. _follow_up,
  233. owns_event=getattr(cli, "_owns_process_notification", None),
  234. linger_budget=quiet_notify_linger_seconds(),
  235. )
  236. finally:
  237. cli._quiet_notify_linger_done = True
  238. if isinstance(continued, dict):
  239. result = continued
  240. # A teammate's reply displaced the answer this run prints; tell the spawner.
  241. _report_turn(result)
  242. response = result.get("final_response", "") if isinstance(result, dict) else str(result)
  243. # Surface backend errors that produced no visible output (e.g. invalid model slug
  244. # -> provider 4xx) on stderr so piped stdout stays clean.
  245. if emitter is not None:
  246. pass # the result record below carries text/error; nothing else may touch stdout
  247. elif (
  248. not response and isinstance(result, dict) and result.get("error")
  249. and (result.get("failed") or result.get("partial"))
  250. ):
  251. print(t("gateway.model.error_prefix", error=result["error"]), file=sys.stderr)
  252. elif response:
  253. print(response)
  254. # ONE exit-code decision point for this driver, shared with the non-quiet one-shot
  255. # path via _single_query_exit_code: a quota/billing wall keeps the EX_TEMPFAIL
  256. # sentinel so the dispatcher releases the task without counting a failure, and any
  257. # other unfinished worker turn exits non-zero instead of ending as a silent rc=0
  258. # that reads as a protocol violation. Computed BEFORE goal continuation — the
  259. # post-recovery disposition must be authoritative for the rest of the driver.
  260. _exit_code = _single_query_exit_code(result)
  261. # Kanban goal_mode: keep working in THIS session until a judge agrees the card is
  262. # done, the worker terminates it, or the turn budget runs out (sticky block).
  263. # ONLY a settled, authorized turn may continue: a result that remains
  264. # failed/unfinished — recovery exhausted or DENIED (lease expired, claim lost,
  265. # quota wall, interrupt, terminal settlement) — must reach the shared exit path
  266. # below without goal continuation. goal_run_status() checks only run identity,
  267. # not the claim lock or either expiry, so an unreaped expired-lease row still
  268. # reports "running" and a continue verdict would re-enter the model under an
  269. # authority this process can no longer prove (round-3 finding).
  270. if os.environ.get("HERMES_KANBAN_GOAL_MODE") == "1" and _exit_code == 0:
  271. try:
  272. _run_kanban_goal_loop_q(cli, response)
  273. except Exception as _goal_exc:
  274. logger.debug("kanban goal loop failed: %s", _goal_exc)
  275. if emitter is None:
  276. print(f"\nsession_id: {cli.session_id}", file=sys.stderr)
  277. if emitter is not None:
  278. _exit_code = emitter.emit_result(result, session_id=cli.session_id or "", exit_code=_exit_code)
  279. exit_single_query(_exit_code)
  280. def _route_single_query_images(cli, query, effective_query, single_query_images, single_query_image_urls):
  281. """Attach one-shot images natively when the model supports vision, else pre-describe them as text."""
  282. if not (single_query_images or single_query_image_urls):
  283. return effective_query
  284. # Same image-routing decision as the interactive path: a vision-capable model
  285. # (incl. custom-provider models declaring `model.supports_vision: true`) gets
  286. # native image_url parts; otherwise the text pipeline (vision_analyze
  287. # pre-description).
  288. _img_mode = "text"
  289. _build_parts = None
  290. try:
  291. from agent.image_routing import build_native_content_parts as _build_parts
  292. from agent.image_routing import decide_image_input_mode
  293. from hermes_cli.config import load_config
  294. _img_mode = decide_image_input_mode(
  295. (cli.provider or "").strip(), (cli.model or "").strip(), load_config(),
  296. requested_provider=(cli.requested_provider or "").strip(),
  297. )
  298. except Exception:
  299. _img_mode = "text"
  300. def _text_fallback():
  301. # ``_preprocess_images_with_vision`` only knows local files; when only URLs
  302. # were supplied keep the original query text intact.
  303. if single_query_images:
  304. return cli._preprocess_images_with_vision(query, single_query_images, announce=False)
  305. return effective_query
  306. if _img_mode != "native" or _build_parts is None:
  307. return _text_fallback()
  308. try:
  309. _parts, _skipped = _build_parts(
  310. query if isinstance(query, str) else "",
  311. [str(p) for p in single_query_images],
  312. image_urls=list(single_query_image_urls) or None,
  313. )
  314. if any(p.get("type") == "image_url" for p in _parts):
  315. return _parts
  316. return _text_fallback() # all images unreadable
  317. except Exception:
  318. return _text_fallback()
  319. def _collect_kanban_task_images(single_query_images):
  320. """Kanban workers: image paths/URLs in the task body join the first turn's attachments."""
  321. single_query_image_urls: list[str] = []
  322. _kanban_task_id = os.environ.get("HERMES_KANBAN_TASK", "").strip()
  323. if not _kanban_task_id:
  324. return single_query_image_urls
  325. try:
  326. from hermes_cli import kanban_db as _kb
  327. from hermes_cli import kanban_db_connect as _kbc
  328. from agent.image_routing import extract_image_refs as _extract_refs
  329. with _kbc.connect_closing() as _conn:
  330. _task = _kb.get_task(_conn, _kanban_task_id)
  331. _body = getattr(_task, "body", "") if _task is not None else ""
  332. if _body:
  333. _kb_paths, _kb_urls = _extract_refs(_body)
  334. # Dedupe against any --image the user already passed.
  335. _seen = {str(p) for p in single_query_images}
  336. for _p in _kb_paths:
  337. if _p not in _seen:
  338. _seen.add(_p)
  339. single_query_images.append(Path(_p))
  340. single_query_image_urls.extend(_kb_urls)
  341. except Exception as _exc:
  342. # Best-effort enrichment; never block worker startup on it.
  343. logger.debug("kanban image-ref extraction failed: %s", _exc)
  344. return single_query_image_urls
  345. def _install_single_query_signal_handlers(cli):
  346. """Route SIGINT/SIGTERM/SIGHUP through agent.interrupt() before unwinding; kanban workers hard-exit.
  347. A plain KeyboardInterrupt only unwinds the main thread, so tool worker threads
  348. would orphan the setsid child; the interrupt + grace window lets them kill it.
  349. """
  350. from cli import _arm_exit_watchdog_on_shutdown_signal, _flush_logging_and_stdio, _flush_one_shot_session_store, _interrupt_agent_for_signal
  351. import signal as _signal
  352. def _kill_foreground_and_exit(*_):
  353. # The worker's command runs in its own process group: SIGKILL it or it outlives os._exit.
  354. with suppress(Exception):
  355. from tools.environments.base import kill_live_foreground_processes
  356. kill_live_foreground_processes(now=True)
  357. os._exit(0)
  358. def _signal_handler_q(signum, frame):
  359. logger.debug("Received signal %s in single-query mode", signum)
  360. _arm_exit_watchdog_on_shutdown_signal() # covers wedges in the unwind below
  361. _interrupt_agent_for_signal(getattr(cli, "agent", None), signum)
  362. # Kanban: a non-daemon worker blocked in _wait_for_process survives KeyboardInterrupt
  363. # and the dispatcher sees 'running' forever, so os._exit(0) (SIGALRM deadman guards
  364. # a blocking flush). That skips atexit + the token-drain hook, hence the explicit flush.
  365. # Kanban worker exit path (#28181): SIGTERM hits a dispatcher-spawned worker that's likely in a
  366. # non-daemon thread waiting on a child subprocess in _wait_for_process. Raising KeyboardInterrupt
  367. # only unwinds the main thread; the worker thread keeps running, the process gets reparented to
  368. # init, and the dispatcher's _pid_alive check returns True forever — task stuck in 'running'
  369. # indefinitely. Skip the controlled-unwind dance and call os._exit(0) so the kernel reclaims the PID
  370. # immediately and detect_crashed_workers can reclaim the stale claim on the next tick. Flush logging
  371. # + stdout/stderr first so the final debug trace isn't lost; SIGALRM deadman guards the flush
  372. # against any rare blocking-I/O case (the reporter measured flush in <1ms; the alarm is a failsafe,
  373. # not the common path).
  374. if os.environ.get("HERMES_KANBAN_TASK"):
  375. with suppress(Exception):
  376. if hasattr(_signal, "SIGALRM"):
  377. _signal.signal(_signal.SIGALRM, _kill_foreground_and_exit)
  378. _signal.alarm(5)
  379. with suppress(Exception):
  380. # Durable flush FIRST: memory-provider shutdown inside _run_cleanup can issue aux-LLM calls,
  381. # and nothing after it may fail in a way that loses the turn (#88583).
  382. # os._exit(0) skips atexit AND SessionDB's token-drain hook, so flush + finalize the session
  383. # store here or the worker's turn (and its usage deltas) never become durable (#88583 /
  384. # #50881 class). Best-effort under the SIGALRM deadman above.
  385. _flush_one_shot_session_store(cli)
  386. # The one-shot exit's shared_metrics shutdown_runtimes is skipped too: bounded inside the deadman.
  387. from hermes_cli.observability.shared_metrics_process import flush_before_hard_exit
  388. flush_before_hard_exit()
  389. _flush_logging_and_stdio()
  390. _kill_foreground_and_exit()
  391. raise KeyboardInterrupt()
  392. with suppress(Exception): # restricted environments
  393. for _name in ("SIGINT", "SIGTERM", "SIGHUP"):
  394. if hasattr(_signal, _name):
  395. _signal.signal(getattr(_signal, _name), _signal_handler_q)
  396. def _configure_quiet_agent(agent) -> None:
  397. """Neutralize every stdout-writing callback so -Q stdout carries only the final response."""
  398. agent.quiet_mode = True
  399. agent.suppress_status_output = True
  400. agent.stream_delta_callback = None
  401. agent.tool_gen_callback = None
  402. agent.reasoning_callback = None
  403. # The diff/progress callbacks print directly and are gated by neither quiet_mode nor
  404. # tool_progress_mode, so they must go too; "off" also covers the executor's direct prints.
  405. agent.tool_progress_callback = None
  406. agent.tool_start_callback = None
  407. agent.tool_complete_callback = None
  408. agent.tool_progress_mode = "off"
  409. def _run_single_query_mode(cli, query, image, quiet, oneshot, stream_json: bool = False):
  410. """``-q``/``--image`` entry: seed an interactive session on a TTY, else run the one-shot turn and exit.
  411. ``stream_json`` (implies quiet) swaps the plain-text final answer for the JSONL event protocol."""
  412. from cli import _SeededQueryMessage, _collect_kanban_task_images, _collect_query_images, _configure_quiet_agent, _finalize_single_query, _route_single_query_images, _run_kanban_goal_loop_chat, _run_quiet_single_query, _should_seed_interactive, _single_query_exit_code
  413. if _should_seed_interactive(query, image, quiet, oneshot):
  414. seeded_query, seeded_images = _collect_query_images(query, image)
  415. logger.info(
  416. "Seeding interactive session with -q prompt (%d chars, %d images)",
  417. len(seeded_query or ""), len(seeded_images),
  418. )
  419. cli._seeded_first_message = _SeededQueryMessage(seeded_query, seeded_images)
  420. return cli.run()
  421. cli._single_query_mode = True # agent waits the full MCP cold-start before its only tool snapshot
  422. # No PluginManager._cli_ref (#67597): the turn's plugin tools run in the gateway, and this process
  423. # loads no plugins (PLG-7).
  424. # No user can answer approval prompts: the approval gate takes the deterministic path.
  425. # One-shot mode: no between-turns MCP late-binding refresh, so the agent must wait the full MCP
  426. # cold-start bound before its first (and only) tool snapshot. See #51316.
  427. # Mark single-query for the approval gate. cli.py sets HERMES_INTERACTIVE earlier for interactive sudo
  428. # prompts, but a -q run has NO user waiting to answer approval prompts. The gate reads this marker (via
  429. # gateway.session_context.get_session_env, which falls back to os.environ when the session-context layer
  430. # isn't engaged) and takes the deterministic approvals.single_query_mode path instead of waiting the
  431. # full timeout. See #86878.
  432. os.environ["HERMES_SINGLE_QUERY_SESSION"] = "1"
  433. from hermes_cli.quiet_single_query import exit_single_query
  434. if os.environ.get("HERMES_KANBAN_TASK"):
  435. from tools.kanban_tools import register_current_worker_from_env
  436. if not register_current_worker_from_env():
  437. # No exit trailer: the task log now belongs to the run that replaced this one.
  438. print(t("cli.single_query.kanban_run_reclaimed"), file=sys.stderr)
  439. sys.exit(0)
  440. if not cli._claim_active_session("cli", stderr=bool(quiet)):
  441. exit_single_query(1)
  442. try:
  443. query, single_query_images = _collect_query_images(query, image)
  444. single_query_image_urls = _collect_kanban_task_images(single_query_images)
  445. from hermes_cli.observability.shared_metrics_startup import record_cli_one_shot_ready
  446. record_cli_one_shot_ready()
  447. if quiet:
  448. # Quiet mode: suppress banner, spinner, tool previews.
  449. cli.tool_progress_mode = "off"
  450. emitter = None
  451. if stream_json:
  452. # Built BEFORE credentials/agent init so a failed start still closes the protocol
  453. # (init + result) instead of exiting 1 with an empty stdout.
  454. from hermes_cli.stream_json import StreamJsonEmitter
  455. emitter = StreamJsonEmitter(model=getattr(cli, "model", "") or "", session_id=cli.session_id or "")
  456. if cli._ensure_runtime_credentials():
  457. effective_query: Any = _route_single_query_images(
  458. cli, query, query, single_query_images, single_query_image_urls
  459. )
  460. turn_route = cli._resolve_turn_agent_config(effective_query)
  461. if turn_route["signature"] != cli._active_agent_route_signature:
  462. cli.agent = None
  463. if cli._init_agent(
  464. model_override=turn_route["model"],
  465. runtime_override=turn_route["runtime"],
  466. request_overrides=turn_route.get("request_overrides"),
  467. ):
  468. _configure_quiet_agent(cli.agent)
  469. if emitter is not None:
  470. emitter.attach(cli.agent)
  471. _run_quiet_single_query(cli, effective_query, emitter=emitter)
  472. fail_code = _single_query_exit_code(
  473. None, credentials_rate_limited=getattr(cli, "_credentials_rate_limited", False),
  474. credentials_terminal=getattr(cli, "_credentials_terminal", False))
  475. if emitter is not None:
  476. emitter.emit_result({"failed": True, "error": "credentials or agent init failed"},
  477. session_id=cli.session_id or "", exit_code=fail_code)
  478. exit_single_query(fail_code) # credentials or agent init failed
  479. # No welcome banner (~420 ms cold); session id / resume hint come from _print_exit_summary().
  480. _query_label = query or ("[image attached]" if single_query_images else "")
  481. if _query_label:
  482. cli.console.print(f"[bold blue]{t('cli.single_query.query_label')}[/] {_query_label}")
  483. cli._show_security_advisories()
  484. # Same author contract as `-Q`: a spawner that sets HERMES_TURN_AUTHOR names who wrote this run's
  485. # prompts. Consumed before the first turn so tool subprocesses never inherit it; every turn of
  486. # the run (recovery and goal follow-ups included) carries it to memory providers.
  487. from agent.turn_author import take_turn_author_from_env
  488. cli._single_query_turn_author = take_turn_author_from_env()
  489. response = cli.chat(query, images=single_query_images or None)
  490. # Kanban worker: a failed-silently turn used to end the run as rc=0 with no
  491. # terminal kanban call, so the dispatcher booked a protocol violation and
  492. # cold-restarted the task from scratch. Retry the authorised turn IN PLACE
  493. # (see agent/kanban_turn_recovery.py) and CARRY THE RECOVERED RESPONSE: the
  494. # goal judge below must evaluate the deliverable of the latest settled turn,
  495. # never the stale provider error of the turn recovery replaced (re-review P2).
  496. from agent.kanban_turn_recovery import recover_failed_kanban_turns
  497. def _nonquiet_recover_turn(nudge):
  498. nonlocal response
  499. response = cli.chat(nudge)
  500. return response
  501. recover_failed_kanban_turns(
  502. _nonquiet_recover_turn,
  503. lambda: getattr(cli, "_last_turn_result", None),
  504. emit=lambda msg: print(msg, file=sys.stderr, flush=True),
  505. )
  506. # Kanban goal_mode on the `-q` path: same judge loop as `-Q`, but each follow-up turn
  507. # runs through cli.chat so the worker log keeps its live tool feed (the dispatcher
  508. # used to force -Q here, which left goal_mode cards with a blank Worker log).
  509. # Gated on the post-recovery disposition exactly like the `-Q` block: a result that
  510. # remains failed/unfinished — recovery exhausted or DENIED (claim lost, quota wall,
  511. # interrupt, terminal settlement) — must reach the shared exit path below with zero
  512. # further model entry, because goal_run_status() checks run identity only and would
  513. # otherwise continue under an authority this process can no longer prove.
  514. if os.environ.get("HERMES_KANBAN_GOAL_MODE") == "1" and _single_query_exit_code(cli._last_turn_result) == 0:
  515. try:
  516. _run_kanban_goal_loop_chat(cli, response or "")
  517. except Exception as _goal_exc:
  518. logger.debug("kanban goal loop failed: %s", _goal_exc)
  519. cli._print_exit_summary(clear_screen=False)
  520. # Same exit contract as `-Q`: scripts and the Kanban dispatcher read the outcome from
  521. # the exit code. This path used to fall through to an implicit 0 for every outcome.
  522. exit_single_query(_single_query_exit_code(
  523. cli._last_turn_result,
  524. credentials_rate_limited=getattr(cli, "_credentials_rate_limited", False),
  525. credentials_terminal=getattr(cli, "_credentials_terminal", False)))
  526. finally:
  527. _finalize_single_query(cli)