gateway_commands.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. """Editor slash commands on the gateway path; each one is an existing gateway verb.
  2. Main served these in-process (``acp_adapter/commands.py``). The reports are the owner's own
  3. ``slash.exec`` reads, ``/model``, ``/compress`` and ``/reset`` the retained ``session.mutate``
  4. controls, ``/steer`` the owner's ``session.steer``; ``/queue`` and an idle ``/steer`` become the
  5. next prompt, which the session's FIFO runs after any turn in flight. ``/title <name>`` is the
  6. ``rename`` mutation and ``/undo`` / ``/retry`` the ``rewind`` one, as in the classic transport
  7. client (``hermes_cli/gateway_chat_commands.py``). Every other registry command goes to the owner's
  8. ``slash.exec`` like there: it runs what it serves for this session and refuses the rest, and that
  9. refusal reaches the editor as a reply naming the command, never a failed prompt.
  10. """
  11. from __future__ import annotations
  12. from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
  13. class CommandRefused(GatewayClientError):
  14. """A refusal the editor shows as the command's reply (the prompt itself ends normally)."""
  15. async def run_command(agent, session_id, command, arg):
  16. """``(reply, None)`` for a command answered here, or ``(None, text)`` when ``text`` is to be
  17. submitted as the prompt. A refusal raises ``CommandRefused`` (or the owner's RPC error).
  18. ``ROUTES`` (below) is the one table of what ACP answers itself; every other registry command,
  19. the reads included, is the owner's ``slash.exec`` answer (``_forward``)."""
  20. route = ROUTES.get(command)
  21. if route is None:
  22. return await _forward(agent, await agent._client(), session_id, command, arg)
  23. return await route[1](agent, session_id, command, arg)
  24. async def _branch(agent, session_id, command, arg):
  25. raise CommandRefused("/branch: use your editor's fork session action (ACP session/fork)")
  26. async def _help(agent, session_id, command, arg):
  27. from acp_adapter.gateway_session_meta import help_text
  28. return help_text(), None
  29. async def _prompt(agent, session_id, command, arg):
  30. if not arg:
  31. return f"Usage: /{command} <{'guidance' if command == 'steer' else 'prompt'}>", None
  32. steered = await _steer(agent, session_id, arg) if command == 'steer' else None
  33. return (steered, None) if steered else (None, arg)
  34. async def _title(agent, session_id, command, arg):
  35. client = await agent._client()
  36. if not arg:
  37. return await _forward(agent, client, session_id, command, arg)
  38. return await _rename(agent, client, session_id, arg), None
  39. async def _info(agent, session_id, command, arg):
  40. client = await agent._client()
  41. if command == 'model' and arg:
  42. return await _mutate(agent, client, session_id, command, arg), None
  43. info = await client.rpc('session.info', session_id=session_id)
  44. return (_tools_text(info) if command == 'tools' else _model_text('Current model', info)), None
  45. async def _mutation(agent, session_id, command, arg):
  46. return await _mutate(agent, await agent._client(), session_id, command, arg), None
  47. async def _rewind_command(agent, session_id, command, arg):
  48. return await _rewind(agent, await agent._client(), session_id, command, arg)
  49. async def _discard_unknown(agent, session_id, _command, admission_id):
  50. """Acknowledge one exact lost turn and refresh its FIFO snapshot."""
  51. if not admission_id:
  52. return 'Usage: /discard <lost admission id>', None
  53. # Pending-only refreshes: adopting the whole snapshot would advance its reply cursor past
  54. # messages and approvals the editor's event pump has not projected yet.
  55. await agent._refresh_unknown(session_id)
  56. lost = next((row for row in agent._snapshots[session_id].get('pending', [])
  57. if row.get('admission_id') == admission_id and row.get('status') == 'unknown'), None)
  58. if lost is None:
  59. return (f'No unknown (lost) admission with id {admission_id}; refresh the session and try again.', None)
  60. client = await agent._client()
  61. await client.rpc('prompt.resolve_unknown', session_id=session_id, admission_id=admission_id,
  62. execution_generation=lost['execution_generation'])
  63. await agent._refresh_unknown(session_id)
  64. return 'Discarded the lost turn. Queued messages can continue.', None
  65. async def _forward(agent, client, session_id, command, arg):
  66. """The owner's ``slash.exec`` answer: its report, a turn to submit (a skill body or the turn a
  67. command built, after its notice), or the shared refusal for a command it does not serve."""
  68. import acp
  69. from hermes_cli.gateway_chat_commands import refusal
  70. try:
  71. reply = await client.rpc('slash.exec', session_id=session_id, command=f'/{command} {arg}'.strip())
  72. except GatewayRPCError as exc:
  73. if str(exc) != 'unsupported_command':
  74. raise
  75. raise CommandRefused(refusal(command)) from exc
  76. if reply.get('type') in ('skill', 'send'):
  77. if reply.get('notice') and agent._conn:
  78. await agent._conn.session_update(session_id=agent._editor_id(session_id),
  79. update=acp.update_agent_message_text(reply['notice'] + '\n'))
  80. return None, reply['message']
  81. return str(reply.get('output') or reply.get('notice') or f'/{command}: no output'), None
  82. async def _rename(agent, client, session_id, title):
  83. payload = {'title': title}
  84. result = await agent._mutations.apply(client, session_id, 'rename', payload)
  85. agent._mutations.acknowledge(session_id, 'rename', payload)
  86. return f"Session title set: {result.get('title') or title}"
  87. async def _rewind(agent, client, session_id, command, arg):
  88. """``/undo [N]`` reports the removed message (an editor has no composer to put it back in);
  89. ``/retry`` resubmits the last user turn's lossless text as this prompt."""
  90. from agent.i18n import t
  91. from hermes_cli.gateway_chat_commands import _rewind_to
  92. retry = command == 'retry'
  93. if not retry and arg and not (arg.isdigit() and int(arg) > 0):
  94. raise CommandRefused('Usage: /undo [N]')
  95. turns = 1 if retry else int(arg or 1)
  96. target = _rewind_to(turns, retry=retry)
  97. def payload(snapshot):
  98. # The target check runs on the CAS snapshot before anything is archived: its refusal (an
  99. # image turn /retry cannot resend) is the command's reply. Transport errors stay failures.
  100. try:
  101. return target(snapshot)
  102. except GatewayClientError as exc:
  103. raise CommandRefused(str(exc)) from exc
  104. result = await agent._mutations.apply(client, session_id, 'rewind', payload)
  105. if result.get('status') == 'nothing' or not result.get('rewound_count'):
  106. agent._mutations.acknowledge(session_id, 'rewind', payload)
  107. return t('cli.session.retry_no_user_message' if retry else 'cli.session.undo_no_user_message'), None
  108. # Retained until the refresh lands: a repeat after a lost refresh replays this rewind instead of
  109. # deriving a new target from the already-shortened transcript (which would drop the turn before).
  110. await agent._adopt(session_id, await client.rpc('session.resume', session_id=session_id))
  111. agent._mutations.acknowledge(session_id, 'rewind', payload)
  112. content = (result.get('target_message') or {}).get('content')
  113. if retry:
  114. from agent.context_compressor import retryable_user_text
  115. try:
  116. text = retryable_user_text(content)
  117. except ValueError as exc:
  118. raise CommandRefused(f'/retry: {exc}') from exc
  119. if not text.strip():
  120. return t('cli.session.retry_no_user_message'), None
  121. return None, text
  122. removed = content if isinstance(content, str) else ''
  123. count = result['rewound_count']
  124. return (f"Undid {turns} turn{'s' if turns != 1 else ''} ({count} message(s)).\n"
  125. + (f"Removed message: {removed}" if removed else '')).rstrip(), None
  126. async def _steer(agent, session_id, text):
  127. """Guidance for this editor's running turn; None when there is none to steer (main ran an idle
  128. steer as a plain prompt, and a turn that ended meanwhile leaves the text for the next one).
  129. The generation steered is our own admission's (``prompt.receipt``), never the session's latest:
  130. while our prompt still waits behind another client's turn, that turn is not ours to redirect."""
  131. admission_id = agent._admissions.get(session_id)
  132. if admission_id is None:
  133. return None
  134. client = await agent._client()
  135. receipt = await client.rpc('prompt.receipt', session_id=session_id, admission_id=admission_id)
  136. if receipt.get('status') != 'started':
  137. return None
  138. try:
  139. result = await client.rpc('session.steer', session_id=session_id, text=text,
  140. execution_generation=receipt['execution_generation'])
  141. except GatewayRPCError as exc:
  142. # Only a turn that ended meanwhile (its generation moved on) leaves the text for the next
  143. # prompt; any other refusal (permission, unsupported control, not ready) is the answer.
  144. if str(exc) == 'stale_generation':
  145. return None
  146. raise
  147. if result.get('voice_stopped') is True:
  148. # TUI-26: the guidance was a bare stop phrase that ended this LOCAL session's voice chat;
  149. # no turn saw it, and sending it on as a prompt would admit ``stop`` as a turn.
  150. from agent.i18n import t
  151. return t('cli.voice.stop_phrase_typed')
  152. if result.get('status') != 'queued':
  153. return None
  154. return f"⏩ Steer queued for the active turn: {text[:80]}{'...' if len(text) > 80 else ''}"
  155. async def _mutate(agent, client, session_id, command, arg):
  156. from hermes_cli.gateway_mutations import slash_mutation
  157. operation, payload = ('reset', {}) if command in {'new', 'clear'} else slash_mutation('/' + command, arg)
  158. confirm = agent._model_confirmer(session_id) if operation == 'model' else None
  159. result = await agent._mutations.apply(client, session_id, operation, payload, confirm=confirm)
  160. # Answers that changed nothing (declined, deferred to the next turn, a preview, nothing to remove).
  161. unchanged = _UNCHANGED.get(result.get('status'))
  162. if unchanged is not None:
  163. reply = unchanged(result)
  164. else:
  165. await agent._adopt(session_id, await client.rpc('session.resume', session_id=session_id))
  166. if operation in {'reset', 'compress'}:
  167. await _refresh_context(agent, client, session_id, operation)
  168. reply = {'model': lambda: _model_text('Model switched to', result),
  169. 'compress': lambda: _summary_text(result) or 'Context compressed.',
  170. 'reset': lambda: 'Conversation history cleared.'}[operation]()
  171. agent._mutations.acknowledge(session_id, operation, payload)
  172. return reply
  173. def _cancelled_text(_result):
  174. from agent.i18n import t
  175. return t('cli.model.switch_cancelled')
  176. # A mutation answer that committed nothing, so the editor's snapshot is still current: a declined
  177. # guarded pick, a pick during a running turn (stored for the next turn), a read-only compress
  178. # preview, and a compress with nothing removable (the owner's shared report).
  179. _UNCHANGED = {
  180. 'cancelled': _cancelled_text,
  181. 'deferred': lambda result: deferred_pick_text(result),
  182. 'preview': lambda result: '\n'.join(result['lines']),
  183. 'noop': lambda result: _summary_text(result) or 'No changes from compression.',
  184. }
  185. async def _refresh_context(agent, client, session_id, operation):
  186. """The editor's context indicator after /reset or /compress. Both are session boundaries that
  187. evict the owner's agent, so ``session.stats`` has no window until the next turn builds one: the
  188. window shown stays (the model is unchanged) and its occupancy is the new transcript's, nothing
  189. after a reset, the compressed messages' estimate (the summary's own figure) after a compress."""
  190. stats = await client.rpc('session.stats', session_id=session_id)
  191. if stats.get('context_length') is None:
  192. from agent.model_metadata import estimate_request_tokens_rough
  193. messages = [m for m in agent._snapshots[session_id].get('messages') or [] if not m.get('archived')]
  194. stats = {**stats, 'context_length': (agent._usage.get(session_id) or {}).get('context_length'),
  195. 'context_tokens': estimate_request_tokens_rough(messages) if operation == 'compress' else 0}
  196. await agent._project_usage(session_id, agent._editor_id(session_id), stats)
  197. def deferred_pick_text(result):
  198. return f"{result.get('model') or 'The picked model'} applies from your next message."
  199. def refused_pick_text(update):
  200. """The owner's ``session.updated`` for a deferred pick it dropped at the turn boundary."""
  201. current = update.get('model') or 'the current model'
  202. if update.get('provider'):
  203. current += f" ({update['provider']})"
  204. return (f"Model switch to {update.get('target_model') or 'the picked model'} was not applied "
  205. f"({update.get('reason') or 'refused'}); still using {current}.")
  206. def _summary_text(result):
  207. summary = result.get('summary') or {}
  208. return '\n'.join(filter(None, (summary.get('headline'), summary.get('token_line'), summary.get('note'))))
  209. def _model_text(label, fields):
  210. lines = [f"{label}: {fields.get('model') or 'unknown'}"]
  211. if fields.get('provider'):
  212. lines.append(f"Provider: {fields['provider']}")
  213. return '\n'.join(lines)
  214. def _tools_text(info):
  215. """The session's tools by toolset (``session.info`` ``tools``: toolset -> tool names)."""
  216. groups = info.get('tools') or {}
  217. names = sorted({name for tools in groups.values() for name in tools})
  218. if not names:
  219. toolsets = info.get('enabled_toolsets') or []
  220. return f"Enabled toolsets: {', '.join(toolsets)}" if toolsets else "No tools available."
  221. lines = [f"Available tools ({len(names)}):"]
  222. lines.extend(f" {toolset}: {', '.join(sorted(tools))}" for toolset, tools in sorted(groups.items()) if tools)
  223. return '\n'.join(lines)
  224. # What ACP answers itself: command -> (the parity table's ACP cell, handler). Dispatch reads this and
  225. # ``scripts/gen_gateway_command_parity.py`` documents it, so a route cannot change without the table.
  226. # Any command not here goes to the owner's ``slash.exec`` (``_forward``). ``/clear`` is main's
  227. # "new session + clear screen"; here it is ``/new``'s reset of this session.
  228. ROUTES = {
  229. 'branch': ('ACP fork_session', _branch),
  230. 'discard': ('prompt.resolve_unknown', _discard_unknown),
  231. 'help': ('local', _help),
  232. 'steer': ('session.steer', _prompt),
  233. 'queue': ('prompt.submit', _prompt),
  234. 'title': ('session.mutate rename (bare: slash.exec)', _title),
  235. 'undo': ('session.mutate rewind', _rewind_command),
  236. 'retry': ('session.mutate rewind + resubmit', _rewind_command),
  237. 'tools': ('session.info', _info),
  238. 'model': ('session.mutate model', _info),
  239. 'compress': ('session.mutate compress', _mutation),
  240. 'new': ('session.mutate reset', _mutation),
  241. 'clear': ('session.mutate reset', _mutation),
  242. }