truncated-tool.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /**
  2. * Truncated Tool Example - Demonstrates proper output truncation for custom tools
  3. *
  4. * Custom tools MUST truncate their output to avoid overwhelming the LLM context.
  5. * The built-in limit is 50KB (~10k tokens) and 2000 lines, whichever is hit first.
  6. *
  7. * This example shows how to:
  8. * 1. Use the built-in truncation utilities
  9. * 2. Write full output to a temp file when truncated
  10. * 3. Inform the LLM where to find the complete output
  11. * 4. Custom rendering of tool calls and results
  12. *
  13. * The `rg` tool here wraps ripgrep with proper truncation. Compare this to the
  14. * built-in `grep` tool in src/core/tools/grep.ts for a more complete implementation.
  15. */
  16. import { mkdtemp, writeFile } from "node:fs/promises";
  17. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  18. import {
  19. DEFAULT_MAX_BYTES,
  20. DEFAULT_MAX_LINES,
  21. formatSize,
  22. type TruncationResult,
  23. truncateHead,
  24. withFileMutationQueue,
  25. } from "@earendil-works/pi-coding-agent";
  26. import { Text } from "@earendil-works/pi-tui";
  27. import { execSync } from "child_process";
  28. import { tmpdir } from "os";
  29. import { join } from "path";
  30. import { Type } from "typebox";
  31. const RgParams = Type.Object({
  32. pattern: Type.String({ description: "Search pattern (regex)" }),
  33. path: Type.Optional(Type.String({ description: "Directory to search (default: current directory)" })),
  34. glob: Type.Optional(Type.String({ description: "File glob pattern, e.g. '*.ts'" })),
  35. });
  36. interface RgDetails {
  37. pattern: string;
  38. path?: string;
  39. glob?: string;
  40. matchCount: number;
  41. truncation?: TruncationResult;
  42. fullOutputPath?: string;
  43. }
  44. export default function (pi: ExtensionAPI) {
  45. pi.registerTool({
  46. name: "rg",
  47. label: "ripgrep",
  48. // Document the truncation limits in the tool description so the LLM knows
  49. description: `Search file contents using ripgrep. Output is truncated to ${DEFAULT_MAX_LINES} lines or ${formatSize(DEFAULT_MAX_BYTES)} (whichever is hit first). If truncated, full output is saved to a temp file.`,
  50. parameters: RgParams,
  51. async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
  52. const { pattern, path: searchPath, glob } = params;
  53. // Build the ripgrep command
  54. const args = ["rg", "--line-number", "--color=never"];
  55. if (glob) args.push("--glob", glob);
  56. args.push(pattern);
  57. args.push(searchPath || ".");
  58. let output: string;
  59. try {
  60. output = execSync(args.join(" "), {
  61. cwd: ctx.cwd,
  62. encoding: "utf-8",
  63. maxBuffer: 100 * 1024 * 1024, // 100MB buffer to capture full output
  64. });
  65. } catch (err: any) {
  66. // ripgrep exits with 1 when no matches found
  67. if (err.status === 1) {
  68. return {
  69. content: [{ type: "text", text: "No matches found" }],
  70. details: { pattern, path: searchPath, glob, matchCount: 0 } as RgDetails,
  71. };
  72. }
  73. throw new Error(`ripgrep failed: ${err.message}`);
  74. }
  75. if (!output.trim()) {
  76. return {
  77. content: [{ type: "text", text: "No matches found" }],
  78. details: { pattern, path: searchPath, glob, matchCount: 0 } as RgDetails,
  79. };
  80. }
  81. // Apply truncation using built-in utilities
  82. // truncateHead keeps the first N lines/bytes (good for search results)
  83. // truncateTail keeps the last N lines/bytes (good for logs/command output)
  84. const truncation = truncateHead(output, {
  85. maxLines: DEFAULT_MAX_LINES,
  86. maxBytes: DEFAULT_MAX_BYTES,
  87. });
  88. // Count matches (each non-empty line with a match)
  89. const matchCount = output.split("\n").filter((line) => line.trim()).length;
  90. const details: RgDetails = {
  91. pattern,
  92. path: searchPath,
  93. glob,
  94. matchCount,
  95. };
  96. let resultText = truncation.content;
  97. if (truncation.truncated) {
  98. // Save full output to a temp file so LLM can access it if needed
  99. const tempDir = await mkdtemp(join(tmpdir(), "pi-rg-"));
  100. const tempFile = join(tempDir, "output.txt");
  101. await withFileMutationQueue(tempFile, async () => {
  102. await writeFile(tempFile, output, "utf8");
  103. });
  104. details.truncation = truncation;
  105. details.fullOutputPath = tempFile;
  106. // Add truncation notice - this helps the LLM understand the output is incomplete
  107. const truncatedLines = truncation.totalLines - truncation.outputLines;
  108. const truncatedBytes = truncation.totalBytes - truncation.outputBytes;
  109. resultText += `\n\n[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`;
  110. resultText += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`;
  111. resultText += ` ${truncatedLines} lines (${formatSize(truncatedBytes)}) omitted.`;
  112. resultText += ` Full output saved to: ${tempFile}]`;
  113. }
  114. return {
  115. content: [{ type: "text", text: resultText }],
  116. details,
  117. };
  118. },
  119. // Custom rendering of the tool call (shown before/during execution)
  120. renderCall(args, theme, _context) {
  121. let text = theme.fg("toolTitle", theme.bold("rg "));
  122. text += theme.fg("accent", `"${args.pattern}"`);
  123. if (args.path) {
  124. text += theme.fg("muted", ` in ${args.path}`);
  125. }
  126. if (args.glob) {
  127. text += theme.fg("dim", ` --glob ${args.glob}`);
  128. }
  129. return new Text(text, 0, 0);
  130. },
  131. // Custom rendering of the tool result
  132. renderResult(result, { expanded, isPartial }, theme, _context) {
  133. const details = result.details as RgDetails | undefined;
  134. // Handle streaming/partial results
  135. if (isPartial) {
  136. return new Text(theme.fg("warning", "Searching..."), 0, 0);
  137. }
  138. // No matches
  139. if (!details || details.matchCount === 0) {
  140. return new Text(theme.fg("dim", "No matches found"), 0, 0);
  141. }
  142. // Build result display
  143. let text = theme.fg("success", `${details.matchCount} matches`);
  144. // Show truncation warning if applicable
  145. if (details.truncation?.truncated) {
  146. text += theme.fg("warning", " (truncated)");
  147. }
  148. // In expanded view, show the actual matches
  149. if (expanded) {
  150. const content = result.content[0];
  151. if (content?.type === "text") {
  152. // Show first 20 lines in expanded view, or all if fewer
  153. const lines = content.text.split("\n").slice(0, 20);
  154. for (const line of lines) {
  155. text += `\n${theme.fg("dim", line)}`;
  156. }
  157. if (content.text.split("\n").length > 20) {
  158. text += `\n${theme.fg("muted", "... (use read tool to see full output)")}`;
  159. }
  160. }
  161. // Show temp file path if truncated
  162. if (details.fullOutputPath) {
  163. text += `\n${theme.fg("dim", `Full output: ${details.fullOutputPath}`)}`;
  164. }
  165. }
  166. return new Text(text, 0, 0);
  167. },
  168. });
  169. }