interactive-shell.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. /**
  2. * Interactive Shell Commands Extension
  3. *
  4. * Enables running interactive commands (vim, git rebase -i, htop, etc.)
  5. * with full terminal access. The TUI suspends while they run.
  6. *
  7. * Usage:
  8. * pi -e examples/extensions/interactive-shell.ts
  9. *
  10. * !vim file.txt # Auto-detected as interactive
  11. * !i any-command # Force interactive mode with !i prefix
  12. * !git rebase -i HEAD~3
  13. * !htop
  14. *
  15. * Configuration via environment variables:
  16. * INTERACTIVE_COMMANDS - Additional commands (comma-separated)
  17. * INTERACTIVE_EXCLUDE - Commands to exclude (comma-separated)
  18. *
  19. * Note: This only intercepts user `!` commands, not agent bash tool calls.
  20. * If the agent runs an interactive command, it will fail (which is fine).
  21. */
  22. import { spawnSync } from "node:child_process";
  23. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  24. // Default interactive commands - editors, pagers, git ops, TUIs
  25. const DEFAULT_INTERACTIVE_COMMANDS = [
  26. // Editors
  27. "vim",
  28. "nvim",
  29. "vi",
  30. "nano",
  31. "emacs",
  32. "pico",
  33. "micro",
  34. "helix",
  35. "hx",
  36. "kak",
  37. // Pagers
  38. "less",
  39. "more",
  40. "most",
  41. // Git interactive
  42. "git commit",
  43. "git rebase",
  44. "git merge",
  45. "git cherry-pick",
  46. "git revert",
  47. "git add -p",
  48. "git add --patch",
  49. "git add -i",
  50. "git add --interactive",
  51. "git stash -p",
  52. "git stash --patch",
  53. "git reset -p",
  54. "git reset --patch",
  55. "git checkout -p",
  56. "git checkout --patch",
  57. "git difftool",
  58. "git mergetool",
  59. // System monitors
  60. "htop",
  61. "top",
  62. "btop",
  63. "glances",
  64. // File managers
  65. "ranger",
  66. "nnn",
  67. "lf",
  68. "mc",
  69. "vifm",
  70. // Git TUIs
  71. "tig",
  72. "lazygit",
  73. "gitui",
  74. // Fuzzy finders
  75. "fzf",
  76. "sk",
  77. // Remote sessions
  78. "ssh",
  79. "telnet",
  80. "mosh",
  81. // Database clients
  82. "psql",
  83. "mysql",
  84. "sqlite3",
  85. "mongosh",
  86. "redis-cli",
  87. // Kubernetes/Docker
  88. "kubectl edit",
  89. "kubectl exec -it",
  90. "docker exec -it",
  91. "docker run -it",
  92. // Other
  93. "tmux",
  94. "screen",
  95. "ncdu",
  96. ];
  97. function getInteractiveCommands(): string[] {
  98. const additional =
  99. process.env.INTERACTIVE_COMMANDS?.split(",")
  100. .map((s) => s.trim())
  101. .filter(Boolean) ?? [];
  102. const excluded = new Set(process.env.INTERACTIVE_EXCLUDE?.split(",").map((s) => s.trim().toLowerCase()) ?? []);
  103. return [...DEFAULT_INTERACTIVE_COMMANDS, ...additional].filter((cmd) => !excluded.has(cmd.toLowerCase()));
  104. }
  105. function isInteractiveCommand(command: string): boolean {
  106. const trimmed = command.trim().toLowerCase();
  107. const commands = getInteractiveCommands();
  108. for (const cmd of commands) {
  109. const cmdLower = cmd.toLowerCase();
  110. // Match at start
  111. if (trimmed === cmdLower || trimmed.startsWith(`${cmdLower} `) || trimmed.startsWith(`${cmdLower}\t`)) {
  112. return true;
  113. }
  114. // Match after pipe: "cat file | less"
  115. const pipeIdx = trimmed.lastIndexOf("|");
  116. if (pipeIdx !== -1) {
  117. const afterPipe = trimmed.slice(pipeIdx + 1).trim();
  118. if (afterPipe === cmdLower || afterPipe.startsWith(`${cmdLower} `)) {
  119. return true;
  120. }
  121. }
  122. }
  123. return false;
  124. }
  125. export default function (pi: ExtensionAPI) {
  126. pi.on("user_bash", async (event, ctx) => {
  127. let command = event.command;
  128. let forceInteractive = false;
  129. // Check for !i prefix (command comes without the leading !)
  130. // The prefix parsing happens before this event, so we check if command starts with "i "
  131. if (command.startsWith("i ") || command.startsWith("i\t")) {
  132. forceInteractive = true;
  133. command = command.slice(2).trim();
  134. }
  135. const shouldBeInteractive = forceInteractive || isInteractiveCommand(command);
  136. if (!shouldBeInteractive) {
  137. return; // Let normal handling proceed
  138. }
  139. // No UI available (print mode, RPC, etc.)
  140. if (ctx.mode !== "tui") {
  141. return {
  142. result: { output: "(interactive commands require TUI)", exitCode: 1, cancelled: false, truncated: false },
  143. };
  144. }
  145. // Use ctx.ui.custom() to get TUI access, then run the command
  146. const exitCode = await ctx.ui.custom<number | null>((tui, _theme, _kb, done) => {
  147. // Stop TUI to release terminal
  148. tui.stop();
  149. // Clear screen
  150. process.stdout.write("\x1b[2J\x1b[H");
  151. // Run command with full terminal access
  152. const shell = process.env.SHELL || "/bin/sh";
  153. const result = spawnSync(shell, ["-c", command], {
  154. stdio: "inherit",
  155. env: process.env,
  156. });
  157. // Restart TUI
  158. tui.start();
  159. tui.requestRender(true);
  160. // Signal completion
  161. done(result.status);
  162. // Return empty component (immediately disposed since done() was called)
  163. return { render: () => [], invalidate: () => {} };
  164. });
  165. // Return result to prevent default bash handling
  166. const output =
  167. exitCode === 0
  168. ? "(interactive command completed successfully)"
  169. : `(interactive command exited with code ${exitCode})`;
  170. return {
  171. result: {
  172. output,
  173. exitCode: exitCode ?? 1,
  174. cancelled: false,
  175. truncated: false,
  176. },
  177. };
  178. });
  179. }