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

# 9.4 Permission Request Interaction Flow

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

***

When the permission evaluation result is `ask`, OpenCode needs to pause the Agent's execution and hand decision-making authority to the user. This section provides a detailed analysis of this interaction flow -- from initiating the permission request, displaying the TUI popup, receiving the user's response, to subsequent processing.

## 9.4.1 PermissionNext.Request Data Structure

The permission request (Request) is the core data structure of the `ask` flow:

```typescript
export const Request = z.object({
  id: Identifier.schema("permission"),     // Unique identifier
  sessionID: Identifier.schema("session"), // Owning Session ID
  permission: z.string(),                  // Permission type (e.g., "bash")
  patterns: z.string().array(),            // List of patterns requiring approval
  metadata: z.record(z.string(), z.any()), // Metadata (for TUI display)
  always: z.string().array(),              // Patterns to authorize on "always"
  tool: z.object({                         // Tool call information (optional)
    messageID: z.string(),
    callID: z.string(),
  }).optional(),
})
```

Purpose of each field:

* **`id`**: A unique identifier for each permission request, used to locate the request when replying later.
* **`sessionID`**: Associates with the Session that initiated the request, used for batch-approving requests in the same Session on `always` reply.
* **`permission`**: The permission type name, such as `"bash"`, `"edit"`, `"read"`.
* **`patterns`**: The list of specific patterns requiring approval. For example, a Bash command may involve multiple patterns -- the command itself (`"npm install"`) and external directory paths it accesses. All patterns must be approved for the operation to proceed.
* **`metadata`**: Additional information for TUI display, such as tool name, command content, file path, etc. It does not participate in permission evaluation and is purely for the user interface.
* **`always`**: The list of patterns that should be permanently authorized when the user selects `always`. It is usually the same as `patterns`, but can differ -- for example, certain sensitive patterns may only allow "one-time" authorization and not "permanent" authorization.
* **`tool`**: Optional tool call context information, including message ID and call ID, used to precisely locate the tool call that triggered the request in the TUI.

## 9.4.2 Permission Request -> TUI Popup -> User Response -> Decision Storage

The complete permission request interaction flow is as follows:

```
+-----------+     +---------------+     +----------+     +----------+
| Agent     |     | PermissionNext|     |   Bus    |     |   TUI    |
| (Tool)    |     |    .ask()     |     |          |     |          |
+-----+-----+     +------+-------+     +----+-----+     +----+-----+
      |                  |                   |                |
      |  Request perm    |                   |                |
      +----------------->|                   |                |
      |                  |                   |                |
      |                  |  evaluate() -> ask |                |
      |                  |                   |                |
      |                  |  publish(Asked)    |                |
      |                  +------------------>|                |
      |                  |                   |  Event.Asked    |
      |                  |                   +--------------->|
      |                  |                   |                |
      |  <- pause(await) |                   |  Display popup |
      |                  |                   |                |
      |                  |                   |  User choice   |
      |                  |                   |<---------------+
      |                  |                   |                |
      |                  |  reply(response)  |                |
      |                  |<------------------+                |
      |                  |                   |                |
      |                  |  resolve/reject   |                |
      |  <- resume ------+                   |                |
      |                  |                   |                |
```

### Step 1: ask() Initiates the Request

The `ask()` function is the entry point for permission requests. It takes permission information and a Ruleset, evaluating the permission status of each pattern:

```typescript
export const ask = fn(
  Request.partial({ id: true }).extend({ ruleset: Ruleset }),
  async (input) => {
    const s = await state()
    const { ruleset, ...request } = input

    for (const pattern of request.patterns ?? []) {
      const rule = evaluate(request.permission, pattern, ruleset, s.approved)

      if (rule.action === "deny") {
        // Reject immediately, throw error
        throw new DeniedError(
          ruleset.filter((r) => Wildcard.match(request.permission, r.permission))
        )
      }

      if (rule.action === "ask") {
        // Create pending request, publish event, wait for user reply
        const id = input.id ?? Identifier.ascending("permission")
        return new Promise<void>((resolve, reject) => {
          s.pending[id] = { info: { id, ...request }, resolve, reject }
          Bus.publish(Event.Asked, { id, ...request })
        })
      }

      if (rule.action === "allow") continue  // Allow, continue checking next pattern
    }
  },
)
```

Key details:

1. **Per-pattern evaluation**: Each `pattern` is evaluated individually. If any single pattern's evaluation result is `deny`, the entire operation is rejected.
2. **Promise suspension**: When the evaluation result is `ask`, `ask()` returns a Promise. The `resolve` and `reject` functions of this Promise are stored in the `pending` Map, waiting to be resolved when `reply()` is called -- this is the classic "externalized resolve" pattern.
3. **Event notification**: The TUI is notified of a new pending permission request via `Bus.publish(Event.Asked, ...)`.
4. **Approved rules participate in evaluation**: Note the fourth argument to `evaluate()`, `s.approved` -- rules previously approved via `always` also participate in evaluation, avoiding repeated prompts.

### Step 2: TUI Displays the Popup

The TUI layer (implemented in `cli/cmd/tui/`) subscribes to the `permission.asked` event. When the event arrives, the TUI displays a permission confirmation dialog showing:

* The permission type (e.g., "Bash command execution")
* The specific operation content (e.g., the command to execute, the file path to modify)
* Three options: **Once** (just this time), **Always** (always allow), **Reject**

### Step 3: reply() Processes the User Response

The user's choice is passed back to the permission system via the `reply()` function:

