gateway_chat_commands.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. """Classic CLI slash commands on the shared gateway, beyond the view's own controls.
  2. ``GatewayChatView.command`` answers the controls it owns (/stop /approve /answer /discard
  3. /branch /model /compress /yolo /quit). This module adds the session commands main's classic
  4. CLI ran in-process, mapped onto what the owner serves -- the mapping Ink uses
  5. (``ui-tui/src/app/slash/canonicalSessionCommands.ts``):
  6. - ``/title <name>`` -> ``session.mutate rename``; bare ``/title`` -> the owner's report
  7. - ``/undo [N]`` / ``/retry`` -> ``session.mutate rewind`` to the Nth-newest user turn
  8. (``/undo`` puts the removed text back in the composer, ``/retry`` resubmits it)
  9. - ``/new [title]`` / ``/reset`` -> ``session.create`` with this session's frozen launch request
  10. - ``/usage`` -> the owner's session report plus this view's last committed turn
  11. - ``/tools`` -> the toolsets frozen at launch
  12. - every other registry command -> ``slash.exec``: the owner runs its reviewed reads and
  13. refuses the rest, which prints where the command stands (the parity table below).
  14. """
  15. import contextlib
  16. import sys
  17. import uuid
  18. from hermes_cli.gateway_client import GatewayClientError
  19. PARITY_DOC = "https://hermes-agent.nousresearch.com/docs/developer-guide/gateway-command-parity"
  20. # Registry command (canonical name) -> how the classic view answers it itself. Every other
  21. # registry command goes to the owner through ``slash.exec``. Read by the parity inventory
  22. # (scripts/gen_gateway_command_parity.py).
  23. VIEW_ROUTES = {
  24. "quit": "detach", "stop": "session.interrupt", "approve": "approval.respond (prompt id)",
  25. "branch": "session.mutate branch", "model": "session.mutate model", "compress": "session.mutate compress",
  26. "yolo": "config.set yolo", "help": "local",
  27. "title": "session.mutate rename", "undo": "session.mutate rewind", "retry": "session.mutate rewind + resubmit",
  28. "new": "session.create", "clear": "session.create", "usage": "slash.exec + last-turn receipt",
  29. "tools": "session.info launch toolsets",
  30. }
  31. def refusal(name):
  32. return f"/{name} is not available on the shared gateway yet. Parity table: {PARITY_DOC}"
  33. def _user_turns(snapshot):
  34. """Human-authored live user rows (``row_id`` = durable ``messages.id``), oldest first: no display-only
  35. kind other than a typed /steer, never a compaction handoff carrier, never a row a compression
  36. archived (shown in the snapshot's history, not a turn to rewind to)."""
  37. from agent.context_compressor import is_user_originated_turn
  38. return [row for row in snapshot.get("messages", [])
  39. if type(row.get("row_id")) is int and row.get("display_kind") in (None, "", "steer")
  40. and not row.get("archived") and is_user_originated_turn(row)]
  41. def _rewind_to(turns_back, *, retry=False):
  42. def payload(snapshot):
  43. turns = _user_turns(snapshot)
  44. if len(turns) < turns_back:
  45. return None
  46. target = turns[-turns_back]
  47. if retry:
  48. # Main's retry_last order: a turn that cannot be resent losslessly as text (an image
  49. # turn) is refused on the CAS snapshot, before session.mutate archives it.
  50. from agent.context_compressor import retryable_user_text, user_originated_turn_view
  51. try:
  52. retryable_user_text((user_originated_turn_view(target) or {}).get("content"))
  53. except ValueError as exc:
  54. raise GatewayClientError(f"/retry: {exc}") from exc
  55. return {"target_message_id": target["row_id"]}
  56. return payload
  57. async def _mutate(view, operation, payload):
  58. result = await view.mutations.apply(view.client, view.session_id, operation, payload)
  59. view.mutations.acknowledge(view.session_id, operation, payload)
  60. return result
  61. async def _rewind(view, turns_back, *, retry=False):
  62. """The rewound user turn's text (``/retry``: its lossless resend text), or None when there was
  63. nothing to rewind."""
  64. payload = _rewind_to(turns_back, retry=retry)
  65. result = await view.mutations.apply(view.client, view.session_id, "rewind", payload)
  66. if result.get("status") == "nothing" or not result.get("rewound_count"):
  67. view.mutations.acknowledge(view.session_id, "rewind", payload)
  68. return None
  69. # Retained until the refresh lands: a repeat after a lost refresh replays this rewind instead of
  70. # deriving a new target from the already-shortened transcript (which would drop the turn before).
  71. snapshot = await view.client.rpc("session.resume", session_id=view.session_id)
  72. view.mutations.acknowledge(view.session_id, "rewind", payload)
  73. view.generation = snapshot["execution_generation"]
  74. content = (result.get("target_message") or {}).get("content")
  75. if retry:
  76. from agent.context_compressor import retryable_user_text
  77. with contextlib.suppress(ValueError):
  78. return retryable_user_text(content), result["rewound_count"]
  79. return content if isinstance(content, str) else "", result["rewound_count"]
  80. async def _title(view, rest):
  81. if not rest:
  82. return await forward(view, "title", "")
  83. result = await _mutate(view, "rename", {"title": rest})
  84. print(f"Session title set: {result.get('title') or rest}")
  85. async def _undo(view, rest):
  86. from agent.i18n import t
  87. if rest and not (rest.isdigit() and int(rest) > 0):
  88. raise GatewayClientError("Usage: /undo [N]")
  89. turns = int(rest or 1)
  90. rewound = await _rewind(view, turns)
  91. if rewound is None:
  92. print(t("cli.session.undo_no_user_message"))
  93. return
  94. text, count = rewound
  95. print(f"Undid {turns} turn{'s' if turns != 1 else ''} ({count} message(s)); the removed message is in the composer.")
  96. view.prefill = text
  97. async def _retry(view, rest):
  98. from agent.i18n import t
  99. rewound = await _rewind(view, 1, retry=True)
  100. if rewound is None or not rewound[0].strip():
  101. print(t("cli.session.retry_no_user_message"))
  102. return
  103. print(f"\n{'─' * 40}\n● {rewound[0]}", flush=True)
  104. await view.submit(rewound[0])
  105. async def _new(view, rest):
  106. """A fresh session with this one's frozen launch request (model, toolsets, cwd, ...); the old
  107. session stays resumable by its id. A title is a separate rename so an existing title is a
  108. conflict, never a silent attach to that other session."""
  109. from agent.i18n import t
  110. info = await view.client.rpc("session.info", session_id=view.session_id)
  111. accepted = set((await view.client.rpc("runtime.describe")).get("session_create", {}).get("parameters", []))
  112. request = {key: value for key, value in (info.get("launch_request") or {}).items()
  113. if key in accepted and key not in {"request_id", "title"}}
  114. if info.get("cwd") and "cwd" in accepted:
  115. request["cwd"] = info["cwd"]
  116. # The frozen request never holds the launch key; the one this terminal supplied rides along.
  117. if getattr(view, "launch_api_key", None) and "api_key" in accepted:
  118. request["api_key"] = view.launch_api_key
  119. from hermes_cli.gateway_chat import client_env_policy
  120. request.update(client_env_policy(accepted)) # never in launch_request: this shell's, sent afresh
  121. snapshot = await view.client.rpc("session.create", request_id=uuid.uuid4().hex, **request)
  122. await view.adopt(snapshot)
  123. print(t("cli.session.new_session"))
  124. print(f"Session: {view.session_id}", file=sys.stderr, flush=True)
  125. if rest:
  126. await _title(view, rest)
  127. async def _usage(view, rest):
  128. if rest: # `/usage reset` redeems a credit: the owner decides (and refuses it for local sessions)
  129. return await forward(view, "usage", rest)
  130. await forward(view, "usage", "")
  131. admission = next(reversed(view.completions), None)
  132. if admission is None:
  133. return
  134. receipt = await view.client.rpc("prompt.receipt", session_id=view.session_id,
  135. admission_id=admission, include_result=True)
  136. result = receipt.get("result") or {}
  137. if not isinstance(result, dict) or not result:
  138. return
  139. lines = ["", "Last turn:", f" Model: {result.get('model') or view.model}"]
  140. for label, key in (("Input tokens", "input_tokens"), ("Output tokens", "output_tokens"),
  141. ("Total tokens", "total_tokens"), ("API calls", "api_calls")):
  142. lines.append(f" {label}: {int(result.get(key) or 0):,}")
  143. if isinstance(result.get("estimated_cost_usd"), (int, float)):
  144. lines.append(f" Cost: ${result['estimated_cost_usd']:.4f}")
  145. print("\n".join(lines))
  146. async def _tools(view, rest):
  147. info = await view.client.rpc("session.info", session_id=view.session_id)
  148. toolsets = (info.get("launch_request") or {}).get("toolsets")
  149. if isinstance(toolsets, list) and toolsets:
  150. print("Toolsets frozen at launch: " + ", ".join(map(str, toolsets)))
  151. else:
  152. print("This session runs the profile's CLI toolsets as they were at launch (`hermes tools list`).")
  153. print("Changing toolsets mid-session (/tools enable|disable) " + refusal("tools").split(" ", 1)[1])
  154. async def forward(view, name, rest):
  155. """Run a registry command (or a skill) on the owner; its refusal names where the command stands."""
  156. from hermes_cli.gateway_client import GatewayRPCError
  157. try:
  158. reply = await view.client.rpc("slash.exec", session_id=view.session_id,
  159. command=name + (" " + rest if rest else ""))
  160. except GatewayRPCError as exc:
  161. if str(exc) != "unsupported_command":
  162. raise
  163. from hermes_cli.commands import resolve_command
  164. print(refusal(name) if resolve_command(name) else f"Unknown command: /{name} (use /help)")
  165. return
  166. if reply.get("type") in ("skill", "send"):
  167. # A prompt directive is the client's durable submit (same contract as Ink and Desktop):
  168. # a skill body, or the turn a command built (/plan, /goal's kickoff...) after its notice.
  169. if reply.get("notice"):
  170. print(reply["notice"])
  171. print(f"\n{'─' * 40}\n● {reply.get('display') or '/' + name}", flush=True)
  172. await view.submit(reply["message"])
  173. else:
  174. print(reply.get("output") or f"/{name}: no output")
  175. _VIEW_CONTROLS = frozenset({"quit", "stop", "approve", "branch", "model", "compress", "yolo", "help"})
  176. # /clear is main's "new session + clear screen"; the gateway view keeps scrollback and starts fresh.
  177. _HANDLERS = {"title": _title, "undo": _undo, "retry": _retry, "new": _new, "clear": _new, "usage": _usage,
  178. "tools": _tools}
  179. async def run_command(view, command, rest):
  180. """Any slash command the view's own controls did not take."""
  181. from hermes_cli.commands import resolve_command
  182. name = command.lstrip("/")
  183. definition = resolve_command(name)
  184. canonical = definition.name if definition else name
  185. if canonical in _VIEW_CONTROLS and canonical != name:
  186. # An alias of a control the view owns (/fork, /compact, /exit): answer it as the canonical.
  187. return await view.command(f"/{canonical} {rest}".rstrip())
  188. handler = _HANDLERS.get(canonical)
  189. if handler is not None:
  190. await handler(view, rest.strip())
  191. else:
  192. await forward(view, canonical, rest.strip())
  193. return True
  194. def help_text():
  195. from gateway.session_commands import _READ_COMMANDS
  196. reports = " ".join(f"/{name}" for name in sorted(_READ_COMMANDS - {"help"}))
  197. return ("/stop, /approve <id> <choice>, /answer <id> <text>, /discard <admission_id> (turn lost during "
  198. "restart), /yolo [on|off], /quit (detach). /branch [title], /model <model> [--provider name], "
  199. "/compress [here [N] | <focus>] [--preview]. /title [name], /undo [N], /retry, /new [title] "
  200. f"(/reset), /usage, /tools.\nReports run by the gateway: {reports}.\nParity table: {PARITY_DOC}")