From dafd221d30d700e0aa7013d928f6c33fd794bc32 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 25 Jul 2025 00:16:09 -0700 Subject: [PATCH] tool permissions --- src/permissions/README.md | 92 ++++++ src/permissions/defaultPolicies.ts | 25 ++ src/permissions/index.ts | 20 ++ src/permissions/permissionChecker.test.ts | 293 ++++++++++++++++++ src/permissions/permissionChecker.ts | 91 ++++++ src/permissions/permissionManager.test.ts | 225 ++++++++++++++ src/permissions/permissionManager.ts | 97 ++++++ src/permissions/types.ts | 26 ++ src/streamChatResponse.ts | 115 ++++++- src/ui/Selector.tsx | 20 +- src/ui/TUIChat.tsx | 39 ++- src/ui/components/MemoizedMessage.tsx | 146 ++++----- .../components/ToolPermissionRequest.test.tsx | 78 +++++ src/ui/components/ToolPermissionRequest.tsx | 83 +++++ src/ui/components/ToolPermissionSelector.tsx | 118 +++++++ src/ui/hooks/useChat.ts | 37 +++ src/ui/hooks/useMessageRenderer.tsx | 8 +- src/ui/types.ts | 9 +- 18 files changed, 1430 insertions(+), 92 deletions(-) create mode 100644 src/permissions/README.md create mode 100644 src/permissions/defaultPolicies.ts create mode 100644 src/permissions/index.ts create mode 100644 src/permissions/permissionChecker.test.ts create mode 100644 src/permissions/permissionChecker.ts create mode 100644 src/permissions/permissionManager.test.ts create mode 100644 src/permissions/permissionManager.ts create mode 100644 src/permissions/types.ts create mode 100644 src/ui/components/ToolPermissionRequest.test.tsx create mode 100644 src/ui/components/ToolPermissionRequest.tsx create mode 100644 src/ui/components/ToolPermissionSelector.tsx diff --git a/src/permissions/README.md b/src/permissions/README.md new file mode 100644 index 000000000..56846da52 --- /dev/null +++ b/src/permissions/README.md @@ -0,0 +1,92 @@ +# Tool Permissions System + +The tool permissions system allows you to control which tools the AI can use and how it can use them. There are three permission levels: + +- **allow**: The tool will be executed automatically without asking for permission +- **ask**: The tool will prompt the user for permission before execution +- **exclude**: The tool will be filtered out entirely and won't be available to the AI + +## Default Policies + +The system comes with sensible default policies: + +- Read-only tools (`readFile`, `listFiles`, `searchCode`, `fetch`) are **allowed** by default +- Write operations (`writeFile`) require **confirmation** (ask) +- Terminal commands (`runTerminalCommand`) require **confirmation** (ask) +- MCP tools with IDE prefix are **allowed** by default +- Other MCP tools require **confirmation** (ask) +- Any unmatched tools default to **ask** + +## How It Works + +### 1. Tool Filtering (Exclude Policy) + +Tools with "exclude" permission are filtered out before being sent to the AI model. This means the AI won't even know these tools exist. + +### 2. Permission Checking (Ask Policy) + +When the AI tries to use a tool with "ask" permission, the system will: + +1. Display a permission request in the UI +2. Wait for user approval (y/n) +3. Execute the tool if approved, or return an error if denied + +### 3. Automatic Execution (Allow Policy) + +Tools with "allow" permission are executed immediately without user intervention. + +## Architecture + +### Core Components + +- **`types.ts`**: Defines the permission policy types and interfaces +- **`defaultPolicies.ts`**: Contains the hardcoded default permission policies +- **`permissionChecker.ts`**: Implements the permission checking logic +- **`permissionManager.ts`**: Manages permission requests and user responses +- **UI Components**: Handle displaying permission requests and collecting user input + +### Data Flow + +1. **Tool Loading**: `getAllTools()` in `streamChatResponse.ts` filters out excluded tools +2. **Tool Execution**: Before executing each tool call, permissions are checked +3. **User Interaction**: For "ask" policies, UI displays permission request +4. **Execution**: Tool is executed or denied based on permission result + +## UI Integration + +The permission system integrates with the existing chat UI: + +- Permission requests appear as special message types +- Users can approve/deny with y/n keys +- The decision is shown in the chat history +- The system handles the async nature of permission requests + +## Future Enhancements + +The system is designed to be extensible for future features like: + +- Custom permission policies loaded from configuration +- "Remember this decision" functionality +- Argument-based permission matching (partially implemented) +- Per-session or per-project permission overrides + +## Example Usage + +```typescript +// Check permission for a tool call +const result = checkToolPermission({ + name: "writeFile", + arguments: { path: "/important.txt", content: "data" }, +}); + +if (result.permission === "ask") { + // Request user permission +} + +// Filter excluded tools +const allowedTools = filterExcludedTools([ + "readFile", + "dangerousTool", + "writeFile", +]); +``` diff --git a/src/permissions/defaultPolicies.ts b/src/permissions/defaultPolicies.ts new file mode 100644 index 000000000..37e67695d --- /dev/null +++ b/src/permissions/defaultPolicies.ts @@ -0,0 +1,25 @@ +import { ToolPermissionPolicy } from "./types.js"; + +/** + * Default permission policies for all built-in tools. + * These policies are applied in order - first match wins. + */ +export const DEFAULT_TOOL_POLICIES: ToolPermissionPolicy[] = [ + // Read-only tools are generally safe to allow + { tool: "readFile", permission: "allow" }, + { tool: "listFiles", permission: "allow" }, + { tool: "searchCode", permission: "allow" }, + { tool: "fetch", permission: "allow" }, + + // Write operations should require confirmation + { tool: "writeFile", permission: "ask" }, + + // Terminal commands should require confirmation by default + { tool: "runTerminalCommand", permission: "ask" }, + + // Exit tool is generally safe (headless mode only) + { tool: "exit", permission: "allow" }, + + // Default fallback - ask for any unmatched tools + { tool: "*", permission: "ask" }, +]; diff --git a/src/permissions/index.ts b/src/permissions/index.ts new file mode 100644 index 000000000..7af3ebf24 --- /dev/null +++ b/src/permissions/index.ts @@ -0,0 +1,20 @@ +export type { + PermissionCheckResult, + PermissionPolicy, + ToolCallRequest, + ToolPermissionPolicy, + ToolPermissions, +} from "./types.js"; + +export { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; +export { + checkToolPermission, + filterExcludedTools, + matchesToolPattern, + matchesArguments, +} from "./permissionChecker.js"; +export { + toolPermissionManager, + ToolPermissionManager, +} from "./permissionManager.js"; +export type { PermissionRequestResult } from "./permissionManager.js"; diff --git a/src/permissions/permissionChecker.test.ts b/src/permissions/permissionChecker.test.ts new file mode 100644 index 000000000..8218e3f52 --- /dev/null +++ b/src/permissions/permissionChecker.test.ts @@ -0,0 +1,293 @@ +import { + checkToolPermission, + filterExcludedTools, + matchesToolPattern, + matchesArguments, +} from "./permissionChecker.js"; +import { ToolPermissions } from "./types.js"; + +describe("Permission Checker", () => { + describe("matchesToolPattern", () => { + it("should match exact tool names", () => { + expect(matchesToolPattern("readFile", "readFile")).toBe(true); + expect(matchesToolPattern("writeFile", "readFile")).toBe(false); + }); + + it("should match universal wildcard", () => { + expect(matchesToolPattern("anyTool", "*")).toBe(true); + expect(matchesToolPattern("readFile", "*")).toBe(true); + expect(matchesToolPattern("", "*")).toBe(true); + }); + + it("should match prefix wildcards", () => { + expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe(true); + expect(matchesToolPattern("mcp__filesystem__read", "mcp__*")).toBe(true); + expect(matchesToolPattern("builtin__readFile", "mcp__*")).toBe(false); + }); + + it("should match suffix wildcards", () => { + expect(matchesToolPattern("readFile", "*File")).toBe(true); + expect(matchesToolPattern("writeFile", "*File")).toBe(true); + expect(matchesToolPattern("readData", "*File")).toBe(false); + }); + + it("should match complex wildcard patterns", () => { + expect(matchesToolPattern("test_function_123", "test_*_123")).toBe(true); + expect(matchesToolPattern("test_abc_123", "test_*_123")).toBe(true); + expect(matchesToolPattern("test_function_456", "test_*_123")).toBe(false); + }); + + it("should handle empty strings", () => { + expect(matchesToolPattern("", "")).toBe(true); + expect(matchesToolPattern("tool", "")).toBe(false); + expect(matchesToolPattern("", "tool")).toBe(false); + }); + + it("should handle special regex characters in patterns", () => { + expect(matchesToolPattern("test.file", "test.file")).toBe(true); + expect(matchesToolPattern("test_file", "test.file")).toBe(false); + expect(matchesToolPattern("test[file]", "test[file]")).toBe(true); + }); + }); + + describe("matchesArguments", () => { + it("should return true when no patterns provided", () => { + expect(matchesArguments({ path: "/test.txt" })).toBe(true); + expect(matchesArguments({})).toBe(true); + expect(matchesArguments({ any: "value" }, undefined)).toBe(true); + }); + + it("should match exact argument values", () => { + const args = { path: "/test.txt", mode: "read" }; + const patterns = { path: "/test.txt" }; + expect(matchesArguments(args, patterns)).toBe(true); + + const nonMatchingPatterns = { path: "/other.txt" }; + expect(matchesArguments(args, nonMatchingPatterns)).toBe(false); + }); + + it("should match wildcard argument patterns", () => { + const args = { path: "/any/file.txt", mode: "write" }; + const patterns = { path: "*", mode: "write" }; + expect(matchesArguments(args, patterns)).toBe(true); + + const wildcardOnlyPatterns = { path: "*" }; + expect(matchesArguments(args, wildcardOnlyPatterns)).toBe(true); + }); + + it("should require all patterns to match", () => { + const args = { path: "/test.txt", mode: "read", format: "json" }; + const allMatchingPatterns = { path: "/test.txt", mode: "read" }; + expect(matchesArguments(args, allMatchingPatterns)).toBe(true); + + const partialMatchingPatterns = { path: "/test.txt", mode: "write" }; + expect(matchesArguments(args, partialMatchingPatterns)).toBe(false); + }); + + it("should handle missing arguments", () => { + const args = { path: "/test.txt" }; + const patternsRequiringMissing = { path: "/test.txt", mode: "read" }; + expect(matchesArguments(args, patternsRequiringMissing)).toBe(false); + }); + + it("should handle different data types", () => { + const args = { count: 42, enabled: true, data: null, list: [1, 2, 3] }; + const patterns = { count: 42, enabled: true }; + expect(matchesArguments(args, patterns)).toBe(true); + + const mismatchedPatterns = { count: "42" }; // string vs number + expect(matchesArguments(args, mismatchedPatterns)).toBe(false); + }); + + it("should handle complex object arguments with reference equality", () => { + const configObj = { host: "localhost", port: 3000 }; + const optionsArray = ["verbose", "debug"]; + + const args = { + config: configObj, + options: optionsArray + }; + const patterns = { + config: configObj, // Same reference + options: optionsArray // Same reference + }; + expect(matchesArguments(args, patterns)).toBe(true); + + const differentObjectPatterns = { + config: { host: "localhost", port: 8080 } // Different object + }; + expect(matchesArguments(args, differentObjectPatterns)).toBe(false); + + const differentButEqualObjectPatterns = { + config: { host: "localhost", port: 3000 } // Different reference, same content + }; + expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(false); + }); + }); + + describe("checkToolPermission", () => { + it("should allow tools with allow permission", () => { + const permissions: ToolPermissions = { + policies: [{ tool: "readFile", permission: "allow" }], + }; + + const result = checkToolPermission( + { name: "readFile", arguments: { path: "/test.txt" } }, + permissions + ); + + expect(result.permission).toBe("allow"); + expect(result.matchedPolicy?.tool).toBe("readFile"); + }); + + it("should ask for tools with ask permission", () => { + const permissions: ToolPermissions = { + policies: [{ tool: "writeFile", permission: "ask" }], + }; + + const result = checkToolPermission( + { + name: "writeFile", + arguments: { path: "/test.txt", content: "hello" }, + }, + permissions + ); + + expect(result.permission).toBe("ask"); + expect(result.matchedPolicy?.tool).toBe("writeFile"); + }); + + it("should exclude tools with exclude permission", () => { + const permissions: ToolPermissions = { + policies: [{ tool: "runTerminalCommand", permission: "exclude" }], + }; + + const result = checkToolPermission( + { name: "runTerminalCommand", arguments: { command: "rm -rf /" } }, + permissions + ); + + expect(result.permission).toBe("exclude"); + expect(result.matchedPolicy?.tool).toBe("runTerminalCommand"); + }); + + it("should match wildcard patterns", () => { + const permissions: ToolPermissions = { + policies: [ + { tool: "mcp__*", permission: "ask" }, + { tool: "*", permission: "allow" }, + ], + }; + + const mcpResult = checkToolPermission( + { name: "mcp__ide__getDiagnostics", arguments: {} }, + permissions + ); + expect(mcpResult.permission).toBe("ask"); + expect(mcpResult.matchedPolicy?.tool).toBe("mcp__*"); + + const builtinResult = checkToolPermission( + { name: "readFile", arguments: { path: "/test.txt" } }, + permissions + ); + expect(builtinResult.permission).toBe("allow"); + expect(builtinResult.matchedPolicy?.tool).toBe("*"); + }); + + it("should match based on arguments", () => { + const permissions: ToolPermissions = { + policies: [ + { + tool: "writeFile", + permission: "exclude", + argumentMatches: { path: "/sensitive.txt" }, + }, + { tool: "writeFile", permission: "allow" }, + ], + }; + + const sensitiveResult = checkToolPermission( + { + name: "writeFile", + arguments: { path: "/sensitive.txt", content: "data" }, + }, + permissions + ); + expect(sensitiveResult.permission).toBe("exclude"); + + const normalResult = checkToolPermission( + { + name: "writeFile", + arguments: { path: "/normal.txt", content: "data" }, + }, + permissions + ); + expect(normalResult.permission).toBe("allow"); + }); + + it("should use default policies when no custom permissions provided", () => { + const result = checkToolPermission({ + name: "readFile", + arguments: { path: "/test.txt" }, + }); + + // Should match the default policies (readFile should be "allow") + expect(result.permission).toBe("allow"); + }); + + it("should fall back to ask when no policy matches", () => { + const permissions: ToolPermissions = { + policies: [{ tool: "specificTool", permission: "allow" }], + }; + + const result = checkToolPermission( + { name: "unknownTool", arguments: {} }, + permissions + ); + + expect(result.permission).toBe("ask"); + }); + }); + + describe("filterExcludedTools", () => { + it("should filter out excluded tools", () => { + const permissions: ToolPermissions = { + policies: [ + { tool: "runTerminalCommand", permission: "exclude" }, + { tool: "writeFile", permission: "ask" }, + { tool: "*", permission: "allow" }, + ], + }; + + const tools = [ + "readFile", + "writeFile", + "runTerminalCommand", + "searchCode", + ]; + const filtered = filterExcludedTools(tools, permissions); + + expect(filtered).toEqual(["readFile", "writeFile", "searchCode"]); + expect(filtered).not.toContain("runTerminalCommand"); + }); + + it("should return all tools when none are excluded", () => { + const permissions: ToolPermissions = { + policies: [{ tool: "*", permission: "allow" }], + }; + + const tools = ["readFile", "writeFile", "runTerminalCommand"]; + const filtered = filterExcludedTools(tools, permissions); + + expect(filtered).toEqual(tools); + }); + + it("should use default policies when no permissions provided", () => { + const tools = ["readFile", "writeFile", "runTerminalCommand"]; + const filtered = filterExcludedTools(tools); + + // All tools should be included (none excluded by default) + expect(filtered).toEqual(tools); + }); + }); +}); diff --git a/src/permissions/permissionChecker.ts b/src/permissions/permissionChecker.ts new file mode 100644 index 000000000..d471ae6b6 --- /dev/null +++ b/src/permissions/permissionChecker.ts @@ -0,0 +1,91 @@ +import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; +import { + PermissionCheckResult, + ToolCallRequest, + ToolPermissions, +} from "./types.js"; + +/** + * Checks if a tool name matches a pattern. + * Supports wildcards (*) for pattern matching. + */ +export function matchesToolPattern(toolName: string, pattern: string): boolean { + if (pattern === "*") return true; + if (pattern === toolName) return true; + + // Handle wildcard patterns like "mcp__*" + if (pattern.includes("*")) { + const regexPattern = pattern.replace(/\*/g, ".*").replace(/\?/g, "."); + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(toolName); + } + + return false; +} + +/** + * Checks if tool call arguments match the specified patterns. + */ +export function matchesArguments( + args: Record, + patterns?: Record +): boolean { + if (!patterns) return true; + + for (const [key, pattern] of Object.entries(patterns)) { + const argValue = args[key]; + + if (pattern === "*") continue; // Wildcard matches anything + + // Exact match + if (argValue !== pattern) { + return false; + } + } + + return true; +} + +/** + * Evaluates a tool call request against a set of permission policies. + * Returns the permission for the first matching policy. + */ +export function checkToolPermission( + toolCall: ToolCallRequest, + permissions?: ToolPermissions +): PermissionCheckResult { + const policies = permissions?.policies || DEFAULT_TOOL_POLICIES; + + for (const policy of policies) { + if ( + matchesToolPattern(toolCall.name, policy.tool) && + matchesArguments(toolCall.arguments, policy.argumentMatches) + ) { + return { + permission: policy.permission, + matchedPolicy: policy, + }; + } + } + + // Fallback to "ask" if no policy matches + return { + permission: "ask", + }; +} + +/** + * Filters out tools that have "exclude" permission from a list of tool names. + */ +export function filterExcludedTools( + toolNames: string[], + permissions?: ToolPermissions +): string[] { + return toolNames.filter((toolName) => { + const result = checkToolPermission( + { name: toolName, arguments: {} }, + permissions + ); + return result.permission !== "exclude"; + }); +} diff --git a/src/permissions/permissionManager.test.ts b/src/permissions/permissionManager.test.ts new file mode 100644 index 000000000..66089c5af --- /dev/null +++ b/src/permissions/permissionManager.test.ts @@ -0,0 +1,225 @@ +import { ToolPermissionManager } from "./permissionManager.js"; +import { ToolCallRequest } from "./types.js"; + +describe("ToolPermissionManager", () => { + let manager: ToolPermissionManager; + + beforeEach(() => { + manager = new ToolPermissionManager(); + }); + + afterEach(() => { + // Clean up all listeners + manager.removeAllListeners(); + }); + + describe("Request Management", () => { + it("should generate unique request IDs", async () => { + const toolCall1: ToolCallRequest = { name: "readFile", arguments: { path: "/test1.txt" } }; + const toolCall2: ToolCallRequest = { name: "readFile", arguments: { path: "/test2.txt" } }; + + // Start requests but don't await them + const promise1 = manager.requestPermission(toolCall1); + const promise2 = manager.requestPermission(toolCall2); + + const pendingIds = manager.getPendingRequestIds(); + expect(pendingIds).toHaveLength(2); + expect(pendingIds[0]).not.toBe(pendingIds[1]); + + // Clean up + manager.approveRequest(pendingIds[0]); + manager.approveRequest(pendingIds[1]); + await Promise.all([promise1, promise2]); + }); + + it("should store pending request details correctly", async () => { + const toolCall: ToolCallRequest = { name: "writeFile", arguments: { path: "/test.txt", content: "data" } }; + + const promise = manager.requestPermission(toolCall); + const pendingIds = manager.getPendingRequestIds(); + + expect(pendingIds).toHaveLength(1); + + const requestDetails = manager.getPendingRequest(pendingIds[0]); + expect(requestDetails).toBeDefined(); + expect(requestDetails?.toolCall).toEqual(toolCall); + + // Clean up + manager.approveRequest(pendingIds[0]); + await promise; + }); + + it("should remove request after approval", async () => { + const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } }; + + const promise = manager.requestPermission(toolCall); + const pendingIds = manager.getPendingRequestIds(); + const requestId = pendingIds[0]; + + expect(manager.getPendingRequest(requestId)).toBeDefined(); + + const approved = manager.approveRequest(requestId); + expect(approved).toBe(true); + + const result = await promise; + expect(result.approved).toBe(true); + expect(manager.getPendingRequest(requestId)).toBeUndefined(); + expect(manager.getPendingRequestIds()).toHaveLength(0); + }); + + it("should remove request after rejection", async () => { + const toolCall: ToolCallRequest = { name: "runTerminalCommand", arguments: { command: "rm -rf /" } }; + + const promise = manager.requestPermission(toolCall); + const pendingIds = manager.getPendingRequestIds(); + const requestId = pendingIds[0]; + + const rejected = manager.rejectRequest(requestId); + expect(rejected).toBe(true); + + const result = await promise; + expect(result.approved).toBe(false); + expect(manager.getPendingRequest(requestId)).toBeUndefined(); + }); + + it("should handle approval of non-existent request", () => { + const result = manager.approveRequest("non-existent-id"); + expect(result).toBe(false); + }); + + it("should handle rejection of non-existent request", () => { + const result = manager.rejectRequest("non-existent-id"); + expect(result).toBe(false); + }); + + it("should support remember option for approval", async () => { + const toolCall: ToolCallRequest = { name: "writeFile", arguments: { path: "/test.txt" } }; + + const promise = manager.requestPermission(toolCall); + const requestId = manager.getPendingRequestIds()[0]; + + manager.approveRequest(requestId, true); // Remember = true + + const result = await promise; + expect(result.approved).toBe(true); + expect(result.remember).toBe(true); + }); + }); + + describe("Event Emission", () => { + it("should emit permissionRequested event", (done) => { + const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } }; + + manager.on("permissionRequested", (event) => { + expect(event.requestId).toBeDefined(); + expect(event.toolCall).toEqual(toolCall); + done(); + }); + + manager.requestPermission(toolCall); + }); + + it("should emit permissionResponse event on approval", (done) => { + const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } }; + + manager.on("permissionResponse", (event) => { + expect(event.approved).toBe(true); + expect(event.requestId).toBeDefined(); + done(); + }); + + const promise = manager.requestPermission(toolCall); + const requestId = manager.getPendingRequestIds()[0]; + manager.approveRequest(requestId); + }); + + it("should emit permissionResponse event on rejection", (done) => { + const toolCall: ToolCallRequest = { name: "readFile", arguments: { path: "/test.txt" } }; + + manager.on("permissionResponse", (event) => { + expect(event.approved).toBe(false); + expect(event.requestId).toBeDefined(); + done(); + }); + + const promise = manager.requestPermission(toolCall); + const requestId = manager.getPendingRequestIds()[0]; + manager.rejectRequest(requestId); + }); + + it("should emit permissionResponse even for non-existent requests", (done) => { + manager.on("permissionResponse", (event) => { + expect(event.approved).toBe(true); + expect(event.requestId).toBe("fake-id"); + done(); + }); + + manager.approveRequest("fake-id"); + }); + }); + + describe("Concurrent Requests", () => { + it("should handle multiple concurrent requests", async () => { + const toolCalls = [ + { name: "readFile", arguments: { path: "/file1.txt" } }, + { name: "writeFile", arguments: { path: "/file2.txt", content: "data1" } }, + { name: "runTerminalCommand", arguments: { command: "ls" } }, + ]; + + // Start all requests + const promises = toolCalls.map(toolCall => manager.requestPermission(toolCall)); + + // Get all pending request IDs + const pendingIds = manager.getPendingRequestIds(); + expect(pendingIds).toHaveLength(3); + + // Approve first, reject second, approve third + manager.approveRequest(pendingIds[0]); + manager.rejectRequest(pendingIds[1]); + manager.approveRequest(pendingIds[2]); + + // Wait for all to complete + const results = await Promise.all(promises); + + expect(results[0].approved).toBe(true); + expect(results[1].approved).toBe(false); + expect(results[2].approved).toBe(true); + + // All requests should be cleared + expect(manager.getPendingRequestIds()).toHaveLength(0); + }); + }); + + describe("Edge Cases", () => { + it("should handle empty tool call arguments", async () => { + const toolCall: ToolCallRequest = { name: "exit", arguments: {} }; + + const promise = manager.requestPermission(toolCall); + const requestId = manager.getPendingRequestIds()[0]; + + manager.approveRequest(requestId); + const result = await promise; + + expect(result.approved).toBe(true); + }); + + it("should handle tool calls with complex arguments", async () => { + const toolCall: ToolCallRequest = { + name: "complexTool", + arguments: { + config: { host: "localhost", port: 3000 }, + options: ["verbose", "debug"], + metadata: { created: new Date(), version: "1.0.0" } + } + }; + + const promise = manager.requestPermission(toolCall); + const requestDetails = manager.getPendingRequest(manager.getPendingRequestIds()[0]); + + expect(requestDetails?.toolCall.arguments).toEqual(toolCall.arguments); + + manager.approveRequest(manager.getPendingRequestIds()[0]); + await promise; + }); + }); +}); \ No newline at end of file diff --git a/src/permissions/permissionManager.ts b/src/permissions/permissionManager.ts new file mode 100644 index 000000000..bf7a13b84 --- /dev/null +++ b/src/permissions/permissionManager.ts @@ -0,0 +1,97 @@ +import { EventEmitter } from "events"; +import { ToolCallRequest } from "./types.js"; + +export interface PermissionRequestResult { + approved: boolean; + remember?: boolean; // For future implementation - remember this decision +} + +export class ToolPermissionManager extends EventEmitter { + private pendingRequests = new Map< + string, + { + toolCall: ToolCallRequest; + resolve: (result: PermissionRequestResult) => void; + } + >(); + + private requestCounter = 0; + + /** + * Request permission for a tool call. Returns a promise that resolves + * when the user approves or rejects the request. + */ + async requestPermission( + toolCall: ToolCallRequest + ): Promise { + const requestId = `tool-request-${++this.requestCounter}`; + + return new Promise((resolve) => { + this.pendingRequests.set(requestId, { + toolCall, + resolve, + }); + + // Emit event for UI to handle + this.emit("permissionRequested", { + requestId, + toolCall, + }); + }); + } + + /** + * Approve a pending permission request + */ + approveRequest(requestId: string, remember = false): boolean { + const request = this.pendingRequests.get(requestId); + if (!request) { + // Also try to emit for the new event-based system + this.emit("permissionResponse", { requestId, approved: true }); + return false; + } + + this.pendingRequests.delete(requestId); + request.resolve({ approved: true, remember }); + + // Also emit for the new event-based system + this.emit("permissionResponse", { requestId, approved: true }); + return true; + } + + /** + * Reject a pending permission request + */ + rejectRequest(requestId: string): boolean { + const request = this.pendingRequests.get(requestId); + if (!request) { + // Also try to emit for the new event-based system + this.emit("permissionResponse", { requestId, approved: false }); + return false; + } + + this.pendingRequests.delete(requestId); + request.resolve({ approved: false }); + + // Also emit for the new event-based system + this.emit("permissionResponse", { requestId, approved: false }); + return true; + } + + /** + * Get details of a pending request + */ + getPendingRequest(requestId: string) { + return this.pendingRequests.get(requestId); + } + + /** + * Get all pending request IDs + */ + getPendingRequestIds(): string[] { + return Array.from(this.pendingRequests.keys()); + } +} + +// Global instance +export const toolPermissionManager = new ToolPermissionManager(); diff --git a/src/permissions/types.ts b/src/permissions/types.ts new file mode 100644 index 000000000..081e99803 --- /dev/null +++ b/src/permissions/types.ts @@ -0,0 +1,26 @@ +export type PermissionPolicy = "allow" | "ask" | "exclude"; + +export interface ToolPermissionPolicy { + /** The tool name to match against */ + tool: string; + /** The permission to apply */ + permission: PermissionPolicy; + /** Optional argument matching patterns. If not specified, applies to all calls to this tool */ + argumentMatches?: Record; +} + +export interface ToolPermissions { + /** Array of permission policies that are evaluated in order */ + policies: ToolPermissionPolicy[]; +} + +export interface ToolCallRequest { + name: string; + arguments: Record; +} + +export interface PermissionCheckResult { + permission: PermissionPolicy; + /** The policy that matched this tool call */ + matchedPolicy?: ToolPermissionPolicy; +} diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 3d6207a42..8180f2915 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -9,6 +9,11 @@ import type { } from "openai/resources.mjs"; import { parseArgs } from "./args.js"; import { MCPService } from "./mcp.js"; +import { + checkToolPermission, + filterExcludedTools, +} from "./permissions/index.js"; +import { toolPermissionManager } from "./permissions/permissionManager.js"; import telemetryService from "./telemetry/telemetryService.js"; import { calculateTokenCost } from "./telemetry/utils.js"; import { executeToolCall } from "./tools.js"; @@ -29,7 +34,24 @@ export function getAllTools() { return []; } - const allTools: ChatCompletionTool[] = BUILTIN_TOOLS.map((tool) => ({ + // Get all available tool names + const builtinToolNames = BUILTIN_TOOLS.map((tool) => tool.name); + const mcpToolNames = + MCPService.getInstance() + ?.getTools() + .map((tool) => tool.name) ?? []; + const allToolNames = [...builtinToolNames, ...mcpToolNames]; + + // Filter out excluded tools based on permissions + const allowedToolNames = filterExcludedTools(allToolNames); + const allowedToolNamesSet = new Set(allowedToolNames); + + // Filter builtin tools + const allowedBuiltinTools = BUILTIN_TOOLS.filter((tool) => + allowedToolNamesSet.has(tool.name) + ); + + const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({ type: "function" as const, function: { name: tool.name, @@ -49,10 +71,14 @@ export function getAllTools() { }, })); - // Add MCP tools if not in no-tools mode + // Add filtered MCP tools if not in no-tools mode const mcpTools = MCPService.getInstance()?.getTools() ?? []; + const allowedMcpTools = mcpTools.filter((tool) => + allowedToolNamesSet.has(tool.name) + ); + allTools.push( - ...mcpTools.map((tool) => ({ + ...allowedMcpTools.map((tool) => ({ type: "function" as const, function: { name: tool.name, @@ -71,6 +97,11 @@ export interface StreamCallbacks { onToolStart?: (toolName: string, toolArgs?: any) => void; onToolResult?: (result: string, toolName: string) => void; onToolError?: (error: string, toolName?: string) => void; + onToolPermissionRequest?: ( + toolName: string, + toolArgs: any, + requestId: string + ) => void; } interface ToolCall { @@ -423,6 +454,84 @@ export async function streamChatResponse( // Execute tool calls for (const toolCall of toolCalls) { try { + logger.debug("Checking tool permissions", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + + // Check tool permissions + const permissionCheck = checkToolPermission({ + name: toolCall.name, + arguments: toolCall.arguments, + }); + + let approved = false; + + if (permissionCheck.permission === "allow") { + approved = true; + } else if (permissionCheck.permission === "ask") { + // Request permission from user + if (callbacks?.onToolPermissionRequest) { + // Create a promise that resolves when permission is granted/denied + const permissionPromise = new Promise((resolve) => { + const requestId = `tool-request-${toolCall.id}`; + + // Set up listener for permission response + const handlePermissionResponse = (result: { + requestId: string; + approved: boolean; + }) => { + if (result.requestId === requestId) { + toolPermissionManager.off( + "permissionResponse", + handlePermissionResponse + ); + resolve(result.approved); + } + }; + + toolPermissionManager.on( + "permissionResponse", + handlePermissionResponse + ); + + // Notify UI about permission request + callbacks.onToolPermissionRequest!( + toolCall.name, + toolCall.arguments, + requestId + ); + }); + + approved = await permissionPromise; + } else { + // Fallback: deny if no UI callback available + approved = false; + } + } else if (permissionCheck.permission === "exclude") { + // This shouldn't happen as excluded tools are filtered out earlier + approved = false; + } + + if (!approved) { + const deniedMessage = `Permission denied by user`; + logger.info("Tool call denied", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + + chatHistory.push({ + role: "tool", + tool_call_id: toolCall.id, + content: deniedMessage, + }); + + if (callbacks?.onToolResult) { + callbacks.onToolResult(deniedMessage, toolCall.name); + } + continue; + } + logger.debug("Executing tool", { name: toolCall.name, arguments: toolCall.arguments, diff --git a/src/ui/Selector.tsx b/src/ui/Selector.tsx index b01b7a60f..cf58d7a3a 100644 --- a/src/ui/Selector.tsx +++ b/src/ui/Selector.tsx @@ -18,7 +18,11 @@ interface SelectorProps { onSelect: (option: T) => void; onCancel: () => void; onNavigate: (newIndex: number) => void; - renderOption?: (option: T, isSelected: boolean, isCurrent: boolean) => ReactNode; + renderOption?: ( + option: T, + isSelected: boolean, + isCurrent: boolean + ) => ReactNode; } export default function Selector({ @@ -90,13 +94,17 @@ export default function Selector({ ); } - const defaultRenderOption = (option: T, isSelected: boolean, isCurrent: boolean) => ( + const defaultRenderOption = ( + option: T, + isSelected: boolean, + isCurrent: boolean + ) => ( - {isSelected ? "▶ " : " "} + {isSelected ? "> " : " "} {option.name} {option.displaySuffix || ""} {isCurrent ? " (current)" : ""} @@ -120,9 +128,7 @@ export default function Selector({ const render = renderOption || defaultRenderOption; return ( - - {render(option, isSelected, isCurrent)} - + {render(option, isSelected, isCurrent)} ); })} @@ -133,4 +139,4 @@ export default function Selector({ ); -} \ No newline at end of file +} diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 619b0e09d..90bf0da37 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -8,6 +8,7 @@ import { MCPServiceState, ModelServiceState, } from "../services/types.js"; +import { ToolPermissionSelector } from "./components/ToolPermissionSelector.js"; import ConfigSelector from "./ConfigSelector.js"; import { startFileIndexing } from "./FileSearchUI.js"; import FreeTrialStatus from "./FreeTrialStatus.js"; @@ -134,10 +135,13 @@ const TUIChat: React.FC = ({ isWaitingForResponse, responseStartTime, inputMode, + attachedFiles, + activePermissionRequest, handleUserMessage, handleInterrupt, handleFileAttached, resetChatHistory, + handleToolPermissionResponse, } = useChat({ assistant: services.config?.config || undefined, model: services.model?.model || undefined, @@ -205,7 +209,8 @@ const TUIChat: React.FC = ({ showOrgSelector || showConfigSelector || !!loginPrompt || - isShowingFreeTrialTransition; + isShowingFreeTrialTransition || + !!activePermissionRequest; return ( @@ -302,16 +307,28 @@ const TUIChat: React.FC = ({ {/* Input area - only show when not showing free trial transition */} {!isShowingFreeTrialTransition && ( - + <> + {/* Show permission selector when there's an active permission request */} + {activePermissionRequest ? ( + + ) : ( + + )} + )} {/* Free trial status and Continue CLI info - always show */} diff --git a/src/ui/components/MemoizedMessage.tsx b/src/ui/components/MemoizedMessage.tsx index 5227543ec..48a87da42 100644 --- a/src/ui/components/MemoizedMessage.tsx +++ b/src/ui/components/MemoizedMessage.tsx @@ -9,80 +9,88 @@ interface MemoizedMessageProps { index: number; } -export const MemoizedMessage = memo(({ message, index }) => { - const isUser = message.role === "user"; - const isSystem = message.role === "system"; +export const MemoizedMessage = memo( + ({ message, index }) => { + const isUser = message.role === "user"; + const isSystem = message.role === "system"; - if (isSystem) { - switch (message.messageType) { - case "tool-start": - return ( - - ○ {message.content} - - ); - - case "tool-result": - return ( - - - ● - {message.content} + if (isSystem) { + switch (message.messageType) { + case "tool-start": + return ( + + ○ {message.content} - - + ); + + case "tool-result": + const isFailure = message.toolResult?.includes("Permission denied") || + message.toolResult?.includes("Error executing tool"); + return ( + + + ● + {message.content} + + + + - - ); + ); - case "tool-error": - return ( - - - ✗{" "} - - Tool error: {message.content} - - ); + case "tool-error": + return ( + + + ✗{" "} + + Tool error: {message.content} + + ); - default: - return ( - - - {message.content} - - - ); + + default: + return ( + + + {message.content} + + + ); + } } + + return ( + + ● + + {isUser ? ( + {message.content} + ) : ( + + )} + {message.isStreaming && ▋} + + ); + }, + (prevProps, nextProps) => { + // Custom comparison function for better performance + // Only re-render if these properties change + return ( + prevProps.message.content === nextProps.message.content && + prevProps.message.role === nextProps.message.role && + prevProps.message.messageType === nextProps.message.messageType && + prevProps.message.isStreaming === nextProps.message.isStreaming && + prevProps.message.toolName === nextProps.message.toolName && + prevProps.message.toolResult === nextProps.message.toolResult && + prevProps.message.permissionRequestId === + nextProps.message.permissionRequestId && + prevProps.index === nextProps.index + ); } +); - return ( - - ● - - {isUser ? ( - {message.content} - ) : ( - - )} - {message.isStreaming && ▋} - - ); -}, (prevProps, nextProps) => { - // Custom comparison function for better performance - // Only re-render if these properties change - return ( - prevProps.message.content === nextProps.message.content && - prevProps.message.role === nextProps.message.role && - prevProps.message.messageType === nextProps.message.messageType && - prevProps.message.isStreaming === nextProps.message.isStreaming && - prevProps.message.toolName === nextProps.message.toolName && - prevProps.message.toolResult === nextProps.message.toolResult && - prevProps.index === nextProps.index - ); -}); - -MemoizedMessage.displayName = "MemoizedMessage"; \ No newline at end of file +MemoizedMessage.displayName = "MemoizedMessage"; diff --git a/src/ui/components/ToolPermissionRequest.test.tsx b/src/ui/components/ToolPermissionRequest.test.tsx new file mode 100644 index 000000000..1f7f9bf76 --- /dev/null +++ b/src/ui/components/ToolPermissionRequest.test.tsx @@ -0,0 +1,78 @@ +// Note: This test file tests the formatArgs function that was used in the old ToolPermissionRequest component +// The function has been moved to ToolPermissionSelector but these tests are still valid for testing the pure function logic + +// Extract the formatArgs function for testing +// This mirrors the implementation in both ToolPermissionRequest.tsx and ToolPermissionSelector.tsx +function formatArgs(args: any): string { + if (!args || Object.keys(args).length === 0) return ""; + + const firstKey = Object.keys(args)[0]; + const firstValue = args[firstKey]; + + if (typeof firstValue === "string" && firstValue.length > 50) { + return `${firstValue.substring(0, 50)}...`; + } + + return String(firstValue); +} + +describe("formatArgs function", () => { + describe("formatArgs", () => { + it("should return empty string for no arguments", () => { + expect(formatArgs({})).toBe(""); + expect(formatArgs(null)).toBe(""); + expect(formatArgs(undefined)).toBe(""); + }); + + it("should return first argument value as string", () => { + expect(formatArgs({ path: "/test.txt" })).toBe("/test.txt"); + expect(formatArgs({ count: 42 })).toBe("42"); + expect(formatArgs({ enabled: true })).toBe("true"); + expect(formatArgs({ data: null })).toBe("null"); + }); + + it("should truncate long strings", () => { + const longString = "a".repeat(100); + const result = formatArgs({ content: longString }); + expect(result).toBe("a".repeat(50) + "..."); + expect(result.length).toBe(53); // 50 chars + "..." + }); + + it("should not truncate short strings", () => { + const shortString = "a".repeat(30); + const result = formatArgs({ content: shortString }); + expect(result).toBe(shortString); + expect(result).not.toContain("..."); + }); + + it("should handle exactly 50 character strings", () => { + const exactString = "a".repeat(50); + const result = formatArgs({ content: exactString }); + expect(result).toBe(exactString); + expect(result).not.toContain("..."); + }); + + it("should handle 51 character strings", () => { + const slightlyLongString = "a".repeat(51); + const result = formatArgs({ content: slightlyLongString }); + expect(result).toBe("a".repeat(50) + "..."); + }); + + it("should use first key when multiple arguments", () => { + const args = { path: "/test.txt", mode: "read", format: "json" }; + const result = formatArgs(args); + expect(result).toBe("/test.txt"); // Should use first key alphabetically + }); + + it("should handle non-string types", () => { + expect(formatArgs({ arr: [1, 2, 3] })).toBe("1,2,3"); + expect(formatArgs({ obj: { a: 1, b: 2 } })).toBe("[object Object]"); + expect(formatArgs({ num: 123.456 })).toBe("123.456"); + }); + + it("should handle special characters", () => { + expect(formatArgs({ path: "/special/chars!@#$%^&*()_+" })).toBe("/special/chars!@#$%^&*()_+"); + expect(formatArgs({ emoji: "🎉🎊✨" })).toBe("🎉🎊✨"); + }); + }); +}); \ No newline at end of file diff --git a/src/ui/components/ToolPermissionRequest.tsx b/src/ui/components/ToolPermissionRequest.tsx new file mode 100644 index 000000000..468becebe --- /dev/null +++ b/src/ui/components/ToolPermissionRequest.tsx @@ -0,0 +1,83 @@ +import { Box, Text, useInput } from "ink"; +import React, { useState } from "react"; + +interface ToolPermissionRequestProps { + toolName: string; + toolArgs: any; + requestId: string; + onResponse: (requestId: string, approved: boolean) => void; +} + +export const ToolPermissionRequest: React.FC = ({ + toolName, + toolArgs, + requestId, + onResponse, +}) => { + const [responded, setResponded] = useState(false); + + useInput((input, key) => { + if (responded) return; + + if (input === "y" || input === "Y") { + setResponded(true); + onResponse(requestId, true); + } else if (input === "n" || input === "N") { + setResponded(true); + onResponse(requestId, false); + } + }); + + if (responded) { + return null; // Component will be replaced by updated message + } + + const formatArgs = (args: any) => { + if (!args || Object.keys(args).length === 0) return ""; + + const firstKey = Object.keys(args)[0]; + const firstValue = args[firstKey]; + + if (typeof firstValue === "string" && firstValue.length > 50) { + return `${firstValue.substring(0, 50)}...`; + } + + return String(firstValue); + }; + + return ( + + + ⚠ + + Permission Required + + + + + Tool: {toolName} + + + {formatArgs(toolArgs) && ( + + + Args: {formatArgs(toolArgs)} + + + )} + + + Allow this tool call? ( + + y + + / + + n + + ) + + + + ); +}; diff --git a/src/ui/components/ToolPermissionSelector.tsx b/src/ui/components/ToolPermissionSelector.tsx new file mode 100644 index 000000000..2f79cd69b --- /dev/null +++ b/src/ui/components/ToolPermissionSelector.tsx @@ -0,0 +1,118 @@ +import { Box, Text, useInput } from "ink"; +import React, { useState } from "react"; +import { getToolDisplayName } from "../../tools.js"; + +interface PermissionOption { + id: string; + name: string; + color: string; + approved: boolean; +} + +interface ToolPermissionSelectorProps { + toolName: string; + toolArgs: any; + requestId: string; + onResponse: (requestId: string, approved: boolean) => void; +} + +const PERMISSION_OPTIONS: PermissionOption[] = [ + { id: "approve", name: "Continue", color: "green", approved: true }, + { id: "deny", name: "Cancel", color: "red", approved: false }, +]; + +export const ToolPermissionSelector: React.FC = ({ + toolName, + toolArgs, + requestId, + onResponse, +}) => { + const [selectedIndex, setSelectedIndex] = useState(0); + + useInput((input, key) => { + if (key.return) { + const selectedOption = PERMISSION_OPTIONS[selectedIndex]; + onResponse(requestId, selectedOption.approved); + return; + } + + // Tab to continue (approve) + if (key.tab) { + onResponse(requestId, true); + return; + } + + // Escape to reject (deny) + if (key.escape) { + onResponse(requestId, false); + return; + } + + if (key.upArrow) { + setSelectedIndex(Math.max(0, selectedIndex - 1)); + } else if (key.downArrow) { + setSelectedIndex( + Math.min(PERMISSION_OPTIONS.length - 1, selectedIndex + 1) + ); + } + + // Also support y/n for quick responses + if (input === "y" || input === "Y") { + onResponse(requestId, true); + } else if (input === "n" || input === "N") { + onResponse(requestId, false); + } + }); + + const formatArgs = (args: any) => { + if (!args || Object.keys(args).length === 0) return ""; + + const firstKey = Object.keys(args)[0]; + const firstValue = args[firstKey]; + + if (typeof firstValue === "string" && firstValue.length > 60) { + return `${firstValue.substring(0, 60)}...`; + } + + return String(firstValue); + }; + + const formattedArgs = formatArgs(toolArgs); + const displayName = getToolDisplayName(toolName); + + return ( + + + {displayName}({formattedArgs}) + + + + Would you like to continue? + {PERMISSION_OPTIONS.map((option, index) => { + const isSelected = index === selectedIndex; + const shortcut = option.approved ? "(tab)" : "(esc)"; + return ( + + + {isSelected ? "> " : " "} + {option.name} + + + {" "} + {shortcut} + + + ); + })} + + + ); +}; diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index a9ad58371..ff9c83f2e 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -4,6 +4,7 @@ import { useApp } from "ink"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; import path from "path"; import { useEffect, useState } from "react"; +import { toolPermissionManager } from "../../permissions/permissionManager.js"; import { loadSession, saveSession } from "../../session.js"; import { handleSlashCommands } from "../../slashCommands.js"; import { @@ -114,6 +115,11 @@ export function useChat({ const [attachedFiles, setAttachedFiles] = useState< Array<{ path: string; content: string }> >([]); + const [activePermissionRequest, setActivePermissionRequest] = useState<{ + toolName: string; + toolArgs: any; + requestId: string; + } | null>(null); // Remote mode polling useEffect(() => { @@ -548,6 +554,18 @@ export function useChat({ }, ]); }, + onToolPermissionRequest: ( + toolName: string, + toolArgs: any, + requestId: string + ) => { + // Set the active permission request to show the selector + setActivePermissionRequest({ + toolName, + toolArgs, + requestId, + }); + }, }; // Call streamChatResponse with the new history that includes the user message @@ -652,6 +670,23 @@ export function useChat({ setMessages([]); }; + const handleToolPermissionResponse = ( + requestId: string, + approved: boolean + ) => { + // Clear the active permission request + setActivePermissionRequest(null); + + // Send response to permission manager + // The streamChatResponse will handle showing the appropriate message + // through its normal onToolStart/onToolError flow + if (approved) { + toolPermissionManager.approveRequest(requestId); + } else { + toolPermissionManager.rejectRequest(requestId); + } + }; + return { messages, setMessages, @@ -661,9 +696,11 @@ export function useChat({ responseStartTime, inputMode, attachedFiles, + activePermissionRequest, handleUserMessage, handleInterrupt, handleFileAttached, resetChatHistory, + handleToolPermissionResponse, }; } diff --git a/src/ui/hooks/useMessageRenderer.tsx b/src/ui/hooks/useMessageRenderer.tsx index e9f572172..bb8e719d6 100644 --- a/src/ui/hooks/useMessageRenderer.tsx +++ b/src/ui/hooks/useMessageRenderer.tsx @@ -4,7 +4,13 @@ import { DisplayMessage } from "../types.js"; export function useMessageRenderer() { const renderMessage = useCallback((message: DisplayMessage, index: number) => { - return ; + return ( + + ); }, []); return { renderMessage }; diff --git a/src/ui/types.ts b/src/ui/types.ts index 91ec986e5..a478e3d2d 100644 --- a/src/ui/types.ts +++ b/src/ui/types.ts @@ -2,7 +2,14 @@ export interface DisplayMessage { role: string; content: string; isStreaming?: boolean; - messageType?: "tool-start" | "tool-result" | "tool-error" | "system"; + messageType?: + | "tool-start" + | "tool-result" + | "tool-error" + | "system" + | "tool-permission-request"; toolName?: string; toolResult?: string; + toolArgs?: any; + permissionRequestId?: string; }