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

# 9.3 Permission Configuration Hierarchy

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

***

OpenCode's permission system is not determined by a single configuration source but is composed of multiple layered rulesets stacked together. This section analyzes the sources of these layers, their loading order, and override relationships.

## 9.3.1 Agent Default Permissions

Each Agent carries a set of default permission rules when defined. As we saw in Chapter 6, the `build` Agent (OpenCode's primary Agent) has the following default permission configuration:

```typescript
// agent/agent.ts - build Agent permissions
permission: {
  "*": "allow",          // Allow all tools by default
  doom_loop: "ask",      // Ask the user on loop detection
  external_directory: {   // External directory access
    "~/.ssh": "deny",    // Deny access to SSH keys
    "~/.gnupg": "deny",  // Deny access to GPG keys
    "*": "ask",           // Ask user for other external directories
  },
  read: {
    "*.env*": "ask",     // Ask user when reading .env files
    "*": "allow",         // Allow reading other files
  },
}
```

Other auxiliary Agents (such as `explore`, `summary`, `title`) typically have stricter default permissions -- they can only use a small set of read-only tools.

These default permissions are converted into a Ruleset via `fromConfig()`:

```typescript
// Converted Ruleset (in declaration order)
[
  { permission: "*",                  pattern: "*",       action: "allow" },
  { permission: "doom_loop",          pattern: "*",       action: "ask"   },
  { permission: "external_directory", pattern: "~/.ssh",  action: "deny"  },
  { permission: "external_directory", pattern: "~/.gnupg",action: "deny"  },
  { permission: "external_directory", pattern: "*",       action: "ask"   },
  { permission: "read",              pattern: "*.env*",   action: "ask"   },
  { permission: "read",              pattern: "*",        action: "allow" },
]
```

## 9.3.2 User-Configured Permissions

Users can override Agent permission configurations through the `agent` field in `opencode.json`:

```json
{
  "agent": {
    "build": {
      "permission": {
        "bash": {
          "rm *": "deny",
          "docker *": "ask"
        },
        "edit": {
          "*.lock": "deny"
        }
      }
    }
  }
}
```

During Agent loading, user-configured permissions are merged with the Agent's default permissions (see Agent loading logic in Chapter 6). The key code is in `loadAgent()` within `config.ts`:

```typescript
// config.ts - loadAgent()
// Agent-defined permissions + user-configured permissions -> merged permissions
const permission = PermissionNext.merge(
  PermissionNext.fromConfig(agentDefault.permission),
  PermissionNext.fromConfig(userConfig.permission ?? {}),
)
```

Since `merge` is simple array concatenation, user-configured rules are placed after default rules, giving them higher priority during `findLast()` evaluation.

## 9.3.3 Session Runtime Authorization

In addition to static configuration, a Session can carry additional runtime permission rules when created. These rules typically come from user selections on the Session creation interface, or are injected by Plugins:

```typescript
// session/index.ts
export const Info = z.object({
  // ...
  permission: PermissionNext.Ruleset.optional(),
  // ...
})
```

During permission evaluation, Session permissions participate in merging as the last layer of rulesets:

```typescript
// session/prompt.ts
await PermissionNext.ask({
  permission: "task",
  patterns: [part.name],
  sessionID: session.id,
  metadata: { ... },
  always: [part.name],
  ruleset: PermissionNext.merge(
    taskAgent.permission,      // Agent permissions (already includes defaults + user config)
    session.permission ?? [],  // Session runtime permissions (highest priority)
  ),
})
```

Session permissions, being the last ruleset added, have the highest override priority.

### Complete Priority Chain

```
Agent default permissions (lowest priority)
  | merge
User-configured permissions (override default permissions)
  | merge
Session runtime permissions (override all preceding rules, highest priority)
```

A concrete example:

```typescript
// Agent default: allow all bash
[{ permission: "bash", pattern: "*", action: "allow" }]

// + User config: deny rm commands
[{ permission: "bash", pattern: "rm *", action: "deny" }]

// + Session runtime: allow rm in a specific directory
[{ permission: "bash", pattern: "rm /tmp/*", action: "allow" }]

// Final merged Ruleset:
[
  { permission: "bash", pattern: "*",       action: "allow" },  // Agent default
  { permission: "bash", pattern: "rm *",    action: "deny"  },  // User config
  { permission: "bash", pattern: "rm /tmp/*", action: "allow" }, // Session runtime
]

// Evaluation results:
// evaluate("bash", "ls")        -> allow (matches rule 1)
// evaluate("bash", "rm -rf /")  -> deny  (matches rule 2; rule 3 doesn't match "/tmp/*")
// evaluate("bash", "rm /tmp/a") -> allow (matches rule 3, overriding rule 2's deny)
```

## 9.3.4 The always Option -- Persistent Authorization Memory

When users face an `ask`-type permission request, they have three response options:

```typescript
export const Reply = z.enum(["once", "always", "reject"])
```

| Reply    | Meaning                                                |
| -------- | ------------------------------------------------------ |
| `once`   | Allow just this once                                   |
| `always` | Always allow (within the scope of the current project) |
| `reject` | Reject                                                 |

When the user selects `always`, the system adds a new `allow` rule to the runtime approved list:

```typescript
// permission/next.ts - "always" handling in reply()
if (input.reply === "always") {
  for (const pattern of existing.info.always) {
    s.approved.push({
      permission: existing.info.permission,
      pattern,
      action: "allow",
    })
  }

  existing.resolve()

  // Auto-approve pending permission requests of the same type in the same Session
  const sessionID = existing.info.sessionID
  for (const [id, pending] of Object.entries(s.pending)) {
    if (pending.info.sessionID !== sessionID) continue
    const ok = pending.info.patterns.every(
      (pattern) =>
        evaluate(pending.info.permission, pattern, s.approved).action === "allow",
    )
    if (!ok) continue
    delete s.pending[id]
    Bus.publish(Event.Replied, { ... })
    pending.resolve()
  }
}
```

This code exhibits two key behaviors:

1. **Persistent authorization**: Adds the patterns corresponding to `always` as new `allow` rules to the `s.approved` list. Subsequent identical permission requests will directly match this rule without prompting again.
2. **Batch approval**: After the user selects `always`, the system automatically checks whether other pending permission requests in the same Session are also covered by this new rule -- if so, they are automatically approved. This spares the user from having to approve multiple similar requests one by one.

### Scope of Approved Rules

Approved rules are stored in `Instance.state()`, meaning their lifecycle is bound to the project instance:

```typescript
const state = Instance.state(async () => {
  const projectID = Instance.project.id
  const stored = await Storage.read<Ruleset>(["permission", projectID])
    .catch(() => [] as Ruleset)

  return {
    pending: {},       // Pending permission requests
    approved: stored,  // Approved rules list
  }
})
```

It is worth noting that the source code contains a TODO comment:

```typescript
// TODO: we don't save the permission ruleset to disk yet until there's
// UI to manage it
// await Storage.write(["permission", Instance.project.id], s.approved)
```

This means that in the current version, `always` authorizations are only effective for the duration of a single OpenCode run -- they are lost upon restart. This is an intentional design choice: without a management interface for users to view and revoke authorized rules, not persisting these rules is the safer approach.

***

> **Section Summary**
>
> OpenCode's permission configuration forms a three-tier priority chain: Agent default permissions (lowest) -> User-configured permissions -> Session runtime permissions (highest). All tiers are merged through array concatenation, naturally implementing last-writer-wins override semantics via `findLast()`. An `always` reply dynamically adds `allow` rules at runtime and automatically batch-approves pending requests of the same type in the same Session. In the current version, `always` authorizations are not persisted to disk and are lost on restart -- a safety choice in the absence of a management UI.
