commands_completion.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. """prompt_toolkit completer + inline auto-suggest for slash commands. Kept out of
  2. :mod:`hermes_cli.commands` (which re-exports both classes) so the registry module stays
  3. prompt_toolkit-free for the gateway."""
  4. from __future__ import annotations
  5. import functools
  6. import logging
  7. import os
  8. import shutil
  9. import subprocess
  10. import time
  11. from collections.abc import Callable, Iterable, Mapping
  12. from itertools import chain
  13. from typing import Any, Dict, Optional, Tuple
  14. from prompt_toolkit.auto_suggest import AutoSuggest, Suggestion
  15. from prompt_toolkit.completion import Completer, Completion
  16. from hermes_cli.commands import COMMANDS, SUBCOMMANDS
  17. # (config-file signature, personalities) memo for /personality completion.
  18. _personalities_memo: Optional[
  19. tuple[tuple[Optional[str], Optional[int], Optional[int]], dict[str, Any]]
  20. ] = None
  21. def _personalities_from_cli_config() -> dict[str, Any]:
  22. """``available_personalities(load_cli_config())`` memoised on config path+signature:
  23. load_cli_config() is a full YAML parse + deep merge and the completer runs per keystroke.
  24. Falls back to a fresh load when the file cannot be stat'ed."""
  25. global _personalities_memo
  26. from cli import load_cli_config
  27. from hermes_cli.personality import available_personalities
  28. try:
  29. from hermes_cli.config import get_config_path
  30. from hermes_cli.config_backend import config_cache_version
  31. cfg_path = get_config_path()
  32. sig = (str(cfg_path), *config_cache_version(cfg_path))
  33. except Exception:
  34. sig = (None, None, None, None, None)
  35. if _personalities_memo is None or _personalities_memo[0] != sig:
  36. _personalities_memo = (sig, available_personalities(load_cli_config()))
  37. return _personalities_memo[1]
  38. def _file_size_label(path: str) -> str:
  39. """Return a compact human-readable file size, or '' on error."""
  40. try:
  41. size = os.path.getsize(path)
  42. except OSError:
  43. return ""
  44. if size < 1024:
  45. return f"{size}B"
  46. if size < 1024 ** 2:
  47. return f"{size / 1024:.0f}K"
  48. return f"{size / 1024 ** 2:.1f}M" if size < 1024 ** 3 else f"{size / 1024 ** 3:.1f}G"
  49. def _completion(text: str, word: str, display: str, meta) -> Completion:
  50. """``Completion`` replacing the *word* under the cursor."""
  51. return Completion(text, start_position=-len(word), display=display, display_meta=meta)
  52. def _prefix_completions(
  53. rows: Iterable[tuple[str, Any]], partial: str, *, skip_exact: bool = True):
  54. """A Completion per ``(name, meta)`` whose name starts with the case-folded *partial*."""
  55. lowered = partial.lower()
  56. for name, meta in rows:
  57. if name.startswith(lowered) and not (skip_exact and name == lowered):
  58. yield _completion(name, partial, name, meta)
  59. def _split_args(sub_text: str) -> tuple[list[str], str]:
  60. """``(completed_words, partial)``; a trailing space means a fresh word."""
  61. parts = sub_text.split()
  62. if sub_text.endswith(" ") or not parts:
  63. return parts, ""
  64. return parts[:-1], parts[-1]
  65. # Dynamic argument completers: (sub_text, sub_lower) -> Completion iterator
  66. def _quiet(gen_fn):
  67. """Generator decorator: any exception while producing completions just ends the stream."""
  68. @functools.wraps(gen_fn)
  69. def wrapper(*args):
  70. try:
  71. yield from gen_fn(*args)
  72. except Exception:
  73. return
  74. return wrapper
  75. @_quiet
  76. def _skin_completions(sub_text: str, sub_lower: str):
  77. """/skin — available skins."""
  78. from hermes_cli.skin_engine import list_skins
  79. rows = ((s["name"], s.get("description", "") or s.get("source", "")) for s in list_skins())
  80. yield from _prefix_completions(rows, sub_text)
  81. @_quiet
  82. def _personality_completions(sub_text: str, sub_lower: str):
  83. """/personality — ``none`` plus configured personalities."""
  84. from hermes_cli.personality import describe_personality
  85. personalities = _personalities_from_cli_config()
  86. rows = chain(
  87. [("none", "clear personality overlay")],
  88. ((name, describe_personality(prompt)) for name, prompt in personalities.items()))
  89. yield from _prefix_completions(rows, sub_text)
  90. @_quiet
  91. def _tools_completions(sub_text: str, sub_lower: str):
  92. """/tools — subcommand, then toolset / MCP-server names for enable|disable. Toolsets are
  93. offered only when the subcommand would change their state; MCP server prefixes always."""
  94. completed, partial = _split_args(sub_text)
  95. if not completed:
  96. yield from _prefix_completions(((s, None) for s in ("list", "disable", "enable")), partial)
  97. return
  98. subcommand = completed[0].lower()
  99. if subcommand not in ("enable", "disable"):
  100. return
  101. already = set(completed[1:])
  102. from hermes_cli.config import load_config_readonly
  103. from hermes_cli.tools_config import (
  104. CONFIGURABLE_TOOLSETS, _get_platform_tools, _get_plugin_toolset_keys)
  105. # Readonly loader: per keystroke and never mutates, so skip load_config()'s deepcopy.
  106. # Read-only path: the completer only inspects the config (toolset enable state + MCP server names) — it
  107. # never mutates it. Use the readonly loader so the per-keystroke completion doesn't pay the defensive
  108. # deepcopy (perf(agent) #74322 converted 29 call sites to the readonly loader; this per-keystroke site
  109. # was missed).
  110. config = load_config_readonly()
  111. enabled = _get_platform_tools(config, "cli", include_default_mcp_servers=False)
  112. mcp_servers = config.get("mcp_servers") or {}
  113. want_enabled = subcommand != "enable"
  114. rows = [(k, label) for k, label, _d in CONFIGURABLE_TOOLSETS]
  115. rows += [(k, "plugin toolset") for k in sorted(_get_plugin_toolset_keys())]
  116. rows = [(k, m) for k, m in rows if (k in enabled) == want_enabled]
  117. if isinstance(mcp_servers, dict):
  118. rows += [(f"{srv}:", f"MCP server '{srv}'") for srv in sorted(mcp_servers)]
  119. yield from _prefix_completions(
  120. ((k, m) for k, m in rows if k not in already), partial, skip_exact=False)
  121. def _handoff_completions(sub_text: str, sub_lower: str):
  122. """/handoff — connected gateway platforms, first arg only. A home channel is not required
  123. (often learned at runtime); the meta hints whether one is set."""
  124. completed, partial = _split_args(sub_text)
  125. if completed:
  126. return
  127. try:
  128. from gateway.config import load_gateway_config
  129. gw = load_gateway_config()
  130. platforms = gw.get_connected_platforms()
  131. except Exception:
  132. return
  133. for platform in platforms:
  134. name = platform.value
  135. if not name.startswith(partial.lower()):
  136. continue
  137. try:
  138. home = gw.get_home_channel(platform)
  139. except Exception:
  140. home = None
  141. home_name = getattr(home, "name", None) if home else None
  142. yield _completion(
  143. name, partial, name, f"→ {home_name}" if home_name else "send this session here")
  144. # base command -> (handler(sub_text, sub_lower), single_word_only). Single-word handlers only
  145. # run while the first argument is typed; /tools and /handoff parse multi-word input themselves.
  146. _DYNAMIC_COMPLETIONS: dict[str, tuple[Callable[..., Any], bool]] = {
  147. "/skin": (_skin_completions, True),
  148. "/personality": (_personality_completions, True),
  149. "/tools": (_tools_completions, False),
  150. "/handoff": (_handoff_completions, False)}
  151. def _extract_path_word(text: str) -> str | None:
  152. """Word under the cursor when it contains ``/`` and no ``://`` scheme (URLs aren't paths)."""
  153. word = text.rpartition(" ")[2]
  154. return word if word and "://" not in word and "/" in word else None
  155. def _dir_completions(
  156. expanded: str, word: str, limit: int, text_for: Callable[[str], str],
  157. want_dir: bool | None = None):
  158. """Directory-listing completions for *expanded*: entries matched case-insensitively on the
  159. typed basename (all entries after a trailing ``/``), sorted, limited to *limit*.
  160. ``text_for(full_path)`` builds the completion text (without trailing ``/``); *want_dir*
  161. restricts to dirs / files."""
  162. if expanded.endswith("/"):
  163. search_dir, prefix = expanded, ""
  164. else:
  165. search_dir, prefix = os.path.dirname(expanded) or ".", os.path.basename(expanded)
  166. try:
  167. entries = os.listdir(search_dir)
  168. except OSError:
  169. return
  170. prefix_lower = prefix.lower()
  171. count = 0
  172. for entry in sorted(entries):
  173. if not entry.lower().startswith(prefix_lower):
  174. continue
  175. full_path = os.path.join(search_dir, entry)
  176. is_dir = os.path.isdir(full_path)
  177. if want_dir is not None and want_dir != is_dir:
  178. continue
  179. if count >= limit:
  180. break
  181. suffix = "/" if is_dir else ""
  182. yield _completion(
  183. text_for(full_path) + suffix, word, entry + suffix,
  184. "dir" if is_dir else _file_size_label(full_path))
  185. count += 1
  186. def _path_completions(word: str, limit: int = 30):
  187. """Path completions for *word*, keeping the user's style (~, absolute, relative)."""
  188. if word.startswith("~"):
  189. text_for = lambda fp: "~/" + os.path.relpath(fp, os.path.expanduser("~"))
  190. else:
  191. text_for = str if os.path.isabs(word) else os.path.relpath
  192. yield from _dir_completions(os.path.expanduser(word), word, limit, text_for)
  193. _STATIC_CONTEXT_REFS = (
  194. ("@diff", "Git working tree diff"),
  195. ("@staged", "Git staged diff"),
  196. ("@file:", "Attach a file"),
  197. ("@folder:", "Attach a folder"),
  198. ("@git:", "Git log with diffs (e.g. @git:5)"),
  199. ("@url:", "Fetch web content"))
  200. def _score_path(filepath: str, query: str) -> int:
  201. """Score a file path against a fuzzy query. Higher = better; 0 = no match; 1 = empty query."""
  202. if not query:
  203. return 1
  204. lower_file = os.path.basename(filepath).lower()
  205. lower_q = query.lower()
  206. for score, hit in ((100, lower_file == lower_q), (80, lower_file.startswith(lower_q)),
  207. (60, lower_q in lower_file), (40, lower_q in filepath.lower())):
  208. if hit:
  209. return score
  210. # Abbreviation: query chars in order in the filename ("fo" ~ "file_operations"); bonus when
  211. # >= half land on word boundaries (_-./).
  212. qi = boundary_hits = 0
  213. prev = "_" # treat start as boundary
  214. for c in lower_file:
  215. if qi < len(lower_q) and c == lower_q[qi]:
  216. boundary_hits += prev in "_-./"
  217. qi += 1
  218. prev = c
  219. return 0 if qi < len(lower_q) else 35 if boundary_hits >= len(lower_q) * 0.5 else 25
  220. class SlashCommandCompleter(Completer):
  221. """Autocomplete for built-in slash commands, subcommands, and skill commands."""
  222. # Bare-run picker commands get no trailing space: "/model " would block the picker.
  223. _PICKER_COMMANDS = frozenset({"model", "skin", "personality"})
  224. # Module-level helpers exposed as staticmethods for existing callers/tests.
  225. _extract_path_word = staticmethod(_extract_path_word)
  226. _path_completions = staticmethod(_path_completions)
  227. _personality_completions = staticmethod(_personality_completions)
  228. _tools_completions = staticmethod(_tools_completions)
  229. def __init__(
  230. self,
  231. skill_commands_provider: Callable[[], Mapping[str, dict[str, Any]]] | None = None,
  232. command_filter: Callable[[str], bool] | None = None,
  233. skill_bundles_provider: Callable[[], Mapping[str, dict[str, Any]]] | None = None,
  234. plugin_commands_provider: Callable[[], Mapping[str, str] | None] | None = None) -> None:
  235. self._skill_commands_provider = skill_commands_provider
  236. self._plugin_commands_provider = plugin_commands_provider
  237. self._command_filter = command_filter
  238. self._skill_bundles_provider = skill_bundles_provider
  239. # Cached project file list for fuzzy @ completions
  240. self._file_cache: list[str] = []
  241. self._file_cache_time: float = 0.0
  242. self._file_cache_cwd: str = ""
  243. def _command_allowed(self, slash_command: str) -> bool:
  244. try:
  245. return self._command_filter is None or bool(self._command_filter(slash_command))
  246. except Exception:
  247. return True
  248. @staticmethod
  249. def _call_provider(provider) -> Mapping[str, dict[str, Any]]:
  250. try:
  251. return (provider() if provider is not None else None) or {}
  252. except Exception:
  253. return {}
  254. def _iter_skill_commands(self) -> Mapping[str, dict[str, Any]]:
  255. return self._call_provider(self._skill_commands_provider)
  256. @staticmethod
  257. def _normalize_skill_token(token: str) -> str:
  258. """Canonical hyphenated /slug; mirrors resolve_skill_command_key() (``_`` == ``-``)."""
  259. return "/" + token.lstrip("/").replace("_", "-").lower()
  260. def _is_skill_command(self, token: str) -> bool:
  261. from agent.skill_commands import resolve_slash_key
  262. return resolve_slash_key(token.lstrip("/"), self._iter_skill_commands()) is not None
  263. def _stacked_skill_completions(self, text: str):
  264. """Skill-command completions for stacked invocations (``/skill-a /skill-b do XYZ``): only
  265. while every completed token is a distinct skill command, the cap is not reached, and the
  266. current word starts with ``/`` — instruction text must never get skill suggestions."""
  267. try:
  268. from agent.skill_commands import _MAX_STACKED_SKILLS as _cap
  269. except Exception:
  270. _cap = 5
  271. completed, current_word = _split_args(text)
  272. skill_cmds = self._iter_skill_commands()
  273. from agent.skill_commands import resolve_slash_key
  274. seen: set[str] = set()
  275. for token in completed:
  276. key = resolve_slash_key(token.lstrip("/"), skill_cmds)
  277. if key is None or key in seen:
  278. return
  279. seen.add(key)
  280. if len(seen) >= _cap or not current_word.startswith("/"):
  281. return # a bare space after the chain may start the instruction
  282. word_key = self._normalize_skill_token(current_word)
  283. for cmd, info in skill_cmds.items():
  284. if cmd in seen or not self._normalize_skill_token(cmd).startswith(word_key):
  285. continue
  286. # Exact match: trailing space keeps the dropdown open for the next stacked token.
  287. yield _completion(
  288. f"{cmd} " if self._normalize_skill_token(cmd) == word_key else cmd, current_word, cmd,
  289. f"⚡ {info.get('description', 'Skill command')}")
  290. @staticmethod
  291. def _completion_text(cmd_name: str, word: str) -> str:
  292. """Replacement text; exact matches get a trailing space (else prompt_toolkit hides the
  293. menu on a no-op replacement) — except _PICKER_COMMANDS."""
  294. exact = cmd_name == word and cmd_name not in SlashCommandCompleter._PICKER_COMMANDS
  295. return f"{cmd_name} " if exact else cmd_name
  296. @staticmethod
  297. def _extract_context_word(text: str) -> str | None:
  298. """Extract a bare ``@`` token for context reference completions."""
  299. word = text.rpartition(" ")[2]
  300. return word if word.startswith("@") else None
  301. def _context_completions(self, word: str, limit: int = 30):
  302. """@ completions: static refs, ``@file:``/``@folder:`` paths, else fuzzy project files."""
  303. lowered = word.lower()
  304. for candidate, meta in _STATIC_CONTEXT_REFS:
  305. if candidate.startswith(lowered) and candidate != lowered:
  306. yield _completion(candidate, word, candidate, meta)
  307. # Bare `@file` / `@folder` (no colon yet) already opens the picker.
  308. for prefix in ("@file:", "@folder:"):
  309. bare = prefix[:-1]
  310. if word == bare or word.startswith(prefix):
  311. expanded = os.path.expanduser("" if word == bare else word[len(prefix):])
  312. if not expanded or expanded == ".":
  313. expanded = "./"
  314. # `@folder:` = dirs only, `@file:` = files only (else `@folder:` lists dotfiles).
  315. yield from _dir_completions(
  316. expanded, word, limit, lambda fp: f"{prefix}{os.path.relpath(fp)}",
  317. want_dir=(prefix == "@folder:"))
  318. return
  319. yield from self._fuzzy_file_completions(word, word[1:], limit)
  320. def _get_project_files(self) -> list[str]:
  321. """Cached project file list (5s TTL); rg (gitignore-aware) then fd."""
  322. cwd = os.getcwd()
  323. now = time.monotonic()
  324. if self._file_cache and self._file_cache_cwd == cwd and now - self._file_cache_time < 5.0:
  325. return self._file_cache
  326. files: list[str] = []
  327. for cmd in (
  328. ["rg", "--files", "--sortr=modified", cwd],
  329. ["rg", "--files", cwd],
  330. ["fd", "--type", "f", "--base-directory", cwd]):
  331. if not shutil.which(cmd[0]):
  332. continue
  333. try:
  334. proc = subprocess.run(
  335. cmd, capture_output=True, text=True, timeout=2,
  336. cwd=cwd, encoding="utf-8", errors="replace", check=False)
  337. except (subprocess.TimeoutExpired, OSError):
  338. continue
  339. if proc.returncode != 0 or not proc.stdout.strip():
  340. continue
  341. for p in proc.stdout.strip().split("\n")[:5000]:
  342. try:
  343. files.append(os.path.relpath(p, cwd) if os.path.isabs(p) else p)
  344. except ValueError:
  345. continue # Windows: relpath raises across mounts/drive letters
  346. break
  347. self._file_cache, self._file_cache_time, self._file_cache_cwd = files, now, cwd
  348. return files
  349. def _fuzzy_file_completions(self, word: str, query: str, limit: int = 20):
  350. """Fuzzy file completions for bare @query (no query = recently modified files)."""
  351. files = self._get_project_files()
  352. if query:
  353. scored = sorted(
  354. ((s, fp) for fp in files if (s := _score_path(fp, query)) > 0),
  355. key=lambda x: (-x[0], x[1]))
  356. files = [fp for _, fp in scored]
  357. for fp in files[:limit]:
  358. is_dir = fp.endswith("/")
  359. meta = "dir" if is_dir else _file_size_label(os.path.join(os.getcwd(), fp))
  360. if query:
  361. meta = f"{fp} {meta}" if meta else fp
  362. yield _completion(
  363. f"@{'folder' if is_dir else 'file'}:{fp}", word, os.path.basename(fp), meta)
  364. def get_completions(self, document, complete_event):
  365. text = document.text_before_cursor
  366. if not text.startswith("/"):
  367. ctx_word = self._extract_context_word(text)
  368. path_word = _extract_path_word(text)
  369. if ctx_word is not None:
  370. yield from self._context_completions(ctx_word)
  371. elif path_word is not None:
  372. yield from _path_completions(path_word)
  373. return
  374. parts = text.split(maxsplit=1)
  375. base_cmd = parts[0].lower()
  376. if len(parts) > 1 or text.endswith(" "):
  377. # Completing arguments: base command already typed.
  378. sub_text = parts[1] if len(parts) > 1 else ""
  379. first_arg = " " not in sub_text
  380. # Stacked slash-skill chain (see split_stacked_skill_commands in agent/skill_commands).
  381. if self._is_skill_command(base_cmd):
  382. yield from self._stacked_skill_completions(text)
  383. return
  384. handler, single_word = _DYNAMIC_COMPLETIONS.get(base_cmd, (None, False))
  385. if handler is not None and (not single_word or first_arg):
  386. yield from handler(sub_text, sub_text.lower())
  387. elif first_arg and base_cmd in SUBCOMMANDS and self._command_allowed(base_cmd):
  388. yield from _prefix_completions(
  389. ((s, None) for s in SUBCOMMANDS[base_cmd]), sub_text)
  390. return
  391. word = text[1:]
  392. def _cmd_completion(cmd_name: str, meta: str):
  393. return _completion(self._completion_text(cmd_name, word), word, f"/{cmd_name}", meta)
  394. for cmd, desc in COMMANDS.items():
  395. if self._command_allowed(cmd) and cmd[1:].startswith(word):
  396. yield _cmd_completion(cmd[1:], desc)
  397. for cmd, info in self._call_provider(self._skill_bundles_provider).items():
  398. if cmd[1:].startswith(word):
  399. skill_count = len(info.get("skills", []))
  400. yield _cmd_completion(
  401. cmd[1:], f"▣ {info.get('description', 'Skill bundle')} ({skill_count} skills)")
  402. for cmd, info in self._iter_skill_commands().items():
  403. if cmd[1:].startswith(word):
  404. yield _cmd_completion(cmd[1:], f"⚡ {info.get('description', 'Skill command')}")
  405. for cmd_name, desc in self._plugin_commands().items():
  406. if cmd_name.startswith(word):
  407. yield _cmd_completion(cmd_name, f"🔌 {desc or 'Plugin command'}")
  408. def _plugin_commands(self) -> Mapping[str, str]:
  409. """``{name: description}``: the provider's (the classic CLI asks its gateway), else, when it
  410. has none (None), this process's plugin registry."""
  411. try:
  412. found = self._plugin_commands_provider() if self._plugin_commands_provider else None
  413. if found is None:
  414. from hermes_cli.plugins import get_plugin_commands
  415. found = {name: info.get("description", "") for name, info in get_plugin_commands().items()}
  416. return found
  417. except Exception: # a plugin's registry or the gateway call must never break typing
  418. logging.getLogger(__name__).debug("plugin command completion unavailable", exc_info=True)
  419. return {}
  420. class SlashCommandAutoSuggest(AutoSuggest):
  421. """Inline ghost-text for slash commands and subcommands; history fallback for other input."""
  422. def __init__(
  423. self, history_suggest: AutoSuggest | None = None,
  424. completer: SlashCommandCompleter | None = None) -> None:
  425. self._history = history_suggest
  426. self._completer = completer # Reuse its model cache
  427. def _allowed(self, cmd: str) -> bool:
  428. return self._completer is None or self._completer._command_allowed(cmd)
  429. def _history_suggestion(self, buffer, document):
  430. return self._history.get_suggestion(buffer, document) if self._history else None
  431. def get_suggestion(self, buffer, document):
  432. text = document.text_before_cursor
  433. if not text.startswith("/"):
  434. return self._history_suggestion(buffer, document)
  435. parts = text.split(maxsplit=1)
  436. base_cmd = parts[0].lower()
  437. if len(parts) == 1 and not text.endswith(" "):
  438. # Still typing the name: prefer the SHORTEST match so /he ghosts "lp", not "artbeat".
  439. word = text[1:].lower()
  440. for cmd in sorted(COMMANDS, key=len):
  441. cmd_name = cmd[1:]
  442. if self._allowed(cmd) and cmd_name.startswith(word) and cmd_name != word:
  443. return Suggestion(cmd_name[len(word):])
  444. return None
  445. sub_text = parts[1] if len(parts) > 1 else ""
  446. sub_lower = sub_text.lower()
  447. # Stacked skill chain: ghost the rest of the next skill name, else history fallback.
  448. if self._completer is not None and self._completer._is_skill_command(base_cmd):
  449. for completion in self._completer._stacked_skill_completions(text):
  450. start = completion.start_position
  451. remainder = completion.text[-start:] if start else completion.text
  452. if remainder.strip():
  453. return Suggestion(remainder)
  454. if not self._allowed(base_cmd):
  455. return None
  456. if " " not in sub_text:
  457. for sub in SUBCOMMANDS.get(base_cmd, ()):
  458. if sub.startswith(sub_lower) and sub != sub_lower:
  459. return Suggestion(sub[len(sub_text):])
  460. return self._history_suggestion(buffer, document)
  461. def cli_slash_completer(cli):
  462. """The classic CLI prompt's slash completer; on a gateway session its skills and plugin commands are
  463. the gateway's (``commands.catalog``), so completing loads no plugin in the CLI process."""
  464. from cli import _session_skill_commands, get_skill_bundles
  465. from hermes_cli import gateway_plugin_commands
  466. return SlashCommandCompleter(
  467. skill_commands_provider=lambda: _session_skill_commands(cli), command_filter=cli._command_available,
  468. skill_bundles_provider=lambda: get_skill_bundles(), plugin_commands_provider=lambda: gateway_plugin_commands.names(cli))