session_commands.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. """Bound local slash commands; prompt directives use the client's durable submit.
  2. Desktop and Ink both submit ``skill``/``send`` results with their own input ID.
  3. Executing those here would double-submit and bypass their retry identity.
  4. """
  5. import asyncio
  6. from contextlib import contextmanager
  7. import logging
  8. import os
  9. from pathlib import Path
  10. import shlex
  11. from gateway.session_cron_commands import cron_read
  12. from hermes_state_runtime import RuntimeStoreError
  13. logger = logging.getLogger(__name__)
  14. # Reviewed gateway handlers only: listing a command is not permission to run it. Each read was
  15. # run through its real handler against a local session (website/docs/developer-guide/
  16. # gateway-command-parity.md); a handler that reads messaging-only state or writes config is not here.
  17. _READ_COMMANDS = frozenset({'help', 'commands', 'status', 'context', 'version', 'whoami',
  18. 'usage', 'insights', 'profile', 'diff', 'memory', 'kanban', 'topup',
  19. 'suggestions', 'bundles', 'skills'})
  20. _CONTROL_COMMANDS = frozenset({'title'})
  21. # Authoring/workflow commands whose messaging handler (``_command_handler_table``) runs as-is for a
  22. # local session: goal/loop/heartbeat state on the session's row, the review/refine forks of its
  23. # cached agent, the /debug summary upload, /blueprint's job creation. A turn the handler would have
  24. # pushed onto the adapter FIFO comes back as a ``send`` directive (gateway/session_command_sink.py).
  25. _HANDLER_CONTROLS = frozenset({'goal', 'subgoal', 'loop', 'heartbeat', 'review', 'refine', 'debug', 'curator',
  26. 'login', 'autoprune'})
  27. # Idle-path commands the messaging gateway answers by rewriting the turn (``_hm_cmd_<name>``,
  28. # gateway/run_inbound.py): the rewritten text is returned as the client's ``send`` directive.
  29. _PROMPT_COMMANDS = frozenset({'plan', 'learn', 'init', 'moa', 'blueprint', 'egress'})
  30. # Per-session settings: the messaging handler itself, made session-correct for a local session
  31. # (gateway/session_setting_commands.py). Admission-fenced like any control.
  32. _SETTING_COMMANDS = frozenset({'reasoning', 'voice', 'approvals', 'codex-runtime', 'footer', 'busy', 'verbose',
  33. 'yolo', 'fast', 'personality'})
  34. # Typed `/approve` / `/deny`: the messaging handler resolves THIS session's waiting approval (its
  35. # route is the session key), the same waiter `approval.respond` answers by prompt id.
  36. _APPROVAL_COMMANDS = frozenset({'approve', 'deny'})
  37. # Reports with no messaging handler: the classic CLI's own text, built by the owner for this
  38. # session (gateway/session_info_reads.py).
  39. _INFO_READS = frozenset({'toolsets', 'platforms'})
  40. # The classic CLI's own handler, run by the owner (gateway/session_cron_commands.py): the profile's cron store
  41. # belongs to the gateway whose ticker fires its jobs, so no client writes it. Bare ``/cron`` and ``list``
  42. # read; every other form (add/edit/pause/resume/run/remove) is a control that writes the store. A write runs
  43. # only on a connection that is not attached to the session: the classic CLI's command socket
  44. # (GatewayConnection.call_until), which waits with no deadline. A viewer's own connection (Ink, Desktop, ACP
  45. # send /cron there) answers its reads, prompts and interrupts one request at a time with a deadline, and a
  46. # /cron run lasts as long as its job, so it keeps main's refusal whichever surface created the session.
  47. _OWNER_COMMANDS = frozenset({'cron'})
  48. # Commands that move the session's goal/loop/heartbeat state: every viewer's cards repaint after them.
  49. _AUTOMATION_COMMANDS = frozenset({'goal', 'subgoal', 'loop', 'heartbeat'})
  50. # Kanban verbs that only read the board. ``create`` would also subscribe the LOCAL chat to
  51. # messaging notifications, and every other verb mutates the board.
  52. _KANBAN_READS = frozenset({'', 'help', '--help', '-h', '?', 'list', 'ls', 'show', 'stats', 'assignees',
  53. 'context', 'runs', 'log', 'diagnostics', 'diag'})
  54. def _split(arg):
  55. """``arg`` as a shlex-splitting handler parses it: an unclosed quote can't run there either, so it is
  56. refused by name (before ``pre_command`` fires) instead of failing as an internal error."""
  57. try:
  58. return shlex.split(arg) if arg.strip() else []
  59. except ValueError as exc:
  60. raise RuntimeStoreError('invalid_params', field='arg', detail=str(exc)) from None
  61. def _first_token(arg):
  62. """/kanban's verb as its handler parses it (shlex, hermes_cli/kanban.py ``run_slash``)."""
  63. tokens = iter(_split(arg))
  64. for token in tokens:
  65. if token == '--board':
  66. next(tokens, None)
  67. elif not token.startswith('--board='):
  68. return token.lower()
  69. return ''
  70. def _first_word(arg):
  71. """The first whitespace-separated word, as main's CLI and the messaging /memory and /skills
  72. handlers split it: a quote later in the line belongs to the argument (`/memory pending it's`)."""
  73. words = arg.split(None, 1)
  74. return words[0].lower() if words else ''
  75. # The read-only argument forms of a read command whose other subcommands write: ``/usage reset``
  76. # redeems a credit, ``/suggestions accept|catalog`` schedules cron jobs delivering to this
  77. # (non-messaging) chat. The review queues read like main's CLI: only the first word counts.
  78. _READ_ARGUMENTS = {
  79. 'skills': lambda arg: _first_word(arg) in {'', 'pending', 'diff'},
  80. 'usage': lambda arg: not arg.strip(),
  81. 'memory': lambda arg: _first_word(arg) in {'', 'pending'},
  82. 'suggestions': lambda arg: not arg.strip(),
  83. 'kanban': lambda arg: _first_token(arg) in _KANBAN_READS,
  84. }
  85. # The write forms of a command whose reads are above: the messaging handler's own review verbs,
  86. # applied for this session's profile (`/memory` and `/skills` approve|reject their staged queues;
  87. # `approval` updates their config.yaml switch, as main's CLI wrote it).
  88. _CONTROL_ARGUMENTS = {
  89. 'skills': lambda arg: _first_word(arg) in {'approve', 'apply', 'reject', 'deny', 'drop', 'approval', 'mode'},
  90. 'memory': lambda arg: _first_word(arg) in {'approve', 'apply', 'reject', 'deny', 'drop', 'approval', 'mode'},
  91. }
  92. # The setting forms a local session cannot deliver: `/voice tts` asks the owner to voice every reply,
  93. # and a local session's audio plays only in its client. Read like the handler reads it (no shlex): an
  94. # unbalanced quote in any other `/voice` argument still reaches the handler.
  95. _REFUSED_ARGUMENTS = {
  96. 'voice': lambda arg: arg.strip().lower() == 'tts',
  97. }
  98. # What to use instead, for the client-local commands a shared-gateway session cannot run: they act
  99. # on the host's profiles, state snapshots, terminal or git checkout, which the gateway may not share
  100. # with the client. Rides the ``unsupported_command`` refusal as ``data.detail`` (the reason stays the
  101. # same, so shipped clients keep working); Ink and Desktop print it under the refusal.
  102. REFUSAL_HINTS = {
  103. 'export': 'Run `hermes profile export [name] -o <file>` in a terminal.',
  104. 'import': 'Run `hermes profile import <archive> [--name <name>]` in a terminal.',
  105. 'snapshot': 'Run `hermes backup --quick` in a terminal (restore: `hermes --cli`, then /snapshot restore).',
  106. 'handoff': 'Hand off from the classic CLI: `hermes --cli --resume <session>`, then /handoff <platform>.',
  107. 'hatch': 'Generate a pet from the classic CLI (`hermes --cli`, then /hatch), or use /pet to pick one.',
  108. 'worktree': 'Start in a fresh worktree with `hermes -w`, or use the classic CLI (`hermes --cli`).',
  109. 'palette': 'Type / to search commands (the composer completes and filters them).',
  110. }
  111. def command_verdict(name, arg=''):
  112. """``read`` / ``control`` / ``refused`` for a canonical registry command on a local session."""
  113. if _REFUSED_ARGUMENTS.get(name, lambda _a: False)(arg):
  114. return 'refused'
  115. if name in _OWNER_COMMANDS:
  116. return 'read' if cron_read(_split(arg)) is not None else 'control' # main's /cron handler shlex-splits
  117. if (name in _CONTROL_COMMANDS or name in _HANDLER_CONTROLS or name in _PROMPT_COMMANDS
  118. or name in _SETTING_COMMANDS or name in _APPROVAL_COMMANDS
  119. or _CONTROL_ARGUMENTS.get(name, lambda _a: False)(arg)):
  120. return 'control'
  121. if name in _INFO_READS or (name in _READ_COMMANDS and _READ_ARGUMENTS.get(name, lambda _arg: True)(arg)):
  122. return 'read'
  123. return 'refused'
  124. def _parse(params, dispatch):
  125. allowed = {'session_id', 'profile', 'name', 'arg'} if dispatch else {'session_id', 'profile', 'command'}
  126. if (set(params) - allowed or any(not isinstance(v, str) for v in params.values())):
  127. raise RuntimeStoreError('invalid_params')
  128. text = params.get('name', '') if dispatch else params.get('command', '')
  129. parts = text.strip().lstrip('/').split(None, 1)
  130. if not parts or (dispatch and len(parts) != 1):
  131. raise RuntimeStoreError('invalid_params')
  132. return parts[0], params.get('arg', '') if dispatch else (parts[1] if len(parts) > 1 else '')
  133. def _resolve_alias(name, arg):
  134. from gateway.run import _load_gateway_config
  135. from hermes_cli.commands import resolve_command
  136. quick = _load_gateway_config().get('quick_commands') or {}
  137. seen = set()
  138. while resolve_command(name) is None and name in quick:
  139. if name in seen:
  140. raise RuntimeStoreError('invalid_params')
  141. seen.add(name)
  142. entry = quick[name]
  143. if not isinstance(entry, dict) or entry.get('type') not in {'alias', 'exec'}:
  144. raise RuntimeStoreError('unsupported_command')
  145. if entry['type'] == 'exec':
  146. return name, arg
  147. target = entry.get('target')
  148. if not isinstance(target, str) or not target.strip():
  149. raise RuntimeStoreError('invalid_params')
  150. parts = target.strip().lstrip('/').split(None, 1)
  151. name = parts[0]
  152. arg = ' '.join(p for p in (*parts[1:], arg) if p)
  153. return name, arg
  154. def _runner_command(name):
  155. """``('exec', shell)`` for a ``type: exec`` quick command, ``('plugin', registered)`` for a plugin
  156. slash command, else None (read in the owning profile's scope). The exact registered name wins over
  157. Telegram's ``_`` -> ``-`` form, as main's CLI looked it up: ``foo_bar`` is its own command."""
  158. from gateway.run import _load_gateway_config
  159. from hermes_cli.plugins import get_plugin_command_handler
  160. entry = (_load_gateway_config().get('quick_commands') or {}).get(name)
  161. if isinstance(entry, dict) and entry.get('type') == 'exec':
  162. return 'exec', str(entry.get('command') or '')
  163. return next((('plugin', registered) for registered in dict.fromkeys((name, name.replace('_', '-')))
  164. if get_plugin_command_handler(registered)), None)
  165. async def _run_runner_command(runner, live, name, arg, kind, shell):
  166. """The messaging gateway's own quick-command / plugin-command dispatch for this session
  167. (``run_inbound_hooks``): the operator's slash access policy, the 30 s sanitized-env exec with
  168. redacted output, the plugin handler under this session's env scope."""
  169. from agent.i18n import t
  170. from gateway.platforms.base import MessageEvent
  171. if kind == 'exec':
  172. if not shell:
  173. return t('gateway.quick_command.no_command', command=name)
  174. refused = runner._check_slash_access(live.source, name)
  175. if refused:
  176. return refused
  177. from gateway.session_policy import policy_for_source
  178. policy = policy_for_source(runner, live.source)
  179. cwd = getattr(policy, 'cwd', None) or None
  180. if cwd is None or not await asyncio.to_thread(os.path.isdir, cwd):
  181. # Never fall back to the gateway's own folder: a relative command would act there.
  182. raise RuntimeStoreError('cwd_unavailable')
  183. return await runner._hm_run_exec_quick_command(name, shell, cwd=cwd)
  184. # Plugin-only: the runner's quick commands are the launch profile's under multiplex, and this
  185. # session's own were already resolved above in its profile (``_resolve_alias``/``_runner_command``),
  186. # so is the registered name (``shell``) the handler is looked up by.
  187. from hermes_cli.plugins import get_plugin_command_handler
  188. handler = get_plugin_command_handler(shell)
  189. if handler is None:
  190. raise RuntimeStoreError('unsupported_command')
  191. event = MessageEvent(text='/' + name + (' ' + arg if arg else ''), source=live.source)
  192. # The session's own entry, so HERMES_SESSION_ID is bound as on its turns: a background job
  193. # the handler starts records this session as its parent.
  194. entry = await asyncio.to_thread(runner.session_store.lookup_by_session_key, live.route)
  195. try:
  196. # The argument as typed, like main's CLI: no messaging dash repair.
  197. return await runner._hm_run_plugin_handler(handler, event, live.source, entry, args=arg)
  198. except Exception as e: # main's CLI printed it; messaging (run_inbound_hooks) still only logs it
  199. logger.warning("Plugin command dispatch failed: %s", e, exc_info=True)
  200. return t('cli.plugin.command_error', error=str(e) or type(e).__name__)
  201. def _skill_directive(name, arg, route):
  202. """A local session's ``/skill`` (its plugin skills included, as on main's interactive surfaces),
  203. stacked ``/skill-a /skill-b do X`` too: built here, so no client loads plugins to resolve one."""
  204. from agent.i18n import t
  205. from agent.skill_commands import (
  206. build_skill_invocation_message, build_stacked_skill_invocation_message, describe_skill_invocation,
  207. get_interactive_skill_commands, resolve_slash_key, split_stacked_skill_commands,
  208. )
  209. skills = get_interactive_skill_commands()
  210. key = resolve_slash_key(name, skills)
  211. if key is None:
  212. raise RuntimeStoreError('unsupported_command')
  213. extra, instruction = split_stacked_skill_commands(arg, interactive=True)
  214. stacked = build_stacked_skill_invocation_message([key, *extra], instruction, task_id=route) if extra else None
  215. message = stacked[0] if stacked else build_skill_invocation_message(key, arg, task_id=route)
  216. if not message:
  217. raise RuntimeStoreError('command_unavailable')
  218. missing = stacked[2] if stacked else []
  219. return {'type': 'skill', 'name': ', '.join(stacked[1]) if stacked else skills[key]['name'], 'message': message,
  220. 'display': describe_skill_invocation(message, separator=' '),
  221. **({'notice': t('cli.skills.skipped_missing', names=', '.join(missing))} if missing else {})}
  222. async def _tui_read(authority, actor, ref, name, arg, before):
  223. """Main's TUI sidecar text for a TUI session's /status or /context read, else None;
  224. ``before`` (its ``pre_command``) runs once the read is accepted."""
  225. from gateway.session_local import authorize_local_source
  226. from gateway.session_policy import policy_for_source
  227. from gateway.session_tui_reads import run_tui_read, tui_read
  228. live = authority.sessions[ref.session_id]
  229. if authorize_local_source(authority.runner, live.source) is not True:
  230. return None
  231. policy = policy_for_source(authority.runner, live.source)
  232. render = tui_read(policy, name, arg)
  233. if render is None:
  234. return None
  235. authority.authorize(actor, ref, 'session:read')
  236. await before()
  237. return await run_tui_read(authority, ref, live, policy, render, arg)
  238. # Messaging's running-agent escape hatches (hooks.md ``pre_command``: ``/stop``, approval controls):
  239. # while a turn runs no plugin observer sits in front of them. Every other command that runs fires.
  240. _ESCAPE_HATCHES = frozenset({'stop'}) | _APPROVAL_COMMANDS
  241. _PRE_COMMAND_PENDING = 32 # one session's queued deliveries; past it a delivery is dropped (logged)
  242. _PRE_COMMAND_TAILS = {} # (profile, session id) -> (that session's last queued delivery, pending count)
  243. async def _on_own_thread(fn):
  244. """``fn()`` on a daemon thread of its own (under the caller's contextvars), awaited on the loop: never
  245. the loop's shared executor, and no shared worker a callback waiting out its bound
  246. (``plugins.hook_callback_timeout``, enforced by the hook dispatcher: abandoned worker, suppression,
  247. cap) holds from another session. One session runs one delivery at a time, so this is at most one
  248. thread per session with a delivery in flight."""
  249. from agent.memory_provider import spawn_context_thread
  250. loop = asyncio.get_running_loop()
  251. done = loop.create_future()
  252. def settle():
  253. if not done.done(): # else the delivery was cancelled
  254. done.set_result(None)
  255. def run():
  256. try:
  257. fn()
  258. except Exception: # fire_pre_command_hook never raises: anything here is a bug, never the caller's
  259. logger.exception('pre_command delivery failed')
  260. finally:
  261. try:
  262. loop.call_soon_threadsafe(settle)
  263. except RuntimeError: # the loop closed (gateway shutdown): nobody awaits it any more
  264. pass
  265. try:
  266. spawn_context_thread(run, name='hermes-pre-command').start()
  267. except RuntimeError as exc: # no thread available: this delivery is skipped, as the dispatcher skips
  268. logger.warning('pre_command delivery skipped: %s', exc)
  269. return
  270. await done
  271. def _pre_command(authority, ref, canonical, alias, arg):
  272. """Queue main's ``pre_command`` observer for a recognized command typed in a local session, fired
  273. here for every surface (classic CLI, Ink, Desktop), so no client loads plugin code to fire it; the
  274. delivery task, or None when not fired. One session's deliveries fire in arrival order; the hook
  275. dispatcher bounds each callback, and one still running for this session (hung) is skipped for its
  276. later commands, never run out of order, while other sessions' deliveries go on. ``surface`` and
  277. ``platform`` keep main's ``cli`` on every local surface (Ink and Desktop fired it through the CLI
  278. slash worker). During a turn every command that still runs fires, as main's CLI did, except the
  279. escape hatches."""
  280. from gateway.run import _profile_runtime_scope
  281. from gateway.session_local import authorize_local_source
  282. live = authority.sessions[ref.session_id]
  283. if ((canonical in _ESCAPE_HATCHES and authority._handle(ref).execution_state != 'idle')
  284. or authorize_local_source(authority.runner, live.source) is not True):
  285. return None
  286. home, key = Path(authority.profile_id), (authority.profile_id, ref.session_id)
  287. previous, pending = _PRE_COMMAND_TAILS.get(key, (None, 0))
  288. if previous is not None and previous.get_loop() is not asyncio.get_running_loop():
  289. previous, pending = None, 0 # a retired loop's delivery (an in-process restart) never resolves on this one
  290. if pending >= _PRE_COMMAND_PENDING:
  291. logger.warning('pre_command for /%s dropped: %d deliveries already queued for this session', canonical, pending)
  292. return None
  293. def fire(): # bound to the session it fires for: a key-less inject_message from the hook lands there
  294. from gateway.session_context import scoped_session_key
  295. from hermes_cli.plugins import fire_pre_command_hook
  296. with _profile_runtime_scope(home), scoped_session_key(live.route):
  297. fire_pre_command_hook(surface='cli', command=canonical, alias_used=alias, args_raw=arg,
  298. session_key=ref.session_id, platform='cli')
  299. async def deliver():
  300. if previous is not None:
  301. await asyncio.wait({previous})
  302. await _on_own_thread(fire)
  303. def settle(done):
  304. tail, count = _PRE_COMMAND_TAILS.get(key, (None, 0))
  305. if tail is done:
  306. _PRE_COMMAND_TAILS.pop(key)
  307. elif count:
  308. _PRE_COMMAND_TAILS[key] = (tail, count - 1)
  309. task = asyncio.ensure_future(deliver())
  310. _PRE_COMMAND_TAILS[key] = (task, pending + 1)
  311. task.add_done_callback(settle)
  312. return task
  313. async def _pre_command_before(authority, ref, canonical, alias, arg):
  314. """``pre_command`` before the gateway runs the command itself (``slash.exec``/``command.dispatch``)."""
  315. task = _pre_command(authority, ref, canonical, alias, arg)
  316. if task is not None:
  317. await asyncio.wait({task})
  318. async def observe_command(connection, ref, params):
  319. """``command.observe``: a recognized command the classic CLI or Ink runs itself on this session.
  320. ``pre_command`` fires here, in the session's profile, after the reply: the client never waits on a
  321. plugin and never loads one. Plain data only (the command name as typed and its arguments)."""
  322. from hermes_cli.commands import resolve_command
  323. from hermes_cli.profiles import profile_matches_home
  324. authority, actor = connection.authority, connection.actor
  325. authority.authorize(actor, ref, 'session:read')
  326. name, arg = _parse(params, True)
  327. if params.get('profile') and not profile_matches_home(params['profile'], Path(authority.profile_id)):
  328. raise RuntimeStoreError('profile_mismatch')
  329. definition = resolve_command(name)
  330. if definition is None:
  331. raise RuntimeStoreError('unsupported_command')
  332. return {'queued': _pre_command(authority, ref, definition.name, name.lower(), arg) is not None}
  333. @contextmanager
  334. def _accepting(before):
  335. """``before`` as the busy dispatcher's acceptance hook: a mid-run variant that refuses its arguments
  336. (``/goal <new text>``) never reaches it, so a refused command fires no ``pre_command``."""
  337. from gateway.run_busy import BUSY_ACCEPTED
  338. token = BUSY_ACCEPTED.set(before)
  339. try:
  340. yield
  341. finally:
  342. BUSY_ACCEPTED.reset(token)
  343. @contextmanager
  344. def _session_workspace(runner, source):
  345. """The session's frozen terminal policy (``TERMINAL_CWD`` = its launch cwd), so ``/diff``
  346. reads the caller's checkout instead of the gateway process's configured directory."""
  347. import json
  348. from agent.runtime_cwd import reset_session_cwd, set_session_cwd
  349. from gateway.session_policy import policy_for_source
  350. from tools.terminal_scope import reset_terminal_scope, set_terminal_scope
  351. policy = policy_for_source(runner, source)
  352. if policy is None:
  353. yield
  354. return
  355. cwd_token = set_session_cwd(policy.cwd)
  356. terminal_token = set_terminal_scope(json.loads(policy.terminal_json))
  357. try:
  358. yield
  359. finally:
  360. reset_terminal_scope(terminal_token)
  361. reset_session_cwd(cwd_token)
  362. async def execute_command(connection, ref, params, *, dispatch=False):
  363. authority, actor = connection.authority, connection.actor
  364. authority.authorize(actor, ref, 'session:read')
  365. name, arg = _parse(params, dispatch)
  366. from hermes_cli.commands import resolve_command
  367. from hermes_cli.profiles import profile_matches_home
  368. home = Path(authority.profile_id)
  369. if params.get('profile') and not profile_matches_home(params['profile'], home):
  370. raise RuntimeStoreError('profile_mismatch')
  371. from gateway.run import _profile_runtime_scope
  372. def resolve():
  373. with _profile_runtime_scope(home):
  374. return _resolve_alias(name, arg)
  375. name, arg = await asyncio.to_thread(resolve)
  376. definition = resolve_command(name)
  377. canonical = definition.name if definition else name
  378. verdict = command_verdict(canonical, arg) if definition else None
  379. fired = []
  380. async def before(): # pre_command, once, for a recognized command that is about to run
  381. if not fired:
  382. fired.append(canonical)
  383. await _pre_command_before(authority, ref, canonical, name.lower(), arg)
  384. if definition is not None and (tui := await _tui_read(authority, actor, ref, canonical, arg, before)) is not None:
  385. return tui
  386. runner_command = None
  387. if definition is None:
  388. def lookup():
  389. with _profile_runtime_scope(home):
  390. return _runner_command(name)
  391. runner_command = await asyncio.to_thread(lookup)
  392. capability = ('session:read' if verdict == 'read' else
  393. 'session:approve' if canonical in _APPROVAL_COMMANDS else
  394. 'session:control' if definition or runner_command else 'session:submit')
  395. authority.authorize(actor, ref, capability)
  396. live = authority.sessions[ref.session_id]
  397. if verdict == 'refused' or (verdict == 'control' and canonical in _OWNER_COMMANDS
  398. and ref.session_id in connection.subscriptions):
  399. raise RuntimeStoreError('unsupported_command', detail=REFUSAL_HINTS.get(canonical))
  400. from gateway.session_history_mount import is_history_mount, read_only
  401. if is_history_mount(live):
  402. raise read_only() # no policy or agent to run even a read command against
  403. from gateway.session_local import authorize_local_source
  404. if authorize_local_source(authority.runner, live.source) is not True:
  405. raise RuntimeStoreError('permission_denied')
  406. if capability != 'session:read':
  407. authority._require_admission_open()
  408. if definition is not None and (canonical in _INFO_READS or canonical in _OWNER_COMMANDS
  409. or authority._handle(ref).execution_state == 'idle'):
  410. await before() # mid-run the busy dispatcher fires it once it accepts the command (``BUSY_ACCEPTED``)
  411. if runner_command is not None:
  412. from gateway.plugin_command_choice import viewer_choices
  413. with (_profile_runtime_scope(home), _session_workspace(authority.runner, live.source),
  414. viewer_choices(live, ref.session_id)):
  415. output = await _run_runner_command(authority.runner, live, name, arg, *runner_command)
  416. return {'type': 'exec', 'output': _text(output)}
  417. if definition is None:
  418. def build(): # in the session's folder: its trusted project skills, as its catalog lists them
  419. with _profile_runtime_scope(home), _session_workspace(authority.runner, live.source):
  420. return _skill_directive(name, arg, live.route)
  421. return await asyncio.to_thread(build)
  422. if canonical in _INFO_READS:
  423. from gateway.session_info_reads import run_info_read
  424. return await run_info_read(authority, live, canonical)
  425. if canonical in _OWNER_COMMANDS:
  426. from gateway.session_cron_commands import run_cron
  427. return await run_cron(authority, arg)
  428. from gateway.platforms.base import MessageEvent
  429. from gateway.session_command_sink import capture
  430. typed = '/' + canonical + (' ' + arg if arg else '')
  431. event = MessageEvent(text=typed, source=live.source)
  432. runner = authority.runner
  433. prompt = None
  434. # Use the registry's existing busy contract, not a local approximation.
  435. with (_profile_runtime_scope(home), _session_workspace(runner, live.source), capture() as sink,
  436. _accepting(before)):
  437. if authority._handle(ref).execution_state != 'idle':
  438. output = await runner._dispatch_busy_slash_command(event, definition, live.route, live.source)
  439. elif canonical in _PROMPT_COMMANDS:
  440. await before() # a no-op unless the turn ended since the check above
  441. handled, output = await getattr(runner, '_hm_cmd_' + canonical.replace('-', '_'))(
  442. event, live.source, live.route)
  443. if not handled:
  444. prompt = event.text
  445. else:
  446. await before()
  447. if canonical == 'reasoning':
  448. from gateway.run_config_loaders import GatewayConfigLoadersMixin
  449. from gateway.session_setting_commands import commit_reasoning_command
  450. await commit_reasoning_command(authority, actor, ref,
  451. *GatewayConfigLoadersMixin._parse_reasoning_command_args(arg))
  452. handler = runner._command_handler_table((canonical,))[canonical]
  453. output = await handler(event)
  454. if canonical in _APPROVAL_COMMANDS:
  455. # Settle the answered prompt for every viewer now (`approval.settled`), as approval.respond does.
  456. handle = authority._handle(ref)
  457. live.controls.snapshot(ref.session_id, handle.execution_generation
  458. if handle.execution_state == 'running' else None)
  459. if canonical in _AUTOMATION_COMMANDS:
  460. from gateway.session_control_actions import publish
  461. publish(authority, ref.session_id)
  462. prompt = prompt if prompt is not None else sink.prompt
  463. if prompt:
  464. # The client submits the turn with its own durable input id; the gateway never does.
  465. notice = '\n'.join(filter(None, [*sink.notices, str(output or '')]))
  466. return {'type': 'send', 'message': prompt, 'display': sink.display or typed,
  467. **({'notice': notice} if notice else {})}
  468. return {'type': 'exec', 'output': '\n'.join(filter(None, [*sink.notices, _text(output)]))}
  469. def _text(output):
  470. """A handler reply as text: ``/blueprint``'s result object carries it in ``.text``."""
  471. return str(getattr(output, 'text', output) or '')