inline-bash.ts 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * Inline Bash Extension - expands inline bash commands in user prompts.
  3. *
  4. * Start pi with this extension:
  5. * pi -e ./examples/extensions/inline-bash.ts
  6. *
  7. * Then type prompts with inline bash:
  8. * What's in !{pwd}?
  9. * The current branch is !{git branch --show-current} and status: !{git status --short}
  10. * My node version is !{node --version}
  11. *
  12. * The !{command} patterns are executed and replaced with their output before
  13. * the prompt is sent to the agent.
  14. *
  15. * Note: Regular !command syntax (whole-line bash) is preserved and works as before.
  16. */
  17. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  18. export default function (pi: ExtensionAPI) {
  19. const PATTERN = /!\{([^}]+)\}/g;
  20. const TIMEOUT_MS = 30000;
  21. pi.on("input", async (event, ctx) => {
  22. const text = event.text;
  23. // Don't process if it's a whole-line bash command (starts with !)
  24. // This preserves the existing !command behavior
  25. if (text.trimStart().startsWith("!") && !text.trimStart().startsWith("!{")) {
  26. return { action: "continue" };
  27. }
  28. // Check if there are any inline bash patterns
  29. if (!PATTERN.test(text)) {
  30. return { action: "continue" };
  31. }
  32. // Reset regex state after test()
  33. PATTERN.lastIndex = 0;
  34. let result = text;
  35. const expansions: Array<{ command: string; output: string; error?: string }> = [];
  36. // Find all matches first (to avoid issues with replacing while iterating)
  37. const matches: Array<{ full: string; command: string }> = [];
  38. let match = PATTERN.exec(text);
  39. while (match) {
  40. matches.push({ full: match[0], command: match[1] });
  41. match = PATTERN.exec(text);
  42. }
  43. // Execute each command and collect results
  44. for (const { full, command } of matches) {
  45. try {
  46. const bashResult = await pi.exec("bash", ["-c", command], {
  47. timeout: TIMEOUT_MS,
  48. });
  49. const output = bashResult.stdout || bashResult.stderr || "";
  50. const trimmed = output.trim();
  51. if (bashResult.code !== 0 && bashResult.stderr) {
  52. expansions.push({
  53. command,
  54. output: trimmed,
  55. error: `exit code ${bashResult.code}`,
  56. });
  57. } else {
  58. expansions.push({ command, output: trimmed });
  59. }
  60. result = result.replace(full, trimmed);
  61. } catch (err) {
  62. const errorMsg = err instanceof Error ? err.message : String(err);
  63. expansions.push({ command, output: "", error: errorMsg });
  64. result = result.replace(full, `[error: ${errorMsg}]`);
  65. }
  66. }
  67. // Show what was expanded (if UI available)
  68. if (ctx.hasUI && expansions.length > 0) {
  69. const summary = expansions
  70. .map((e) => {
  71. const status = e.error ? ` (${e.error})` : "";
  72. const preview = e.output.length > 50 ? `${e.output.slice(0, 50)}...` : e.output;
  73. return `!{${e.command}}${status} -> "${preview}"`;
  74. })
  75. .join("\n");
  76. ctx.ui.notify(`Expanded ${expansions.length} inline command(s):\n${summary}`, "info");
  77. }
  78. return { action: "transform", text: result, images: event.images };
  79. });
  80. }