> 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.1_permission_model_design.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 9.1 Permission Model Design

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

***

An AI Agent can execute shell commands, modify files, and access the network -- capabilities that bring convenience but also introduce significant security risks. An Agent without permission control could accidentally delete critical files, leak API keys stored in environment variables, or execute dangerous system commands. The **permission control system** is the cornerstone of OpenCode's security architecture, ensuring that every sensitive operation performed by the Agent proceeds only with the user's knowledge and authorization.

This section analyzes the data model design of OpenCode's permission system, including the three permission actions, the rule definition structure, and the ruleset merging strategy.

## 9.1.1 Three Permission Actions: allow, deny, ask

OpenCode's permission system is built on three fundamental actions:

```typescript
// permission/next.ts
export const Action = z.enum(["allow", "deny", "ask"])
```

| Action  | Meaning | Effect                                                          |
| ------- | ------- | --------------------------------------------------------------- |
| `allow` | Permit  | Execute directly without user confirmation                      |
| `deny`  | Reject  | Block execution immediately, throwing a `DeniedError`           |
| `ask`   | Prompt  | Pause execution and display a TUI dialog for the user to decide |

These three actions form a complete decision space:

* **`allow`** is the most permissive -- suitable for low-risk operations or operations the user has explicitly trusted (e.g., reading files within the project).
* **`deny`** is the most restrictive -- suitable for operations that should never occur (e.g., the Agent reading sensitive information from `.env` files).
* **`ask`** is the middle ground -- and also the default behavior. When no rule explicitly matches, the system falls back to `ask`.

This three-valued design is more flexible than a simple "allow/deny" binary model. The `ask` action lets users make decisions when they first encounter a particular type of operation, and they can choose "just this once" or "always allow," striking a balance between security and usability.

## 9.1.2 PermissionNext.Rule: permission + pattern + action

A permission rule (Rule) is the atomic unit of the permission system. Each rule consists of three fields:

```typescript
export const Rule = z.object({
  permission: z.string(),  // Permission name (e.g., "bash", "edit", "read")
  pattern: z.string(),     // Matching pattern (supports wildcards)
  action: Action,          // Action (allow / deny / ask)
})
```

The **`permission`** field identifies which permission type this rule applies to. Each tool in OpenCode declares the permission name it requires when defined:

| Tool                 | Permission Name      | Description                          |
| -------------------- | -------------------- | ------------------------------------ |
| Bash                 | `bash`               | Command execution permission         |
| Edit / Write / Patch | `edit`               | File editing permission              |
| Read                 | `read`               | File reading permission              |
| Glob                 | `glob`               | File search permission               |
| Grep                 | `grep`               | Content search permission            |
| Task                 | `task`               | Sub-agent scheduling permission      |
| Skill                | `skill`              | Skill loading permission             |
| WebFetch             | `webfetch`           | Web page fetching permission         |
| WebSearch            | `websearch`          | Web search permission                |
| LSP                  | `lsp`                | Language server permission           |
| TodoWrite            | `todowrite`          | Todo write permission                |
| TodoRead             | `todoread`           | Todo read permission                 |
| ExternalDirectory    | `external_directory` | External directory access permission |
| CodeSearch           | `codesearch`         | Code search permission               |
| --                   | `doom_loop`          | Loop detection permission (special)  |

The **`pattern`** field is a wildcard pattern that further narrows the matching scope of the rule. For example:

* `"*"` -- matches all patterns (broadest)
* `"ls *"` -- matches commands starting with `ls`
* `"/home/user/.env"` -- matches a specific file path
* `"*.md"` -- matches all Markdown files

The **`action`** field specifies the action to take when the rule matches.

Some concrete rule examples:

```typescript
// Allow all bash commands
{ permission: "bash", pattern: "*", action: "allow" }

// Deny reading .env files
{ permission: "read", pattern: "*.env", action: "deny" }

// Ask the user about loop detection behavior
{ permission: "doom_loop", pattern: "*", action: "ask" }

// Allow editing files under the src/ directory
{ permission: "edit", pattern: "src/*", action: "allow" }
```

