> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_09_permission_control_system/9.5_permission_strategies_for_each_tool.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 9.5 Permission Strategies for Each Tool

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2026-02-17

***

In the previous four sections, we analyzed the permission system's architecture from four dimensions: model, engine, configuration, and interaction flow. This section returns to the concrete tool level to examine how different tools leverage the permission system to protect user security.

## 9.5.1 Bash Tool: Command-Level Permissions

Bash is the tool with the most complex permission requirements in OpenCode -- it can execute arbitrary shell commands, carrying the highest risk.

```typescript
// tool/bash.ts
permission: "bash",  // Permission type name
```

When requesting permission, the Bash tool uses the BashArity-processed command prefix as the pattern. For example:

* Executing `npm install lodash` -> permission pattern is `"npm install"`
* Executing `rm -rf /tmp/test` -> permission pattern is `"rm"`

Additionally, if a Bash command involves paths outside the project directory, it also triggers the `external_directory` permission:

```typescript
// tool/bash.ts
permission: "external_directory",
// pattern is the external directory path referenced in the command
```

The build Agent's default permission configuration for Bash is `"*": "allow"` (allow all), but for `external_directory` it makes fine-grained distinctions:

* `~/.ssh` -> `deny` (always denied -- prevents the Agent from accessing SSH keys)
* `~/.gnupg` -> `deny` (always denied -- prevents the Agent from accessing GPG keys)
* Other external directories -> `ask` (prompt the user)

This layered strategy ensures a smooth daily development experience (commands within the project execute directly) while providing strict protection for high-risk operations.

### Loop Detection (Doom Loop)

The Bash tool also participates in a special permission check -- loop detection. When the system detects that the Agent has consecutively executed the same tool call multiple times (same tool, same arguments), it triggers a `doom_loop` permission request:

```typescript
// session/processor.ts
const lastThree = parts.slice(-DOOM_LOOP_THRESHOLD)

if (
  lastThree.length === DOOM_LOOP_THRESHOLD &&
  lastThree.every(
    (p) =>
      p.type === "tool" &&
      p.tool === value.toolName &&
      p.state.status !== "pending" &&
      JSON.stringify(p.state.input) === JSON.stringify(value.input),
  )
) {
  await PermissionNext.ask({
    permission: "doom_loop",
    patterns: [value.toolName],
    // ...
  })
}
```

The default configuration for `doom_loop` permission is `ask` -- the system pauses and asks the user: "The Agent appears to be stuck in a loop. Continue?" This prevents the Agent from infinitely retrying the same failed operation when encountering errors, wasting unnecessary LLM calls and time.

## 9.5.2 Edit/Write Tools: File Path-Level Permissions

File editing tools (Edit, Write, Patch/apply\_patch, MultiEdit) share the same permission name `edit`:

```typescript
// tool/write.ts
permission: "edit",

// tool/edit.ts
permission: "edit",

// tool/apply_patch.ts
permission: "edit",
```

Using the same permission name means users can control all file editing behavior with a single rule. For example:

```json
{
  "permission": {
    "edit": {
      "*.lock": "deny",
      "node_modules/*": "deny",
      "*": "allow"
    }
  }
}
```

This configuration prevents the Agent from modifying lock files and the node\_modules directory (files typically managed automatically by package managers), while allowing edits to other files.

The pattern in permission requests is the target file's path, enabling users to precisely control the Agent's editing scope by file path.

## 9.5.3 Read Tool: Special Protection for .env Files

The Read tool's permission name is `read`:

```typescript
// tool/read.ts
permission: "read",
```

The build Agent provides special `.env` file protection for the Read tool in its default permissions:

```typescript
read: {
  "*.env*": "ask",   // Ask user when reading .env files
  "*": "allow",       // Allow reading other files directly
},
```

Why the special protection for `.env` files? Because they are the standard location for storing API keys, database passwords, and other sensitive information. If the Agent reads the contents of a `.env` file, this information could appear in the LLM's context, theoretically posing a leak risk (although LLM providers typically do not store user conversation content, this remains a best-practice security safeguard).

The wildcard pattern `"*.env*"` matches not only `.env` files but also `.env.local`, `.env.production`, `database.env`, and various other variants, covering common environment variable file naming conventions.

## 9.5.4 Task Tool: Sub-agent Scheduling Permissions

