commands.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * Commands Extension
  3. *
  4. * Demonstrates the pi.getCommands() API by providing a /commands command
  5. * that lists all available slash commands in the current session.
  6. *
  7. * Usage:
  8. * 1. Copy this file to ~/.pi/agent/extensions/ or your project's .pi/extensions/
  9. * 2. Use /commands to see available commands
  10. * 3. Use /commands extensions to filter by source
  11. */
  12. import type { ExtensionAPI, SlashCommandInfo } from "@earendil-works/pi-coding-agent";
  13. export default function commandsExtension(pi: ExtensionAPI) {
  14. pi.registerCommand("commands", {
  15. description: "List available slash commands",
  16. getArgumentCompletions: (prefix) => {
  17. const sources = ["extension", "prompt", "skill"];
  18. const filtered = sources.filter((s) => s.startsWith(prefix));
  19. return filtered.length > 0 ? filtered.map((s) => ({ value: s, label: s })) : null;
  20. },
  21. handler: async (args, ctx) => {
  22. const commands = pi.getCommands();
  23. const sourceFilter = args.trim() as "extension" | "prompt" | "skill" | "";
  24. // Filter by source if specified
  25. const filtered = sourceFilter ? commands.filter((c) => c.source === sourceFilter) : commands;
  26. if (filtered.length === 0) {
  27. ctx.ui.notify(sourceFilter ? `No ${sourceFilter} commands found` : "No commands found", "info");
  28. return;
  29. }
  30. // Build selection items grouped by source
  31. const formatCommand = (cmd: SlashCommandInfo): string => {
  32. const desc = cmd.description ? ` - ${cmd.description}` : "";
  33. return `/${cmd.name}${desc}`;
  34. };
  35. const items: string[] = [];
  36. const sources: Array<{ key: "extension" | "prompt" | "skill"; label: string }> = [
  37. { key: "extension", label: "Extensions" },
  38. { key: "prompt", label: "Prompts" },
  39. { key: "skill", label: "Skills" },
  40. ];
  41. for (const { key, label } of sources) {
  42. const cmds = filtered.filter((c) => c.source === key);
  43. if (cmds.length > 0) {
  44. items.push(`--- ${label} ---`);
  45. items.push(...cmds.map(formatCommand));
  46. }
  47. }
  48. // Show in a selector (user can scroll and see all commands)
  49. const selected = await ctx.ui.select("Available Commands", items);
  50. // If user selected a command (not a header), offer to show its path
  51. if (selected && !selected.startsWith("---")) {
  52. const cmdName = selected.split(" - ")[0].slice(1); // Remove leading /
  53. const cmd = commands.find((c) => c.name === cmdName);
  54. if (cmd?.sourceInfo.path) {
  55. const showPath = await ctx.ui.confirm(cmd.name, `View source path?\n${cmd.sourceInfo.path}`);
  56. if (showPath) {
  57. ctx.ui.notify(cmd.sourceInfo.path, "info");
  58. }
  59. }
  60. }
  61. },
  62. });
  63. }