```typescript
export const reply = fn(
  z.object({
    requestID: Identifier.schema("permission"),
    reply: Reply,
    message: z.string().optional(),  // Optional feedback message on reject
  }),
  async (input) => {
    const s = await state()
    const existing = s.pending[input.requestID]
    if (!existing) return

    delete s.pending[input.requestID]

    // Publish reply event (notify TUI to update the interface)
    Bus.publish(Event.Replied, { ... })

    if (input.reply === "reject") {
      // Reject: reject Promise, and reject all pending requests in the same Session
      existing.reject(
        input.message
          ? new CorrectedError(input.message)
          : new RejectedError()
      )

      // Cascade rejection of all pending requests in the same Session
      for (const [id, pending] of Object.entries(s.pending)) {
        if (pending.info.sessionID === sessionID) {
          delete s.pending[id]
          pending.reject(new RejectedError())
        }
      }
      return
    }

    if (input.reply === "once") {
      // One-time allow: only resolve the current Promise
      existing.resolve()
      return
    }

    if (input.reply === "always") {
      // Permanent allow: add rules + resolve current + batch-approve similar requests
      // (See Section 9.3.4 for details)
    }
  },
)
```

There are several noteworthy design decisions here:

**Cascade rejection**: When the user rejects a permission request, all pending permission requests in the same Session are automatically rejected. This is because once the user explicitly rejects a certain type of operation, the Agent's execution flow may no longer be meaningful -- pending requests are likely subsequent steps in the same operation chain.

**CorrectedError vs RejectedError**: Users can attach a message when rejecting. If a message is attached, a `CorrectedError` is thrown (the Agent sees the user's feedback and attempts to adjust its strategy); otherwise, a `RejectedError` is thrown (the Agent only knows the operation was rejected).

```typescript
// Two types of rejection errors
export class RejectedError extends Error {
  constructor() {
    super("The user rejected permission to use this specific tool call.")
  }
}

export class CorrectedError extends Error {
  constructor(message: string) {
    super(`The user rejected permission to use this specific tool call ` +
          `with the following feedback: ${message}`)
  }
}
```

This distinction is clever -- the `CorrectedError` message is seen by the LLM, which adjusts its subsequent behavior accordingly, while `RejectedError` is simply an interruption.

## 9.4.3 arity.ts -- Permission Granularity Control

When the Bash tool requests permission, it needs to determine the "granularity" of the command -- what exactly does the user see in the TUI? Is it the full command `npm install lodash --save`, or a simplified `npm install`?

The `BashArity` module solves this problem. It maintains an extensive command arity dictionary that defines the "meaningful prefix" length for each command:

```typescript
// permission/arity.ts
export namespace BashArity {
  export function prefix(tokens: string[]) {
    for (let len = tokens.length; len > 0; len--) {
      const prefix = tokens.slice(0, len).join(" ")
      const arity = ARITY[prefix]
      if (arity !== undefined) return tokens.slice(0, arity)
    }
    if (tokens.length === 0) return []
    return tokens.slice(0, 1)  // Default: take the first token
  }

  const ARITY: Record<string, number> = {
    cat: 1,           // cat file.txt -> "cat"
    git: 2,           // git checkout main -> "git checkout"
    npm: 2,           // npm install -> "npm install"
    "npm run": 3,     // npm run dev -> "npm run dev"
    docker: 2,        // docker run nginx -> "docker run"
    "docker compose": 3,  // docker compose up -> "docker compose up"
    // ... 100+ command arity definitions in total
  }
}
```

> **Extended Explanation: Arity**
>
> In programming language theory, "arity" refers to the number of arguments a function takes. Here, OpenCode borrows this term to mean the number of tokens that constitute the "meaningful prefix" of a command for permission purposes. For example, `git` has an arity of 2, meaning the first two tokens (`git checkout`) together form the semantically meaningful unit for permission checking.

How the `prefix()` function works:

1. Split the command into a token array (e.g., `["npm", "run", "dev", "--port", "3000"]`).
2. Attempt to match prefixes in the ARITY dictionary from longest to shortest.
3. Once a match is found, return the token sub-array of the corresponding length.
4. If no match is found, default to returning the first token.

Matching examples:

| Full Command           | Matched Prefix   | Arity | Permission Pattern    |
| ---------------------- | ---------------- | ----- | --------------------- |
| `cat /etc/passwd`      | `cat`            | 1     | `"cat"`               |
| `git checkout main`    | `git`            | 2     | `"git checkout"`      |
| `npm run dev`          | `npm run`        | 3     | `"npm run dev"`       |
| `npm install lodash`   | `npm`            | 2     | `"npm install"`       |
| `docker compose up -d` | `docker compose` | 3     | `"docker compose up"` |
| `python script.py`     | `python`         | 2     | `"python script.py"`  |

The ingenuity of this design lies in **longest prefix matching**:

* `npm` has an arity of 2, so `npm install` is approved as a whole.
* But `npm run` has an arity of 3, so `npm run dev` includes the specific script name.

This ensures permission approval granularity is "human-understandable" -- users see neither a vague `npm` nor a verbose full command line, but rather a command prefix that precisely conveys the intent.

The ARITY dictionary covers over 100 common commands, spanning package managers (npm, pip, cargo), container tools (docker, podman), version control (git), cloud platform CLIs (aws, gcloud, az), and other common toolchains.

***

> **Section Summary**
>
> The complete permission request interaction flow is: `ask()` evaluates permission -> `Bus.publish(Event.Asked)` notifies the TUI -> TUI displays a popup -> user makes a choice -> `reply()` processes the response -> `resolve`/`reject` the Promise to resume/interrupt Agent execution. `reject` cascades rejection to all pending requests in the same Session, and the distinction between `CorrectedError`/`RejectedError` provides the Agent with different levels of feedback. The `BashArity` module controls Bash permission display granularity through a command arity dictionary, ensuring users see "human-understandable" command prefixes rather than full command lines.
