minimal-mode.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. /**
  2. * Minimal Mode Example - Demonstrates a "minimal" tool display mode
  3. *
  4. * This extension overrides built-in tools to provide custom rendering:
  5. * - Collapsed mode: Only shows the tool call (command/path), no output
  6. * - Expanded mode: Shows full output like the built-in renderers
  7. *
  8. * This demonstrates how a "minimal mode" could work, where ctrl+o cycles through:
  9. * - Standard: Shows truncated output (current default)
  10. * - Expanded: Shows full output (current expanded)
  11. * - Minimal: Shows only tool call, no output (this extension's collapsed mode)
  12. *
  13. * Usage:
  14. * pi -e ./minimal-mode.ts
  15. *
  16. * Then use ctrl+o to toggle between minimal (collapsed) and full (expanded) views.
  17. */
  18. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  19. import {
  20. createBashTool,
  21. createEditTool,
  22. createFindTool,
  23. createGrepTool,
  24. createLsTool,
  25. createReadTool,
  26. createWriteTool,
  27. } from "@earendil-works/pi-coding-agent";
  28. import { Text } from "@earendil-works/pi-tui";
  29. import { homedir } from "os";
  30. /**
  31. * Shorten a path by replacing home directory with ~
  32. */
  33. function shortenPath(path: string): string {
  34. const home = homedir();
  35. if (path.startsWith(home)) {
  36. return `~${path.slice(home.length)}`;
  37. }
  38. return path;
  39. }
  40. // Cache for built-in tools by cwd
  41. const toolCache = new Map<string, ReturnType<typeof createBuiltInTools>>();
  42. function createBuiltInTools(cwd: string) {
  43. return {
  44. read: createReadTool(cwd),
  45. bash: createBashTool(cwd),
  46. edit: createEditTool(cwd),
  47. write: createWriteTool(cwd),
  48. find: createFindTool(cwd),
  49. grep: createGrepTool(cwd),
  50. ls: createLsTool(cwd),
  51. };
  52. }
  53. function getBuiltInTools(cwd: string) {
  54. let tools = toolCache.get(cwd);
  55. if (!tools) {
  56. tools = createBuiltInTools(cwd);
  57. toolCache.set(cwd, tools);
  58. }
  59. return tools;
  60. }
  61. export default function (pi: ExtensionAPI) {
  62. // =========================================================================
  63. // Read Tool
  64. // =========================================================================
  65. pi.registerTool({
  66. name: "read",
  67. label: "read",
  68. description:
  69. "Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files.",
  70. parameters: getBuiltInTools(process.cwd()).read.parameters,
  71. async execute(toolCallId, params, signal, onUpdate, ctx) {
  72. const tools = getBuiltInTools(ctx.cwd);
  73. return tools.read.execute(toolCallId, params, signal, onUpdate);
  74. },
  75. renderCall(args, theme, _context) {
  76. const path = shortenPath(args.path || "");
  77. let pathDisplay = path ? theme.fg("accent", path) : theme.fg("toolOutput", "...");
  78. // Show line range if specified
  79. if (args.offset !== undefined || args.limit !== undefined) {
  80. const startLine = args.offset ?? 1;
  81. const endLine = args.limit !== undefined ? startLine + args.limit - 1 : "";
  82. pathDisplay += theme.fg("warning", `:${startLine}${endLine ? `-${endLine}` : ""}`);
  83. }
  84. return new Text(`${theme.fg("toolTitle", theme.bold("read"))} ${pathDisplay}`, 0, 0);
  85. },
  86. renderResult(result, { expanded }, theme, _context) {
  87. // Minimal mode: show nothing in collapsed state
  88. if (!expanded) {
  89. return new Text("", 0, 0);
  90. }
  91. // Expanded mode: show full output
  92. const textContent = result.content.find((c) => c.type === "text");
  93. if (!textContent || textContent.type !== "text") {
  94. return new Text("", 0, 0);
  95. }
  96. const lines = textContent.text.split("\n");
  97. const output = lines.map((line) => theme.fg("toolOutput", line)).join("\n");
  98. return new Text(`\n${output}`, 0, 0);
  99. },
  100. });
  101. // =========================================================================
  102. // Bash Tool
  103. // =========================================================================
  104. pi.registerTool({
  105. name: "bash",
  106. label: "bash",
  107. description:
  108. "Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first).",
  109. parameters: getBuiltInTools(process.cwd()).bash.parameters,
  110. async execute(toolCallId, params, signal, onUpdate, ctx) {
  111. const tools = getBuiltInTools(ctx.cwd);
  112. return tools.bash.execute(toolCallId, params, signal, onUpdate);
  113. },
  114. renderCall(args, theme, _context) {
  115. const command = args.command || "...";
  116. const timeout = args.timeout as number | undefined;
  117. const timeoutSuffix = timeout ? theme.fg("muted", ` (timeout ${timeout}s)`) : "";
  118. return new Text(theme.fg("toolTitle", theme.bold(`$ ${command}`)) + timeoutSuffix, 0, 0);
  119. },
  120. renderResult(result, { expanded }, theme, _context) {
  121. // Minimal mode: show nothing in collapsed state
  122. if (!expanded) {
  123. return new Text("", 0, 0);
  124. }
  125. // Expanded mode: show full output
  126. const textContent = result.content.find((c) => c.type === "text");
  127. if (!textContent || textContent.type !== "text") {
  128. return new Text("", 0, 0);
  129. }
  130. const output = textContent.text
  131. .trim()
  132. .split("\n")
  133. .map((line) => theme.fg("toolOutput", line))
  134. .join("\n");
  135. if (!output) {
  136. return new Text("", 0, 0);
  137. }
  138. return new Text(`\n${output}`, 0, 0);
  139. },
  140. });
  141. // =========================================================================
  142. // Write Tool
  143. // =========================================================================
  144. pi.registerTool({
  145. name: "write",
  146. label: "write",
  147. description:
  148. "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
  149. parameters: getBuiltInTools(process.cwd()).write.parameters,
  150. async execute(toolCallId, params, signal, onUpdate, ctx) {
  151. const tools = getBuiltInTools(ctx.cwd);
  152. return tools.write.execute(toolCallId, params, signal, onUpdate);
  153. },
  154. renderCall(args, theme, _context) {
  155. const path = shortenPath(args.path || "");
  156. const pathDisplay = path ? theme.fg("accent", path) : theme.fg("toolOutput", "...");
  157. const lineCount = args.content ? args.content.split("\n").length : 0;
  158. const lineInfo = lineCount > 0 ? theme.fg("muted", ` (${lineCount} lines)`) : "";
  159. return new Text(`${theme.fg("toolTitle", theme.bold("write"))} ${pathDisplay}${lineInfo}`, 0, 0);
  160. },
  161. renderResult(result, { expanded }, theme, _context) {
  162. // Minimal mode: show nothing (file was written)
  163. if (!expanded) {
  164. return new Text("", 0, 0);
  165. }
  166. // Expanded mode: show error if any
  167. if (result.content.some((c) => c.type === "text" && c.text)) {
  168. const textContent = result.content.find((c) => c.type === "text");
  169. if (textContent?.type === "text" && textContent.text) {
  170. return new Text(`\n${theme.fg("error", textContent.text)}`, 0, 0);
  171. }
  172. }
  173. return new Text("", 0, 0);
  174. },
  175. });
  176. // =========================================================================
  177. // Edit Tool
  178. // =========================================================================
  179. pi.registerTool({
  180. name: "edit",
  181. label: "edit",
  182. description:
  183. "Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.",
  184. parameters: getBuiltInTools(process.cwd()).edit.parameters,
  185. async execute(toolCallId, params, signal, onUpdate, ctx) {
  186. const tools = getBuiltInTools(ctx.cwd);
  187. return tools.edit.execute(toolCallId, params, signal, onUpdate);
  188. },
  189. renderCall(args, theme, _context) {
  190. const path = shortenPath(args.path || "");
  191. const pathDisplay = path ? theme.fg("accent", path) : theme.fg("toolOutput", "...");
  192. return new Text(`${theme.fg("toolTitle", theme.bold("edit"))} ${pathDisplay}`, 0, 0);
  193. },
  194. renderResult(result, { expanded }, theme, _context) {
  195. // Minimal mode: show nothing in collapsed state
  196. if (!expanded) {
  197. return new Text("", 0, 0);
  198. }
  199. // Expanded mode: show diff or error
  200. const textContent = result.content.find((c) => c.type === "text");
  201. if (!textContent || textContent.type !== "text") {
  202. return new Text("", 0, 0);
  203. }
  204. // For errors, show the error message
  205. const text = textContent.text;
  206. if (text.includes("Error") || text.includes("error")) {
  207. return new Text(`\n${theme.fg("error", text)}`, 0, 0);
  208. }
  209. // Otherwise show the text (would be nice to show actual diff here)
  210. return new Text(`\n${theme.fg("toolOutput", text)}`, 0, 0);
  211. },
  212. });
  213. // =========================================================================
  214. // Find Tool
  215. // =========================================================================
  216. pi.registerTool({
  217. name: "find",
  218. label: "find",
  219. description:
  220. "Find files by name pattern (glob). Searches recursively from the specified path. Output limited to 200 results.",
  221. parameters: getBuiltInTools(process.cwd()).find.parameters,
  222. async execute(toolCallId, params, signal, onUpdate, ctx) {
  223. const tools = getBuiltInTools(ctx.cwd);
  224. return tools.find.execute(toolCallId, params, signal, onUpdate);
  225. },
  226. renderCall(args, theme, _context) {
  227. const pattern = args.pattern || "";
  228. const path = shortenPath(args.path || ".");
  229. const limit = args.limit;
  230. let text = `${theme.fg("toolTitle", theme.bold("find"))} ${theme.fg("accent", pattern)}`;
  231. text += theme.fg("toolOutput", ` in ${path}`);
  232. if (limit !== undefined) {
  233. text += theme.fg("toolOutput", ` (limit ${limit})`);
  234. }
  235. return new Text(text, 0, 0);
  236. },
  237. renderResult(result, { expanded }, theme, _context) {
  238. if (!expanded) {
  239. // Minimal: just show count
  240. const textContent = result.content.find((c) => c.type === "text");
  241. if (textContent?.type === "text") {
  242. const count = textContent.text.trim().split("\n").filter(Boolean).length;
  243. if (count > 0) {
  244. return new Text(theme.fg("muted", ` → ${count} files`), 0, 0);
  245. }
  246. }
  247. return new Text("", 0, 0);
  248. }
  249. // Expanded: show full results
  250. const textContent = result.content.find((c) => c.type === "text");
  251. if (!textContent || textContent.type !== "text") {
  252. return new Text("", 0, 0);
  253. }
  254. const output = textContent.text
  255. .trim()
  256. .split("\n")
  257. .map((line) => theme.fg("toolOutput", line))
  258. .join("\n");
  259. return new Text(`\n${output}`, 0, 0);
  260. },
  261. });
  262. // =========================================================================
  263. // Grep Tool
  264. // =========================================================================
  265. pi.registerTool({
  266. name: "grep",
  267. label: "grep",
  268. description:
  269. "Search file contents by regex pattern. Uses ripgrep for fast searching. Output limited to 200 matches.",
  270. parameters: getBuiltInTools(process.cwd()).grep.parameters,
  271. async execute(toolCallId, params, signal, onUpdate, ctx) {
  272. const tools = getBuiltInTools(ctx.cwd);
  273. return tools.grep.execute(toolCallId, params, signal, onUpdate);
  274. },
  275. renderCall(args, theme, _context) {
  276. const pattern = args.pattern || "";
  277. const path = shortenPath(args.path || ".");
  278. const glob = args.glob;
  279. const limit = args.limit;
  280. let text = `${theme.fg("toolTitle", theme.bold("grep"))} ${theme.fg("accent", `/${pattern}/`)}`;
  281. text += theme.fg("toolOutput", ` in ${path}`);
  282. if (glob) {
  283. text += theme.fg("toolOutput", ` (${glob})`);
  284. }
  285. if (limit !== undefined) {
  286. text += theme.fg("toolOutput", ` limit ${limit}`);
  287. }
  288. return new Text(text, 0, 0);
  289. },
  290. renderResult(result, { expanded }, theme, _context) {
  291. if (!expanded) {
  292. // Minimal: just show match count
  293. const textContent = result.content.find((c) => c.type === "text");
  294. if (textContent?.type === "text") {
  295. const count = textContent.text.trim().split("\n").filter(Boolean).length;
  296. if (count > 0) {
  297. return new Text(theme.fg("muted", ` → ${count} matches`), 0, 0);
  298. }
  299. }
  300. return new Text("", 0, 0);
  301. }
  302. // Expanded: show full results
  303. const textContent = result.content.find((c) => c.type === "text");
  304. if (!textContent || textContent.type !== "text") {
  305. return new Text("", 0, 0);
  306. }
  307. const output = textContent.text
  308. .trim()
  309. .split("\n")
  310. .map((line) => theme.fg("toolOutput", line))
  311. .join("\n");
  312. return new Text(`\n${output}`, 0, 0);
  313. },
  314. });
  315. // =========================================================================
  316. // Ls Tool
  317. // =========================================================================
  318. pi.registerTool({
  319. name: "ls",
  320. label: "ls",
  321. description:
  322. "List directory contents with file sizes. Shows files and directories with their sizes. Output limited to 500 entries.",
  323. parameters: getBuiltInTools(process.cwd()).ls.parameters,
  324. async execute(toolCallId, params, signal, onUpdate, ctx) {
  325. const tools = getBuiltInTools(ctx.cwd);
  326. return tools.ls.execute(toolCallId, params, signal, onUpdate);
  327. },
  328. renderCall(args, theme, _context) {
  329. const path = shortenPath(args.path || ".");
  330. const limit = args.limit;
  331. let text = `${theme.fg("toolTitle", theme.bold("ls"))} ${theme.fg("accent", path)}`;
  332. if (limit !== undefined) {
  333. text += theme.fg("toolOutput", ` (limit ${limit})`);
  334. }
  335. return new Text(text, 0, 0);
  336. },
  337. renderResult(result, { expanded }, theme, _context) {
  338. if (!expanded) {
  339. // Minimal: just show entry count
  340. const textContent = result.content.find((c) => c.type === "text");
  341. if (textContent?.type === "text") {
  342. const count = textContent.text.trim().split("\n").filter(Boolean).length;
  343. if (count > 0) {
  344. return new Text(theme.fg("muted", ` → ${count} entries`), 0, 0);
  345. }
  346. }
  347. return new Text("", 0, 0);
  348. }
  349. // Expanded: show full listing
  350. const textContent = result.content.find((c) => c.type === "text");
  351. if (!textContent || textContent.type !== "text") {
  352. return new Text("", 0, 0);
  353. }
  354. const output = textContent.text
  355. .trim()
  356. .split("\n")
  357. .map((line) => theme.fg("toolOutput", line))
  358. .join("\n");
  359. return new Text(`\n${output}`, 0, 0);
  360. },
  361. });
  362. }