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

# 5.4 Permission Checks in Tool Invocations

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

***

## 5.4.1 When and How `ctx.ask()` Is Called

Every tool that performs a sensitive operation calls `ctx.ask()` before execution to initiate a permission request:

```typescript
// Permission check in edit.ts
await ctx.ask({
  permission: "edit",
  patterns: [path.relative(Instance.worktree, filePath)],
  always: ["*"],
  metadata: {
    filepath: filePath,
    diff: diff,
    existed: existed,
  },
})
```

**Parameter Descriptions**:

* `permission`: The permission category name (e.g., `"edit"`, `"bash"`, `"read"`)
* `patterns`: Matching patterns. For file operations, these are relative paths; for command execution, these are the command contents
* `always`: The matching patterns to remember if the user selects "Always Allow"
* `metadata`: Additional information displayed to the user (e.g., diff content, file path)

## 5.4.2 User Interaction Flow for Permission Requests

When the permission rule is `"ask"`, the system enters the following flow:

```
1. Tool calls ctx.ask()
       |
2. PermissionNext evaluates the permission rule
       |
       +-- "allow" -> Return immediately, tool continues execution
       +-- "deny"  -> Throw RejectedError, tool aborts
       +-- "ask"   -> Create a Permission Request
              |
3. Publish the permission request event via Bus
       |
4. The frontend (TUI/Web) receives the event and displays a confirmation dialog
       |
5. The user makes a choice:
       +-- "Allow"         -> Allow this time only
       +-- "Always Allow"  -> Permanently allow this pattern
       +-- "Deny"          -> Reject
       |
6. The frontend submits the user's decision via the API
   POST /project/:id/session/:sid/permission/:pid
       |
7. The Promise from ctx.ask() resolves/rejects
       |
8. The tool continues execution or aborts
```

**Permission Granularity by Tool**:

| Tool                 | Permission Name      | Matching Pattern          | Example                       |
| -------------------- | -------------------- | ------------------------- | ----------------------------- |
| `bash`               | `bash`               | Command text / file paths | `"rm -rf dist"`               |
| `edit`               | `edit`               | Relative file path        | `"src/index.ts"`              |
| `write`              | `write`              | Relative file path        | `"new-file.ts"`               |
| `read`               | `read`               | Relative file path        | `".env"` (special protection) |
| `task`               | `task`               | Agent name                | `"explore"`                   |
| `external_directory` | `external_directory` | Directory path            | `"/usr/local/..."`            |

**Special Handling for the Bash Tool**:

The Bash tool uses a Tree-sitter parser to analyze commands and extract the file paths they involve. This allows permission checks to operate at file-level granularity, rather than coarsely allowing or denying all commands. `BashArity` (`permission/arity.ts`) implements this fine-grained permission granularity classification.

**The `always` Memory Mechanism**:

When the user selects "Always Allow," the permission pattern is remembered and stored. Subsequent requests matching the same pattern are automatically approved without displaying a confirmation dialog. The storage granularity is controlled by the `always` field -- for example, `["*"]` means all file edits are automatically allowed, while `["src/*.ts"]` means only edits to TypeScript files under `src/` are automatically allowed.

***

This concludes the full architecture of the Tool system: from abstraction layer design, to registration and discovery, to the implementation of 20+ built-in tools, and finally the complete permission check flow. Tools are the "hands and feet" of an Agent -- in the next chapter, we will analyze the Agent itself: the system that gives these tools a "brain."
