diff --git a/example-permissions.yaml b/example-permissions.yaml new file mode 100644 index 000000000..05f2e5c83 --- /dev/null +++ b/example-permissions.yaml @@ -0,0 +1,23 @@ +# Example permissions.yaml file +# This shows how you can configure tool permissions + +# Tools that are automatically allowed without prompting +allow: + - Read # or read_file, read, READ - all normalized + - List # or list_files + - Search # or search_code + +# Tools that require user confirmation before execution +ask: + - Write # or write_file + - Terminal # or run_terminal_command, Bash, bash + +# Tools that are completely excluded (model won't know they exist) +exclude: + - Exit # or exit + +# You can also use wildcards +# allow: +# - mcp__* # Allow all MCP tools +# exclude: +# - * # Exclude everything else \ No newline at end of file diff --git a/spec/config-loading.md b/spec/config-loading.md new file mode 100644 index 000000000..0f474b5a7 --- /dev/null +++ b/spec/config-loading.md @@ -0,0 +1,191 @@ +# Configuration Loading Behavior Specification + +## Overview + +This document specifies the behavior of the CLI's configuration loading system, including precedence rules, authentication interactions, and error handling. + +## Authentication Precedence + +**Authentication Source Priority:** + +1. **Environment Variable**: `CONTINUE_API_KEY` environment variable +2. **File-Based Auth**: `~/.continue/auth.json` file +3. **No Authentication**: Unauthenticated mode + +**Authentication Effects:** + +- **Environment Auth**: Always uses personal organization, no config URI persistence +- **File Auth**: Supports organizations, persists config URIs, token refresh +- **No Auth**: Limited to default assistant, no personalization + +## Configuration Source Precedence + +**When CLI is invoked, config source is determined in this order:** + +1. **CLI `--config` Flag** (highest priority) + + - File path (starts with `.`, `/`, `~`): Loads local YAML file + - Assistant slug (`owner/package`): Fetches from Continue platform + - Overrides any saved preferences + +2. **Saved Config URI** (if no `--config` flag) + + - Retrieved from authentication config + - Converts `file://` URIs back to file paths + - Converts `slug://` URIs back to assistant slugs + +3. **Default Resolution** (if no flag and no saved URI) + - **Authenticated**: First user assistant from `listAssistants()` + - **config.yaml**: The saved config file at `~/.continue/config.yaml` + - **Unauthenticated**: Falls back to `continuedev/default-agent` + +## Authentication State Interactions + +### Authenticated Users + +**Available Options:** + +- Personal assistants +- Organization assistants (if organization selected) +- Local YAML files +- Public assistants + +**Behavior:** + +- `listAssistants()` returns personalized results +- Config selections are saved as URIs in auth config +- Organization context affects available assistants + +### Unauthenticated Users + +**Available Options:** + +- Local YAML files only +- Default assistant (`continuedev/default-agent`) + +**Behavior:** + +- No access to personal or organization assistants +- No config URI persistence +- Direct fallback to default when no config specified + +### Environment Variable Auth (`CONTINUE_API_KEY`) + +**Behavior:** + +- Treated as authenticated for API access +- Always uses personal organization context +- No persistence of config URIs +- Cannot switch organizations + +## Organization Context + +**Organization Selection:** + +- **Interactive Mode**: Auto-selects first available organization +- **Headless Mode**: Defaults to personal organization +- **Environment Auth**: Always personal organization + +**Effects on Config Loading:** + +- Organization ID passed to all API calls +- Affects which assistants appear in `listAssistants()` +- Organization changes trigger complete config reload + +## Error Handling Behavior + +### Config Loading Errors + +**File Not Found:** + +- Local file specified but doesn't exist +- **Result**: Error thrown, CLI exits + +**Invalid YAML:** + +- Local file exists but has syntax errors +- **Result**: Parsing error thrown, CLI exits + +**Network Failures:** + +- API calls fail for assistant slugs +- **Result**: Network error bubbled up, CLI exits + +**Assistant Not Found:** + +- Valid slug format but assistant doesn't exist +- **Result**: 404 error from API, CLI exits + +### Fallback Scenarios + +**No User Assistants:** + +- Authenticated user has no personal assistants +- **Result**: Falls back to `continuedev/default-agent` + +**Default Agent Unavailable:** + +- Fallback to default agent fails +- **Result**: Error thrown, CLI cannot start + +**Token Expired:** + +- Saved auth token is expired +- **Result**: Automatic refresh attempted, re-auth required if refresh fails + +## Config URI Persistence + +**When URIs are Saved:** + +- Any successful config load via service layer +- File paths converted to `file://path/to/config.yaml` +- Assistant slugs converted to `slug://owner/package` + +**When URIs are NOT Saved:** + +- Environment variable authentication in use +- Config loading failures +- Unauthenticated sessions + +## Rule Integration + +**Rule Processing:** + +- `--rule` flags processed independently of config loading +- Multiple rules supported, injected into system message +- Rule failures are warnings, don't prevent config loading +- Rule sources: file paths, hub slugs, direct strings + +## Session Continuity + +**Next Session Behavior:** + +- **With Saved URI**: Uses saved config automatically +- **CLI Override**: `--config` flag overrides saved URI and updates it +- **Config Switching**: UI actions update saved URI for future sessions + +**Cross-Session State:** + +- Authentication persists until logout +- Organization selection persists +- Config URI persists (except for environment auth) + +## Complete Decision Flow + +``` +1. Parse CLI arguments +2. Load authentication state (env var > file > none) +3. Determine config source: + - CLI --config flag provided? Use it + - Saved config URI exists? Use it + - Default resolution based on auth state +4. Load configuration: + - File path? Parse YAML locally + - Assistant slug? Fetch from API + - Default resolution? List assistants or use default +5. Process and inject rules +6. Save config URI (if authenticated via file) +7. Initialize services with loaded config +``` + +This behavior ensures users get predictable config loading with clear precedence rules while maintaining session continuity and graceful fallbacks. diff --git a/spec/permissions.md b/spec/permissions.md index b4340aa5e..380c7bfba 100644 --- a/spec/permissions.md +++ b/spec/permissions.md @@ -1,34 +1,74 @@ # Permissions +## Permission types + +To make sure that users can oversee the actions of the LLM, we implement a permissions system. Every tool has one of the following permissions: + +- `allow`: The tool will be automatically called without asking +- `ask`: We will ask the user before calling the tool, giving them the options to accept or reject +- `exclude`: This tool will be completely excluded, so the model won't even know it exists + +## Rule precedence + +There is a default set of permissions for the builtin tools in [`src/permissions/defaultPolicies.ts`](../src/permissions/defaultPolicies.ts). But these policies can be overriden by multiple layers. The order of precedence is as follows, which the earlier items taking precedence: + +1. Command line flags +2. Permissions in `config.yaml` / configuration +3. Permissions in `~/.continue/permissions.yaml` +4. Default policies + +## Tool matching patterns + +We use a tool matching pattern to match tools to permissions. This format looks like the following: + +- `Read` matches any call to the `Read` tool +- `Read(*)` also matches any call to the `Read` tool +- `Read(**/*.ts)` matches any call to the `Read` tool where the primary parameter matches the glob pattern `**/*.ts`. + +Note that for an `exclude` policy, it doesn't make sense to have argument matching. + +## Command line flags + +Each of the `--allow`, `--ask`, and `--exclude` flags allow you to set the permission for a tool. Usage must be a "tool matching pattern" as described above for each flag, with each providing a policy that will be added to the list of policies in order. + ```bash +# Allow Read, Ask Write, and Exclude Bash cn --allow Read --ask Write --exclude Bash +# No tools except for Read cn --no-tools --allow Read -cn --only Read +# Ideas for later +# cn --only Read -cn --mcp anthropic/filesystem --no-tools --allow anthropic/filesystem/read_file +# cn --mcp anthropic/filesystem --no-tools --allow anthropic/filesystem/read_file ``` +## `config.yaml` / Configuration (implement later) + +::: info +This should not be implemented yet. +::: + +To let users define their permissions as a part of their custom assistant, they can do so in the permissions section of `config.yaml` or their configuration: + ```yaml -mcpServers: - - name: GitHub MCP - type: streamable-http - url: https://api.github.com/mcp - permissions: - - tool: Read - permission: allow - - tool: Write - permission: ask - - tool: Bash - permission: exclude + allow: + - Read(*) -permissions: - - Read(*) - - ~Write(**/*.ts) - - !Bash(*) + ask: + - Write(**/*.py) + exclude: + - Write +``` + +## `~/.continue/permissions.yaml` (personal settings) + +It would be frustrating for users to have to set the same permissions across all of their assistants, so we provide them a file for personal settings. It should be basically equivalent to the `permissions` section of `config.yaml`: + +```yaml title="~/.continue/permissions.yaml" allow: - Read(*) @@ -38,3 +78,7 @@ ask: exclude: - Write ``` + +Except that it's important to understand that this file is _not_ intended to be edited by the user. It is only for persistence, and users should interact with their permissions by using the TUI. + +This file should be created the first time that the CLI starts. diff --git a/spec/testing-strategies.md b/spec/testing-strategies.md new file mode 100644 index 000000000..39f7ab16f --- /dev/null +++ b/spec/testing-strategies.md @@ -0,0 +1,149 @@ +# Testing Strategies + +This document provides an overview of the different testing strategies used in this repository, when to use each type, and links to examples. + +## Test Types + +### 1. Unit Tests + +**Purpose**: Test individual functions, utilities, and modules in isolation. + +**When to use**: + +- Testing pure functions with predictable inputs/outputs +- Testing utility functions and helpers +- Testing business logic components +- Testing error handling and edge cases + +**Framework**: Jest with TypeScript support + +**Examples**: + +- [`src/util/formatError.test.ts`](../src/util/formatError.test.ts) - Tests error formatting utility +- [`src/util/exponentialBackoff.test.ts`](../src/util/exponentialBackoff.test.ts) - Tests backoff logic +- [`src/logging.test.ts`](../src/logging.test.ts) - Tests logging functionality +- [`src/args.test.ts`](../src/args.test.ts) - Tests argument parsing + +**How to run**: `npm test` (includes linting) + +### 2. Service Tests + +**Purpose**: Test service classes and dependency injection system. + +**When to use**: + +- Testing service initialization and lifecycle +- Testing service dependencies and injection +- Testing service container behavior +- Testing service configuration loading + +**Examples**: + +- [`src/services/ServiceContainer.test.ts`](../src/services/ServiceContainer.test.ts) - Tests dependency injection +- [`src/services/ConfigService.test.ts`](../src/services/ConfigService.test.ts) - Tests configuration loading +- [`src/services/circular-dependencies.test.ts`](../src/services/circular-dependencies.test.ts) - Tests circular dependency detection + +### 3. UI Component Tests + +**Purpose**: Test React components using Ink testing library for terminal UI. + +**When to use**: + +- Testing component rendering and display +- Testing user interactions and input handling +- Testing component state changes +- Testing message display and formatting + +**Framework**: Jest + Ink Testing Library + React Testing utilities + +**Examples**: + +- [`src/ui/__tests__/TUIChat.basic.test.tsx`](../src/ui/__tests__/TUIChat.basic.test.tsx) - Basic rendering tests +- [`src/ui/__tests__/TUIChat.messages.test.tsx`](../src/ui/__tests__/TUIChat.messages.test.tsx) - Message display tests +- [`src/ui/__tests__/TUIChat.input.test.tsx`](../src/ui/__tests__/TUIChat.input.test.tsx) - Input handling tests +- [`src/ui/MarkdownRenderer.test.tsx`](../src/ui/MarkdownRenderer.test.tsx) - Markdown rendering tests + +**Test Checklist**: See [`src/ui/UI_TEST_CHECKLIST.md`](../src/ui/UI_TEST_CHECKLIST.md) for comprehensive UI testing guidelines. + +### 4. E2E (End-to-End) Tests + +**Purpose**: Test complete user workflows and CLI behavior in realistic scenarios. + +**When to use**: + +- Testing full CLI command execution +- Testing authentication flows +- Testing configuration loading and switching +- Testing tool execution and responses +- Testing headless and interactive modes + +**Examples**: + +- [`src/e2e/auth.test.ts`](../src/e2e/auth.test.ts) - Authentication workflows +- [`src/e2e/basic-commands.test.ts`](../src/e2e/basic-commands.test.ts) - Basic CLI commands +- [`src/e2e/headless-tool-calls.test.ts`](../src/e2e/headless-tool-calls.test.ts) - Tool execution in headless mode +- [`src/e2e/config-switching.test.tsx`](../src/e2e/config-switching.test.tsx) - Configuration switching + +## Testing Infrastructure + +### Test Helpers + +**Service Container Testing**: + +- [`src/test-helpers/testServiceContainer.ts`](../src/test-helpers/testServiceContainer.ts) - Mock service container setup +- [`src/test-helpers/ui-test-context.ts`](../src/test-helpers/ui-test-context.ts) - UI test context setup + +**CLI Testing**: + +- Test helpers in [`src/test-helpers/`](../src/test-helpers/) for CLI command execution + +### Mocks + +**UI Mocks**: [`src/ui/__mocks__/`](../src/ui/__mocks__/) + +- Syntax highlighter mocks +- Component mocks for testing + +**Service Mocks**: [`src/__mocks__/`](../src/__mocks__/) + +- Authentication mocks +- Service mocks +- Logging mocks + +## Configuration + +**Jest Configuration**: [`jest.config.mjs`](../jest.config.mjs) + +- TypeScript support with ES modules +- React/Ink component testing setup +- Mock configurations +- Test timeout and environment settings + +## Running Tests + +```bash +# Run all tests with linting +npm test + +# Run tests in watch mode (Jest only) +npx jest --watch + +# Run specific test file +npx jest src/util/formatError.test.ts + +# Run tests with coverage +npx jest --coverage +``` + +## Best Practices + +1. **Unit Tests**: Focus on pure functions and isolated logic +2. **Service Tests**: Test dependency injection and service lifecycle +3. **UI Tests**: Test user-visible behavior, not implementation details +4. **E2E Tests**: Test complete user workflows and CLI behavior + +5. **Keep tests focused**: One behavior per test +6. **Use descriptive names**: Test names should explain what's being tested +7. **Minimal mocking**: Only mock external dependencies and APIs +8. **Test error cases**: Include negative test cases and edge conditions +9. **Maintain test isolation**: Each test should be independent diff --git a/spec/wire-format.md b/spec/wire-format.md index 6b176b395..f77f4413c 100644 --- a/spec/wire-format.md +++ b/spec/wire-format.md @@ -1,6 +1,6 @@ # HTTP Wire Protocol: `cn remote` � `cn serve` -This document describes the HTTP protocol used for communication between the `cn remote` client and `cn serve` server. +This document describes the HTTP protocol used for communication between the `cn remote` client and `cn serve` server ## Overview diff --git a/src/commands/BaseCommandOptions.ts b/src/commands/BaseCommandOptions.ts new file mode 100644 index 000000000..95e34af80 --- /dev/null +++ b/src/commands/BaseCommandOptions.ts @@ -0,0 +1,27 @@ +/** + * Base interface for command options that are shared across multiple commands + */ +export interface BaseCommandOptions { + /** Path to configuration file */ + config?: string; + /** Array of rule specifications (can be file paths, hub slugs, or string content) */ + rule?: string[]; + /** Array of tools to allow (overrides default policies) */ + allow?: string[]; + /** Array of tools to ask permission for (overrides default policies) */ + ask?: string[]; + /** Array of tools to exclude from use (overrides default policies) */ + exclude?: string[]; +} + +/** + * Extended base options that include verbose and tool control flags + */ +export interface ExtendedCommandOptions extends BaseCommandOptions { + /** Enable verbose logging */ + verbose?: boolean; + /** Only allow readonly tools */ + readonly?: boolean; + /** Disable all tools */ + noTools?: boolean; +} \ No newline at end of file diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 6c2101521..30d6075c3 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -17,13 +17,12 @@ import { startTUIChat } from "../ui/index.js"; import { safeStdout } from "../util/consoleOverride.js"; import { formatError } from "../util/formatError.js"; import logger from "../util/logger.js"; +import { BaseCommandOptions } from "./BaseCommandOptions.js"; import { posthogService } from "../telemetry/posthogService.js"; -export interface ChatOptions { +export interface ChatOptions extends BaseCommandOptions { headless?: boolean; - config?: string; resume?: boolean; - rule?: string[]; // Array of rule specifications } async function initializeChatHistory( @@ -110,6 +109,11 @@ async function runHeadlessMode( configPath: options.config, rules: options.rule, headless: true, + toolPermissionOverrides: { + allow: options.allow, + ask: options.ask, + exclude: options.exclude, + }, }); // Get required services from the service container @@ -176,7 +180,11 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { console.log(CONTINUE_ASCII_ART); // Start TUI immediately - it will handle service loading - await startTUIChat(prompt, options.resume, options.config, options.rule); + await startTUIChat(prompt, options.resume, options.config, options.rule, { + allow: options.allow, + ask: options.ask, + exclude: options.exclude, + }); return; } diff --git a/src/commands/commands.ts b/src/commands/commands.ts index b245f9655..ab0569f11 100644 --- a/src/commands/commands.ts +++ b/src/commands/commands.ts @@ -47,6 +47,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ description: "Switch organization", category: "system", }, + { + name: "model", + description: "Switch between available chat models", + category: "system", + }, { name: "config", description: "Switch configuration", diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 55d322e62..d1d404364 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -5,13 +5,12 @@ import type { ChatCompletionMessageParam } from "openai/resources.mjs"; import path from "path"; import { promisify } from "util"; import { - ensureOrganization, getAssistantSlug, - getOrganizationId, - loadAuthConfig, } from "../auth/workos.js"; -import { runNormalFlow } from "../onboarding.js"; +import { toolPermissionManager } from "../permissions/permissionManager.js"; import { saveSession } from "../session.js"; +import { getService, initializeServices, SERVICE_NAMES } from "../services/index.js"; +import { AuthServiceState, ConfigServiceState, ModelServiceState } from "../services/types.js"; import { streamChatResponse, type StreamCallbacks } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; import telemetryService from "../telemetry/telemetryService.js"; @@ -19,19 +18,23 @@ import { getToolDisplayName } from "../tools.js"; import { DisplayMessage } from "../ui/types.js"; import { formatError } from "../util/formatError.js"; import logger from "../util/logger.js"; +import { ExtendedCommandOptions } from "./BaseCommandOptions.js"; const execAsync = promisify(exec); -interface ServeOptions { - config?: string; - readonly?: boolean; - noTools?: boolean; - verbose?: boolean; - rule?: string[]; +interface ServeOptions extends ExtendedCommandOptions { timeout?: string; port?: string; } +interface PendingPermission { + toolName: string; + toolArgs: any; + requestId: string; + timestamp: number; +} + + interface ServerState { chatHistory: ChatCompletionMessageParam[]; displayMessages: DisplayMessage[]; // Messages formatted for display with tool info @@ -43,6 +46,7 @@ interface ServerState { currentAbortController: AbortController | null; shouldInterrupt: boolean; serverRunning: boolean; + pendingPermission: PendingPermission | null; } export async function serve(prompt?: string, options: ServeOptions = {}) { @@ -50,32 +54,44 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { const timeoutMs = timeoutSeconds * 1000; const port = parseInt(options.port || "8000", 10); - // Initialize authentication - const authConfig = loadAuthConfig(); + // Initialize services with tool permission overrides + await initializeServices({ + toolPermissionOverrides: { + allow: options.allow, + ask: options.ask, + exclude: options.exclude, + }, + configPath: options.config, + rules: options.rule, + headless: true, // Skip onboarding in serve mode + }); - // Initialize with normal flow (skip onboarding like headless mode) - const { config, llmApi, model } = await runNormalFlow( - authConfig, - options.config, - options.rule - ); + // Get initialized services from the service container + const [configState, modelState] = await Promise.all([ + getService(SERVICE_NAMES.CONFIG), + getService(SERVICE_NAMES.MODEL), + ]); - // Ensure organization is selected if authenticated - let finalAuthConfig = authConfig; - if (config && authConfig) { - finalAuthConfig = await ensureOrganization(authConfig, true); // headless mode - if (finalAuthConfig) { - const organizationId = getOrganizationId(finalAuthConfig); - if (organizationId) { - telemetryService.updateOrganization(organizationId); - } - } + if (!configState.config || !modelState.llmApi || !modelState.model) { + throw new Error("Failed to initialize required services"); + } + + const { config, llmApi, model } = { + config: configState.config, + llmApi: modelState.llmApi, + model: modelState.model, + }; + + // Organization selection is already handled in initializeServices + const authState = await getService(SERVICE_NAMES.AUTH); + if (authState.organizationId) { + telemetryService.updateOrganization(authState.organizationId); } // Log configuration information - const organizationId = getOrganizationId(finalAuthConfig || authConfig) || 'personal'; + const organizationId = authState.organizationId || 'personal'; const assistantName = config.name; - const assistantSlug = getAssistantSlug(finalAuthConfig || authConfig); + const assistantSlug = getAssistantSlug(authState.authConfig); const modelProvider = model.provider; const modelName = model.model; @@ -83,6 +99,9 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { console.log(chalk.dim(` Organization: ${organizationId}`)); console.log(chalk.dim(` Assistant: ${assistantName}${assistantSlug ? ` (${assistantSlug})` : ''}`)); console.log(chalk.dim(` Model: ${modelProvider}/${modelName}`)); + if (options.config) { + console.log(chalk.dim(` Config file: ${options.config}`)); + } // Initialize chat history let chatHistory: ChatCompletionMessageParam[] = []; @@ -103,6 +122,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { currentAbortController: null, shouldInterrupt: false, serverRunning: true, + pendingPermission: null, }; // Record session start @@ -119,6 +139,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { chatHistory: state.displayMessages, // Send display messages with proper formatting isProcessing: state.isProcessing, messageQueueLength: state.messageQueue.length, + pendingPermission: state.pendingPermission, }); }); @@ -151,6 +172,42 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { } }); + // POST /permission - Approve or reject pending tool permission + app.post("/permission", async (req: Request, res: Response) => { + state.lastActivity = Date.now(); + + const { requestId, approved } = req.body; + + if (!state.pendingPermission) { + return res.status(400).json({ error: "No pending permission request" }); + } + + if (state.pendingPermission.requestId !== requestId) { + return res.status(400).json({ error: "Invalid request ID" }); + } + + // Remove the permission request message + const lastMsg = state.displayMessages[state.displayMessages.length - 1]; + if (lastMsg && lastMsg.messageType === "tool-permission-request") { + state.displayMessages.pop(); + } + + // Send the permission response to the toolPermissionManager + if (approved) { + toolPermissionManager.approveRequest(requestId); + } else { + toolPermissionManager.rejectRequest(requestId); + } + + // Clear pending permission state + state.pendingPermission = null; + + res.json({ + success: true, + approved, + }); + }); + // GET /diff - Return git diff against main branch app.get("/diff", async (_req: Request, res: Response) => { state.lastActivity = Date.now(); @@ -231,14 +288,17 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { const server = app.listen(port, () => { console.log(chalk.green(`Server started on http://localhost:${port}`)); console.log(chalk.dim("Endpoints:")); - console.log(chalk.dim(" GET /state - Get current agent state")); + console.log(chalk.dim(" GET /state - Get current agent state")); console.log( - chalk.dim(" POST /message - Send a message (body: { message: string })") + chalk.dim(" POST /message - Send a message (body: { message: string })") ); console.log( - chalk.dim(" GET /diff - Get git diff against main branch") + chalk.dim(" POST /permission - Approve/reject tool (body: { requestId, approved })") ); - console.log(chalk.dim(" POST /exit - Gracefully shut down the server")); + console.log( + chalk.dim(" GET /diff - Get git diff against main branch") + ); + console.log(chalk.dim(" POST /exit - Gracefully shut down the server")); console.log( chalk.dim( `\nServer will shut down after ${timeoutSeconds} seconds of inactivity` @@ -471,6 +531,29 @@ async function streamChatResponseWithInterruption( toolName, }); }, + onToolPermissionRequest: ( + toolName: string, + toolArgs: any, + requestId: string + ) => { + // Set pending permission state + state.pendingPermission = { + toolName, + toolArgs, + requestId, + timestamp: Date.now(), + }; + + // Add a display message indicating permission is needed + state.displayMessages.push({ + role: "system", + content: `⚠️ Tool ${toolName} requires permission`, + messageType: "tool-permission-request" as any, + toolName, + }); + + // Don't wait here - the streamChatResponse will handle waiting + }, }; try { diff --git a/src/config.ts b/src/config.ts index 2e473fe1e..64c90897e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -22,6 +22,7 @@ import { getOrganizationId, } from "./auth/workos.js"; import { CLIPlatformClient } from "./CLIPlatformClient.js"; +import { loadConfiguration } from "./configLoader.js"; import { env } from "./env.js"; import { MCPService } from "./mcp.js"; @@ -123,79 +124,6 @@ export function getApiClient( ); } -export async function loadConfig( - authConfig: AuthConfig, - config: string | undefined, - organizationId: string | null, - apiClient?: DefaultApiInterface -): Promise { - if (!apiClient) { - apiClient = getApiClient(authConfig?.accessToken); - } - - if (!config) { - // Fall back to listing assistants and taking the first one - const assistants = await apiClient.listAssistants({ - alwaysUseProxy: "false", - organizationId: organizationId ?? undefined, - }); - - if (assistants.length === 0) { - // In case the user doesn't have any assistants, we fall back to a default - TODO - const resp = await apiClient.getAssistant({ - ownerSlug: "continuedev", - packageSlug: "default-agent", - organizationId: organizationId ?? undefined, - }); - - if (!resp.configResult.config) { - throw new Error("Failed to load default agent."); - } - return resp.configResult.config as AssistantUnrolled; - } - - const result = assistants[0].configResult; - - if (result.errors?.length || !result.config) { - throw new Error(result.errors?.join("\n") ?? "Failed to load assistant."); - } - - return result.config as AssistantUnrolled; - } - - if ( - config.startsWith(".") || - config.startsWith("/") || - config.startsWith("~") - ) { - // Load from file - const configYaml = await loadConfigYaml( - authConfig?.accessToken ?? null, - config, - organizationId, - apiClient - ); - - return configYaml; - } else { - // Load from slug - const [ownerSlug, packageSlug] = config.split("/"); - const resp = await apiClient.getAssistant({ - ownerSlug, - packageSlug, - alwaysUseProxy: "false", - organizationId: organizationId ?? undefined, - }); - - const result = resp.configResult; - if (result.errors?.length || !result.config) { - throw new Error(result.errors?.join("\n") ?? "Failed to load assistant."); - } - - return result.config as AssistantUnrolled; - } -} - export async function initialize( authConfig: AuthConfig, configPath: string | undefined @@ -206,14 +134,9 @@ export async function initialize( mcpService: MCPService; apiClient: DefaultApiInterface; }> { - const organizationId = getOrganizationId(authConfig); const apiClient = getApiClient(authConfig?.accessToken); - const config = await loadConfig( - authConfig, - configPath, - organizationId, - apiClient - ); + const result = await loadConfiguration(authConfig, configPath, apiClient); + const config = result.config; const [llmApi, model] = getLlmApi(config, authConfig); const mcpService = await MCPService.create(config); diff --git a/src/configLoader.ts b/src/configLoader.ts new file mode 100644 index 000000000..3c54366c9 --- /dev/null +++ b/src/configLoader.ts @@ -0,0 +1,334 @@ +import { + AssistantUnrolled, + RegistryClient, + unrollAssistant, +} from "@continuedev/config-yaml"; +import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; +import chalk from "chalk"; +import * as fs from "fs"; +import { dirname } from "node:path"; +import * as os from "os"; +import * as path from "path"; +import { + AuthConfig, + getAccessToken, + getConfigUri, + getOrganizationId, + isEnvironmentAuthConfig, + updateConfigUri, + uriToPath, + uriToSlug, +} from "./auth/workos.js"; +import { CLIPlatformClient } from "./CLIPlatformClient.js"; +import { env } from "./env.js"; + +export interface ConfigLoadResult { + config: AssistantUnrolled; + source: ConfigSource; +} + +export type ConfigSource = + | { type: "cli-flag"; path: string } + | { type: "saved-uri"; uri: string } + | { type: "user-assistant"; slug: string } + | { type: "default-config-yaml" } + | { type: "default-agent" }; + +/** + * Streamlined configuration loader that implements the specification + * with clear precedence and fallback logic in a single testable function. + */ +export async function loadConfiguration( + authConfig: AuthConfig, + cliConfigPath: string | undefined, + apiClient: DefaultApiInterface +): Promise { + const organizationId = getOrganizationId(authConfig); + const accessToken = getAccessToken(authConfig); + + // Step 1: Determine config source using precedence rules + const configSource = determineConfigSource(authConfig, cliConfigPath); + + // Step 2: Load configuration from the determined source + const config = await loadFromSource(configSource, accessToken, organizationId, apiClient); + + // Step 3: Save config URI for session continuity (only for file-based auth) + if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) { + const uri = getUriFromSource(configSource); + if (uri) { + updateConfigUri(uri); + } + } + + return { config, source: configSource }; +} + +/** + * Determines the configuration source using the specification's precedence rules: + * 1. CLI --config flag (highest priority) + * 2. Saved config URI (if no CLI flag) + * 3. Default resolution (if no flag and no saved URI) + */ +function determineConfigSource( + authConfig: AuthConfig, + cliConfigPath: string | undefined +): ConfigSource { + // Priority 1: CLI --config flag + if (cliConfigPath) { + return { type: "cli-flag", path: cliConfigPath }; + } + + // Priority 2: Saved config URI (only for file-based auth) + if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) { + const savedUri = getConfigUri(authConfig); + if (savedUri) { + return { type: "saved-uri", uri: savedUri }; + } + } + + // Priority 3: Default resolution based on auth state + if (authConfig !== null) { + // Authenticated: try user assistants first + return { type: "user-assistant", slug: "" }; // Empty slug means "first available" + } else { + // Unauthenticated: check for default config.yaml, then fallback to default agent + const defaultConfigPath = path.join(os.homedir(), ".continue", "config.yaml"); + if (fs.existsSync(defaultConfigPath)) { + return { type: "default-config-yaml" }; + } + return { type: "default-agent" }; + } +} + +/** + * Loads configuration from the determined source with appropriate error handling + */ +async function loadFromSource( + source: ConfigSource, + accessToken: string | null, + organizationId: string | null, + apiClient: DefaultApiInterface +): Promise { + try { + switch (source.type) { + case "cli-flag": + return await loadFromCliFlag(source.path, accessToken, organizationId, apiClient); + + case "saved-uri": + return await loadFromSavedUri(source.uri, accessToken, organizationId, apiClient); + + case "user-assistant": + return await loadUserAssistantWithFallback(organizationId, apiClient); + + case "default-config-yaml": + return await loadDefaultConfigYaml(accessToken, organizationId, apiClient); + + case "default-agent": + return await loadDefaultAgent(organizationId, apiClient); + + default: + throw new Error(`Unknown config source type: ${(source as any).type}`); + } + } catch (error) { + // If we're trying user assistants and it fails, fall back to default agent + if (source.type === "user-assistant") { + console.warn(chalk.yellow("Failed to load user assistants, falling back to default agent")); + return await loadDefaultAgent(organizationId, apiClient); + } + throw error; + } +} + +/** + * Loads configuration from CLI --config flag + * Supports both file paths and assistant slugs + */ +async function loadFromCliFlag( + configPath: string, + accessToken: string | null, + organizationId: string | null, + apiClient: DefaultApiInterface +): Promise { + if (isFilePath(configPath)) { + // Load local YAML file + return await loadConfigYaml(configPath, accessToken, organizationId, apiClient); + } else { + // Load assistant slug + return await loadAssistantSlug(configPath, organizationId, apiClient); + } +} + +/** + * Loads configuration from saved URI in auth config + */ +async function loadFromSavedUri( + uri: string, + accessToken: string | null, + organizationId: string | null, + apiClient: DefaultApiInterface +): Promise { + const filePath = uriToPath(uri); + if (filePath) { + return await loadConfigYaml(filePath, accessToken, organizationId, apiClient); + } + + const slug = uriToSlug(uri); + if (slug) { + return await loadAssistantSlug(slug, organizationId, apiClient); + } + + throw new Error(`Invalid saved config URI: ${uri}`); +} + +/** + * Loads first available user assistant with fallback to default agent + */ +async function loadUserAssistantWithFallback( + organizationId: string | null, + apiClient: DefaultApiInterface +): Promise { + const assistants = await apiClient.listAssistants({ + alwaysUseProxy: "false", + organizationId: organizationId ?? undefined, + }); + + if (assistants.length > 0) { + const result = assistants[0].configResult; + if (result.errors?.length || !result.config) { + throw new Error(result.errors?.join("\n") ?? "Failed to load assistant."); + } + return result.config as AssistantUnrolled; + } + + // No user assistants, fall back to default agent + return await loadDefaultAgent(organizationId, apiClient); +} + +/** + * Loads default config.yaml from ~/.continue/config.yaml + */ +async function loadDefaultConfigYaml( + accessToken: string | null, + organizationId: string | null, + apiClient: DefaultApiInterface +): Promise { + const defaultConfigPath = path.join(os.homedir(), ".continue", "config.yaml"); + return await loadConfigYaml(defaultConfigPath, accessToken, organizationId, apiClient); +} + +/** + * Loads the default continuedev/default-agent + */ +async function loadDefaultAgent( + organizationId: string | null, + apiClient: DefaultApiInterface +): Promise { + const resp = await apiClient.getAssistant({ + ownerSlug: "continuedev", + packageSlug: "default-agent", + organizationId: organizationId ?? undefined, + }); + + if (!resp.configResult.config) { + throw new Error("Failed to load default agent."); + } + + return resp.configResult.config as AssistantUnrolled; +} + +/** + * Loads a local YAML configuration file + */ +async function loadConfigYaml( + filePath: string, + accessToken: string | null, + organizationId: string | null, + apiClient: DefaultApiInterface +): Promise { + const unrollResult = await unrollAssistant( + { filePath, uriType: "file" }, + new RegistryClient({ + accessToken: accessToken ?? undefined, + apiBase: env.apiBase, + rootPath: dirname(filePath), + }), + { + currentUserSlug: "", + alwaysUseProxy: false, + orgScopeId: organizationId, + renderSecrets: true, + platformClient: new CLIPlatformClient(organizationId, apiClient), + onPremProxyUrl: null, + } + ); + + const errorDetails = unrollResult.errors; + if (!unrollResult.config) { + throw new Error(`Failed to load config file:\n${errorDetails}`); + } else if (errorDetails?.length) { + const warnings = + errorDetails?.length > 1 + ? errorDetails.map((d) => `\n- ${d.message}`) + : errorDetails[0].message; + console.warn(chalk.dim(`Warning: ${warnings}`)); + } + + return unrollResult.config; +} + +/** + * Loads an assistant by slug from the Continue platform + */ +async function loadAssistantSlug( + slug: string, + organizationId: string | null, + apiClient: DefaultApiInterface +): Promise { + const [ownerSlug, packageSlug] = slug.split("/"); + if (!ownerSlug || !packageSlug) { + throw new Error(`Invalid assistant slug format. Expected "owner/package", got: ${slug}`); + } + + const resp = await apiClient.getAssistant({ + ownerSlug, + packageSlug, + alwaysUseProxy: "false", + organizationId: organizationId ?? undefined, + }); + + const result = resp.configResult; + if (result.errors?.length || !result.config) { + throw new Error(result.errors?.join("\n") ?? "Failed to load assistant."); + } + + return result.config as AssistantUnrolled; +} + +/** + * Determines if a config path is a file path vs assistant slug + */ +function isFilePath(configPath: string): boolean { + return ( + configPath.startsWith(".") || + configPath.startsWith("/") || + configPath.startsWith("~") + ); +} + +/** + * Converts a config source back to a URI for persistence + */ +function getUriFromSource(source: ConfigSource): string | null { + switch (source.type) { + case "cli-flag": + return isFilePath(source.path) + ? `file://${source.path}` + : `slug://${source.path}`; + case "saved-uri": + return source.uri; + case "default-config-yaml": + return `file://${path.join(os.homedir(), ".continue", "config.yaml")}`; + default: + return null; + } +} \ No newline at end of file diff --git a/src/e2e/config-switching.test.tsx b/src/e2e/config-switching.test.tsx index 5dcb6c67b..64f2b2e4f 100644 --- a/src/e2e/config-switching.test.tsx +++ b/src/e2e/config-switching.test.tsx @@ -49,11 +49,11 @@ describe('Config Switching Implementation Test', () => { // The updateConfigPath method is key to reactive config switching }); - test('loadConfig function exists for configuration loading', async () => { - const configModule = await import('../config.js'); + test('loadConfiguration function exists for configuration loading', async () => { + const configLoaderModule = await import('../configLoader.js'); - // Verify loadConfig function exists and is callable - expect(typeof configModule.loadConfig).toBe('function'); + // Verify loadConfiguration function exists and is callable + expect(typeof configLoaderModule.loadConfiguration).toBe('function'); // This is what ConfigService.updateConfigPath uses to load new configs }); @@ -76,7 +76,7 @@ describe('Config Switching Implementation Test', () => { userAction: 'select different configuration', codeFlow: [ 'useConfigSelector calls services.config.updateConfigPath(newPath)', - 'ConfigService.updateConfigPath loads new config via loadConfig()', + 'ConfigService.updateConfigPath loads new config via loadConfiguration()', 'ConfigService calls serviceContainer.set(CONFIG, newState)', 'ConfigService calls serviceContainer.reload(MODEL)', 'ConfigService calls serviceContainer.reload(MCP)', @@ -107,7 +107,7 @@ describe('Config Switching Implementation Test', () => { expect(updateConfigPathSource).toContain('serviceContainer.reload'); expect(updateConfigPathSource).toContain('SERVICE_NAMES.MODEL'); expect(updateConfigPathSource).toContain('SERVICE_NAMES.MCP'); - expect(updateConfigPathSource).toContain('loadConfig'); + expect(updateConfigPathSource).toContain('loadConfiguration'); // This confirms our implementation has the right structure for reactive updates console.log('✅ ConfigService.updateConfigPath implementation contains required reactive calls'); diff --git a/src/e2e/headless-tool-calls.test.ts b/src/e2e/headless-tool-calls.test.ts index 888bc9a4e..c7d94cfca 100644 --- a/src/e2e/headless-tool-calls.test.ts +++ b/src/e2e/headless-tool-calls.test.ts @@ -1,14 +1,14 @@ +import * as http from "http"; import { cleanupTestContext, createTestContext, runCLI, } from "../test-helpers/cli-helpers.js"; import { - setupMockLLMTest, cleanupMockLLMServer, + setupMockLLMTest, type MockLLMServer, } from "../test-helpers/mock-llm-server.js"; -import * as http from "http"; describe("E2E: Headless Mode with Tool Calls", () => { let context: any; @@ -28,27 +28,44 @@ describe("E2E: Headless Mode with Tool Calls", () => { it("should print nothing when response contains only tool calls in headless mode", async () => { // In headless mode, the CLI makes only one request and exits // If that response contains only tool calls, nothing is printed - + mockServer = await setupMockLLMTest(context, { customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => { - if (req.method === "POST" && req.url === "/chat/completions") { - res.writeHead(200, { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache", - "Connection": "keep-alive", - }); + // Collect request body first + let body = ""; + req.on("data", (chunk) => { + body += chunk.toString(); + }); - // Send only tool call (no text content) - res.write(`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_123","type":"function","function":{"name":"search_code"}}]},"index":0}]}\n\n`); - res.write(`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"pattern\\":\\"createTestContext\\"}"}}]},"index":0}]}\n\n`); - - // End the stream - res.write(`data: [DONE]\n\n`); - res.end(); - } else { - res.writeHead(404); - res.end("Not found"); - } + req.on("end", () => { + if (req.method === "POST" && req.url === "/chat/completions") { + res.writeHead(200, { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }); + + // Send only tool call (no text content) + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_123","type":"function","function":{"name":"search_code"}}]},"index":0}]}\n\n` + ); + res.write( + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"pattern\\":\\"createTestContext\\"}"}}]},"index":0}]}\n\n` + ); + + // Send usage data + res.write( + `data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n` + ); + + // End the stream + res.write(`data: [DONE]\n\n`); + res.end(); + } else { + res.writeHead(404); + res.end("Not found"); + } + }); }, }); @@ -62,46 +79,4 @@ describe("E2E: Headless Mode with Tool Calls", () => { expect(result.stdout).toBe(""); expect(result.exitCode).toBe(0); }, 20000); - - it("should print initial text when response contains both text and tool calls", async () => { - // In headless mode, if the response contains both text and tool calls, - // only the text portion is printed (tool calls are not executed in headless single-turn mode) - - mockServer = await setupMockLLMTest(context, { - customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => { - if (req.method === "POST" && req.url === "/chat/completions") { - res.writeHead(200, { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache", - "Connection": "keep-alive", - }); - - // Send initial text with tool calls - res.write(`data: {"choices":[{"delta":{"content":"I'll help you with that. Let me search for information."},"index":0}]}\n\n`); - - // Tool calls (which won't result in follow-up in headless mode) - res.write(`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_search","type":"function","function":{"name":"search_code"}}]},"index":0}]}\n\n`); - res.write(`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"pattern\\":\\"runCLI\\"}"}}]},"index":0}]}\n\n`); - - // End the stream - res.write(`data: [DONE]\n\n`); - res.end(); - } else { - res.writeHead(404); - res.end("Not found"); - } - }, - }); - - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath, "Run multiple tool calls"], - timeout: 15000, - }); - - // In headless mode, only the text content before tool calls is printed - expect(result.stdout).toBe("I'll help you with that. Let me search for information."); - expect(result.stdout).not.toContain("search_code"); - expect(result.exitCode).toBe(0); - }, 20000); - -}); \ No newline at end of file +}); diff --git a/src/e2e/local-config-switching.test.tsx b/src/e2e/local-config-switching.test.tsx index 10b98008b..f6bc23881 100644 --- a/src/e2e/local-config-switching.test.tsx +++ b/src/e2e/local-config-switching.test.tsx @@ -84,9 +84,9 @@ describe('Local Config Switching Investigation', () => { }); test('hypothesis: local config loading has different behavior', async () => { - // The loadConfig function has two different code paths: + // The loadConfiguration function has different code paths: - const { loadConfig } = await import('../config.js'); + const { loadConfiguration } = await import('../configLoader.js'); // Path 1: Local file loading (lines 176-189 in config.ts) // if (config.startsWith(".") || config.startsWith("/") || config.startsWith("~")) { @@ -101,10 +101,10 @@ describe('Local Config Switching Investigation', () => { // return result.config; // } - // Hypothesis: The loadConfig function works correctly, but something else is different + // Hypothesis: The loadConfiguration function works correctly, but something else is different // about how local configs are handled in the ConfigService or service container - expect(typeof loadConfig).toBe('function'); + expect(typeof loadConfiguration).toBe('function'); // The issue might be: // 1. Different state management for local vs remote configs @@ -125,7 +125,7 @@ describe('Local Config Switching Investigation', () => { // Question: Could the assistant slug clearing/setting be interfering // with the config loading process? - // In loadConfig, when config is undefined, it checks for saved assistant slug: + // In loadConfiguration, when config is undefined, it checks for saved assistant slug: // const assistantSlug = getAssistantSlug(authConfig); // if (assistantSlug) { config = assistantSlug; } @@ -137,7 +137,7 @@ describe('Local Config Switching Investigation', () => { const { ConfigService } = await import('../services/ConfigService.js'); // The ConfigService.updateConfigPath method should work the same for both types: - // 1. Load new config via loadConfig(authConfig, newConfigPath, ...) + // 1. Load new config via loadConfiguration(authConfig, newConfigPath, ...) // 2. Update this.currentState = { config, configPath: newConfigPath } // 3. Call serviceContainer.set(CONFIG, this.currentState) // 4. Call serviceContainer.reload(MODEL) and serviceContainer.reload(MCP) diff --git a/src/index.ts b/src/index.ts index 89596b5ce..bcc4ce6dd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,7 @@ import { logout } from "./commands/logout.js"; import { remoteTest } from "./commands/remote-test.js"; import { remote } from "./commands/remote.js"; import { serve } from "./commands/serve.js"; +import { addCommonOptions, mergeParentOptions } from "./shared-options.js"; import { configureConsoleForHeadless } from "./util/consoleOverride.js"; import logger from "./util/logger.js"; import { readStdinSync } from "./util/stdin.js"; @@ -33,24 +34,11 @@ program .version(getVersion()); // Root command - chat functionality (default) -program +// Add common options to the root command +addCommonOptions(program) .argument("[prompt]", "Optional prompt to send to the assistant") .option("-p, --print", "Print response and exit (useful for pipes)") - .option("--config ", "Path to configuration file") .option("--resume", "Resume from last session") - .option("--readonly", "Only allow readonly tools") - .option("--no-tools", "Disable all tools") - .option("-v, --verbose", "Enable verbose logging") - .option( - "--rule ", - "Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.", - (value: string, previous: string[] | undefined) => { - const array = Array.isArray(previous) ? previous : []; - array.push(value); - return array; - }, - [] as string[] - ) .action(async (prompt, options) => { // Configure console overrides FIRST, before any other logging const isHeadless = options.print; @@ -114,23 +102,9 @@ program }); // Serve subcommand -program +const serveCommand = program .command("serve [prompt]") .description("Start an HTTP server with /state and /message endpoints") - .option("--config ", "Path to configuration file") - .option("--readonly", "Only allow readonly tools") - .option("--no-tools", "Disable all tools") - .option("-v, --verbose", "Enable verbose logging") - .option( - "--rule ", - "Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.", - (value: string, previous: string[] | undefined) => { - const array = Array.isArray(previous) ? previous : []; - array.push(value); - return array; - }, - [] as string[] - ) .option( "--timeout ", "Inactivity timeout in seconds (default: 300)", @@ -138,11 +112,15 @@ program ) .option("--port ", "Port to run the server on (default: 8000)", "8000") .action(async (prompt, options) => { - if (options.verbose) { + // Merge parent options with subcommand options + const mergedOptions = mergeParentOptions(program, options); + + if (mergedOptions.verbose) { logger.setLevel("debug"); logger.debug("Verbose logging enabled"); } - await serve(prompt, options); + + await serve(prompt, mergedOptions); }); // Remote test subcommand (for development) 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..d08c5f375 --- /dev/null +++ b/src/permissions/defaultPolicies.ts @@ -0,0 +1,28 @@ +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: "read_file", permission: "allow" }, + { tool: "list_files", permission: "allow" }, + { tool: "search_code", permission: "allow" }, + { tool: "fetch", permission: "allow" }, + + // Write operations should require confirmation + { tool: "write_file", permission: "ask" }, + + // Terminal commands should require confirmation by default + { tool: "run_terminal_command", permission: "ask" }, + + // Exit tool is generally safe (headless mode only) + { tool: "exit", permission: "allow" }, + + // View diff is read-only + { tool: "view_diff", 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..7e5fca074 --- /dev/null +++ b/src/permissions/index.ts @@ -0,0 +1,29 @@ +export type { + PermissionCheckResult, + PermissionPolicy, + ToolCallRequest, + ToolPermissionPolicy, + ToolPermissions, +} from "./types.js"; + +export { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; +export { + checkToolPermission, + filterExcludedTools, + matchesArguments, + matchesToolPattern, +} from "./permissionChecker.js"; +export { + toolPermissionManager, + ToolPermissionManager, +} from "./permissionManager.js"; +export type { PermissionRequestResult } from "./permissionManager.js"; +export { + ensurePermissionsYamlExists, + loadPermissionsYaml, + PERMISSIONS_YAML_PATH, + yamlConfigToPolicies, +} from "./permissionsYamlLoader.js"; +export type { PermissionsYamlConfig } from "./permissionsYamlLoader.js"; +export { resolvePermissionPrecedence } from "./precedenceResolver.js"; +export type { PermissionSources } from "./precedenceResolver.js"; diff --git a/src/permissions/permissionChecker.test.ts b/src/permissions/permissionChecker.test.ts new file mode 100644 index 000000000..8c183bf08 --- /dev/null +++ b/src/permissions/permissionChecker.test.ts @@ -0,0 +1,380 @@ +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); + expect(matchesToolPattern("testa", "test[abc]")).toBe(false); + expect(matchesToolPattern("test[abc]", "test[abc]")).toBe(true); + expect(matchesToolPattern("test(abc)", "test(abc)")).toBe(true); + expect(matchesToolPattern("test+plus", "test+plus")).toBe(true); + expect(matchesToolPattern("test^caret", "test^caret")).toBe(true); + expect(matchesToolPattern("test$dollar", "test$dollar")).toBe(true); + expect(matchesToolPattern("test{brace}", "test{brace}")).toBe(true); + expect(matchesToolPattern("test|pipe", "test|pipe")).toBe(true); + expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe(true); + }); + + it("should handle wildcard patterns with special regex characters", () => { + expect(matchesToolPattern("test[abc].txt", "test[abc].*")).toBe(true); + expect(matchesToolPattern("test[abc]_file", "test[abc].*")).toBe(false); + expect(matchesToolPattern("mcp__tool[1]", "mcp__*")).toBe(true); + expect(matchesToolPattern("file.test.txt", "*.test.*")).toBe(true); + expect(matchesToolPattern("(tool)_name", "(tool)*")).toBe(true); + expect(matchesToolPattern("tool+plus_extra", "tool+plus*")).toBe(true); + }); + + describe("Bash command patterns", () => { + it("should match Bash command patterns with run_terminal_command", () => { + expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { command: "ls" })).toBe(true); + expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { command: "ls -la" })).toBe(true); + expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { command: "pwd" })).toBe(false); + }); + + it("should match Bash command patterns with Bash display name", () => { + expect(matchesToolPattern("Bash", "Bash(git*)", { command: "git status" })).toBe(true); + expect(matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" })).toBe(true); + expect(matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" })).toBe(false); + }); + + it("should match exact Bash commands", () => { + expect(matchesToolPattern("run_terminal_command", "Bash(ls)", { command: "ls" })).toBe(true); + expect(matchesToolPattern("run_terminal_command", "Bash(ls)", { command: "ls -la" })).toBe(false); + }); + + it("should not match Bash patterns for non-bash tools", () => { + expect(matchesToolPattern("read_file", "Bash(ls*)", { command: "ls" })).toBe(false); + expect(matchesToolPattern("write_file", "Bash(git*)", { command: "git status" })).toBe(false); + }); + + it("should not match Bash patterns without command argument", () => { + expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", {})).toBe(false); + expect(matchesToolPattern("run_terminal_command", "Bash(ls*)", { other: "value" })).toBe(false); + }); + + it("should handle complex Bash command patterns", () => { + expect(matchesToolPattern("run_terminal_command", "Bash(npm*)", { command: "npm install" })).toBe(true); + expect(matchesToolPattern("run_terminal_command", "Bash(npm*)", { command: "npm run build" })).toBe(true); + expect(matchesToolPattern("run_terminal_command", "Bash(git*commit*)", { command: "git commit -m 'test'" })).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: "read_file", + arguments: { path: "/test.txt" }, + }); + + // Should match the default policies (read_file 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"); + }); + + it("should match Bash command patterns in checkToolPermission", () => { + const permissions: ToolPermissions = { + policies: [ + { tool: "Bash(ls*)", permission: "allow" }, + { tool: "Bash(git*)", permission: "ask" }, + { tool: "run_terminal_command", permission: "ask" }, // Fallback for other commands + ], + }; + + // Should match "Bash(ls*)" pattern and allow + const lsResult = checkToolPermission( + { name: "run_terminal_command", arguments: { command: "ls -la" } }, + permissions + ); + expect(lsResult.permission).toBe("allow"); + expect(lsResult.matchedPolicy?.tool).toBe("Bash(ls*)"); + + // Should match "Bash(git*)" pattern and ask + const gitResult = checkToolPermission( + { name: "run_terminal_command", arguments: { command: "git status" } }, + permissions + ); + expect(gitResult.permission).toBe("ask"); + expect(gitResult.matchedPolicy?.tool).toBe("Bash(git*)"); + + // Should match general fallback for other commands + const npmResult = checkToolPermission( + { name: "run_terminal_command", arguments: { command: "npm install" } }, + permissions + ); + expect(npmResult.permission).toBe("ask"); + expect(npmResult.matchedPolicy?.tool).toBe("run_terminal_command"); + }); + }); + + 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..20208c675 --- /dev/null +++ b/src/permissions/permissionChecker.ts @@ -0,0 +1,142 @@ +import { getServiceSync } from "../services/index.js"; +import { SERVICE_NAMES } from "../services/types.js"; +import type { ToolPermissionServiceState } from "../services/types.js"; +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. + * Also handles special Bash command patterns like "Bash(ls*)" + */ +export function matchesToolPattern( + toolName: string, + pattern: string, + toolArguments?: Record +): boolean { + if (pattern === "*") return true; + if (pattern === toolName) return true; + + // Handle special Bash command patterns like "Bash(ls*)" + const bashCommandMatch = pattern.match(/^Bash\((.+)\)$/); + if (bashCommandMatch) { + // Check if this is a bash/terminal tool (either normalized name or display name) + const isBashTool = toolName === "run_terminal_command" || toolName === "Bash"; + if (isBashTool && toolArguments?.command) { + const commandPattern = bashCommandMatch[1]; + const command = toolArguments.command; + + // Handle command patterns with wildcards + if (commandPattern.includes("*") || commandPattern.includes("?")) { + // Escape all regex metacharacters except * and ? + const escaped = commandPattern.replace(/[.+^${}()|[\]\\]/g, "\\$&"); + // Convert * and ? to their regex equivalents + const regexPattern = escaped.replace(/\*/g, ".*").replace(/\?/g, "."); + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(command); + } + + // Exact command match + return command === commandPattern; + } + return false; + } + + // Handle regular wildcard patterns like "mcp__*" + if (pattern.includes("*") || pattern.includes("?")) { + // Escape all regex metacharacters except * and ? + const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&"); + // Convert * and ? to their regex equivalents + const regexPattern = escaped.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 { + // Get permissions from service if not provided + let policies = permissions?.policies; + + if (!policies) { + const serviceResult = getServiceSync( + SERVICE_NAMES.TOOL_PERMISSIONS + ); + + // Only use defaults if service is not ready, not registered, or has no value + // This allows critical runtime errors to propagate properly + if (serviceResult.state !== 'ready' || !serviceResult.value) { + policies = DEFAULT_TOOL_POLICIES; + } else { + policies = serviceResult.value.permissions.policies || DEFAULT_TOOL_POLICIES; + } + } + + for (const policy of policies) { + if ( + matchesToolPattern(toolCall.name, policy.tool, toolCall.arguments) && + 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/permissionsYamlLoader.test.ts b/src/permissions/permissionsYamlLoader.test.ts new file mode 100644 index 000000000..aaee1d3ab --- /dev/null +++ b/src/permissions/permissionsYamlLoader.test.ts @@ -0,0 +1,88 @@ +import { yamlConfigToPolicies } from "./permissionsYamlLoader.js"; + +describe("permissionsYamlLoader", () => { + describe("yamlConfigToPolicies", () => { + it("should convert YAML config to policies with proper order", () => { + const config = { + allow: ["Read", "List"], + ask: ["Write"], + exclude: ["Bash"], + }; + + const policies = yamlConfigToPolicies(config); + + expect(policies).toEqual([ + { tool: "run_terminal_command", permission: "exclude" }, + { tool: "write_file", permission: "ask" }, + { tool: "read_file", permission: "allow" }, + { tool: "list_files", permission: "allow" }, + ]); + }); + + it("should normalize tool names", () => { + const config = { + allow: ["read", "READ", "read_file"], + }; + + const policies = yamlConfigToPolicies(config); + + expect(policies).toEqual([ + { tool: "read_file", permission: "allow" }, + { tool: "read_file", permission: "allow" }, + { tool: "read_file", permission: "allow" }, + ]); + }); + + it("should handle empty config", () => { + const config = {}; + + const policies = yamlConfigToPolicies(config); + + expect(policies).toEqual([]); + }); + + it("should handle wildcard patterns", () => { + const config = { + allow: ["mcp__*"], + exclude: ["*"], + }; + + const policies = yamlConfigToPolicies(config); + + expect(policies).toEqual([ + { tool: "*", permission: "exclude" }, + { tool: "mcp__*", permission: "allow" }, + ]); + }); + + it("should handle missing permission types", () => { + const config = { + allow: ["Read"], + // ask and exclude are undefined + }; + + const policies = yamlConfigToPolicies(config); + + expect(policies).toEqual([{ tool: "read_file", permission: "allow" }]); + }); + + it("should handle all permission types", () => { + const config = { + allow: ["Read", "List"], + ask: ["Write", "Terminal"], + exclude: ["Fetch", "Exit"], + }; + + const policies = yamlConfigToPolicies(config); + + expect(policies).toEqual([ + { tool: "fetch", permission: "exclude" }, + { tool: "exit", permission: "exclude" }, + { tool: "write_file", permission: "ask" }, + { tool: "run_terminal_command", permission: "ask" }, + { tool: "read_file", permission: "allow" }, + { tool: "list_files", permission: "allow" }, + ]); + }); + }); +}); diff --git a/src/permissions/permissionsYamlLoader.ts b/src/permissions/permissionsYamlLoader.ts new file mode 100644 index 000000000..3eaea9820 --- /dev/null +++ b/src/permissions/permissionsYamlLoader.ts @@ -0,0 +1,133 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import * as yaml from "yaml"; +import logger from "../util/logger.js"; +import { normalizeToolName } from "./toolNameMapping.js"; +import { ToolPermissionPolicy } from "./types.js"; + +export const PERMISSIONS_YAML_PATH = path.join( + os.homedir(), + ".continue", + "permissions.yaml" +); + +export interface PermissionsYamlConfig { + allow?: string[]; + ask?: string[]; + exclude?: string[]; +} + +/** + * Loads permissions from ~/.continue/permissions.yaml + * Returns null if file doesn't exist or can't be parsed + */ +export function loadPermissionsYaml(): PermissionsYamlConfig | null { + try { + if (!fs.existsSync(PERMISSIONS_YAML_PATH)) { + logger.debug("Permissions YAML file does not exist", { + path: PERMISSIONS_YAML_PATH, + }); + return null; + } + + const content = fs.readFileSync(PERMISSIONS_YAML_PATH, "utf-8"); + const parsed = yaml.parse(content) as PermissionsYamlConfig; + + // Validate the structure + if (parsed && typeof parsed === "object") { + const validKeys = ["allow", "ask", "exclude"]; + const hasValidStructure = Object.keys(parsed).every( + (key) => + validKeys.includes(key) && + (!parsed[key as keyof PermissionsYamlConfig] || + Array.isArray(parsed[key as keyof PermissionsYamlConfig])) + ); + + if (hasValidStructure) { + logger.debug("Loaded permissions from YAML", { + allow: parsed.allow?.length || 0, + ask: parsed.ask?.length || 0, + exclude: parsed.exclude?.length || 0, + }); + return parsed; + } + } + + logger.warn("Invalid permissions YAML structure", { + path: PERMISSIONS_YAML_PATH, + }); + return null; + } catch (error) { + logger.error("Failed to load permissions YAML", { + error, + path: PERMISSIONS_YAML_PATH, + }); + return null; + } +} + +/** + * Converts permissions YAML config to ToolPermissionPolicy array + */ +export function yamlConfigToPolicies( + config: PermissionsYamlConfig +): ToolPermissionPolicy[] { + const policies: ToolPermissionPolicy[] = []; + + // Order matters: more restrictive policies first + if (config.exclude) { + for (const tool of config.exclude) { + const normalizedName = normalizeToolName(tool); + policies.push({ tool: normalizedName, permission: "exclude" }); + } + } + + if (config.ask) { + for (const tool of config.ask) { + const normalizedName = normalizeToolName(tool); + policies.push({ tool: normalizedName, permission: "ask" }); + } + } + + if (config.allow) { + for (const tool of config.allow) { + const normalizedName = normalizeToolName(tool); + policies.push({ tool: normalizedName, permission: "allow" }); + } + } + + return policies; +} + +/** + * Creates the permissions.yaml file with default content if it doesn't exist + */ +export async function ensurePermissionsYamlExists(): Promise { + const dir = path.dirname(PERMISSIONS_YAML_PATH); + + // Ensure directory exists + if (!fs.existsSync(dir)) { + await fs.promises.mkdir(dir, { recursive: true }); + } + + // Create file if it doesn't exist + if (!fs.existsSync(PERMISSIONS_YAML_PATH)) { + const defaultContent = `# cn tool permissions + +# Tools that are automatically allowed without prompting +allow: [] + +# Tools that require user confirmation before execution +ask: [] + +# Tools that are completely excluded (model won't know they exist) +exclude: [] +`; + + await fs.promises.writeFile(PERMISSIONS_YAML_PATH, defaultContent, "utf-8"); + logger.info("Created default permissions.yaml", { + path: PERMISSIONS_YAML_PATH, + }); + } +} diff --git a/src/permissions/policyWriter.test.ts b/src/permissions/policyWriter.test.ts new file mode 100644 index 000000000..bf5f83596 --- /dev/null +++ b/src/permissions/policyWriter.test.ts @@ -0,0 +1,38 @@ +import { generatePolicyRule } from "./policyWriter.js"; + +describe("policyWriter", () => { + describe("generatePolicyRule", () => { + it("should return display name for regular tools", () => { + expect(generatePolicyRule("Read", { file_path: "/test" })).toBe("Read"); + expect(generatePolicyRule("Write", { file_path: "/test", content: "test" })).toBe("Write"); + expect(generatePolicyRule("List", { path: "/test" })).toBe("List"); + expect(generatePolicyRule("Search", { pattern: "test" })).toBe("Search"); + expect(generatePolicyRule("Grep", { pattern: "test" })).toBe("Grep"); // Unknown tool, passes through + }); + + it("should generate command-specific patterns for Bash tool", () => { + expect(generatePolicyRule("Bash", { command: "ls -la" })).toBe("Bash(ls*)"); + expect(generatePolicyRule("Bash", { command: "git status" })).toBe("Bash(git*)"); + expect(generatePolicyRule("Bash", { command: "npm install" })).toBe("Bash(npm*)"); + }); + + it("should handle complex bash commands", () => { + expect(generatePolicyRule("Bash", { command: "ls -la && echo test" })).toBe("Bash(ls*)"); + expect(generatePolicyRule("Bash", { command: "find . -name '*.ts' | head -10" })).toBe("Bash(find*)"); + expect(generatePolicyRule("Bash", { command: " grep -r test . " })).toBe("Bash(grep*)"); + }); + + it("should fallback to display name for bash tools without command", () => { + expect(generatePolicyRule("Bash", {})).toBe("Bash"); + expect(generatePolicyRule("Bash", { command: "" })).toBe("Bash"); + expect(generatePolicyRule("Bash", { command: " " })).toBe("Bash"); + }); + + it("should handle tool name normalization", () => { + expect(generatePolicyRule("bash", { command: "ls" })).toBe("Bash(ls*)"); + expect(generatePolicyRule("BASH", { command: "pwd" })).toBe("Bash(pwd*)"); + expect(generatePolicyRule("read", { file_path: "/test" })).toBe("Read"); + expect(generatePolicyRule("write", { file_path: "/test", content: "test" })).toBe("Write"); + }); + }); +}); \ No newline at end of file diff --git a/src/permissions/policyWriter.ts b/src/permissions/policyWriter.ts new file mode 100644 index 000000000..c70fe41b5 --- /dev/null +++ b/src/permissions/policyWriter.ts @@ -0,0 +1,67 @@ +import * as fs from "fs"; +import * as yaml from "yaml"; +import { PERMISSIONS_YAML_PATH, PermissionsYamlConfig, loadPermissionsYaml } from "./permissionsYamlLoader.js"; +import { normalizeToolName, getDisplayName } from "./toolNameMapping.js"; +import logger from "../util/logger.js"; + +/** + * Generates a policy rule for a given tool call + * For most tools, returns the display name (e.g., "Read", "Write") + * For Bash tool, generates command-specific patterns like "Bash(ls*)" + */ +export function generatePolicyRule(toolName: string, toolArgs: any): string { + const normalizedName = normalizeToolName(toolName); + + // For Bash tool (run_terminal_command), create command-specific policies + if (normalizedName === "run_terminal_command" && toolArgs?.command) { + const command = toolArgs.command.trim(); + // Extract the first command (before pipes, &&, ||, etc.) + const firstCommand = command.split(/[;&|]|&&|\|\|/)[0]?.trim(); + if (firstCommand) { + // Extract just the command name (before spaces or flags) + const commandName = firstCommand.split(/\s+/)[0]; + return `Bash(${commandName}*)`; + } + } + + // For all other tools, return the display name + return getDisplayName(normalizedName); +} + +/** + * Adds a policy rule to the permissions.yaml file + */ +export async function addPolicyToYaml(policyRule: string): Promise { + try { + // Load existing config or create empty one + let config: PermissionsYamlConfig = loadPermissionsYaml() || {}; + + // Ensure allow array exists + if (!config.allow) { + config.allow = []; + } + + // Add the policy if it doesn't already exist + if (!config.allow.includes(policyRule)) { + config.allow.push(policyRule); + + // Write the updated config back to the file + const yamlContent = yaml.stringify(config); + + // Add header comment + const finalContent = `# Continue CLI Permissions Configuration +# This file is managed by the Continue CLI and should not be edited manually. +# Use the TUI to modify permissions interactively. + +${yamlContent}`; + + await fs.promises.writeFile(PERMISSIONS_YAML_PATH, finalContent, "utf-8"); + logger.info(`Added policy rule to permissions.yaml: ${policyRule}`); + } else { + logger.debug(`Policy rule already exists: ${policyRule}`); + } + } catch (error) { + logger.error("Failed to add policy to permissions.yaml", { error, policyRule }); + throw error; + } +} \ No newline at end of file diff --git a/src/permissions/precedenceResolver.test.ts b/src/permissions/precedenceResolver.test.ts new file mode 100644 index 000000000..7e69810fe --- /dev/null +++ b/src/permissions/precedenceResolver.test.ts @@ -0,0 +1,144 @@ +import { jest } from "@jest/globals"; +import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; +import { resolvePermissionPrecedence } from "./precedenceResolver.js"; +import { ToolPermissionPolicy } from "./types.js"; + +describe("precedenceResolver", () => { + describe("resolvePermissionPrecedence", () => { + it("should return default policies when no overrides", () => { + const policies = resolvePermissionPrecedence({ + useDefaults: true, + personalSettings: false, // Disable to avoid file system access + }); + + expect(policies).toEqual(DEFAULT_TOOL_POLICIES); + }); + + it("should prioritize command line flags over defaults", () => { + const policies = resolvePermissionPrecedence({ + commandLineFlags: { + exclude: ["read_file"], + allow: ["write_file"], + }, + personalSettings: false, + useDefaults: true, + }); + + // Command line flags should come first + expect(policies[0]).toEqual({ tool: "read_file", permission: "exclude" }); + expect(policies[1]).toEqual({ tool: "write_file", permission: "allow" }); + }); + + it("should handle wildcard patterns", () => { + const policies = resolvePermissionPrecedence({ + commandLineFlags: { + allow: ["mcp__*"], + exclude: ["*"], + }, + useDefaults: false, + personalSettings: false, + }); + + expect(policies).toEqual([ + { tool: "*", permission: "exclude" }, + { tool: "mcp__*", permission: "allow" }, + ]); + }); + + it("should normalize tool names in command line flags", () => { + const policies = resolvePermissionPrecedence({ + commandLineFlags: { + allow: ["Read", "write", "BASH"], + }, + useDefaults: false, + personalSettings: false, + }); + + expect(policies).toEqual([ + { tool: "read_file", permission: "allow" }, + { tool: "write_file", permission: "allow" }, + { tool: "run_terminal_command", permission: "allow" }, + ]); + }); + + it("should handle empty command line flags", () => { + const policies = resolvePermissionPrecedence({ + commandLineFlags: {}, + useDefaults: true, + personalSettings: false, + }); + + expect(policies).toEqual(DEFAULT_TOOL_POLICIES); + }); + + it("should maintain order within each permission type for CLI flags", () => { + const policies = resolvePermissionPrecedence({ + commandLineFlags: { + exclude: ["Write", "Bash"], + ask: ["List", "Search"], + allow: ["Read", "Fetch"], + }, + useDefaults: false, + personalSettings: false, + }); + + // Order should be: exclude, ask, allow (as specified in the function) + expect(policies).toEqual([ + { tool: "write_file", permission: "exclude" }, + { tool: "run_terminal_command", permission: "exclude" }, + { tool: "list_files", permission: "ask" }, + { tool: "search_code", permission: "ask" }, + { tool: "read_file", permission: "allow" }, + { tool: "fetch", permission: "allow" }, + ]); + }); + + it("should apply config permissions with proper precedence", () => { + const configPolicies: ToolPermissionPolicy[] = [ + { tool: "write_file", permission: "allow" }, + { tool: "read_file", permission: "ask" }, + ]; + + const policies = resolvePermissionPrecedence({ + commandLineFlags: { + exclude: ["read_file"], // Should override config + }, + configPermissions: configPolicies, + personalSettings: false, + useDefaults: false, + }); + + // CLI flag should override config + expect(policies[0]).toEqual({ tool: "read_file", permission: "exclude" }); + // Config policy should be present + expect(policies[1]).toEqual({ tool: "write_file", permission: "allow" }); + }); + + it("should handle all layers with proper precedence", () => { + const configPolicies: ToolPermissionPolicy[] = [ + { tool: "search_code", permission: "ask" }, + ]; + + const policies = resolvePermissionPrecedence({ + commandLineFlags: { + allow: ["Write"], + }, + configPermissions: configPolicies, + personalSettings: false, + useDefaults: true, + }); + + // Find the write_file policy - should be from CLI (allow) + const writePolicy = policies.find(p => p.tool === "write_file"); + expect(writePolicy?.permission).toBe("allow"); + + // Find the search_code policy - should be from config + const searchPolicy = policies.find(p => p.tool === "search_code"); + expect(searchPolicy?.permission).toBe("ask"); + + // Should still have default policies + const readPolicy = policies.find(p => p.tool === "read_file"); + expect(readPolicy).toBeDefined(); + }); + }); +}); \ No newline at end of file diff --git a/src/permissions/precedenceResolver.ts b/src/permissions/precedenceResolver.ts new file mode 100644 index 000000000..b3a6da6e9 --- /dev/null +++ b/src/permissions/precedenceResolver.ts @@ -0,0 +1,143 @@ +import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; +import { loadPermissionsYaml, yamlConfigToPolicies } from "./permissionsYamlLoader.js"; +import { normalizeToolName } from "./toolNameMapping.js"; +import { ToolPermissionPolicy } from "./types.js"; +import logger from "../util/logger.js"; + +export interface PermissionSources { + /** Command line flags - highest precedence */ + commandLineFlags?: { + allow?: string[]; + ask?: string[]; + exclude?: string[]; + }; + /** Config.yaml permissions - second precedence (not implemented yet) */ + configPermissions?: ToolPermissionPolicy[]; + /** ~/.continue/permissions.yaml - third precedence */ + personalSettings?: boolean; // Whether to load from permissions.yaml + /** Default policies - lowest precedence */ + useDefaults?: boolean; +} + +/** + * Resolves permission policies from all sources according to precedence rules. + * This function implements the clean precedence logic from the specification: + * + * 1. Command line flags (highest) + * 2. Permissions in config.yaml (when implemented) + * 3. Permissions in ~/.continue/permissions.yaml + * 4. Default policies (lowest) + * + * Earlier sources completely override later ones on a per-tool basis. + */ +export function resolvePermissionPrecedence(sources: PermissionSources): ToolPermissionPolicy[] { + const layers: { + name: string; + policies: ToolPermissionPolicy[]; + }[] = []; + + // Layer 4: Default policies (lowest precedence) + if (sources.useDefaults !== false) { + layers.push({ + name: "defaults", + policies: [...DEFAULT_TOOL_POLICIES] + }); + } + + // Layer 3: Personal settings from ~/.continue/permissions.yaml + if (sources.personalSettings !== false) { + const yamlConfig = loadPermissionsYaml(); + if (yamlConfig) { + const yamlPolicies = yamlConfigToPolicies(yamlConfig); + if (yamlPolicies.length > 0) { + layers.push({ + name: "personal-settings", + policies: yamlPolicies + }); + } + } + } + + // Layer 2: Config permissions (when implemented) + if (sources.configPermissions) { + layers.push({ + name: "config", + policies: sources.configPermissions + }); + } + + // Layer 1: Command line flags (highest precedence) + if (sources.commandLineFlags) { + const cliPolicies = commandLineFlagsToPolicies(sources.commandLineFlags); + if (cliPolicies.length > 0) { + layers.push({ + name: "cli-flags", + policies: cliPolicies + }); + } + } + + // Combine layers with proper precedence + const combinedPolicies = combineLayersWithPrecedence(layers); + + logger.debug("Resolved permission precedence", { + layers: layers.map(l => ({ name: l.name, count: l.policies.length })), + totalPolicies: combinedPolicies.length + }); + + return combinedPolicies; +} + +/** + * Converts command line flags to policies + */ +function commandLineFlagsToPolicies(flags: { + allow?: string[]; + ask?: string[]; + exclude?: string[]; +}): ToolPermissionPolicy[] { + const policies: ToolPermissionPolicy[] = []; + + // Order matters for CLI flags too + if (flags.exclude) { + for (const tool of flags.exclude) { + const normalizedName = normalizeToolName(tool); + policies.push({ tool: normalizedName, permission: "exclude" }); + } + } + + if (flags.ask) { + for (const tool of flags.ask) { + const normalizedName = normalizeToolName(tool); + policies.push({ tool: normalizedName, permission: "ask" }); + } + } + + if (flags.allow) { + for (const tool of flags.allow) { + const normalizedName = normalizeToolName(tool); + policies.push({ tool: normalizedName, permission: "allow" }); + } + } + + return policies; +} + +/** + * Combines permission layers with proper precedence. + * Higher precedence layers come later in the array and are prepended to the result. + */ +function combineLayersWithPrecedence(layers: Array<{ name: string; policies: ToolPermissionPolicy[] }>): ToolPermissionPolicy[] { + // Start with empty array + let combined: ToolPermissionPolicy[] = []; + + // Add layers in order (lowest to highest precedence) + // Since we're building from lowest to highest, and we want first-match-wins, + // we prepend higher precedence policies + for (const layer of layers) { + // Prepend this layer's policies (higher precedence at the front) + combined = [...layer.policies, ...combined]; + } + + return combined; +} \ No newline at end of file diff --git a/src/permissions/runtimeOverrides.ts b/src/permissions/runtimeOverrides.ts new file mode 100644 index 000000000..f9725839a --- /dev/null +++ b/src/permissions/runtimeOverrides.ts @@ -0,0 +1,50 @@ +/** + * Runtime permission overrides that are set synchronously from command line + * This ensures they're available immediately, before services are initialized + */ + +import { normalizeToolName } from "./toolNameMapping.js"; +import { ToolPermissionPolicy } from "./types.js"; + +let runtimeOverrides: ToolPermissionPolicy[] | null = null; + +export function setRuntimePermissionOverrides(overrides: { + allow?: string[]; + ask?: string[]; + exclude?: string[]; +}) { + if (!overrides.allow && !overrides.ask && !overrides.exclude) { + runtimeOverrides = null; + return; + } + + const policies: ToolPermissionPolicy[] = []; + + // Convert runtime overrides to policies + if (overrides.exclude) { + for (const tool of overrides.exclude) { + const normalizedName = normalizeToolName(tool); + policies.push({ tool: normalizedName, permission: "exclude" }); + } + } + + if (overrides.ask) { + for (const tool of overrides.ask) { + const normalizedName = normalizeToolName(tool); + policies.push({ tool: normalizedName, permission: "ask" }); + } + } + + if (overrides.allow) { + for (const tool of overrides.allow) { + const normalizedName = normalizeToolName(tool); + policies.push({ tool: normalizedName, permission: "allow" }); + } + } + + runtimeOverrides = policies; +} + +export function getRuntimePermissionOverrides(): ToolPermissionPolicy[] | null { + return runtimeOverrides; +} \ No newline at end of file diff --git a/src/permissions/toolNameMapping.ts b/src/permissions/toolNameMapping.ts new file mode 100644 index 000000000..97f711130 --- /dev/null +++ b/src/permissions/toolNameMapping.ts @@ -0,0 +1,77 @@ +/** + * Maps common display names and variations to actual tool names + */ +const TOOL_NAME_MAPPINGS: Record = { + // Display name mappings + "Read": "read_file", + "Write": "write_file", + "List": "list_files", + "Search": "search_code", + "Bash": "run_terminal_command", + "Terminal": "run_terminal_command", + "Fetch": "fetch", + "Exit": "exit", + "Diff": "view_diff", + + // Common variations (case insensitive) + "read": "read_file", + "write": "write_file", + "list": "list_files", + "search": "search_code", + "bash": "run_terminal_command", + "terminal": "run_terminal_command", + "cmd": "run_terminal_command", + "command": "run_terminal_command", + "fetch": "fetch", + "exit": "exit", + "diff": "view_diff", + + // Actual tool names (passthrough) + "read_file": "read_file", + "write_file": "write_file", + "list_files": "list_files", + "search_code": "search_code", + "run_terminal_command": "run_terminal_command", + "view_diff": "view_diff", +}; + +/** + * Normalizes a tool name from various formats (display name, variations) to the actual tool name + */ +export function normalizeToolName(input: string): string { + // First try exact match (case sensitive) + if (TOOL_NAME_MAPPINGS[input]) { + return TOOL_NAME_MAPPINGS[input]; + } + + // Try case insensitive match + const lowerInput = input.toLowerCase(); + for (const [key, value] of Object.entries(TOOL_NAME_MAPPINGS)) { + if (key.toLowerCase() === lowerInput) { + return value; + } + } + + // If no mapping found, return as-is (might be an MCP tool or future tool) + return input; +} + +/** + * Gets the display name for a normalized tool name + * Returns the preferred display name (e.g., "read_file" -> "Read") + */ +export function getDisplayName(normalizedName: string): string { + // Create a reverse mapping from normalized names to display names + const reverseMapping: Record = { + "read_file": "Read", + "write_file": "Write", + "list_files": "List", + "search_code": "Search", + "run_terminal_command": "Bash", + "fetch": "Fetch", + "exit": "Exit", + "view_diff": "Diff", + }; + + return reverseMapping[normalizedName] || normalizedName; +} \ No newline at end of file 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/services/ConfigService.ts b/src/services/ConfigService.ts index 915e9130e..82d073cba 100644 --- a/src/services/ConfigService.ts +++ b/src/services/ConfigService.ts @@ -4,11 +4,7 @@ import { processRule } from "../args.js"; import { AuthConfig, loadAuthConfig, - pathToUri, - slugToUri, - updateConfigUri, } from "../auth/workos.js"; -import { loadConfig } from "../config.js"; import logger from "../util/logger.js"; import { serviceContainer } from "./ServiceContainer.js"; import { @@ -39,12 +35,11 @@ export class ConfigService { rules?: string[] ): Promise { try { - let config = await loadConfig( - authConfig, - configPath, - organizationId, - apiClient - ); + // Use the new streamlined config loader + const { loadConfiguration } = await import("../configLoader.js"); + const result = await loadConfiguration(authConfig, configPath, apiClient); + + let config = result.config; // Inject rules if provided if (rules && rules.length > 0) { @@ -56,15 +51,7 @@ export class ConfigService { configPath, }; - // Save config URI to auth config - if (configPath) { - const configUri = this.isFilePath(configPath) - ? pathToUri(configPath) - : slugToUri(configPath); - updateConfigUri(configUri); - } else { - updateConfigUri(null); - } + // Config URI persistence is now handled by the streamlined loader logger.debug("ConfigService initialized successfully"); return this.currentState; @@ -97,12 +84,11 @@ export class ConfigService { }); try { - let config = await loadConfig( - authConfig, - newConfigPath, - organizationId, - apiClient - ); + // Use the new streamlined config loader + const { loadConfiguration } = await import("../configLoader.js"); + const result = await loadConfiguration(authConfig, newConfigPath, apiClient); + + let config = result.config; // Inject rules if provided if (rules && rules.length > 0) { @@ -114,11 +100,7 @@ export class ConfigService { configPath: newConfigPath, }; - // Save config URI to auth config - const configUri = this.isFilePath(newConfigPath) - ? pathToUri(newConfigPath) - : slugToUri(newConfigPath); - updateConfigUri(configUri); + // Config URI persistence is now handled by the streamlined loader logger.debug("Configuration switched successfully", { newConfigPath, @@ -223,30 +205,21 @@ export class ConfigService { throw new Error("API client not available"); } - // Load the new configuration - let config = await loadConfig( - authConfig, - newConfigPath, - authState.organizationId || null, + // Load the new configuration using streamlined loader + const { loadConfiguration } = await import("../configLoader.js"); + const result = await loadConfiguration( + authConfig, + newConfigPath, apiClientState.apiClient ); // Update internal state this.currentState = { - config, + config: result.config, configPath: newConfigPath, }; - // Save config URI to auth config - if (newConfigPath) { - const configUri = this.isFilePath(newConfigPath) - ? pathToUri(newConfigPath) - : slugToUri(newConfigPath); - updateConfigUri(configUri); - } else { - // Clear config URI when switching to undefined - updateConfigUri(null); - } + // Config URI persistence is now handled by the streamlined loader // Update the CONFIG service in the container serviceContainer.set(SERVICE_NAMES.CONFIG, this.currentState); @@ -257,7 +230,7 @@ export class ConfigService { logger.debug("Configuration path updated successfully", { newConfigPath, - configName: config.name, + configName: result.config.name, }); } catch (error: any) { logger.error("Failed to update configuration path:", error); @@ -265,14 +238,4 @@ export class ConfigService { } } - /** - * Check if a config path is a file path vs assistant slug - */ - private isFilePath(configPath: string): boolean { - return ( - configPath.startsWith(".") || - configPath.startsWith("/") || - configPath.startsWith("~") - ); - } } diff --git a/src/services/ModelService.test.ts b/src/services/ModelService.test.ts new file mode 100644 index 000000000..13cdcbb46 --- /dev/null +++ b/src/services/ModelService.test.ts @@ -0,0 +1,125 @@ +import { describe, it, expect, beforeEach } from '@jest/globals'; +import { ModelService } from './ModelService.js'; +import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml'; +import { AuthConfig } from '../auth/workos.js'; + +describe('ModelService', () => { + let modelService: ModelService; + let mockAssistant: AssistantUnrolled; + let mockAuthConfig: AuthConfig; + + beforeEach(() => { + modelService = new ModelService(); + + mockAssistant = { + name: 'test-assistant', + version: '1.0.0', + models: [ + { + provider: 'openai', + model: 'gpt-4', + name: 'GPT-4', + apiKey: 'test-key', + roles: ['chat'], + } as ModelConfig, + { + provider: 'anthropic', + model: 'claude-3', + name: 'Claude 3', + apiKey: 'test-key', + roles: ['chat'], + } as ModelConfig, + { + provider: 'openai', + model: 'gpt-3.5', + name: 'GPT-3.5', + apiKey: 'test-key', + roles: ['embed'], + } as ModelConfig, + ], + } as AssistantUnrolled; + + mockAuthConfig = { + accessToken: 'test-token', + refreshToken: 'test-refresh', + userEmail: 'test@example.com', + userId: 'test-user', + organizationId: 'test-org', + expiresAt: Date.now() + 3600000, // 1 hour from now + }; + }); + + describe('getAvailableChatModels', () => { + it('should return only models with chat role', async () => { + await modelService.initialize(mockAssistant, mockAuthConfig); + + const models = modelService.getAvailableChatModels(); + + expect(models).toHaveLength(2); + expect(models[0]).toEqual({ + provider: 'openai', + name: 'GPT-4', + index: 0, + }); + expect(models[1]).toEqual({ + provider: 'anthropic', + name: 'Claude 3', + index: 1, + }); + }); + + it('should throw error when no chat models available during initialization', async () => { + mockAssistant.models = [ + { + provider: 'openai', + model: 'text-embedding-ada-002', + name: 'Ada Embeddings', + roles: ['embed'], + } as ModelConfig, + ]; + + await expect(modelService.initialize(mockAssistant, mockAuthConfig)) + .rejects.toThrow('No models with the chat role found in the configured assistant'); + }); + }); + + describe('switchModel', () => { + it('should switch to a different model by index', async () => { + await modelService.initialize(mockAssistant, mockAuthConfig); + + const initialModel = modelService.getModelInfo(); + expect(initialModel?.name).toBe('GPT-4'); + + await modelService.switchModel(1); + + const newModel = modelService.getModelInfo(); + expect(newModel?.name).toBe('Claude 3'); + }); + + it('should throw error for invalid model index', async () => { + await modelService.initialize(mockAssistant, mockAuthConfig); + + await expect(modelService.switchModel(5)).rejects.toThrow('Invalid model index: 5'); + await expect(modelService.switchModel(-1)).rejects.toThrow('Invalid model index: -1'); + }); + + it('should throw error when service not initialized', async () => { + await expect(modelService.switchModel(0)).rejects.toThrow('ModelService not initialized'); + }); + }); + + describe('getCurrentModelIndex', () => { + it('should return correct index of current model', async () => { + await modelService.initialize(mockAssistant, mockAuthConfig); + + expect(modelService.getCurrentModelIndex()).toBe(0); + + await modelService.switchModel(1); + expect(modelService.getCurrentModelIndex()).toBe(1); + }); + + it('should return -1 when no model is set', () => { + expect(modelService.getCurrentModelIndex()).toBe(-1); + }); + }); +}); \ No newline at end of file diff --git a/src/services/ModelService.ts b/src/services/ModelService.ts index a2a84c1a6..d69afa6da 100644 --- a/src/services/ModelService.ts +++ b/src/services/ModelService.ts @@ -1,7 +1,7 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { BaseLlmApi, constructLlmApi, LLMConfig } from "@continuedev/openai-adapters"; import { getLlmApi } from '../config.js'; -import { AuthConfig } from '../auth/workos.js'; +import { AuthConfig, getAccessToken, getOrganizationId } from '../auth/workos.js'; import logger from '../util/logger.js'; import { ModelServiceState } from './types.js'; @@ -14,6 +14,9 @@ export class ModelService { llmApi: null, model: null }; + private availableModels: ModelConfig[] = []; + private assistant: AssistantUnrolled | null = null; + private authConfig: AuthConfig | null = null; /** * Initialize the model service @@ -25,6 +28,12 @@ export class ModelService { logger.debug('Initializing ModelService'); try { + this.assistant = assistant; + this.authConfig = authConfig; + this.availableModels = (assistant.models?.filter((model) => + model && model.roles?.includes("chat") + ) || []) as ModelConfig[]; + const [llmApi, model] = getLlmApi(assistant, authConfig); this.currentState = { @@ -34,7 +43,8 @@ export class ModelService { logger.debug('ModelService initialized successfully', { modelProvider: model.provider, - modelName: (model as any).name || 'unnamed' + modelName: (model as any).name || 'unnamed', + availableModels: this.availableModels.length }); return this.currentState; @@ -61,6 +71,12 @@ export class ModelService { logger.debug('Updating ModelService'); try { + this.assistant = assistant; + this.authConfig = authConfig; + this.availableModels = (assistant.models?.filter((model) => + model && model.roles?.includes("chat") + ) || []) as ModelConfig[]; + const [llmApi, model] = getLlmApi(assistant, authConfig); this.currentState = { @@ -70,7 +86,8 @@ export class ModelService { logger.debug('ModelService updated successfully', { modelProvider: model.provider, - modelName: (model as any).name || 'unnamed' + modelName: (model as any).name || 'unnamed', + availableModels: this.availableModels.length }); return this.currentState; @@ -100,4 +117,96 @@ export class ModelService { name: (this.currentState.model as any).name || 'unnamed' }; } + + /** + * Get list of available chat models + */ + getAvailableChatModels(): Array<{ provider: string; name: string; index: number }> { + return this.availableModels.map((model, index) => ({ + provider: model.provider, + name: (model as any).name || (model as any).model || 'unnamed', + index + })); + } + + /** + * Switch to a different chat model by index + */ + async switchModel(modelIndex: number): Promise { + if (!this.assistant || !this.authConfig) { + throw new Error('ModelService not initialized'); + } + + if (modelIndex < 0 || modelIndex >= this.availableModels.length) { + throw new Error(`Invalid model index: ${modelIndex}. Available models: 0-${this.availableModels.length - 1}`); + } + + const selectedModel = this.availableModels[modelIndex]; + logger.debug('Switching to model', { + modelIndex, + provider: selectedModel.provider, + name: (selectedModel as any).name || 'unnamed' + }); + + try { + const accessToken = getAccessToken(this.authConfig); + const organizationId = getOrganizationId(this.authConfig); + + const config: LLMConfig = + selectedModel.provider === "continue-proxy" + ? { + provider: selectedModel.provider, + requestOptions: selectedModel.requestOptions, + apiBase: selectedModel.apiBase, + apiKey: accessToken ?? undefined, + env: { + apiKeyLocation: (selectedModel as any).apiKeyLocation, + orgScopeId: organizationId, + proxyUrl: undefined, + }, + } + : { + provider: selectedModel.provider as any, + apiKey: selectedModel.apiKey, + apiBase: selectedModel.apiBase, + requestOptions: selectedModel.requestOptions, + env: selectedModel.env, + }; + + const llmApi = constructLlmApi(config); + + if (!llmApi) { + throw new Error('Failed to initialize LLM with selected model'); + } + + this.currentState = { + llmApi, + model: selectedModel + }; + + logger.debug('Model switched successfully', { + modelProvider: selectedModel.provider, + modelName: (selectedModel as any).name || 'unnamed' + }); + + return this.currentState; + } catch (error: any) { + logger.error('Failed to switch model:', error); + throw error; + } + } + + /** + * Get current model index + */ + getCurrentModelIndex(): number { + if (!this.currentState.model) { + return -1; + } + + return this.availableModels.findIndex(model => + model.provider === this.currentState.model?.provider && + (model as any).name === (this.currentState.model as any).name + ); + } } \ No newline at end of file diff --git a/src/services/ServiceContainer.ts b/src/services/ServiceContainer.ts index 35f346034..b7b2fddc2 100644 --- a/src/services/ServiceContainer.ts +++ b/src/services/ServiceContainer.ts @@ -38,6 +38,28 @@ export class ServiceContainer extends EventEmitter { logger.debug(`Registered service: ${serviceName}`, { dependencies: deps }); } + /** + * Register a service with an immediate value (no factory needed) + * Used when the service is already initialized + */ + registerValue( + serviceName: string, + value: T + ): void { + // Set the service as ready with the provided value + this.services.set(serviceName, { + value, + state: 'ready', + error: null, + lastUpdated: new Date() + }); + + // Emit ready event + this.emit(`${serviceName}:ready`, value); + + logger.debug(`Registered service with immediate value: ${serviceName}`); + } + /** * Get current service result (synchronous) */ diff --git a/src/services/ToolPermissionService.integration.test.ts b/src/services/ToolPermissionService.integration.test.ts new file mode 100644 index 000000000..639dda6ed --- /dev/null +++ b/src/services/ToolPermissionService.integration.test.ts @@ -0,0 +1,104 @@ +import { jest } from "@jest/globals"; +import { DEFAULT_TOOL_POLICIES } from "../permissions/defaultPolicies.js"; +import { ToolPermissionService } from "./ToolPermissionService.js"; + +describe("ToolPermissionService E2E", () => { + let service: ToolPermissionService; + + beforeEach(() => { + service = new ToolPermissionService(); + }); + + it("should handle complete flow from initialization to usage", async () => { + // Initialize with overrides + const overrides = { + allow: ["dangerous_tool"], + ask: ["sensitive_tool"], + exclude: ["forbidden_tool", "write_*"] + }; + + const state = await service.initialize(overrides); + + // Verify the compiled policies + const policies = state.permissions.policies; + + // Find the runtime override policies (they should be at the beginning) + const excludePolicy1 = policies.find(p => p.tool === "forbidden_tool" && p.permission === "exclude"); + const excludePolicy2 = policies.find(p => p.tool === "write_*" && p.permission === "exclude"); + const askPolicy = policies.find(p => p.tool === "sensitive_tool" && p.permission === "ask"); + const allowPolicy = policies.find(p => p.tool === "dangerous_tool" && p.permission === "allow"); + + // Verify runtime overrides are present + expect(excludePolicy1).toBeDefined(); + expect(excludePolicy2).toBeDefined(); + expect(askPolicy).toBeDefined(); + expect(allowPolicy).toBeDefined(); + + // Verify all default policies are present + for (const defaultPolicy of DEFAULT_TOOL_POLICIES) { + const foundPolicy = policies.find(p => + p.tool === defaultPolicy.tool && p.permission === defaultPolicy.permission + ); + expect(foundPolicy).toBeDefined(); + } + }); + + it("should allow dynamic updates after initialization", async () => { + // Start with defaults (may include additional policies from permissions.yaml) + await service.initialize(); + + let permissions = service.getPermissions(); + + // Verify all default policies are present (may have additional ones) + for (const defaultPolicy of DEFAULT_TOOL_POLICIES) { + const foundPolicy = permissions.policies.find(p => + p.tool === defaultPolicy.tool && p.permission === defaultPolicy.permission + ); + expect(foundPolicy).toBeDefined(); + } + + // Update with new policies (this replaces ALL policies) + const newPolicies = [ + { tool: "*", permission: "ask" as const } // Ask for everything + ]; + + service.updatePermissions(newPolicies); + + permissions = service.getPermissions(); + expect(permissions.policies).toEqual(newPolicies); + expect(permissions.policies.length).toBe(1); + }); + + it("should maintain state consistency", async () => { + const overrides = { + exclude: ["test_tool"] + }; + + await service.initialize(overrides); + + // Both getState and getPermissions should return same data + const state = service.getState(); + const permissions = service.getPermissions(); + + expect(state.permissions).toBe(permissions); + expect(state.permissions.policies[0]).toEqual({ tool: "test_tool", permission: "exclude" }); + }); + + it("should handle concurrent access correctly", async () => { + // Initialize service + await service.initialize({ allow: ["tool1"] }); + + // Simulate concurrent reads + const promises = Array(10).fill(null).map(() => + Promise.resolve(service.getPermissions()) + ); + + const results = await Promise.all(promises); + + // All should return the same reference + const firstResult = results[0]; + results.forEach(result => { + expect(result).toBe(firstResult); + }); + }); +}); \ No newline at end of file diff --git a/src/services/ToolPermissionService.test.ts.bak b/src/services/ToolPermissionService.test.ts.bak new file mode 100644 index 000000000..d20a58467 --- /dev/null +++ b/src/services/ToolPermissionService.test.ts.bak @@ -0,0 +1,353 @@ +import { jest } from "@jest/globals"; +import { DEFAULT_TOOL_POLICIES } from "../permissions/defaultPolicies.js"; +import { ToolPermissionPolicy } from "../permissions/types.js"; + +// Mock the dependencies +jest.unstable_mockModule("../util/logger.js", () => ({ + default: { + debug: jest.fn(), + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }, +})); + +jest.unstable_mockModule("../permissions/precedenceResolver.js", () => ({ + resolvePermissionPrecedence: jest.fn(), +})); + +jest.unstable_mockModule("../permissions/permissionsYamlLoader.js", () => ({ + ensurePermissionsYamlExists: jest.fn(), + loadPermissionsYaml: jest.fn(), + yamlConfigToPolicies: jest.fn(), + PERMISSIONS_YAML_PATH: "/home/user/.continue/permissions.yaml", +})); + +// Import after mocking +const precedenceResolver = await import("../permissions/precedenceResolver.js"); +const permissionsYamlLoader = await import("../permissions/permissionsYamlLoader.js"); +const { ToolPermissionService } = await import("./ToolPermissionService.js"); + +const mockPrecedenceResolver = precedenceResolver as jest.Mocked< + typeof precedenceResolver +>; +const mockPermissionsYamlLoader = permissionsYamlLoader as jest.Mocked< + typeof permissionsYamlLoader +>; + +describe("ToolPermissionService", () => { + let service: InstanceType; + + beforeEach(() => { + jest.clearAllMocks(); + service = new ToolPermissionService(); + + // Default mock for ensurePermissionsYamlExists + mockPermissionsYamlLoader.ensurePermissionsYamlExists.mockResolvedValue( + undefined + ); + }); + + describe("initialization", () => { + it("should initialize with default policies when no overrides provided", async () => { + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + DEFAULT_TOOL_POLICIES + ); + + const state = await service.initialize(); + + expect( + mockPrecedenceResolver.resolvePermissionPrecedence + ).toHaveBeenCalledWith({ + commandLineFlags: undefined, + personalSettings: true, + useDefaults: true, + }); + expect(state.permissions.policies).toEqual(DEFAULT_TOOL_POLICIES); + expect(state.permissions.policies.length).toBe( + DEFAULT_TOOL_POLICIES.length + ); + }); + + it("should use precedence resolver with runtime overrides", async () => { + const overrides = { + allow: ["TestTool1"], + ask: ["TestTool2"], + exclude: ["TestTool3"], + }; + + const expectedPolicies: ToolPermissionPolicy[] = [ + { tool: "TestTool3", permission: "exclude" }, + { tool: "TestTool2", permission: "ask" }, + { tool: "TestTool1", permission: "allow" }, + ...DEFAULT_TOOL_POLICIES, + ]; + + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + expectedPolicies + ); + + const state = await service.initialize(overrides); + const policies = state.permissions.policies; + + expect( + mockPrecedenceResolver.resolvePermissionPrecedence + ).toHaveBeenCalledWith({ + commandLineFlags: overrides, + personalSettings: true, + useDefaults: true, + }); + expect(policies).toEqual(expectedPolicies); + }); + + it("should handle empty override arrays", async () => { + const overrides = { + allow: [], + ask: [], + exclude: [], + }; + + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + DEFAULT_TOOL_POLICIES + ); + + const state = await service.initialize(overrides); + + expect( + mockPrecedenceResolver.resolvePermissionPrecedence + ).toHaveBeenCalledWith({ + commandLineFlags: overrides, + personalSettings: true, + useDefaults: true, + }); + expect(state.permissions.policies).toEqual(DEFAULT_TOOL_POLICIES); + }); + + it("should handle partial overrides", async () => { + const overrides = { + allow: ["OnlyAllowTool"], + // ask and exclude are undefined + }; + + const expectedPolicies: ToolPermissionPolicy[] = [ + { tool: "OnlyAllowTool", permission: "allow" }, + ...DEFAULT_TOOL_POLICIES, + ]; + + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + expectedPolicies + ); + + const state = await service.initialize(overrides); + const policies = state.permissions.policies; + + expect( + mockPrecedenceResolver.resolvePermissionPrecedence + ).toHaveBeenCalledWith({ + commandLineFlags: overrides, + personalSettings: true, + useDefaults: true, + }); + expect(policies).toEqual(expectedPolicies); + }); + + it("should handle multiple tools in same override category", async () => { + const overrides = { + exclude: ["Tool1", "Tool2", "Tool3"], + }; + + const expectedPolicies: ToolPermissionPolicy[] = [ + { tool: "Tool1", permission: "exclude" }, + { tool: "Tool2", permission: "exclude" }, + { tool: "Tool3", permission: "exclude" }, + ...DEFAULT_TOOL_POLICIES, + ]; + + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + expectedPolicies + ); + + const state = await service.initialize(overrides); + const policies = state.permissions.policies; + + expect( + mockPrecedenceResolver.resolvePermissionPrecedence + ).toHaveBeenCalledWith({ + commandLineFlags: overrides, + personalSettings: true, + useDefaults: true, + }); + expect(policies).toEqual(expectedPolicies); + }); + }); + + describe("getState", () => { + it("should return current state after initialization", async () => { + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + DEFAULT_TOOL_POLICIES + ); + + await service.initialize(); + const state = service.getState(); + + expect(state).toBeDefined(); + expect(state.permissions).toBeDefined(); + expect(state.permissions.policies).toEqual(DEFAULT_TOOL_POLICIES); + }); + + it("should return state with overrides", async () => { + const overrides = { + allow: ["TestTool"], + }; + + const expectedPolicies: ToolPermissionPolicy[] = [ + { tool: "TestTool", permission: "allow" }, + ...DEFAULT_TOOL_POLICIES, + ]; + + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + expectedPolicies + ); + + await service.initialize(overrides); + const state = service.getState(); + + expect(state.permissions.policies[0]).toEqual({ + tool: "TestTool", + permission: "allow", + }); + }); + }); + + describe("getPermissions", () => { + it("should return permissions object", async () => { + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + DEFAULT_TOOL_POLICIES + ); + + await service.initialize(); + const permissions = service.getPermissions(); + + expect(permissions).toBeDefined(); + expect(permissions.policies).toEqual(DEFAULT_TOOL_POLICIES); + }); + }); + + describe("updatePermissions", () => { + it("should replace all policies with new ones", async () => { + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + DEFAULT_TOOL_POLICIES + ); + + await service.initialize(); + + const newPolicies: ToolPermissionPolicy[] = [ + { tool: "NewTool1", permission: "allow" }, + { tool: "NewTool2", permission: "ask" }, + ]; + + service.updatePermissions(newPolicies); + const state = service.getState(); + + expect(state.permissions.policies).toEqual(newPolicies); + expect(state.permissions.policies.length).toBe(2); + }); + + it("should handle empty policy updates", () => { + service.updatePermissions([]); + const state = service.getState(); + + expect(state.permissions.policies).toEqual([]); + }); + }); + + describe("override precedence", () => { + it("should give precedence to runtime overrides over defaults", async () => { + // Assuming read_file has a default policy + const overrides = { + exclude: ["read_file"], + }; + + // Mock the precedence resolver to return the expected order + const expectedPolicies: ToolPermissionPolicy[] = [ + { tool: "read_file", permission: "exclude" }, // Override comes first + ...DEFAULT_TOOL_POLICIES, + ]; + + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + expectedPolicies + ); + + const state = await service.initialize(overrides); + const policies = state.permissions.policies; + + expect( + mockPrecedenceResolver.resolvePermissionPrecedence + ).toHaveBeenCalledWith({ + commandLineFlags: overrides, + personalSettings: true, + useDefaults: true, + }); + + // The exclude override should come first + expect(policies[0]).toEqual({ tool: "read_file", permission: "exclude" }); + }); + }); + + describe("wildcard support", () => { + it("should support wildcard patterns in overrides", async () => { + const overrides = { + allow: ["mcp__*"], + exclude: ["write_*"], + }; + + const expectedPolicies: ToolPermissionPolicy[] = [ + { tool: "write_*", permission: "exclude" }, + { tool: "mcp__*", permission: "allow" }, + ...DEFAULT_TOOL_POLICIES, + ]; + + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + expectedPolicies + ); + + const state = await service.initialize(overrides); + const policies = state.permissions.policies; + + expect( + mockPrecedenceResolver.resolvePermissionPrecedence + ).toHaveBeenCalledWith({ + commandLineFlags: overrides, + personalSettings: true, + useDefaults: true, + }); + expect(policies).toEqual(expectedPolicies); + }); + }); + + describe("ensurePermissionsYamlExists", () => { + it("should ensure permissions.yaml exists during async initialization", async () => { + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + DEFAULT_TOOL_POLICIES + ); + + await service.initialize(); + + expect( + mockPermissionsYamlLoader.ensurePermissionsYamlExists + ).toHaveBeenCalled(); + }); + + it("should not call ensurePermissionsYamlExists during sync initialization", () => { + mockPrecedenceResolver.resolvePermissionPrecedence.mockReturnValue( + DEFAULT_TOOL_POLICIES + ); + + service.initializeSync(); + + expect( + mockPermissionsYamlLoader.ensurePermissionsYamlExists + ).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/services/ToolPermissionService.ts b/src/services/ToolPermissionService.ts new file mode 100644 index 000000000..b599fcc60 --- /dev/null +++ b/src/services/ToolPermissionService.ts @@ -0,0 +1,83 @@ +import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js"; +import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js"; +import { ToolPermissionPolicy, ToolPermissions } from "../permissions/types.js"; +import logger from "../util/logger.js"; + +export interface ToolPermissionServiceState { + permissions: ToolPermissions; +} + +/** + * Service for managing tool permissions with a single source of truth + */ +export class ToolPermissionService { + private state: ToolPermissionServiceState = { + permissions: { policies: [] } + }; + + /** + * Synchronously initialize with runtime overrides + * Used for immediate availability of command-line permission overrides + */ + initializeSync(runtimeOverrides?: { + allow?: string[]; + ask?: string[]; + exclude?: string[]; + }): ToolPermissionServiceState { + logger.debug("Synchronously initializing ToolPermissionService", { + hasOverrides: !!runtimeOverrides + }); + + // Use the precedence resolver to get properly ordered policies + const compiledPolicies = resolvePermissionPrecedence({ + commandLineFlags: runtimeOverrides, + personalSettings: true, // Enable loading from ~/.continue/permissions.yaml + useDefaults: true + }); + + this.state = { + permissions: { policies: compiledPolicies } + }; + + return this.state; + } + + /** + * Initialize the tool permission service with runtime overrides (async version) + */ + async initialize(runtimeOverrides?: { + allow?: string[]; + ask?: string[]; + exclude?: string[]; + }): Promise { + // Ensure permissions.yaml exists before loading + await ensurePermissionsYamlExists(); + + // Use the synchronous version after ensuring the file exists + return this.initializeSync(runtimeOverrides); + } + + /** + * Get the current permission state + */ + getState(): ToolPermissionServiceState { + return this.state; + } + + /** + * Get the compiled permissions + */ + getPermissions(): ToolPermissions { + return this.state.permissions; + } + + /** + * Update permissions (e.g., when config changes) + */ + updatePermissions(newPolicies: ToolPermissionPolicy[]) { + this.state = { + permissions: { policies: newPolicies } + }; + logger.debug(`Updated tool permissions with ${newPolicies.length} policies`); + } +} \ No newline at end of file diff --git a/src/services/ToolPermissionService.unit.test.ts b/src/services/ToolPermissionService.unit.test.ts new file mode 100644 index 000000000..71793ca81 --- /dev/null +++ b/src/services/ToolPermissionService.unit.test.ts @@ -0,0 +1,77 @@ +import { ToolPermissionService } from "./ToolPermissionService.js"; + +describe("ToolPermissionService unit tests", () => { + let service: ToolPermissionService; + + beforeEach(() => { + service = new ToolPermissionService(); + }); + + describe("synchronous initialization", () => { + it("should initialize with runtime overrides", () => { + const overrides = { + allow: ["TestTool1"], + ask: ["TestTool2"], + exclude: ["TestTool3"], + }; + + const state = service.initializeSync(overrides); + + // Verify the state is set + expect(state).toBeDefined(); + expect(state.permissions).toBeDefined(); + expect(state.permissions.policies).toBeDefined(); + expect(state.permissions.policies.length).toBeGreaterThan(0); + + // Verify the overrides are in the policies + const toolNames = state.permissions.policies.map((p) => p.tool); + expect(toolNames).toContain("TestTool3"); + expect(toolNames).toContain("TestTool2"); + expect(toolNames).toContain("TestTool1"); + }); + + it("should handle empty overrides", () => { + const overrides = { + allow: [], + ask: [], + exclude: [], + }; + + const state = service.initializeSync(overrides); + + expect(state).toBeDefined(); + expect(state.permissions).toBeDefined(); + expect(state.permissions.policies).toBeDefined(); + expect(state.permissions.policies.length).toBeGreaterThan(0); + }); + }); + + describe("getState and getPermissions", () => { + it("should return consistent state", () => { + service.initializeSync({ allow: ["TestTool"] }); + + const state = service.getState(); + const permissions = service.getPermissions(); + + expect(state.permissions).toBe(permissions); + expect(state.permissions.policies).toBe(permissions.policies); + }); + }); + + describe("updatePermissions", () => { + it("should replace all policies", () => { + service.initializeSync(); + + const newPolicies = [ + { tool: "NewTool1", permission: "allow" as const }, + { tool: "NewTool2", permission: "ask" as const }, + ]; + + service.updatePermissions(newPolicies); + const state = service.getState(); + + expect(state.permissions.policies).toEqual(newPolicies); + expect(state.permissions.policies.length).toBe(2); + }); + }); +}); diff --git a/src/services/index.ts b/src/services/index.ts index b1aaa28e0..f9b03ed0d 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -5,6 +5,7 @@ import { ConfigService } from "./ConfigService.js"; import { MCPServiceWrapper } from "./MCPServiceWrapper.js"; import { ModelService } from "./ModelService.js"; import { serviceContainer } from "./ServiceContainer.js"; +import { ToolPermissionService } from "./ToolPermissionService.js"; import { ApiClientServiceState, AuthServiceState, @@ -19,6 +20,7 @@ const configService = new ConfigService(); const modelService = new ModelService(); const apiClientService = new ApiClientService(); const mcpServiceWrapper = new MCPServiceWrapper(); +const toolPermissionService = new ToolPermissionService(); /** * Initialize all services and register them with the service container @@ -26,7 +28,20 @@ const mcpServiceWrapper = new MCPServiceWrapper(); export async function initializeServices(options: ServiceInitOptions = {}) { logger.debug("Initializing service registry"); - // Register service factories with dependencies + // Handle tool permissions specially for immediate availability + if (options.toolPermissionOverrides) { + // Initialize synchronously and register the value immediately + const permissionState = toolPermissionService.initializeSync(options.toolPermissionOverrides); + serviceContainer.registerValue(SERVICE_NAMES.TOOL_PERMISSIONS, permissionState); + } else { + // Register normal factory for lazy initialization + serviceContainer.register( + SERVICE_NAMES.TOOL_PERMISSIONS, + () => toolPermissionService.initialize(), + [] + ); + } + serviceContainer.register( SERVICE_NAMES.AUTH, () => authService.initialize(), @@ -160,6 +175,7 @@ export function reloadService(serviceName: string) { */ export function areServicesReady(): boolean { return [ + SERVICE_NAMES.TOOL_PERMISSIONS, SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.CONFIG, @@ -184,6 +200,7 @@ export const services = { model: modelService, apiClient: apiClientService, mcp: mcpServiceWrapper, + toolPermissions: toolPermissionService, } as const; // Export the service container for advanced usage diff --git a/src/services/types.ts b/src/services/types.ts index c99a6061d..3d4dafab6 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -3,6 +3,7 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import { AuthConfig } from "../auth/workos.js"; import { MCPService } from "../mcp.js"; +import { ToolPermissions } from "../permissions/types.js"; /** * Service lifecycle states @@ -56,6 +57,10 @@ export interface ApiClientServiceState { apiClient: DefaultApiInterface | null; } +export interface ToolPermissionServiceState { + permissions: ToolPermissions; +} + /** * Service names as constants to prevent typos */ @@ -64,7 +69,8 @@ export const SERVICE_NAMES = { CONFIG: 'config', MODEL: 'model', MCP: 'mcp', - API_CLIENT: 'apiClient' + API_CLIENT: 'apiClient', + TOOL_PERMISSIONS: 'toolPermissions' } as const; /** @@ -74,4 +80,9 @@ export interface ServiceInitOptions { configPath?: string; rules?: string[]; headless?: boolean; + toolPermissionOverrides?: { + allow?: string[]; + ask?: string[]; + exclude?: string[]; + }; } \ No newline at end of file diff --git a/src/shared-options.ts b/src/shared-options.ts new file mode 100644 index 000000000..9feeb5eae --- /dev/null +++ b/src/shared-options.ts @@ -0,0 +1,76 @@ +import { Command } from "commander"; + +// Function to add common options to any command +export function addCommonOptions(command: Command): Command { + return command + .option("--config ", "Path to configuration file") + .option("--readonly", "Only allow readonly tools") + .option("--no-tools", "Disable all tools") + .option("-v, --verbose", "Enable verbose logging") + .option( + "--rule ", + "Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.", + (value: string, previous: string[] | undefined) => { + const array = Array.isArray(previous) ? previous : []; + array.push(value); + return array; + }, + [] as string[] + ) + .option( + "--allow ", + "Allow specified tool (overrides default policies). Can be specified multiple times.", + (value: string, previous: string[] | undefined) => { + const array = Array.isArray(previous) ? previous : []; + array.push(value); + return array; + }, + [] as string[] + ) + .option( + "--ask ", + "Ask for permission before using specified tool (overrides default policies). Can be specified multiple times.", + (value: string, previous: string[] | undefined) => { + const array = Array.isArray(previous) ? previous : []; + array.push(value); + return array; + }, + [] as string[] + ) + .option( + "--exclude ", + "Exclude specified tool from use (overrides default policies). Can be specified multiple times.", + (value: string, previous: string[] | undefined) => { + const array = Array.isArray(previous) ? previous : []; + array.push(value); + return array; + }, + [] as string[] + ); +} + +// Function to merge parent options into subcommand options +export function mergeParentOptions(parentCommand: Command, options: any): any { + const parentOpts = parentCommand.opts(); + const mergedOptions = { ...options }; + + // List of options to inherit from parent if not present in subcommand + const inheritableOptions = [ + 'config', + 'readonly', + 'tools', + 'verbose', + 'rule', + 'allow', + 'ask', + 'exclude' + ]; + + for (const optName of inheritableOptions) { + if (parentOpts[optName] !== undefined && mergedOptions[optName] === undefined) { + mergedOptions[optName] = parentOpts[optName]; + } + } + + return mergedOptions; +} \ No newline at end of file diff --git a/src/slashCommands.ts b/src/slashCommands.ts index 9777e438b..c2bbc44a5 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -19,6 +19,7 @@ export async function handleSlashCommands( newInput?: string; clear?: boolean; openConfigSelector?: boolean; + openModelSelector?: boolean; } | null> { // Only trigger slash commands if slash is the very first character if (input.startsWith("/") && input.trim().startsWith("/")) { @@ -124,6 +125,10 @@ export async function handleSlashCommands( }; } + case "model": + // Open model selector UI + return { openModelSelector: true }; + case "org": posthogService.capture("useSlashCommand", { name: "org", diff --git a/src/streamChatResponse.test.ts b/src/streamChatResponse.test.ts new file mode 100644 index 000000000..4fa3a6bba --- /dev/null +++ b/src/streamChatResponse.test.ts @@ -0,0 +1,282 @@ +import { describe, expect, it, jest } from "@jest/globals"; +import type { ChatCompletionChunk } from "openai/resources/chat/completions.mjs"; + +// Test the chunk processing logic that was identified as buggy +describe("streamChatResponse - chunk ordering bug", () => { + // Helper to create a chunk with content + function contentChunk(content: string): ChatCompletionChunk { + return { + id: "test", + object: "chat.completion.chunk", + created: Date.now(), + model: "test-model", + choices: [{ + index: 0, + delta: { content }, + finish_reason: null, + }], + }; + } + + // Helper to create a chunk with tool call + function toolCallChunk( + id: string, + name?: string, + args?: string + ): ChatCompletionChunk { + return { + id: "test", + object: "chat.completion.chunk", + created: Date.now(), + model: "test-model", + choices: [{ + index: 0, + delta: { + tool_calls: [{ + index: 0, + id, + type: "function", + function: { + name: name || undefined, + arguments: args || undefined, + }, + }], + }, + finish_reason: null, + }], + }; + } + + // Simulate the chunk processing logic from streamChatResponse.ts + function processChunks(chunks: ChatCompletionChunk[]): { + content: string; + finalContent: string; + hasToolCalls: boolean; + toolCallsMap: Map; + } { + let aiResponse = ""; + const toolCallsMap = new Map(); + const indexToIdMap = new Map(); // Track index to ID mapping + let hasToolCalls = false; + + for (const chunk of chunks) { + if (!chunk.choices || !chunk.choices[0]) continue; + + const choice = chunk.choices[0]; + if (!choice.delta) continue; + + // Handle content + if (choice.delta.content) { + aiResponse += choice.delta.content; + } + + // Handle tool calls + if (choice.delta.tool_calls) { + hasToolCalls = true; + for (const toolCallDelta of choice.delta.tool_calls) { + let toolCallId: string | undefined; + + // If we have an ID, use it and map the index + if (toolCallDelta.id) { + toolCallId = toolCallDelta.id; + if (toolCallDelta.index !== undefined) { + indexToIdMap.set(toolCallDelta.index, toolCallId); + } + + // Create tool call entry if it doesn't exist + if (!toolCallsMap.has(toolCallId)) { + toolCallsMap.set(toolCallId, { + id: toolCallId, + name: "", + argumentsStr: "", + }); + } + } else if (toolCallDelta.index !== undefined) { + // No ID, but we have an index - look up the ID from our map + toolCallId = indexToIdMap.get(toolCallDelta.index); + } + + if (!toolCallId) continue; + + const toolCall = toolCallsMap.get(toolCallId); + if (!toolCall) continue; + + if (toolCallDelta.function?.name) { + toolCall.name = toolCallDelta.function.name; + } + + if (toolCallDelta.function?.arguments) { + toolCall.argumentsStr += toolCallDelta.function.arguments; + } + } + } + } + + // The fixed behavior: always preserve content + const finalContent = aiResponse; + + return { + content: aiResponse, + finalContent: finalContent, + hasToolCalls, + toolCallsMap, + }; + } + + it("content after tool calls is preserved", () => { + const chunks = [ + contentChunk(""), + toolCallChunk("call_123", "read_file", '{"filepath": "/README.md"}'), + contentChunk(""), + contentChunk("I'll read the README file for you."), + ]; + + const result = processChunks(chunks); + + expect(result.content).toBe("I'll read the README file for you."); + expect(result.hasToolCalls).toBe(true); + + // Fixed: finalContent now preserves the content + expect(result.finalContent).toBe("I'll read the README file for you."); + }); + + it("content before tool calls is preserved", () => { + const chunks = [ + contentChunk("Let me search for that. "), + toolCallChunk("call_123", "search_code", '{"pattern": "test"}'), + ]; + + const result = processChunks(chunks); + + expect(result.content).toBe("Let me search for that. "); + expect(result.hasToolCalls).toBe(true); + + // Fixed: finalContent preserves content before tool calls + expect(result.finalContent).toBe("Let me search for that. "); + }); + + it("handles the exact problematic sequence from the logs", () => { + const chunks = [ + contentChunk(""), + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", "read_file", ""), + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '{"filepath'), + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '": "/Use'), + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, 'rs/nate/gh/c'), + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, 'ontinuede'), + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, 'v/cli/README'), + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '.md"}'), + contentChunk(""), + contentChunk("I'll read the README file for you."), + ]; + + const result = processChunks(chunks); + + expect(result.content).toBe("I'll read the README file for you."); + expect(result.hasToolCalls).toBe(true); + + // Fixed: content is preserved + expect(result.finalContent).toBe("I'll read the README file for you."); + }); + + it("shows content works fine without tool calls", () => { + const chunks = [ + contentChunk("Hello "), + contentChunk("world!"), + ]; + + const result = processChunks(chunks); + + expect(result.content).toBe("Hello world!"); + expect(result.hasToolCalls).toBe(false); + + // Without tool calls, finalContent is correct + expect(result.finalContent).toBe("Hello world!"); + }); + + // Helper to create a tool call chunk with optional ID + function toolCallChunkWithIndex( + index: number, + id?: string, + name?: string, + args?: string + ): ChatCompletionChunk { + const toolCall: any = { + index, + type: "function" as const, + function: {} + }; + + if (id) toolCall.id = id; + if (name) toolCall.function.name = name; + if (args !== undefined) toolCall.function.arguments = args; + + return { + id: "test", + object: "chat.completion.chunk" as const, + created: Date.now(), + model: "test-model", + choices: [{ + index: 0, + delta: { tool_calls: [toolCall] }, + finish_reason: null, + }], + }; + } + + it("handles provider that only sends tool ID in first chunk then uses index", () => { + // Create chunks that simulate a provider sending ID only in first chunk + const chunks = [ + contentChunk("I'll read the README.md file for you and then say hello!"), + // First chunk has ID + toolCallChunkWithIndex(0, "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", "read_file", ""), + // Subsequent chunks only have index, no ID + toolCallChunkWithIndex(0, undefined, undefined, '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'), + ]; + + const result = processChunks(chunks); + + // Content is captured correctly + expect(result.content).toBe("I'll read the README.md file for you and then say hello!"); + expect(result.hasToolCalls).toBe(true); + + // Fixed: finalContent preserves content + expect(result.finalContent).toBe("I'll read the README.md file for you and then say hello!"); + + // Fixed: tool call arguments are preserved using index mapping + const toolCalls = Array.from(result.toolCallsMap.values()); + expect(toolCalls).toHaveLength(1); + expect(toolCalls[0].argumentsStr).toBe('{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'); + }); + + it("handles realistic fragmented arguments from index-based provider", () => { + // Simulate the exact sequence from the user's logs with fragmented JSON + const chunks = [ + contentChunk("I'll read the README.md file for you and then say hello!"), + // First chunk has ID + toolCallChunkWithIndex(0, "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", "read_file", ""), + // Subsequent chunks fragment the JSON arguments + toolCallChunkWithIndex(0, undefined, undefined, '{"filepa'), + toolCallChunkWithIndex(0, undefined, undefined, 'th"'), + toolCallChunkWithIndex(0, undefined, undefined, ': '), + toolCallChunkWithIndex(0, undefined, undefined, '"/U'), + toolCallChunkWithIndex(0, undefined, undefined, 'sers/nate/gh'), + toolCallChunkWithIndex(0, undefined, undefined, '/c'), + toolCallChunkWithIndex(0, undefined, undefined, 'onti'), + toolCallChunkWithIndex(0, undefined, undefined, 'nuedev/cli'), + toolCallChunkWithIndex(0, undefined, undefined, '/READ'), + toolCallChunkWithIndex(0, undefined, undefined, 'ME.m'), + toolCallChunkWithIndex(0, undefined, undefined, 'd"}'), + ]; + + const result = processChunks(chunks); + + // Fixed: Both issues are resolved + // 1. Content is preserved + expect(result.finalContent).toBe("I'll read the README.md file for you and then say hello!"); + + // 2. Tool call arguments are assembled correctly + const toolCalls = Array.from(result.toolCallsMap.values()); + expect(toolCalls[0].argumentsStr).toBe('{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'); + }); + +}); \ No newline at end of file diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 3d6207a42..242e30d83 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 { @@ -133,6 +164,7 @@ async function processStreamingResponse( let aiResponse = ""; let finalContent = ""; const toolCallsMap = new Map(); + const indexToIdMap = new Map(); // Track index to ID mapping let firstTokenTime: number | null = null; let inputTokens = 0; let outputTokens = 0; @@ -206,21 +238,40 @@ async function processStreamingResponse( if (choice.delta.tool_calls) { hasToolCalls = true; for (const toolCallDelta of choice.delta.tool_calls) { - // Get or create tool call + let toolCallId: string | undefined; + + // If we have an ID, use it and map the index if (toolCallDelta.id) { - if (!toolCallsMap.has(toolCallDelta.id)) { - toolCallsMap.set(toolCallDelta.id, { - id: toolCallDelta.id, - name: "", - arguments: null, - argumentsStr: "", - startNotified: false, - }); + toolCallId = toolCallDelta.id; + if (toolCallDelta.index !== undefined && toolCallId) { + indexToIdMap.set(toolCallDelta.index, toolCallId); } + } else if (toolCallDelta.index !== undefined) { + // No ID, but we have an index - look up the ID from our map + toolCallId = indexToIdMap.get(toolCallDelta.index); + } + + if (!toolCallId) { + logger.warn("Tool call delta without ID or valid index mapping", { toolCallDelta }); + continue; + } + + // Create tool call entry if it doesn't exist + if (!toolCallsMap.has(toolCallId)) { + toolCallsMap.set(toolCallId, { + id: toolCallId, + name: "", + arguments: null, + argumentsStr: "", + startNotified: false, + }); } - const toolCall = toolCallsMap.get(toolCallDelta.id || ""); - if (!toolCall) continue; + const toolCall = toolCallsMap.get(toolCallId); + if (!toolCall) { + logger.warn("Tool call not found in map", { toolCallId }); + continue; + } // Update name if (toolCallDelta.function?.name) { @@ -235,13 +286,8 @@ async function processStreamingResponse( try { toolCall.arguments = JSON.parse(toolCall.argumentsStr); - // Notify on first successful parse - if (!toolCall.startNotified && toolCall.name) { - toolCall.startNotified = true; - if (callbacks?.onToolStart) { - callbacks.onToolStart(toolCall.name, toolCall.arguments); - } - } + // Don't notify onToolStart here anymore - wait until after permission check + toolCall.startNotified = true; } catch (e) { // JSON not complete yet, continue } @@ -326,10 +372,8 @@ async function processStreamingResponse( return true; }); - // Set finalContent based on whether this was a tool call or not - // For headless mode: if there's a tool call, we only want to show final text content - // If it's the first response (no tool calls), we save the final content - finalContent = hasToolCalls ? "" : aiResponse; + // Always preserve the content - it should be displayed regardless of tool calls + finalContent = aiResponse; return { content: aiResponse, @@ -423,6 +467,95 @@ 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, + }); + + + // Notify tool start immediately - before permission check + // This ensures the UI shows the tool call even if it's rejected + if (callbacks?.onToolStart) { + callbacks.onToolStart(toolCall.name, toolCall.arguments); + } + + let approved = false; + + if (permissionCheck.permission === "allow") { + approved = true; + } else if (permissionCheck.permission === "ask") { + // Request permission from user + if (callbacks?.onToolPermissionRequest) { + // Use the proper toolPermissionManager API + const toolCallRequest = { + name: toolCall.name, + arguments: toolCall.arguments, + }; + + // Set up listener for permissionRequested event + const handlePermissionRequested = (event: { + requestId: string; + toolCall: { name: string; arguments: any }; + }) => { + if (event.toolCall.name === toolCall.name) { + toolPermissionManager.off( + "permissionRequested", + handlePermissionRequested + ); + // Notify UI about permission request + callbacks.onToolPermissionRequest!( + event.toolCall.name, + event.toolCall.arguments, + event.requestId + ); + } + }; + + toolPermissionManager.on( + "permissionRequested", + handlePermissionRequested + ); + + // Request permission using the proper API + const permissionResult = await toolPermissionManager.requestPermission( + toolCallRequest + ); + + approved = permissionResult.approved; + } 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/test-helpers/__tests__/testServiceContainer.test.ts b/src/test-helpers/__tests__/testServiceContainer.test.ts index 955ed438b..e30b20ffb 100644 --- a/src/test-helpers/__tests__/testServiceContainer.test.ts +++ b/src/test-helpers/__tests__/testServiceContainer.test.ts @@ -1,6 +1,10 @@ +import { jest } from "@jest/globals"; import { createTestServiceContainer } from '../testServiceContainer.js'; describe('TestServiceContainer', () => { + afterEach(() => { + jest.clearAllTimers(); + }); it('should create a container with extended methods', () => { const container = createTestServiceContainer(); diff --git a/src/test-helpers/mock-llm-server.ts b/src/test-helpers/mock-llm-server.ts index 117d3d330..ec526a899 100644 --- a/src/test-helpers/mock-llm-server.ts +++ b/src/test-helpers/mock-llm-server.ts @@ -159,6 +159,9 @@ export async function createMockLLMServer( return; } + // Use unref() to prevent keeping the process alive unnecessarily + server.unref(); + resolve({ server, port: address.port, @@ -248,12 +251,16 @@ export async function cleanupMockLLMServer( } }; - // Force close all connections if method exists + // Destroy all active connections immediately if (typeof mockServer.server.closeAllConnections === "function") { mockServer.server.closeAllConnections(); } - // Try to close the server gracefully + // Set a shorter keep-alive timeout before closing + mockServer.server.keepAliveTimeout = 0; + mockServer.server.headersTimeout = 0; + + // Try to close the server gracefully first if (mockServer.server.listening) { mockServer.server.close((err: any) => { if (err && err.code !== "ERR_SERVER_NOT_RUNNING") { @@ -261,11 +268,21 @@ export async function cleanupMockLLMServer( } resolveOnce(); }); + + // Force close after a short timeout + setTimeout(() => { + if (mockServer.server.listening) { + mockServer.server.closeAllConnections?.(); + // Use unref to prevent keeping the process alive + mockServer.server.unref(); + } + resolveOnce(); + }, 100); } else { resolveOnce(); } // Fallback timeout to ensure cleanup doesn't hang - setTimeout(resolveOnce, 500); + setTimeout(resolveOnce, 200); }); } diff --git a/src/tools/formatters.test.ts b/src/tools/formatters.test.ts new file mode 100644 index 000000000..8f1ddc307 --- /dev/null +++ b/src/tools/formatters.test.ts @@ -0,0 +1,98 @@ +import { jest } from "@jest/globals"; +import { formatToolCall, formatToolArgument } from "./formatters.js"; + +describe("formatToolCall", () => { + const originalCwd = process.cwd(); + + beforeEach(() => { + // Mock process.cwd to return a consistent value + jest.spyOn(process, "cwd").mockReturnValue("/Users/test/project"); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("should format tool name without arguments", () => { + expect(formatToolCall("write_file")).toBe("Write"); + expect(formatToolCall("read_file", {})).toBe("Read"); + // edit_file doesn't exist, so it returns the original name + expect(formatToolCall("edit_file", null)).toBe("edit_file"); + }); + + it("should format tool name with relative path argument", () => { + expect(formatToolCall("write_file", { filepath: "README.md" })).toBe( + "Write(README.md)" + ); + expect(formatToolCall("read_file", { filepath: "src/index.ts" })).toBe( + "Read(src/index.ts)" + ); + }); + + it("should convert absolute paths to relative paths", () => { + expect( + formatToolCall("write_file", { filepath: "/Users/test/project/README.md" }) + ).toBe("Write(README.md)"); + + expect( + formatToolCall("read_file", { + filepath: "/Users/test/project/src/components/App.tsx", + }) + ).toBe("Read(src/components/App.tsx)"); + }); + + it("should handle absolute paths outside the project", () => { + expect( + formatToolCall("write_file", { filepath: "/Users/other/file.txt" }) + ).toBe("Write(../../other/file.txt)"); + }); + + it("should handle non-path arguments", () => { + expect(formatToolCall("search_code", { pattern: "TODO" })).toBe( + "Search(TODO)" + ); + expect(formatToolCall("search_code", { pattern: 123 })).toBe("Search(123)"); + }); + + it("should use first argument when multiple are provided", () => { + expect( + formatToolCall("write_file", { + filepath: "test.txt", + content: "Hello world", + }) + ).toBe("Write(test.txt)"); + }); +}); + +describe("formatToolArgument", () => { + beforeEach(() => { + jest.spyOn(process, "cwd").mockReturnValue("/Users/test/project"); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("should return empty string for null/undefined", () => { + expect(formatToolArgument(null)).toBe(""); + expect(formatToolArgument(undefined)).toBe(""); + }); + + it("should convert absolute paths to relative", () => { + expect(formatToolArgument("/Users/test/project/README.md")).toBe("README.md"); + expect(formatToolArgument("/Users/test/project/src/index.ts")).toBe( + "src/index.ts" + ); + }); + + it("should preserve relative paths", () => { + expect(formatToolArgument("README.md")).toBe("README.md"); + expect(formatToolArgument("./src/index.ts")).toBe("./src/index.ts"); + }); + + it("should handle non-string values", () => { + expect(formatToolArgument(123)).toBe("123"); + expect(formatToolArgument(true)).toBe("true"); + expect(formatToolArgument({ key: "value" })).toBe("[object Object]"); + }); +}); \ No newline at end of file diff --git a/src/tools/formatters.ts b/src/tools/formatters.ts new file mode 100644 index 000000000..0082ce557 --- /dev/null +++ b/src/tools/formatters.ts @@ -0,0 +1,44 @@ +import path from "path"; +import { getToolDisplayName } from "./index.js"; + +/** + * Formats a tool call with its arguments for display + * @param toolName The name of the tool + * @param args The tool arguments + * @returns A formatted string like "ToolName(arg)" or just "ToolName" if no args + */ +export function formatToolCall(toolName: string, args?: any): string { + const displayName = getToolDisplayName(toolName); + + if (!args || Object.keys(args).length === 0) { + return displayName; + } + + // Get the first argument value + const firstValue = Object.values(args)[0]; + const formattedValue = formatToolArgument(firstValue); + + return `${displayName}(${formattedValue})`; +} + +/** + * Formats a single tool argument for display + * @param value The argument value + * @returns A formatted string representation of the value + */ +export function formatToolArgument(value: any): string { + if (value === null || value === undefined) { + return ""; + } + + // Convert absolute paths to relative paths + if (typeof value === "string" && path.isAbsolute(value)) { + const workspaceRoot = process.cwd(); + const relativePath = path.relative(workspaceRoot, value); + // Normalize path separators to forward slashes for cross-platform consistency + return (relativePath || value).replace(/\\/g, "/"); + } + + // Return other values as strings + return String(value); +} \ No newline at end of file diff --git a/src/ui/ModelSelector.tsx b/src/ui/ModelSelector.tsx new file mode 100644 index 000000000..5cf04a8d3 --- /dev/null +++ b/src/ui/ModelSelector.tsx @@ -0,0 +1,73 @@ +import React, { useEffect, useState } from "react"; +import { services } from "../services/index.js"; +import Selector, { SelectorOption } from "./Selector.js"; + +interface ModelOption extends SelectorOption { + index: number; + provider: string; +} + +interface ModelSelectorProps { + onSelect: (model: ModelOption) => void; + onCancel: () => void; +} + +const ModelSelector: React.FC = ({ + onSelect, + onCancel, +}) => { + const [models, setModels] = useState([]); + const [selectedIndex, setSelectedIndex] = useState(0); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [currentModelIndex, setCurrentModelIndex] = useState(-1); + + useEffect(() => { + const loadModels = async () => { + try { + const availableModels = services.model.getAvailableChatModels(); + const currentIndex = services.model.getCurrentModelIndex(); + + if (availableModels.length === 0) { + setError("No chat models available in the configuration"); + setLoading(false); + return; + } + + const modelOptions: ModelOption[] = availableModels.map((model) => ({ + id: `${model.provider}-${model.name}-${model.index}`, + name: `${model.provider}/${model.name}`, + index: model.index, + provider: model.provider, + })); + + setModels(modelOptions); + setCurrentModelIndex(currentIndex); + setSelectedIndex(Math.max(0, currentIndex)); + setLoading(false); + } catch (err: any) { + setError(err.message || "Failed to load models"); + setLoading(false); + } + }; + + loadModels(); + }, []); + + return ( + = 0 && models[currentModelIndex] ? models[currentModelIndex].id : null} + onSelect={onSelect} + onCancel={onCancel} + onNavigate={setSelectedIndex} + /> + ); +}; + +export default ModelSelector; \ No newline at end of file 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 40862cd23..84eaeecc2 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"; @@ -15,9 +16,11 @@ import FreeTrialTransitionUI from "./FreeTrialTransitionUI.js"; import { useChat } from "./hooks/useChat.js"; import { useConfigSelector } from "./hooks/useConfigSelector.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; +import { useModelSelector } from "./hooks/useModelSelector.js"; import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; import IntroMessage from "./IntroMessage.js"; import LoadingAnimation from "./LoadingAnimation.js"; +import ModelSelector from "./ModelSelector.js"; import OrganizationSelector from "./OrganizationSelector.js"; import Timer from "./Timer.js"; import UpdateNotification from "./UpdateNotification.js"; @@ -158,10 +161,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, @@ -171,6 +177,7 @@ const TUIChat: React.FC = ({ additionalRules, onShowOrgSelector: () => showOrganizationSelector(), onShowConfigSelector: () => showConfigSelectorUI(), + onShowModelSelector: () => showModelSelectorUI(), onLoginPrompt: handleLoginPrompt, onReload: handleReload, // Remote mode configuration @@ -207,6 +214,17 @@ const TUIChat: React.FC = ({ onChatReset: resetChatHistory, }); + const { + showModelSelector, + handleModelSelect, + handleModelCancel, + showModelSelectorUI, + } = useModelSelector({ + onMessage: (message) => { + setMessages((prev) => [...prev, message]); + }, + }); + // Handle free trial transition completion const handleFreeTrialTransitionComplete = () => { setIsShowingFreeTrialTransition(false); @@ -228,8 +246,10 @@ const TUIChat: React.FC = ({ const isInputDisabled = showOrgSelector || showConfigSelector || + showModelSelector || !!loginPrompt || - isShowingFreeTrialTransition; + isShowingFreeTrialTransition || + !!activePermissionRequest; return ( @@ -315,6 +335,14 @@ const TUIChat: React.FC = ({ /> )} + {/* Model selector - shows above input when active */} + {showModelSelector && ( + + )} + {/* Free trial transition UI - replaces input when active */} {isShowingFreeTrialTransition && ( = ({ {/* 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/ToolResultSummary.tsx b/src/ui/ToolResultSummary.tsx index 9b77650ad..78ef9ba24 100644 --- a/src/ui/ToolResultSummary.tsx +++ b/src/ui/ToolResultSummary.tsx @@ -74,6 +74,11 @@ const ToolResultSummary: React.FC = ({ // Handle all other cases with text summary const getSummary = () => { + // Check if this is a user cancellation first + if (content === "Permission denied by user") { + return "Cancelled by user"; + } + // Convert absolute paths to relative paths from workspace root const formatPath = (filePath: string) => { if (path.isAbsolute(filePath)) { diff --git a/src/ui/__tests__/TUIChat.toolPermission.test.tsx b/src/ui/__tests__/TUIChat.toolPermission.test.tsx new file mode 100644 index 000000000..4ff073bbe --- /dev/null +++ b/src/ui/__tests__/TUIChat.toolPermission.test.tsx @@ -0,0 +1,239 @@ +import { jest } from "@jest/globals"; +import { render } from "ink-testing-library"; +import React from "react"; +import { ToolPermissionSelector } from "../components/ToolPermissionSelector.js"; + +describe("TUIChat - Tool Permission Tests", () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.clearAllTimers(); + jest.useRealTimers(); + }); + it("shows ToolPermissionSelector with correct content", async () => { + const handleResponse = jest.fn(); + + const { lastFrame } = render( + + ); + + await jest.advanceTimersByTimeAsync(50); + + const frame = lastFrame(); + + // Verify ToolPermissionSelector is shown + expect(frame).toContain("Edit"); + expect(frame).toContain("Would you like to continue?"); + expect(frame).toContain("Continue"); + expect(frame).toContain("Continue + don't ask again"); + expect(frame).toContain("Cancel"); + expect(frame).toContain("(tab)"); + expect(frame).toContain("(shift+tab)"); + expect(frame).toContain("(esc)"); + }); + + it("handles keyboard shortcuts for permission approval and rejection", async () => { + const handleResponse = jest.fn(); + + const { stdin } = render( + + ); + + await jest.advanceTimersByTimeAsync(50); + + // Test Tab key for approval + stdin.write("\t"); + + await jest.advanceTimersByTimeAsync(50); + + expect(handleResponse).toHaveBeenCalledWith( + "test-request-123", + true, + false + ); + }); + + it("handles escape key for rejection", async () => { + const handleResponse = jest.fn(); + + const { stdin } = render( + + ); + + await jest.advanceTimersByTimeAsync(50); + + // Test escape key for rejection + stdin.write("\x1b"); // ESC key + + await jest.advanceTimersByTimeAsync(50); + + expect(handleResponse).toHaveBeenCalledWith( + "test-request-456", + false, + false + ); + }); + + it("handles 'n' key for rejection", async () => { + const handleResponse = jest.fn(); + + const { stdin } = render( + + ); + + await jest.advanceTimersByTimeAsync(50); + + // Test 'n' key for rejection + stdin.write("n"); + + await jest.advanceTimersByTimeAsync(50); + + expect(handleResponse).toHaveBeenCalledWith( + "test-request-789", + false, + false + ); + }); + + it("handles arrow key navigation in permission selector", async () => { + const handleResponse = jest.fn(); + + const { lastFrame, stdin } = render( + + ); + + await jest.advanceTimersByTimeAsync(50); + + // Initial state should show "> Continue" selected + let frame = lastFrame(); + expect(frame).toMatch(/>\s+Continue/); + + // Test that pressing Enter on default selection triggers approval + stdin.write("\r"); + await jest.advanceTimersByTimeAsync(50); + + expect(handleResponse).toHaveBeenCalledWith( + "test-request-123", + true, + undefined + ); + }); + + it("handles shift+tab key for policy creation", async () => { + const handleResponse = jest.fn(); + + const { stdin } = render( + + ); + + await jest.advanceTimersByTimeAsync(50); + + // Test shift+tab key for approval with policy creation + // In terminal, shift+tab is typically represented as "\x1b[Z" + stdin.write("\x1b[Z"); + + await jest.advanceTimersByTimeAsync(50); + + expect(handleResponse).toHaveBeenCalledWith( + "test-request-policy", + true, + true + ); + }); + + it("shows tool result with red dot and 'Cancelled by user' message", async () => { + // Import the components we need for this test + const { default: ToolResultSummary } = await import( + "../ToolResultSummary.js" + ); + const { MemoizedMessage } = await import( + "../components/MemoizedMessage.js" + ); + + // Test the ToolResultSummary component directly + const { lastFrame: summaryFrame } = render( + + ); + + const summary = summaryFrame(); + expect(summary).toContain("Cancelled by user"); + + // Test the MemoizedMessage component with a tool-result message + const message = { + role: "assistant", + content: "Edit", + messageType: "tool-result" as const, + toolName: "Edit", + toolResult: "Permission denied by user", + }; + + const { lastFrame: messageFrame } = render( + + ); + + await jest.advanceTimersByTimeAsync(100); + + const messageOutput = messageFrame(); + + // Verify the red dot appears + expect(messageOutput).toContain("●"); + + // Verify the tool name appears + expect(messageOutput).toContain("Edit"); + + // The MemoizedMessage component correctly identifies this as a failure + // because message.toolResult includes "Permission denied" + // This causes the red dot to be shown + + // Verify the correct data is passed to the component + expect(message.toolResult).toBe("Permission denied by user"); + expect(message.messageType).toBe("tool-result"); + }); +}); 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..b45ca44fa --- /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 > 60) { + return `${firstValue.substring(0, 60)}...`; + } + + 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(60) + "..."); + expect(result.length).toBe(63); // 60 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 60 character strings", () => { + const exactString = "a".repeat(60); + const result = formatArgs({ content: exactString }); + expect(result).toBe(exactString); + expect(result).not.toContain("..."); + }); + + it("should handle 61 character strings", () => { + const slightlyLongString = "a".repeat(61); + const result = formatArgs({ content: slightlyLongString }); + expect(result).toBe("a".repeat(60) + "..."); + }); + + 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 in insertion order + }); + + 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..7b31d83d5 --- /dev/null +++ b/src/ui/components/ToolPermissionSelector.tsx @@ -0,0 +1,139 @@ +import { Box, Text, useInput } from "ink"; +import React, { useState } from "react"; +import { formatToolCall } from "../../tools/formatters.js"; +import { DetailedToolPreview, ToolPreview } from "./ToolPreview.js"; + +interface PermissionOption { + id: string; + name: string; + color: string; + approved: boolean; + createPolicy?: boolean; +} + +interface ToolPermissionSelectorProps { + toolName: string; + toolArgs: any; + requestId: string; + onResponse: ( + requestId: string, + approved: boolean, + createPolicy?: boolean + ) => void; +} + +const PERMISSION_OPTIONS: PermissionOption[] = [ + { id: "approve", name: "Continue", color: "green", approved: true }, + { + id: "approve_policy", + name: "Continue + don't ask again", + color: "cyan", + approved: true, + createPolicy: 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, + selectedOption.createPolicy + ); + return; + } + + // Tab to continue (approve) + if (key.tab && !key.shift) { + onResponse(requestId, true, false); + return; + } + + // Shift+Tab to continue with policy creation + if (key.tab && key.shift) { + onResponse(requestId, true, true); + return; + } + + // Escape to reject (deny) + if (key.escape) { + onResponse(requestId, false, 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, false); + } else if (input === "n" || input === "N") { + onResponse(requestId, false, false); + } + }); + + const toolCallDisplay = formatToolCall(toolName, toolArgs); + + return ( + + + {toolCallDisplay} + + + {/* Show preview of what the tool will do */} + + + + + {/* Show detailed preview if available */} + + + + Would you like to continue? + {PERMISSION_OPTIONS.map((option, index) => { + const isSelected = index === selectedIndex; + let shortcut = ""; + if (option.id === "approve") shortcut = "(tab)"; + else if (option.id === "approve_policy") shortcut = "(shift+tab)"; + else if (option.id === "deny") shortcut = "(esc)"; + + return ( + + + {isSelected ? "> " : " "} + {option.name} + + + {" "} + {shortcut} + + + ); + })} + + + ); +}; diff --git a/src/ui/components/ToolPreview.tsx b/src/ui/components/ToolPreview.tsx new file mode 100644 index 000000000..dc975eaa0 --- /dev/null +++ b/src/ui/components/ToolPreview.tsx @@ -0,0 +1,163 @@ +import { createTwoFilesPatch } from "diff"; +import * as fs from "fs"; +import { Box, Text } from "ink"; +import React from "react"; +import { formatToolCall, formatToolArgument } from "../../tools/formatters.js"; +import { getToolDisplayName } from "../../tools.js"; +import { ColoredDiff } from "../ColoredDiff.js"; + +interface ToolPreviewProps { + toolName: string; + toolArgs: any; +} + +/** + * Generates a preview of what a tool will do based on its arguments + */ +export const ToolPreview: React.FC = ({ + toolName, + toolArgs, +}) => { + const getPreview = () => { + // For tool calls that match the standard format, use formatToolCall + if (toolName === "read_file" || toolName === "write_file" || toolName === "edit_file") { + return formatToolCall(toolName, toolArgs); + } + + switch (toolName) { + case "list_files": + if (toolArgs.directory) { + return `Will list files in: ${formatToolArgument(toolArgs.directory)}`; + } + return "Will list files in current directory"; + + case "search_code": + if (toolArgs.pattern) { + const truncatedPattern = + toolArgs.pattern.length > 50 + ? toolArgs.pattern.substring(0, 50) + "..." + : toolArgs.pattern; + return `Will search for: "${truncatedPattern}"`; + } + return "Will search the codebase"; + + case "run_terminal_command": + if (toolArgs.command) { + const truncatedCmd = + toolArgs.command.length > 60 + ? toolArgs.command.substring(0, 60) + "..." + : toolArgs.command; + return `Will run: ${truncatedCmd}`; + } + return "Will run a terminal command"; + + case "fetch": + if (toolArgs.url) { + return `Will fetch: ${toolArgs.url}`; + } + return "Will fetch from a URL"; + + case "view_diff": + return "Will show git diff"; + + default: + // For unknown tools, show what args will be passed + const argCount = Object.keys(toolArgs || {}).length; + if (argCount > 0) { + return `Will call ${getToolDisplayName( + toolName + )} with ${argCount} argument${argCount !== 1 ? "s" : ""}`; + } + return `Will call ${getToolDisplayName(toolName)}`; + } + }; + + return ( + + ⎿ + {getPreview()} + + ); +}; + +/** + * Shows a detailed preview for tools where we can predict the output + */ +export const DetailedToolPreview: React.FC = ({ + toolName, + toolArgs, +}) => { + // For edit operations, we could show a diff preview if we have old_string/new_string + if (toolName === "edit_file" && toolArgs.old_string && toolArgs.new_string) { + return ( + + + - {toolArgs.old_string.split("\n")[0]} + + {toolArgs.new_string.split("\n")[0]} + {(toolArgs.old_string.split("\n").length > 1 || + toolArgs.new_string.split("\n").length > 1) && ( + ... + )} + + + ); + } + + // For write operations, show diff preview if file exists + if (toolName === "write_file" && toolArgs.filepath && toolArgs.content) { + try { + if (fs.existsSync(toolArgs.filepath)) { + const oldContent = fs.readFileSync(toolArgs.filepath, "utf-8"); + const newContent = toolArgs.content; + + // Generate a diff preview + const diff = createTwoFilesPatch( + toolArgs.filepath, + toolArgs.filepath, + oldContent, + newContent, + undefined, + undefined, + { context: 2 } + ); + + return ( + + Preview of changes: + + + ); + } else { + // New file - show content preview + const lines = toolArgs.content.split("\n"); + const preview = lines.slice(0, 3); + + return ( + + New file content: + + {preview.map((line: string, i: number) => ( + + {line || " "} + + ))} + {lines.length > 3 && ( + ... ({lines.length - 3} more lines) + )} + + + ); + } + } catch (error) { + // If we can't read the file, just show a simple preview + const lines = toolArgs.content.split("\n"); + return ( + + Content preview ({lines.length} lines) + + ); + } + } + + return null; +}; diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index c94776863..f78d9ed56 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -2,8 +2,8 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; 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 { @@ -12,7 +12,7 @@ import { } from "../../streamChatResponse.js"; import { constructSystemMessage } from "../../systemMessage.js"; import telemetryService from "../../telemetry/telemetryService.js"; -import { getToolDisplayName } from "../../tools.js"; +import { formatToolCall } from "../../tools/formatters.js"; import { formatError } from "../../util/formatError.js"; import logger from "../../util/logger.js"; @@ -28,6 +28,7 @@ interface UseChatProps { additionalRules?: string[]; onShowOrgSelector: () => void; onShowConfigSelector: () => void; + onShowModelSelector?: () => void; onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; // Remote mode props @@ -44,6 +45,7 @@ export function useChat({ additionalRules, onShowOrgSelector, onShowConfigSelector, + onShowModelSelector, onLoginPrompt, onReload, isRemoteMode = false, @@ -115,6 +117,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(() => { @@ -343,6 +350,11 @@ export function useChat({ return; } + if (commandResult.openModelSelector && onShowModelSelector) { + onShowModelSelector(); + return; + } + if (commandResult.clear) { const systemMessage = chatHistory.find( (msg) => msg.role === "system" @@ -492,23 +504,6 @@ export function useChat({ } }, onToolStart: (toolName: string, toolArgs?: any) => { - const formatToolCall = (name: string, args: any) => { - const displayName = getToolDisplayName(name); - if (!args) return displayName; - - const firstValue = Object.values(args)[0]; - const formatPath = (value: any) => { - if (typeof value === "string" && path.isAbsolute(value)) { - const workspaceRoot = process.cwd(); - const relativePath = path.relative(workspaceRoot, value); - return relativePath || value; - } - return value; - }; - - return `${displayName}(${formatPath(firstValue) || ""})`; - }; - if (currentStreamingMessage && currentStreamingMessage.content) { const messageContent = currentStreamingMessage.content; setMessages((prev) => [ @@ -562,6 +557,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 @@ -666,6 +673,48 @@ export function useChat({ setMessages([]); }; + const handleToolPermissionResponse = async ( + requestId: string, + approved: boolean, + createPolicy?: boolean + ) => { + // Capture the current permission request before clearing it + const currentRequest = activePermissionRequest; + + // Clear the active permission request + setActivePermissionRequest(null); + + // Handle policy creation if requested + if (approved && createPolicy && currentRequest) { + try { + const { generatePolicyRule, addPolicyToYaml } = await import( + "../../permissions/policyWriter.js" + ); + + const policyRule = generatePolicyRule( + currentRequest.toolName, + currentRequest.toolArgs + ); + + await addPolicyToYaml(policyRule); + + logger.debug(`Policy created: ${policyRule}`); + } catch (error) { + logger.error("Failed to create policy", { error }); + // Continue with the approval even if policy creation fails + } + } + + // 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, @@ -675,9 +724,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/hooks/useModelSelector.ts b/src/ui/hooks/useModelSelector.ts new file mode 100644 index 000000000..c3b3b3d5a --- /dev/null +++ b/src/ui/hooks/useModelSelector.ts @@ -0,0 +1,71 @@ +import { useState } from "react"; +import { services, serviceContainer, SERVICE_NAMES } from "../../services/index.js"; +import { ModelServiceState } from "../../services/types.js"; + +interface ModelOption { + id: string; + name: string; + index: number; + provider: string; +} + +interface UseModelSelectorProps { + onMessage: (message: { + role: string; + content: string; + messageType: "system"; + }) => void; + onModelSwitch?: () => void; +} + +export function useModelSelector({ + onMessage, + onModelSwitch, +}: UseModelSelectorProps) { + const [showModelSelector, setShowModelSelector] = useState(false); + + const handleModelSelect = async (model: ModelOption) => { + setShowModelSelector(false); + + try { + await services.model.switchModel(model.index); + const modelInfo = services.model.getModelInfo(); + + // Update the service container to trigger re-renders + const currentState = services.model.getState(); + serviceContainer.set(SERVICE_NAMES.MODEL, currentState); + + onMessage({ + role: "system", + content: `Switched to model: ${modelInfo?.provider}/${modelInfo?.name}`, + messageType: "system", + }); + + // Trigger any additional actions after model switch + if (onModelSwitch) { + onModelSwitch(); + } + } catch (error: any) { + onMessage({ + role: "system", + content: `Failed to switch model: ${error.message}`, + messageType: "system", + }); + } + }; + + const handleModelCancel = () => { + setShowModelSelector(false); + }; + + const showModelSelectorUI = () => { + setShowModelSelector(true); + }; + + return { + showModelSelector, + handleModelSelect, + handleModelCancel, + showModelSelectorUI, + }; +} \ No newline at end of file diff --git a/src/ui/index.ts b/src/ui/index.ts index c63b70db7..8a300167e 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -10,13 +10,19 @@ export async function startTUIChat( initialPrompt?: string, resume?: boolean, configPath?: string, - additionalRules?: string[] + additionalRules?: string[], + toolPermissionOverrides?: { + allow?: string[]; + ask?: string[]; + exclude?: string[]; + } ) { // Initialize services in the background - TUI will show loading states initializeServices({ configPath, rules: additionalRules, headless: false, + toolPermissionOverrides, }).catch((error) => { console.error("Failed to initialize services:", error); }); 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; } diff --git a/src/util/exponentialBackoff.ts b/src/util/exponentialBackoff.ts index 8174c7f29..18c73abb8 100644 --- a/src/util/exponentialBackoff.ts +++ b/src/util/exponentialBackoff.ts @@ -199,7 +199,7 @@ export async function* withExponentialBackoff( } const delay = calculateDelay(attempt, opts); - logger.debug('Retry attempt', { attempt, delay, error: err.message }); + logger.debug("Retry attempt", { attempt, delay, error: err.message }); // Only log retry attempts after the first opts.hiddenRetries attempts if (attempt >= opts.hiddenRetries) { @@ -211,7 +211,7 @@ export async function* withExponentialBackoff( } // Wait before retrying - logger.debug('Waiting before retry', { delayMs: delay }); + logger.debug("Waiting before retry", { delayMs: delay }); await new Promise((resolve) => setTimeout(resolve, delay)); } } diff --git a/src/version.ts b/src/version.ts index 618cb67f0..9d7a2282a 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,6 +1,7 @@ import { readFileSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath } from "url"; +import logger from "./util/logger.js"; export function getVersion(): string { try { @@ -15,7 +16,9 @@ export function getVersion(): string { } } -export async function getLatestVersion(signal?: AbortSignal): Promise { +export async function getLatestVersion( + signal?: AbortSignal +): Promise { try { const response = await fetch( "https://registry.npmjs.org/@continuedev/cli/latest", @@ -27,11 +30,11 @@ export async function getLatestVersion(signal?: AbortSignal): Promise { - const parts = version.replace(/^v/, "").split(".").map(part => parseInt(part, 10)); + const parts = version + .replace(/^v/, "") + .split(".") + .map((part) => parseInt(part, 10)); return { major: parts[0] || 0, minor: parts[1] || 0, patch: parts[2] || 0 }; };