cli_process_dock.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. """Background-process rows for the classic CLI live-work dock.
  2. Sibling of ``cli_subagent_monitor``: the dock paints one "Processes" block under the
  3. subagent rows from the same snapshot the ``process_manage`` tool reads, so a
  4. ``terminal(background=true)`` spawn is visible the moment it starts instead of only
  5. when its completion notification lands.
  6. """
  7. from __future__ import annotations
  8. import time
  9. from agent.i18n import t
  10. # A finished process stays on the dock long enough to read its exit line, then
  11. # leaves; the completion notification in the transcript is the durable record.
  12. RETAIN_SECONDS = 60
  13. # Reader-thread exits report "exited"; `kill_process` / `kill_all` stamp "killed".
  14. _STATUS_BY_REASON = {"killed": "killed", "lost": "lost", "failed_start": "failed"}
  15. def _last_output_line(buffer: str) -> str:
  16. for line in reversed((buffer or "").splitlines()):
  17. text = " ".join(line.split())
  18. if text:
  19. return text
  20. return ""
  21. def process_status(entry: dict) -> str:
  22. if entry.get("status") != "exited":
  23. return "running"
  24. reason = _STATUS_BY_REASON.get(entry.get("completion_reason") or "")
  25. if reason:
  26. return reason
  27. return "done" if not entry.get("exit_code") else "failed"
  28. def process_rows(now: float | None = None) -> list:
  29. """Running processes plus those that exited within ``RETAIN_SECONDS``, newest-running first.
  30. The classic CLI is one conversation per OS process, so every registry entry (its own
  31. spawns and any a child handed back) belongs to this dock; gateway-hosted surfaces scope
  32. by session key in ``tui_gateway`` instead.
  33. """
  34. from hermes_cli.gateway_tools import process_registry as _registry
  35. process_registry = _registry() # the gateway session's processes (rewired CLI)
  36. now = time.time() if now is None else now
  37. rows = []
  38. for entry in process_registry.list_sessions():
  39. proc = process_registry.get(entry["session_id"])
  40. if proc is None:
  41. continue
  42. status = process_status(entry)
  43. exited_at = proc.exited_at if status != "running" else 0.0
  44. if status != "running" and now - exited_at > RETAIN_SECONDS:
  45. continue
  46. end = exited_at or now
  47. rows.append({
  48. "kind": "process",
  49. "key": proc.id,
  50. "id": proc.id,
  51. "command": " ".join((proc.command or "").split()) or t("cli.dock.process_goal_label"),
  52. "status": status,
  53. "exit_code": proc.exit_code,
  54. "elapsed": max(0, int(end - proc.started_at)),
  55. "since_exit": max(0, int(now - exited_at)) if exited_at else 0,
  56. "detail": _last_output_line(proc.output_buffer),
  57. })
  58. rows.sort(key=lambda r: (r["status"] != "running", -r["elapsed"] if r["status"] == "running" else r["since_exit"]))
  59. return rows
  60. _GLYPH = {"running": "⚙", "done": "✔", "failed": "✘", "killed": "✘", "lost": "?"}
  61. # Finished-status id → catalog key of the exit verdict (looked up at paint time).
  62. _VERDICT_KEYS = {"done": "cli.dock.exit_code", "failed": "cli.dock.exit_code",
  63. "killed": "cli.dock.verdict_killed", "lost": "cli.dock.verdict_lost"}
  64. def process_activity(row: dict) -> str:
  65. """The trailing ``· …`` part of a dock line: elapsed + latest output while running, the exit
  66. verdict + age once finished."""
  67. if row["status"] == "running":
  68. return f"{row['elapsed']}s · " + (
  69. t("cli.dock.last_output", detail=row["detail"]) if row["detail"] else t("cli.dock.starting"))
  70. verdict = _VERDICT_KEYS[row["status"]]
  71. verdict = t(verdict, code=row["exit_code"])
  72. return t("cli.dock.verdict_ago", verdict=verdict, seconds=row["since_exit"])
  73. def process_glyph(row: dict) -> str:
  74. return _GLYPH.get(row["status"], "?")
  75. def process_tail(process_id: str) -> str:
  76. from hermes_cli.gateway_tools import process_registry as _registry
  77. process_registry = _registry() # the gateway session's processes (rewired CLI)
  78. proc = process_registry.get(process_id)
  79. if proc is None:
  80. return t("cli.dock.process_gone")
  81. text = (proc.output_buffer or "")[-32768:]
  82. text = "".join(c for c in text if c.isprintable() or c in "\n\t")
  83. return text or t("cli.dock.no_output")
  84. def kill(process_id: str) -> dict:
  85. from hermes_cli.gateway_tools import process_registry as _registry
  86. process_registry = _registry() # the gateway session's processes (rewired CLI)
  87. return process_registry.kill_process(process_id)