bundles.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. """Implementation of the ``hermes bundles`` CLI subcommand."""
  2. from __future__ import annotations
  3. import sys
  4. from typing import List
  5. from rich.console import Console
  6. from rich.table import Table
  7. from hermes_cli.cli_output import line_input
  8. from agent.skill_bundles import (
  9. _bundles_dir, delete_bundle, get_bundle, list_bundles, reload_bundles, save_bundle, scan_bundles
  10. )
  11. def _console() -> Console:
  12. return Console()
  13. def _fail(c: Console, message: str) -> None:
  14. c.print(message)
  15. sys.exit(1)
  16. def _cmd_list(args) -> None:
  17. c = _console()
  18. bundles = list_bundles()
  19. if not bundles:
  20. c.print(
  21. f"[dim]No bundles installed yet. Create one with:\n"
  22. f" hermes bundles create <name> --skill skill1 --skill skill2[/]\n"
  23. f"Bundles directory: [bold]{_bundles_dir()}[/]")
  24. return
  25. table = Table(title=f"Skill Bundles ({len(bundles)})", show_lines=False)
  26. table.add_column("Command", style="bold cyan")
  27. table.add_column("Name", style="bold")
  28. table.add_column("Skills", justify="right")
  29. table.add_column("Description")
  30. for info in bundles:
  31. table.add_row(
  32. f"/{info['slug']}",
  33. info["name"],
  34. str(len(info.get("skills", []))),
  35. info.get("description") or "")
  36. c.print(table)
  37. c.print(f"\n[dim]Bundles directory: {_bundles_dir()}[/]")
  38. def _cmd_show(args) -> None:
  39. c = _console()
  40. info = get_bundle(args.name)
  41. if not info:
  42. _fail(c, f"[bold red]Bundle {args.name!r} not found.[/]")
  43. c.print(f"[bold cyan]/{info['slug']}[/] [bold]{info['name']}[/]")
  44. if info.get("description"):
  45. c.print(f" {info['description']}")
  46. c.print(f" [dim]File: {info['path']}[/]")
  47. c.print(f" [bold]Skills ({len(info['skills'])}):[/]")
  48. for s in info["skills"]:
  49. c.print(f" - {s}")
  50. if info.get("instruction"):
  51. c.print(f" [bold]Instruction:[/]\n {info['instruction']}")
  52. def _cmd_create(args) -> None:
  53. c = _console()
  54. name = args.name
  55. skills: list[str] = list(args.skill or [])
  56. if not skills:
  57. # Interactive prompt for skills if none were passed on the CLI.
  58. c.print(
  59. "[dim]No skills passed via --skill. Enter one skill name per line.\n"
  60. "Submit an empty line to finish.[/]")
  61. try:
  62. while True:
  63. line = line_input("skill> ").strip()
  64. if not line:
  65. break
  66. skills.append(line)
  67. except (EOFError, KeyboardInterrupt):
  68. _fail(c, "\n[yellow]Cancelled.[/]")
  69. if not skills:
  70. _fail(c, "[bold red]A bundle must reference at least one skill.[/]")
  71. try:
  72. path = save_bundle(
  73. name, skills, description=args.description or "", instruction=args.instruction or "",
  74. overwrite=bool(args.force))
  75. except FileExistsError as exc:
  76. _fail(c, f"[bold red]{exc}[/]\n[dim]Pass --force to overwrite.[/]")
  77. except ValueError as exc:
  78. _fail(c, f"[bold red]{exc}[/]")
  79. c.print(f"[bold green]Created bundle:[/] {path}")
  80. info = get_bundle(name)
  81. if info:
  82. c.print(
  83. f" Invoke with: [bold cyan]/{info['slug']}[/] "
  84. f"(loads {len(info['skills'])} skills)")
  85. def _cmd_delete(args) -> None:
  86. c = _console()
  87. try:
  88. path = delete_bundle(args.name)
  89. except FileNotFoundError as exc:
  90. _fail(c, f"[bold red]{exc}[/]")
  91. c.print(f"[bold green]Deleted bundle:[/] {path}")
  92. def _cmd_reload(args) -> None:
  93. c = _console()
  94. diff = reload_bundles()
  95. if diff["added"]:
  96. c.print(f"[bold green]Added ({len(diff['added'])}):[/]")
  97. for entry in diff["added"]:
  98. c.print(f" + {entry['name']} — {entry.get('description', '')}")
  99. if diff["removed"]:
  100. c.print(f"[bold red]Removed ({len(diff['removed'])}):[/]")
  101. for entry in diff["removed"]:
  102. c.print(f" - {entry['name']}")
  103. if not diff["added"] and not diff["removed"]:
  104. c.print(f"[dim]No changes. {diff['total']} bundle(s) loaded.[/]")
  105. else:
  106. c.print(f"[dim]Total bundles now: {diff['total']}[/]")
  107. def register_cli(subparser) -> None:
  108. """Build the ``hermes bundles`` argparse tree (called from hermes_cli/main.py, which owns the
  109. top-level subparser)."""
  110. subs = subparser.add_subparsers(dest="bundles_action")
  111. p_list = subs.add_parser("list", help="List installed skill bundles")
  112. p_list.set_defaults(_bundles_handler=_cmd_list)
  113. p_show = subs.add_parser("show", help="Show one bundle's contents")
  114. p_show.add_argument("name", help="Bundle name")
  115. p_show.set_defaults(_bundles_handler=_cmd_show)
  116. p_create = subs.add_parser(
  117. "create",
  118. help="Create a new skill bundle",
  119. description=(
  120. "Create a new bundle. Skills can be passed via --skill (repeat for "
  121. "multiple) or entered interactively when omitted."))
  122. p_create.add_argument("name", help="Bundle name (becomes the /slash command)")
  123. p_create.add_argument(
  124. "--skill", "-s", action="append", default=[],
  125. help="Skill name to include (repeat for multiple)")
  126. p_create.add_argument(
  127. "--description", "-d", default="",
  128. help="Human-readable description shown in /help and `hermes bundles list`")
  129. p_create.add_argument(
  130. "--instruction", "-i", default="",
  131. help="Extra guidance prepended to the loaded skill content")
  132. p_create.add_argument(
  133. "--force", "-f", action="store_true", help="Overwrite an existing bundle with the same name"
  134. )
  135. p_create.set_defaults(_bundles_handler=_cmd_create)
  136. p_delete = subs.add_parser("delete", help="Delete a skill bundle")
  137. p_delete.add_argument("name", help="Bundle name")
  138. p_delete.set_defaults(_bundles_handler=_cmd_delete)
  139. p_reload = subs.add_parser("reload", help="Re-scan the bundles directory and report changes")
  140. p_reload.set_defaults(_bundles_handler=_cmd_reload)
  141. # Ensure a fresh scan when any bundles subcommand runs.
  142. scan_bundles()
  143. def bundles_command(args) -> None:
  144. """Dispatch ``hermes bundles <subcommand>`` to the right handler."""
  145. handler = getattr(args, "_bundles_handler", None) or _cmd_list # no subcommand → list
  146. handler(args)