tool-override.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. /**
  2. * Tool Override Example - Demonstrates overriding built-in tools
  3. *
  4. * Extensions can register tools with the same name as built-in tools to replace them.
  5. * This is useful for:
  6. * - Adding logging or auditing to tool calls
  7. * - Implementing access control or sandboxing
  8. * - Routing tool calls to remote systems (e.g., pi-ssh-remote)
  9. * - Modifying tool behavior for specific workflows
  10. *
  11. * This example overrides the `read` tool to:
  12. * 1. Log all file access to a log file
  13. * 2. Block access to sensitive paths (e.g., .env files)
  14. * 3. Delegate to the original read implementation for allowed files
  15. *
  16. * Since no custom renderCall/renderResult are provided, the built-in renderer
  17. * is used automatically (syntax highlighting, line numbers, truncation warnings).
  18. *
  19. * Usage:
  20. * pi -e ./tool-override.ts
  21. */
  22. import type { TextContent } from "@earendil-works/pi-ai";
  23. import { type ExtensionAPI, getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
  24. import { constants, readFileSync } from "fs";
  25. import { access, appendFile, readFile } from "fs/promises";
  26. import { join, resolve } from "path";
  27. import { Type } from "typebox";
  28. const LOG_FILE = join(getAgentDir(), "read-access.log");
  29. // Paths that are blocked from reading
  30. const BLOCKED_PATTERNS = [
  31. /\.env$/,
  32. /\.env\..+$/,
  33. /secrets?\.(json|yaml|yml|toml)$/i,
  34. /credentials?\.(json|yaml|yml|toml)$/i,
  35. /\/\.ssh\//,
  36. /\/\.aws\//,
  37. /\/\.gnupg\//,
  38. ];
  39. function isBlockedPath(path: string): boolean {
  40. return BLOCKED_PATTERNS.some((pattern) => pattern.test(path));
  41. }
  42. async function logAccess(path: string, allowed: boolean, reason?: string) {
  43. const timestamp = new Date().toISOString();
  44. const status = allowed ? "ALLOWED" : "BLOCKED";
  45. const msg = reason ? ` (${reason})` : "";
  46. const line = `[${timestamp}] ${status}: ${path}${msg}\n`;
  47. try {
  48. await withFileMutationQueue(LOG_FILE, async () => {
  49. await appendFile(LOG_FILE, line);
  50. });
  51. } catch {
  52. // Ignore logging errors
  53. }
  54. }
  55. const readSchema = Type.Object({
  56. path: Type.String({ description: "Path to the file to read (relative or absolute)" }),
  57. offset: Type.Optional(Type.Number({ description: "Line number to start reading from (1-indexed)" })),
  58. limit: Type.Optional(Type.Number({ description: "Maximum number of lines to read" })),
  59. });
  60. export default function (pi: ExtensionAPI) {
  61. pi.registerTool({
  62. name: "read", // Same name as built-in - this will override it
  63. label: "read (audited)",
  64. description:
  65. "Read the contents of a file with access logging. Some sensitive paths (.env, secrets, credentials) are blocked.",
  66. parameters: readSchema,
  67. async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
  68. const { path, offset, limit } = params;
  69. const absolutePath = resolve(ctx.cwd, path);
  70. // Check if path is blocked
  71. if (isBlockedPath(absolutePath)) {
  72. await logAccess(absolutePath, false, "matches blocked pattern");
  73. return {
  74. content: [
  75. {
  76. type: "text",
  77. text: `Access denied: "${path}" matches a blocked pattern (sensitive file). This tool blocks access to .env files, secrets, credentials, and SSH/AWS/GPG directories.`,
  78. },
  79. ],
  80. details: { blocked: true },
  81. };
  82. }
  83. // Log allowed access
  84. await logAccess(absolutePath, true);
  85. // Perform the actual read (simplified implementation)
  86. try {
  87. await access(absolutePath, constants.R_OK);
  88. const content = await readFile(absolutePath, "utf-8");
  89. const lines = content.split("\n");
  90. // Apply offset and limit
  91. const startLine = offset ? Math.max(0, offset - 1) : 0;
  92. const endLine = limit ? startLine + limit : lines.length;
  93. const selectedLines = lines.slice(startLine, endLine);
  94. // Basic truncation (50KB limit)
  95. let text = selectedLines.join("\n");
  96. const maxBytes = 50 * 1024;
  97. if (Buffer.byteLength(text, "utf-8") > maxBytes) {
  98. text = `${text.slice(0, maxBytes)}\n\n[Output truncated at 50KB]`;
  99. }
  100. return {
  101. content: [{ type: "text", text }] as TextContent[],
  102. details: { lines: lines.length },
  103. };
  104. } catch (error: any) {
  105. return {
  106. content: [{ type: "text", text: `Error reading file: ${error.message}` }] as TextContent[],
  107. details: { error: true },
  108. };
  109. }
  110. },
  111. // No renderCall/renderResult - uses built-in renderer automatically
  112. // (syntax highlighting, line numbers, truncation warnings, etc.)
  113. });
  114. // Also register a command to view the access log
  115. pi.registerCommand("read-log", {
  116. description: "View the file access log",
  117. handler: async (_args, ctx) => {
  118. try {
  119. const log = readFileSync(LOG_FILE, "utf-8");
  120. const lines = log.trim().split("\n").slice(-20); // Last 20 entries
  121. ctx.ui.notify(`Recent file access:\n${lines.join("\n")}`, "info");
  122. } catch {
  123. ctx.ui.notify("No access log found", "info");
  124. }
  125. },
  126. });
  127. }