built-in-tool-renderer.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /**
  2. * Built-in Tool Renderer Example - Custom rendering for built-in tools
  3. *
  4. * Demonstrates how to override the rendering of built-in tools (read, bash,
  5. * edit, write) without changing their behavior. Each tool is re-registered
  6. * with the same name, delegating execution to the original implementation
  7. * while providing compact custom renderCall/renderResult functions.
  8. *
  9. * This is useful for users who prefer more concise tool output, or who want
  10. * to highlight specific information (e.g., showing only the diff stats for
  11. * edit, or just the exit code for bash).
  12. *
  13. * How it works:
  14. * - registerTool() with the same name as a built-in replaces it entirely
  15. * - We create instances of the original tools via createReadTool(), etc.
  16. * and delegate execute() to them
  17. * - renderCall() controls what's shown when the tool is invoked
  18. * - renderResult() controls what's shown after execution completes
  19. * - renderShell: "self" lets a tool render its own outer shell instead of
  20. * using the default boxed shell from ToolExecutionComponent
  21. * - The `expanded` flag in renderResult indicates whether the user has
  22. * toggled the tool output open (via ctrl+e or clicking)
  23. *
  24. * Usage:
  25. * pi -e ./built-in-tool-renderer.ts
  26. */
  27. import type { BashToolDetails, EditToolDetails, ExtensionAPI, ReadToolDetails } from "@earendil-works/pi-coding-agent";
  28. import { createBashTool, createEditTool, createReadTool, createWriteTool } from "@earendil-works/pi-coding-agent";
  29. import { Text } from "@earendil-works/pi-tui";
  30. export default function (pi: ExtensionAPI) {
  31. const cwd = process.cwd();
  32. // --- Read tool: show path and line count ---
  33. const originalRead = createReadTool(cwd);
  34. pi.registerTool({
  35. name: "read",
  36. label: "read",
  37. description: originalRead.description,
  38. parameters: originalRead.parameters,
  39. async execute(toolCallId, params, signal, onUpdate) {
  40. return originalRead.execute(toolCallId, params, signal, onUpdate);
  41. },
  42. renderCall(args, theme, _context) {
  43. let text = theme.fg("toolTitle", theme.bold("read "));
  44. text += theme.fg("accent", args.path);
  45. if (args.offset || args.limit) {
  46. const parts: string[] = [];
  47. if (args.offset) parts.push(`offset=${args.offset}`);
  48. if (args.limit) parts.push(`limit=${args.limit}`);
  49. text += theme.fg("dim", ` (${parts.join(", ")})`);
  50. }
  51. return new Text(text, 0, 0);
  52. },
  53. renderResult(result, { expanded, isPartial }, theme, _context) {
  54. if (isPartial) return new Text(theme.fg("warning", "Reading..."), 0, 0);
  55. const details = result.details as ReadToolDetails | undefined;
  56. const content = result.content[0];
  57. if (content?.type === "image") {
  58. return new Text(theme.fg("success", "Image loaded"), 0, 0);
  59. }
  60. if (content?.type !== "text") {
  61. return new Text(theme.fg("error", "No content"), 0, 0);
  62. }
  63. const lineCount = content.text.split("\n").length;
  64. let text = theme.fg("success", `${lineCount} lines`);
  65. if (details?.truncation?.truncated) {
  66. text += theme.fg("warning", ` (truncated from ${details.truncation.totalLines})`);
  67. }
  68. if (expanded) {
  69. const lines = content.text.split("\n").slice(0, 15);
  70. for (const line of lines) {
  71. text += `\n${theme.fg("dim", line)}`;
  72. }
  73. if (lineCount > 15) {
  74. text += `\n${theme.fg("muted", `... ${lineCount - 15} more lines`)}`;
  75. }
  76. }
  77. return new Text(text, 0, 0);
  78. },
  79. });
  80. // --- Bash tool: show command and exit code ---
  81. const originalBash = createBashTool(cwd);
  82. pi.registerTool({
  83. name: "bash",
  84. label: "bash",
  85. description: originalBash.description,
  86. parameters: originalBash.parameters,
  87. async execute(toolCallId, params, signal, onUpdate) {
  88. return originalBash.execute(toolCallId, params, signal, onUpdate);
  89. },
  90. renderCall(args, theme, _context) {
  91. let text = theme.fg("toolTitle", theme.bold("$ "));
  92. const cmd = args.command.length > 80 ? `${args.command.slice(0, 77)}...` : args.command;
  93. text += theme.fg("accent", cmd);
  94. if (args.timeout) {
  95. text += theme.fg("dim", ` (timeout: ${args.timeout}s)`);
  96. }
  97. return new Text(text, 0, 0);
  98. },
  99. renderResult(result, { expanded, isPartial }, theme, _context) {
  100. if (isPartial) return new Text(theme.fg("warning", "Running..."), 0, 0);
  101. const details = result.details as BashToolDetails | undefined;
  102. const content = result.content[0];
  103. const output = content?.type === "text" ? content.text : "";
  104. const exitMatch = output.match(/exit code: (\d+)/);
  105. const exitCode = exitMatch ? parseInt(exitMatch[1], 10) : null;
  106. const lineCount = output.split("\n").filter((l) => l.trim()).length;
  107. let text = "";
  108. if (exitCode === 0 || exitCode === null) {
  109. text += theme.fg("success", "done");
  110. } else {
  111. text += theme.fg("error", `exit ${exitCode}`);
  112. }
  113. text += theme.fg("dim", ` (${lineCount} lines)`);
  114. if (details?.truncation?.truncated) {
  115. text += theme.fg("warning", " [truncated]");
  116. }
  117. if (expanded) {
  118. const lines = output.split("\n").slice(0, 20);
  119. for (const line of lines) {
  120. text += `\n${theme.fg("dim", line)}`;
  121. }
  122. if (output.split("\n").length > 20) {
  123. text += `\n${theme.fg("muted", "... more output")}`;
  124. }
  125. }
  126. return new Text(text, 0, 0);
  127. },
  128. });
  129. // --- Edit tool: show path and diff stats ---
  130. const originalEdit = createEditTool(cwd);
  131. pi.registerTool({
  132. name: "edit",
  133. label: "edit",
  134. description: originalEdit.description,
  135. parameters: originalEdit.parameters,
  136. renderShell: "self",
  137. async execute(toolCallId, params, signal, onUpdate) {
  138. return originalEdit.execute(toolCallId, params, signal, onUpdate);
  139. },
  140. renderCall(args, theme, _context) {
  141. let text = theme.fg("toolTitle", theme.bold("edit "));
  142. text += theme.fg("accent", args.path);
  143. return new Text(text, 0, 0);
  144. },
  145. renderResult(result, { expanded, isPartial }, theme, _context) {
  146. if (isPartial) return new Text(theme.fg("warning", "Editing..."), 0, 0);
  147. const details = result.details as EditToolDetails | undefined;
  148. const content = result.content[0];
  149. if (content?.type === "text" && content.text.startsWith("Error")) {
  150. return new Text(theme.fg("error", content.text.split("\n")[0]), 0, 0);
  151. }
  152. if (!details?.diff) {
  153. return new Text(theme.fg("success", "Applied"), 0, 0);
  154. }
  155. // Count additions and removals from the diff
  156. const diffLines = details.diff.split("\n");
  157. let additions = 0;
  158. let removals = 0;
  159. for (const line of diffLines) {
  160. if (line.startsWith("+") && !line.startsWith("+++")) additions++;
  161. if (line.startsWith("-") && !line.startsWith("---")) removals++;
  162. }
  163. let text = theme.fg("success", `+${additions}`);
  164. text += theme.fg("dim", " / ");
  165. text += theme.fg("error", `-${removals}`);
  166. if (expanded) {
  167. for (const line of diffLines.slice(0, 30)) {
  168. if (line.startsWith("+") && !line.startsWith("+++")) {
  169. text += `\n${theme.fg("success", line)}`;
  170. } else if (line.startsWith("-") && !line.startsWith("---")) {
  171. text += `\n${theme.fg("error", line)}`;
  172. } else {
  173. text += `\n${theme.fg("dim", line)}`;
  174. }
  175. }
  176. if (diffLines.length > 30) {
  177. text += `\n${theme.fg("muted", `... ${diffLines.length - 30} more diff lines`)}`;
  178. }
  179. }
  180. return new Text(text, 0, 0);
  181. },
  182. });
  183. // --- Write tool: show path and size ---
  184. const originalWrite = createWriteTool(cwd);
  185. pi.registerTool({
  186. name: "write",
  187. label: "write",
  188. description: originalWrite.description,
  189. parameters: originalWrite.parameters,
  190. async execute(toolCallId, params, signal, onUpdate) {
  191. return originalWrite.execute(toolCallId, params, signal, onUpdate);
  192. },
  193. renderCall(args, theme, _context) {
  194. let text = theme.fg("toolTitle", theme.bold("write "));
  195. text += theme.fg("accent", args.path);
  196. const lineCount = args.content.split("\n").length;
  197. text += theme.fg("dim", ` (${lineCount} lines)`);
  198. return new Text(text, 0, 0);
  199. },
  200. renderResult(result, { isPartial }, theme, _context) {
  201. if (isPartial) return new Text(theme.fg("warning", "Writing..."), 0, 0);
  202. const content = result.content[0];
  203. if (content?.type === "text" && content.text.startsWith("Error")) {
  204. return new Text(theme.fg("error", content.text.split("\n")[0]), 0, 0);
  205. }
  206. return new Text(theme.fg("success", "Written"), 0, 0);
  207. },
  208. });
  209. }