## 9.1.3 Ruleset: Rule Collections and Merging Strategy

A `Ruleset` is an ordered array of `Rule` objects:

```typescript
export const Ruleset = Rule.array()
export type Ruleset = z.infer<typeof Ruleset>
```

### Converting from Configuration to Ruleset

User permission configurations are typically written in a more concise format (in the `agent.permission` field of `opencode.json`). The `fromConfig()` function converts this concise format into a standard `Ruleset`:

```typescript
export function fromConfig(permission: Config.Permission) {
  const ruleset: Ruleset = []
  for (const [key, value] of Object.entries(permission)) {
    if (typeof value === "string") {
      // Shorthand format: "bash": "allow"
      // -> { permission: "bash", pattern: "*", action: "allow" }
      ruleset.push({
        permission: key,
        action: value,
        pattern: "*",
      })
      continue
    }
    // Detailed format: "edit": { "src/*": "allow", "*.env": "deny" }
    // -> [{ permission: "edit", pattern: "src/*", action: "allow" },
    //    { permission: "edit", pattern: "*.env", action: "deny" }]
    ruleset.push(
      ...Object.entries(value).map(([pattern, action]) => ({
        permission: key,
        pattern: expand(pattern),
        action,
      })),
    )
  }
  return ruleset
}
```

The `expand()` function handles `~` and `$HOME` prefixes in paths, expanding them to the actual home directory path:

```typescript
function expand(pattern: string): string {
  if (pattern.startsWith("~/")) return os.homedir() + pattern.slice(1)
  if (pattern === "~") return os.homedir()
  if (pattern.startsWith("$HOME/")) return os.homedir() + pattern.slice(5)
  if (pattern.startsWith("$HOME")) return os.homedir() + pattern.slice(5)
  return pattern
}
```

### Ruleset Merging Strategy

Multiple Rulesets from different sources need to be merged into a unified rule set. OpenCode's merging strategy is remarkably concise:

```typescript
export function merge(...rulesets: Ruleset[]): Ruleset {
  return rulesets.flat()
}
```

**Merging is simply array concatenation.** This means later rules override earlier rules -- because evaluation uses `findLast()` (searching from the end of the array for the first matching rule). This "last-writer-wins" design naturally forms a **priority chain** for permission hierarchies:

```
Agent default permissions (added first)
-> Overridden by user-configured permissions
  -> Overridden by Session runtime authorizations (added last, highest priority)
```

The elegance of this design lies in the fact that it requires no complex priority tags or weight calculations -- the position within the array alone determines the rule's priority. We will analyze the evaluation engine's `findLast()` logic in detail in Section 9.2.

### On the Coexistence of Two Systems

Attentive readers may have noticed that the OpenCode source code actually contains **two** permission systems:

1. **`PermissionNext`** (`permission/next.ts`): The new permission system, based on the Rule/Ruleset model.
2. **`Permission`** (`permission/index.ts`): The legacy permission system, based on a `type` + `pattern` model.

Both systems currently coexist in the codebase. `PermissionNext` is the newer, more complete implementation, primarily used by the Session system and Processor. The legacy `Permission` is still retained in some code paths (such as the Plugin `permission.ask` hook), but is being gradually replaced by `PermissionNext`.

This chapter primarily analyzes the `PermissionNext` implementation. The core idea of both systems is consistent -- a rule model based on "permission type + matching pattern -> action."

***

> **Section Summary**
>
> OpenCode's permission system is built on a three-valued action model (`allow`/`deny`/`ask`), where `ask` as the default behavior ensures a security-first design philosophy. Permission rules consist of three fields: `permission` (permission type), `pattern` (wildcard pattern), and `action` (action). Rulesets from multiple sources are merged through simple array concatenation, leveraging the `findLast()` evaluation strategy to implement "last-writer-wins" override semantics, allowing permission hierarchies to naturally form a priority chain.