The Task tool is used for scheduling sub-agents and requires the `task` permission:

```typescript
// tool/task.ts
permission: "task",
```

What makes Task permission special is that the permission evaluation considers the target Agent's name. For example, rules can be configured as:

```json
{
  "permission": {
    "task": {
      "explore": "allow",
      "build": "deny"
    }
  }
}
```

This allows the Agent to schedule `explore`-type sub-agents (low-risk read-only searches) but prohibits scheduling `build`-type sub-agents (which can perform high-risk operations like file modifications).

In `session/prompt.ts`, Task permission evaluation uses the sub-agent's name as the pattern:

```typescript
const perm = PermissionNext.evaluate("task", part.name, agent.permission)
```

## 9.5.5 External Directory Access Control (external\_directory)

`external_directory` is a cross-tool permission type -- it does not belong to any specific tool but is triggered by any operation involving file paths outside the project directory.

```typescript
// tool/external-directory.ts
permission: "external_directory",
```

OpenCode's default behavior is to restrict Agent operations to within the current project directory. When the Agent attempts to access a path outside the project directory (e.g., reading `/etc/hosts` or modifying `~/other-project/config.json`), the `external_directory` permission is triggered.

In the default configuration, apart from `~/.ssh` and `~/.gnupg` being hard-coded as `deny`, all other external directory accesses are `ask`:

```typescript
external_directory: {
  "~/.ssh": "deny",
  "~/.gnupg": "deny",
  "*": "ask",
},
```

This design strikes a balance between security and practicality -- the Agent occasionally does need to access files outside the project (e.g., reading global configuration files, installing global tools, etc.), but these operations should not happen without the user's knowledge.

### Tool Permission Disable Detection

The permission system also has a "preflight" feature -- when sending the tool list to the LLM, it pre-filters tools that are globally `deny`-ed:

```typescript
// permission/next.ts
export function disabled(tools: string[], ruleset: Ruleset): Set<string> {
  const result = new Set<string>()
  for (const tool of tools) {
    const permission = EDIT_TOOLS.includes(tool) ? "edit" : tool
    const rule = ruleset.findLast(
      (r) => Wildcard.match(permission, r.permission)
    )
    if (!rule) continue
    if (rule.pattern === "*" && rule.action === "deny") result.add(tool)
  }
  return result
}

const EDIT_TOOLS = ["edit", "write", "patch", "multiedit"]
```

This function is called in `llm.ts`:

```typescript
// session/llm.ts
const disabled = PermissionNext.disabled(
  Object.keys(input.tools),
  input.agent.permission
)
```

If a tool's wildcard rule `"*"` is `deny`, it means the tool is completely disabled -- it should not only be prevented from executing but should not even appear in the LLM's tool list. This prevents the LLM from attempting to call a tool that would inevitably be rejected, wasting valuable inference time.

***

> **Chapter 9 Summary**
>
> OpenCode's permission control system is the central pillar of its security architecture. Built on a concise yet powerful three-valued model (allow/deny/ask), wildcard pattern matching, and a "last-writer-wins" rule merging strategy, it constructs a flexible and robust permission framework.
>
> Key design highlights:
>
> 1. **Secure defaults**: When no rule matches, the default is `ask`, ensuring users always have informed consent.
> 2. **Hierarchical overrides**: Agent defaults -> User configuration -> Session runtime, with priority naturally implemented through array concatenation.
> 3. **Batch approval**: An `always` reply automatically approves similar pending requests, reducing the user's operational burden.
> 4. **Granularity control**: The BashArity dictionary ensures permission requests are displayed at "human-understandable" granularity.
> 5. **Sensitive resource protection**: `.env` files, SSH keys, GPG keys, and other sensitive resources have dedicated protection strategies.
> 6. **Preflight filtering**: Globally denied tools are removed from the LLM's tool list entirely, preventing futile calls.
> 7. **Loop detection**: The `doom_loop` permission prevents the Agent from falling into meaningless repetitive operations.
>
> From an engineering philosophy perspective, OpenCode's permission system embodies the concept of "progressive trust" -- starting with a cautious and conservative posture (`ask`), users can gradually expand the Agent's autonomous scope through `always`, while sensitive operations always have hard-coded protective baselines (`deny`).
