feat: refresh course through workflow and goal loops

This commit is contained in:
Haoran
2026-07-30 19:14:04 +08:00
parent 2dd1852d9e
commit cb8fae1bdd
125 changed files with 10882 additions and 7661 deletions

View File

@@ -1,232 +0,0 @@
# s03: Permission — Check Permissions Before Execution
[中文](README.md) · [English](README.en.md) · [日本語](README.ja.md)
s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20
> *"Check permissions before executing"* — The permission pipeline decides which operations need approval.
>
> **Harness Layer**: Permission — a gate before tool execution.
---
## The Problem
s02's Agent has 5 tools. File tools are protected by `safe_path`, but bash is unrestricted. Ask it to "clean up the project," and it might run `rm -rf /`.
Safety can't rely on trusting the model — it needs code: a check before every tool execution.
---
## The Solution
![Permission Overview](images/permission-overview.en.svg)
s02's loop is fully preserved. The only change is inserting `check_permission()` before tool execution — each tool call passes through three gates in a fixed order: hard deny first, then soft ask, and if neither matches, allow.
The three gates correspond to three decisions:
| Gate | Purpose | On Match |
|------|---------|----------|
| 1. Deny List | Permanently forbidden operations (`rm -rf /`, `sudo`) | Denied immediately, not executed |
| 2. Rule Matching | Context-dependent operations (reading/writing outside workspace, `rm` files) | Passed to Gate 3 |
| 3. User Approval | After Gate 2 matches, pauses for user confirmation | User decides allow or deny |
None of the three gates match → execute directly. Most routine operations take this path.
---
## How It Works
![Permission Pipeline](images/permission-pipeline.en.svg)
**Gate 1**: A hard deny list. Check first; if matched, return a block message. (Teaching demo: simple string matching is not a reliable security mechanism — command variants and shell expansion can bypass it. CC's approach is in the appendix.)
```python
DENY_LIST = [
"rm -rf /", "sudo", "shutdown", "reboot",
"mkfs", "dd if=", "> /dev/sda",
]
def check_deny_list(command: str) -> str | None:
for pattern in DENY_LIST:
if pattern in command:
return f"Blocked: '{pattern}' is on the deny list"
return None
```
**Gate 2**: Rule matching — describes "when to ask the user." Each rule specifies a tool and a check condition.
```python
PERMISSION_RULES = [
{
"tools": ["read_file", "write_file", "edit_file"],
"check": lambda args: not (WORKDIR / args.get("path", "")).resolve().is_relative_to(WORKDIR),
"message": "Access outside workspace",
},
{
"tools": ["bash"],
"check": lambda args: any(kw in args.get("command", "") for kw in ["rm ", "> /etc/", "chmod 777"]),
"message": "Potentially destructive command",
},
]
def check_rules(tool_name: str, args: dict) -> str | None:
for rule in PERMISSION_RULES:
if tool_name in rule["tools"] and rule["check"](args):
return rule["message"]
return None
```
**Gate 3**: After a rule matches, pause for user input.
```python
def ask_user(tool_name: str, args: dict, reason: str) -> str:
print(f"\n{reason}")
print(f" Tool: {tool_name}({args})")
choice = input(" Allow? [y/N] ").strip().lower()
return "allow" if choice in ("y", "yes") else "deny"
```
**All three gates chained together**, inserted before tool execution:
```python
def check_permission(block) -> bool:
# Gate 1: Hard deny
if block.name == "bash":
reason = check_deny_list(block.input.get("command", ""))
if reason:
print(f"\n{reason}")
return False
# Gate 2 + 3: Rule matching → User approval
reason = check_rules(block.name, block.input)
if reason:
decision = ask_user(block.name, block.input, reason)
if decision == "deny":
return False
return True
# In agent_loop — s02's loop with just one line added:
for block in response.content:
if block.type == "tool_use":
if not check_permission(block): # ← NEW
results.append({... "content": "Permission denied."})
continue
output = TOOL_HANDLERS[block.name](**block.input) # s02 original
results.append(...)
```
---
## Changes from s02
| Component | Before (s02) | After (s03) |
|-----------|-------------|-------------|
| Security model | None (trust the model) | Three-gate permission pipeline |
| New functions | — | check_deny_list, check_rules, ask_user, check_permission |
| Loop | Executes all tools directly | Inserts check_permission() before execution |
---
## Try It
```sh
cd learn-claude-code
python s03_permission/code.py
```
Try these prompts:
1. `Create a file called test.txt in the current directory` (should pass through)
2. `Delete the file test.txt` (bash + rm triggers Gate 2)
3. `What files are in the current directory?` (read-only, all pass)
4. `Try to write a file to /etc/something` (writing outside workspace triggers Gate 2)
What to watch for: Which operations pass through? Which need your confirmation? Which are denied outright?
---
## What's Next
Permission checks are in place — but every check is hardcoded as `check_permission()` inside the loop. What if you want to add logging before and after each tool execution? What if you want to auto-trigger a git commit after certain operations? Scattering this extension logic throughout the loop makes it bloat.
→ s04 Hooks: Add hooks to the loop. Extension logic hangs on hooks; the loop stays clean.
<details>
<summary>Dive into CC Source Code</summary>
> The following is based on a review of CC source code `types/permissions.ts`, `utils/permissions/permissions.ts`, `toolExecution.ts`, `utils/permissions/yoloClassifier.ts`, `tools/AgentTool/forkSubagent.ts`.
### 1. PermissionResult: Not 3, but 4
The teaching version's three gates (deny → ask → allow) don't fully correspond to CC. CC's `PermissionResult` has 4 behaviors (`types/permissions.ts:241-266`):
| behavior | Meaning | Teaching Version Equivalent |
|----------|---------|---------------------------|
| `allow` | Allow directly | Gate 3 passes |
| `deny` | Deny directly | Gate 1 matches |
| `ask` | Show dialog to user | Gate 2 matches |
| `passthrough` | Tool doesn't express opinion, passes to generic pipeline | Not in teaching version |
### 2. Production Verification Stages
CC's tool calls don't go through three gates — they go through multiple stages distributed across `checkPermissionsAndCallTool()` (`toolExecution.ts:599-1745`), hooks, `hasPermissionsToUseToolInner()` (`utils/permissions/permissions.ts:1158-1310`), and classifier logic:
1. **Zod schema validation** (`toolExecution.ts:614-680`) — parameter type checking
2. **validateInput()** (`toolExecution.ts:682-733`) — tool-level semantic validation
3. **backfillObservableInput()** (`toolExecution.ts:784`) — backfill legacy fields
4. **PreToolUse hooks** (`toolExecution.ts:800-862`) — hooks can return allow/deny/ask
5. **resolveHookPermissionDecision()** (`toolExecution.ts:921-931`) — coordinate hook + pipeline decisions
6. **hasPermissionsToUseToolInner()** (`permissions.ts:1158-1310`) — multi-layer rule check:
- Entire tool disabled by deny rule → `deny`
- Entire tool flagged by ask rule → `ask`
- `tool.checkPermissions()` tool's own judgment
- Tool itself returns deny → `deny`
- `requiresUserInteraction()``ask`
- Content-related ask rules → `ask` (not bypassable)
- Security check violation → `ask` (not bypassable)
- bypassPermissions mode → `allow`
- Entire tool allowed by allow rule → `allow`
- passthrough → converted to `ask`
### 3. Deny List: Not One File, but 8 Sources
CC doesn't have a single deny list. Permission rules come from 8 sources (`types/permissions.ts:54-62`):
| Source | Configuration Location |
|--------|----------------------|
| `userSettings` | `~/.claude/settings.json` |
| `projectSettings` | `.claude/settings.json` |
| `localSettings` | `settings.local.json` |
| `flagSettings` | Feature flags |
| `policySettings` | Enterprise management policy |
| `cliArg` | `--allowedTools` / `--deniedTools` |
| `command` | Inline command |
| `session` | In-session temporary authorization |
Each rule format: `{ toolName: "Bash", ruleBehavior: "deny", ruleContent: "npm publish:*" }`. Rules from multiple sources are merged, with higher-priority sources overriding lower ones (low to high: user < project < local < flag < policy, plus cliArg, command, session).
### 4. What is isDestructive()
In CC, `isDestructive` (`Tool.ts:405-406`) is **purely for UI display** — showing a `[destructive]` label in the tool list. It doesn't participate in permission decisions. All tools return `false` by default. Only ExitWorktree (on remove) and MCP tools (depending on `annotations.destructiveHint`) override it.
### 5. YoloClassifier (Auto-Approval)
In CC's auto mode, it doesn't pop a dialog every time. `classifyYoloAction` (`utils/permissions/yoloClassifier.ts:1012`) sends the tool call + conversation context to a classifier LLM to judge safety. It first tries acceptEdits mode simulation (`permissions.ts:620-656`, if acceptEdits allows → auto-approve), then checks the safe tool whitelist (`permissions.ts:658-686`), and finally calls the classifier. If the classifier rejects too many times in a row → falls back to manual approval.
### 6. Permission Bubbling
A sub-Agent's (forked via AgentTool) `permissionMode` is set to `'bubble'` (`forkSubagent.ts:50`). This means permission dialogs **bubble up to the parent Agent's terminal**, rather than being silently denied in the sub-Agent. The Bash classifier continues running during this process — displaying the permission dialog while judging in the background whether auto-approval is possible.
### The Teaching Version's Simplification Is Intentional
- Multi-stage pipeline → 3 gates: dramatically lower barrier to understanding
- 8 rule sources → 1 local DENY_LIST: manageable concept count
- isDestructive → omitted (teaching version has no UI layer, and it doesn't participate in permission decisions in CC either)
- YoloClassifier → omitted (depends on additional LLM calls and telemetry)
- Permission bubbling → omitted (s15 covers multi-Agent)
</details>
<!-- translation-sync: zh@v1, en@v1, ja@v1 -->

View File

@@ -1,8 +1,8 @@
# s03: Permission — 実行前に権限を判断する
[中文](README.md) · [English](README.en.md) · [日本語](README.ja.md)
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20
s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20 → s21 → s22
> *"ツール実行前に権限を判断"* — 権限パイプラインは、どの操作に承認が必要かを決める。
>
> **Harness レイヤー**: 権限 — ツール実行前に一つのゲートを追加。

View File

@@ -1,45 +1,45 @@
# s03: Permission — 执行前做权限判断
# s03: Permission — Check Permissions Before Execution
[中文](README.md) · [English](README.en.md) · [日本語](README.ja.md)
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20
> *"工具执行前先做权限判断"* — 权限管线决定哪些操作需要审批。
s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20 → s21 → s22
> *"Check permissions before executing"* — The permission pipeline decides which operations need approval.
>
> **Harness 层**: 权限 — 在工具执行前加一道门。
> **Harness Layer**: Permission — a gate before tool execution.
---
## 问题
## The Problem
s02 Agent 有 5 个工具。file tools 受 `safe_path` 保护,但 bash 不受限制。让它"清理一下项目",可能执行 `rm -rf /`
s02's Agent has 5 tools. File tools are protected by `safe_path`, but bash is unrestricted. Ask it to "clean up the project," and it might run `rm -rf /`.
安全不能靠信任模型,要靠代码——在工具执行之前做判断。
Safety can't rely on trusting the model — it needs code: a check before every tool execution.
---
## 解决方案
## The Solution
![Permission Overview](images/permission-overview.svg)
![Permission Overview](images/permission-overview.en.svg)
s02 的循环完全保留。唯一的变动在工具执行前插入 `check_permission()`——每个工具调用经过三道闸门,顺序固定:硬拒绝优先,软询问次之,都没命中就放行。
s02's loop is fully preserved. The only change is inserting `check_permission()` before tool execution — each tool call passes through three gates in a fixed order: hard deny first, then soft ask, and if neither matches, allow.
三道闸门对应三种决策:
The three gates correspond to three decisions:
| 闸门 | 作用 | 命中后 |
|------|------|--------|
| 1. 拒绝列表 | 永远禁止的操作(`rm -rf /``sudo` | 直接拒绝,不执行 |
| 2. 规则匹配 | 取决于上下文的操作(读/写工作区外、`rm` 文件) | 交给闸门 3 |
| 3. 用户审批 | 闸门 2 命中后,暂停等用户确认 | 用户决定允许或拒绝 |
| Gate | Purpose | On Match |
|------|---------|----------|
| 1. Deny List | Permanently forbidden operations (`rm -rf /`, `sudo`) | Denied immediately, not executed |
| 2. Rule Matching | Context-dependent operations (reading/writing outside workspace, `rm` files) | Passed to Gate 3 |
| 3. User Approval | After Gate 2 matches, pauses for user confirmation | User decides allow or deny |
三道都没命中 → 直接执行。大部分日常操作走这条路。
None of the three gates match → execute directly. Most routine operations take this path.
---
## 工作原理
## How It Works
![Permission Pipeline](images/permission-pipeline.svg)
![Permission Pipeline](images/permission-pipeline.en.svg)
**闸门 1**:一张硬拒绝表,先查,命中就返回阻止信息。(教学示意:简单字符串匹配不是可靠安全机制,命令变体和 shell 展开可能绕过。CC 的做法见附录。)
**Gate 1**: A hard deny list. Check first; if matched, return a block message. (Teaching demo: simple string matching is not a reliable security mechanism — command variants and shell expansion can bypass it. CC's approach is in the appendix.)
```python
DENY_LIST = [
@@ -54,7 +54,7 @@ def check_deny_list(command: str) -> str | None:
return None
```
**闸门 2**:规则匹配——描述"什么时候需要问用户"。每条规则指定工具和检查条件。
**Gate 2**: Rule matching — describes "when to ask the user." Each rule specifies a tool and a check condition.
```python
PERMISSION_RULES = [
@@ -77,7 +77,7 @@ def check_rules(tool_name: str, args: dict) -> str | None:
return None
```
**闸门 3**:规则命中后,暂停等用户输入。
**Gate 3**: After a rule matches, pause for user input.
```python
def ask_user(tool_name: str, args: dict, reason: str) -> str:
@@ -87,18 +87,18 @@ def ask_user(tool_name: str, args: dict, reason: str) -> str:
return "allow" if choice in ("y", "yes") else "deny"
```
**三道闸门串在一起**,插在工具执行之前:
**All three gates chained together**, inserted before tool execution:
```python
def check_permission(block) -> bool:
# 闸门 1: 硬拒绝
# Gate 1: Hard deny
if block.name == "bash":
reason = check_deny_list(block.input.get("command", ""))
if reason:
print(f"\n{reason}")
return False
# 闸门 2 + 3: 规则匹配 → 用户审批
# Gate 2 + 3: Rule matching → User approval
reason = check_rules(block.name, block.input)
if reason:
decision = ask_user(block.name, block.input, reason)
@@ -107,125 +107,125 @@ def check_permission(block) -> bool:
return True
# agent_loop 中——s02 的循环只加了一行:
# In agent_loop — s02's loop with just one line added:
for block in response.content:
if block.type == "tool_use":
if not check_permission(block): # ← 新增
if not check_permission(block): # ← NEW
results.append({... "content": "Permission denied."})
continue
output = TOOL_HANDLERS[block.name](**block.input) # s02 原有
output = TOOL_HANDLERS[block.name](**block.input) # s02 original
results.append(...)
```
---
## 相对 s02 的变更
## Changes from s02
| 组件 | 之前 (s02) | 之后 (s03) |
|------|-----------|-----------|
| 安全模型 | 无(信任模型) | 三道闸门权限管线 |
| 新函数 | — | check_deny_list, check_rules, ask_user, check_permission |
| 循环 | 直接执行所有工具 | 执行前插入 check_permission() |
| Component | Before (s02) | After (s03) |
|-----------|-------------|-------------|
| Security model | None (trust the model) | Three-gate permission pipeline |
| New functions | — | check_deny_list, check_rules, ask_user, check_permission |
| Loop | Executes all tools directly | Inserts check_permission() before execution |
---
## 试一下
## Try It
```sh
cd learn-claude-code
python s03_permission/code.py
```
试试这些 prompt
Try these prompts:
1. `Create a file called test.txt in the current directory`(应该直接通过)
2. `Delete the file test.txt`bash + rm 会触发闸门 2
3. `What files are in the current directory?`(只读,全部通过)
4. `Try to write a file to /etc/something`(写工作区外,触发闸门 2
1. `Create a file called test.txt in the current directory` (should pass through)
2. `Delete the file test.txt` (bash + rm triggers Gate 2)
3. `What files are in the current directory?` (read-only, all pass)
4. `Try to write a file to /etc/something` (writing outside workspace triggers Gate 2)
观察重点:哪些操作直接通过?哪些需要你确认?哪些被直接拒绝?
What to watch for: Which operations pass through? Which need your confirmation? Which are denied outright?
---
## 接下来
## What's Next
权限检查做了——但每次都在循环里硬编码 `check_permission()`。如果我想在每次工具执行前后加日志?如果想在某些操作后自动触发 git commit这些扩展逻辑散落在 loop 里,循环很快就会膨胀。
Permission checks are in place — but every check is hardcoded as `check_permission()` inside the loop. What if you want to add logging before and after each tool execution? What if you want to auto-trigger a git commit after certain operations? Scattering this extension logic throughout the loop makes it bloat.
s04 Hooks → 给循环加钩子,扩展逻辑挂在钩子上,循环保持干净。
s04 Hooks: Add hooks to the loop. Extension logic hangs on hooks; the loop stays clean.
<details>
<summary>深入 CC 源码</summary>
<summary>Dive into CC Source Code</summary>
> 以下基于 CC 源码 `types/permissions.ts``utils/permissions/permissions.ts``toolExecution.ts``utils/permissions/yoloClassifier.ts``tools/AgentTool/forkSubagent.ts` 的核查。
> The following is based on a review of CC source code `types/permissions.ts`, `utils/permissions/permissions.ts`, `toolExecution.ts`, `utils/permissions/yoloClassifier.ts`, `tools/AgentTool/forkSubagent.ts`.
### 一、PermissionResult:不是 3 种,是 4 种
### 1. PermissionResult: Not 3, but 4
教学版的三道闸门deny → ask → allow和 CC 不完全对应。CC 的 `PermissionResult` 有 4 个 behavior`types/permissions.ts:241-266`
The teaching version's three gates (deny → ask → allow) don't fully correspond to CC. CC's `PermissionResult` has 4 behaviors (`types/permissions.ts:241-266`):
| behavior | 含义 | 教学版对应 |
|----------|------|-----------|
| `allow` | 直接允许 | 闸门 3 通过 |
| `deny` | 直接拒绝 | 闸门 1 命中 |
| `ask` | 弹出对话框问用户 | 闸门 2 命中 |
| `passthrough` | 工具不表态,交给通用管线决定 | 教学版无 |
| behavior | Meaning | Teaching Version Equivalent |
|----------|---------|---------------------------|
| `allow` | Allow directly | Gate 3 passes |
| `deny` | Deny directly | Gate 1 matches |
| `ask` | Show dialog to user | Gate 2 matches |
| `passthrough` | Tool doesn't express opinion, passes to generic pipeline | Not in teaching version |
### 二、生产版的验证阶段
### 2. Production Verification Stages
CC 的工具调用不是经过三道闸门,而是经过多个阶段,分布在 `checkPermissionsAndCallTool()``toolExecution.ts:599-1745`)、hooks`hasPermissionsToUseToolInner()``utils/permissions/permissions.ts:1158-1310`)和 classifier 逻辑里:
CC's tool calls don't go through three gates — they go through multiple stages distributed across `checkPermissionsAndCallTool()` (`toolExecution.ts:599-1745`), hooks, `hasPermissionsToUseToolInner()` (`utils/permissions/permissions.ts:1158-1310`), and classifier logic:
1. **Zod schema 验证**`toolExecution.ts:614-680`)— 参数类型检查
2. **validateInput()**`toolExecution.ts:682-733`)— 工具级语义验证
3. **backfillObservableInput()**`toolExecution.ts:784`)— 补全遗留字段
4. **PreToolUse hooks**`toolExecution.ts:800-862`)— 钩子可以返回 allow/deny/ask
5. **resolveHookPermissionDecision()**`toolExecution.ts:921-931`)— 协调钩子+管线决策
6. **hasPermissionsToUseToolInner()**`permissions.ts:1158-1310`)— 多层规则检查:
- 整个工具被 deny rule 禁用`deny`
- 整个工具被 ask rule 标记`ask`
- `tool.checkPermissions()` 工具自己的判断
- 工具自己返回 deny → `deny`
1. **Zod schema validation** (`toolExecution.ts:614-680`) — parameter type checking
2. **validateInput()** (`toolExecution.ts:682-733`) — tool-level semantic validation
3. **backfillObservableInput()** (`toolExecution.ts:784`) — backfill legacy fields
4. **PreToolUse hooks** (`toolExecution.ts:800-862`) — hooks can return allow/deny/ask
5. **resolveHookPermissionDecision()** (`toolExecution.ts:921-931`) — coordinate hook + pipeline decisions
6. **hasPermissionsToUseToolInner()** (`permissions.ts:1158-1310`) — multi-layer rule check:
- Entire tool disabled by deny rule → `deny`
- Entire tool flagged by ask rule → `ask`
- `tool.checkPermissions()` tool's own judgment
- Tool itself returns deny → `deny`
- `requiresUserInteraction()``ask`
- 内容相关的 ask 规则 → `ask`(不可绕过)
- 安全检查违规 → `ask`(不可绕过)
- bypassPermissions 模式`allow`
- 整个工具被 allow rule 放行`allow`
- passthrough → 转为 `ask`
- Content-related ask rules → `ask` (not bypassable)
- Security check violation → `ask` (not bypassable)
- bypassPermissions mode`allow`
- Entire tool allowed by allow rule → `allow`
- passthrough → converted to `ask`
### 三、拒绝列表:不是一个文件,是 8 个来源
### 3. Deny List: Not One File, but 8 Sources
CC 没有单一的 deny list。权限规则来自 8 个来源(`types/permissions.ts:54-62`
CC doesn't have a single deny list. Permission rules come from 8 sources (`types/permissions.ts:54-62`):
| 来源 | 配置位置 |
|------|---------|
| Source | Configuration Location |
|--------|----------------------|
| `userSettings` | `~/.claude/settings.json` |
| `projectSettings` | `.claude/settings.json` |
| `localSettings` | `settings.local.json` |
| `flagSettings` | Feature flags |
| `policySettings` | 企业管理策略 |
| `policySettings` | Enterprise management policy |
| `cliArg` | `--allowedTools` / `--deniedTools` |
| `command` | 内联命令 |
| `session` | 会话内临时授权 |
| `command` | Inline command |
| `session` | In-session temporary authorization |
每条规则格式:`{ toolName: "Bash", ruleBehavior: "deny", ruleContent: "npm publish:*" }`。多个来源的规则合并,高优先级来源覆盖低优先级(从低到高:user < project < local < flag < policy,加上 cliArgcommandsession)。
Each rule format: `{ toolName: "Bash", ruleBehavior: "deny", ruleContent: "npm publish:*" }`. Rules from multiple sources are merged, with higher-priority sources overriding lower ones (low to high: user < project < local < flag < policy, plus cliArg, command, session).
### 四、isDestructive() 是什么
### 4. What is isDestructive()
CC 中 `isDestructive``Tool.ts:405-406`**纯粹是 UI 展示用的**——在工具列表里显示 `[destructive]` 标签。它不参与权限决策。默认所有工具都返回 `false`。只有 ExitWorktreeremove 时)和 MCP 工具(依赖 `annotations.destructiveHint`)覆写了它。
In CC, `isDestructive` (`Tool.ts:405-406`) is **purely for UI display** — showing a `[destructive]` label in the tool list. It doesn't participate in permission decisions. All tools return `false` by default. Only ExitWorktree (on remove) and MCP tools (depending on `annotations.destructiveHint`) override it.
### 五、YoloClassifier(自动审批)
### 5. YoloClassifier (Auto-Approval)
CC 的 auto 模式下,不会每次都弹对话框。`classifyYoloAction``utils/permissions/yoloClassifier.ts:1012`)把工具调用 + 对话上下文发给一个分类器 LLM 判断是否安全。先尝试 acceptEdits 模式模拟(`permissions.ts:620-656`,如果 acceptEdits 允许 → 直接批准),再查安全工具白名单(`permissions.ts:658-686`),最后才调分类器。分类器连续拒绝太多次 → 回退到人工审批。
In CC's auto mode, it doesn't pop a dialog every time. `classifyYoloAction` (`utils/permissions/yoloClassifier.ts:1012`) sends the tool call + conversation context to a classifier LLM to judge safety. It first tries acceptEdits mode simulation (`permissions.ts:620-656`, if acceptEdits allows → auto-approve), then checks the safe tool whitelist (`permissions.ts:658-686`), and finally calls the classifier. If the classifier rejects too many times in a row → falls back to manual approval.
### 六、权限冒泡
### 6. Permission Bubbling
子 Agent通过 AgentTool fork 出来的)的 `permissionMode` 设为 `'bubble'``forkSubagent.ts:50`)。意思是权限弹窗**冒泡到父 Agent 的终端**,而不是在子 Agent 里静默拒绝。Bash 分类器在这个过程中继续跑——给权限对话框显示的同时在后台判断是否可以自动批准。
A sub-Agent's (forked via AgentTool) `permissionMode` is set to `'bubble'` (`forkSubagent.ts:50`). This means permission dialogs **bubble up to the parent Agent's terminal**, rather than being silently denied in the sub-Agent. The Bash classifier continues running during this process — displaying the permission dialog while judging in the background whether auto-approval is possible.
### 教学版的简化是刻意的
### The Teaching Version's Simplification Is Intentional
- 多阶段管线 → 3 道闸门:理解门槛大幅降低
- 8 个规则来源 → 1 个本地 DENY_LIST概念量可控
- isDestructive → 忽略(教学版没有 UI 层CC 里它也不参与权限决策)
- YoloClassifier → 省略(依赖于额外的 LLM 调用和遥测系统)
- 权限冒泡 → 省略s15 才涉及多 Agent
- Multi-stage pipeline → 3 gates: dramatically lower barrier to understanding
- 8 rule sources → 1 local DENY_LIST: manageable concept count
- isDestructive → omitted (teaching version has no UI layer, and it doesn't participate in permission decisions in CC either)
- YoloClassifier → omitted (depends on additional LLM calls and telemetry)
- Permission bubbling → omitted (s15 covers multi-Agent)
</details>

232
s03_permission/README.zh.md Normal file
View File

@@ -0,0 +1,232 @@
# s03: Permission — 执行前做权限判断
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20 → s21 → s22
> *"工具执行前先做权限判断"* — 权限管线决定哪些操作需要审批。
>
> **Harness 层**: 权限 — 在工具执行前加一道门。
---
## 问题
s02 的 Agent 有 5 个工具。file tools 受 `safe_path` 保护,但 bash 不受限制。让它"清理一下项目",可能执行 `rm -rf /`
安全不能靠信任模型,要靠代码——在工具执行之前做判断。
---
## 解决方案
![Permission Overview](images/permission-overview.svg)
s02 的循环完全保留。唯一的变动在工具执行前插入 `check_permission()`——每个工具调用经过三道闸门,顺序固定:硬拒绝优先,软询问次之,都没命中就放行。
三道闸门对应三种决策:
| 闸门 | 作用 | 命中后 |
|------|------|--------|
| 1. 拒绝列表 | 永远禁止的操作(`rm -rf /``sudo` | 直接拒绝,不执行 |
| 2. 规则匹配 | 取决于上下文的操作(读/写工作区外、`rm` 文件) | 交给闸门 3 |
| 3. 用户审批 | 闸门 2 命中后,暂停等用户确认 | 用户决定允许或拒绝 |
三道都没命中 → 直接执行。大部分日常操作走这条路。
---
## 工作原理
![Permission Pipeline](images/permission-pipeline.svg)
**闸门 1**:一张硬拒绝表,先查,命中就返回阻止信息。(教学示意:简单字符串匹配不是可靠安全机制,命令变体和 shell 展开可能绕过。CC 的做法见附录。)
```python
DENY_LIST = [
"rm -rf /", "sudo", "shutdown", "reboot",
"mkfs", "dd if=", "> /dev/sda",
]
def check_deny_list(command: str) -> str | None:
for pattern in DENY_LIST:
if pattern in command:
return f"Blocked: '{pattern}' is on the deny list"
return None
```
**闸门 2**:规则匹配——描述"什么时候需要问用户"。每条规则指定工具和检查条件。
```python
PERMISSION_RULES = [
{
"tools": ["read_file", "write_file", "edit_file"],
"check": lambda args: not (WORKDIR / args.get("path", "")).resolve().is_relative_to(WORKDIR),
"message": "Access outside workspace",
},
{
"tools": ["bash"],
"check": lambda args: any(kw in args.get("command", "") for kw in ["rm ", "> /etc/", "chmod 777"]),
"message": "Potentially destructive command",
},
]
def check_rules(tool_name: str, args: dict) -> str | None:
for rule in PERMISSION_RULES:
if tool_name in rule["tools"] and rule["check"](args):
return rule["message"]
return None
```
**闸门 3**:规则命中后,暂停等用户输入。
```python
def ask_user(tool_name: str, args: dict, reason: str) -> str:
print(f"\n{reason}")
print(f" Tool: {tool_name}({args})")
choice = input(" Allow? [y/N] ").strip().lower()
return "allow" if choice in ("y", "yes") else "deny"
```
**三道闸门串在一起**,插在工具执行之前:
```python
def check_permission(block) -> bool:
# 闸门 1: 硬拒绝
if block.name == "bash":
reason = check_deny_list(block.input.get("command", ""))
if reason:
print(f"\n{reason}")
return False
# 闸门 2 + 3: 规则匹配 → 用户审批
reason = check_rules(block.name, block.input)
if reason:
decision = ask_user(block.name, block.input, reason)
if decision == "deny":
return False
return True
# 在 agent_loop 中——s02 的循环只加了一行:
for block in response.content:
if block.type == "tool_use":
if not check_permission(block): # ← 新增
results.append({... "content": "Permission denied."})
continue
output = TOOL_HANDLERS[block.name](**block.input) # s02 原有
results.append(...)
```
---
## 相对 s02 的变更
| 组件 | 之前 (s02) | 之后 (s03) |
|------|-----------|-----------|
| 安全模型 | 无(信任模型) | 三道闸门权限管线 |
| 新函数 | — | check_deny_list, check_rules, ask_user, check_permission |
| 循环 | 直接执行所有工具 | 执行前插入 check_permission() |
---
## 试一下
```sh
cd learn-claude-code
python s03_permission/code.py
```
试试这些 prompt
1. `Create a file called test.txt in the current directory`(应该直接通过)
2. `Delete the file test.txt`bash + rm 会触发闸门 2
3. `What files are in the current directory?`(只读,全部通过)
4. `Try to write a file to /etc/something`(写工作区外,触发闸门 2
观察重点:哪些操作直接通过?哪些需要你确认?哪些被直接拒绝?
---
## 接下来
权限检查做了——但每次都在循环里硬编码 `check_permission()`。如果我想在每次工具执行前后加日志?如果想在某些操作后自动触发 git commit这些扩展逻辑散落在 loop 里,循环很快就会膨胀。
s04 Hooks → 给循环加钩子,扩展逻辑挂在钩子上,循环保持干净。
<details>
<summary>深入 CC 源码</summary>
> 以下基于 CC 源码 `types/permissions.ts`、`utils/permissions/permissions.ts`、`toolExecution.ts`、`utils/permissions/yoloClassifier.ts`、`tools/AgentTool/forkSubagent.ts` 的核查。
### 一、PermissionResult不是 3 种,是 4 种
教学版的三道闸门deny → ask → allow和 CC 不完全对应。CC 的 `PermissionResult` 有 4 个 behavior`types/permissions.ts:241-266`
| behavior | 含义 | 教学版对应 |
|----------|------|-----------|
| `allow` | 直接允许 | 闸门 3 通过 |
| `deny` | 直接拒绝 | 闸门 1 命中 |
| `ask` | 弹出对话框问用户 | 闸门 2 命中 |
| `passthrough` | 工具不表态,交给通用管线决定 | 教学版无 |
### 二、生产版的验证阶段
CC 的工具调用不是经过三道闸门,而是经过多个阶段,分布在 `checkPermissionsAndCallTool()``toolExecution.ts:599-1745`、hooks、`hasPermissionsToUseToolInner()``utils/permissions/permissions.ts:1158-1310`)和 classifier 逻辑里:
1. **Zod schema 验证**`toolExecution.ts:614-680`)— 参数类型检查
2. **validateInput()**`toolExecution.ts:682-733`)— 工具级语义验证
3. **backfillObservableInput()**`toolExecution.ts:784`)— 补全遗留字段
4. **PreToolUse hooks**`toolExecution.ts:800-862`)— 钩子可以返回 allow/deny/ask
5. **resolveHookPermissionDecision()**`toolExecution.ts:921-931`)— 协调钩子+管线决策
6. **hasPermissionsToUseToolInner()**`permissions.ts:1158-1310`)— 多层规则检查:
- 整个工具被 deny rule 禁用 → `deny`
- 整个工具被 ask rule 标记 → `ask`
- `tool.checkPermissions()` 工具自己的判断
- 工具自己返回 deny → `deny`
- `requiresUserInteraction()``ask`
- 内容相关的 ask 规则 → `ask`(不可绕过)
- 安全检查违规 → `ask`(不可绕过)
- bypassPermissions 模式 → `allow`
- 整个工具被 allow rule 放行 → `allow`
- passthrough → 转为 `ask`
### 三、拒绝列表:不是一个文件,是 8 个来源
CC 没有单一的 deny list。权限规则来自 8 个来源(`types/permissions.ts:54-62`
| 来源 | 配置位置 |
|------|---------|
| `userSettings` | `~/.claude/settings.json` |
| `projectSettings` | `.claude/settings.json` |
| `localSettings` | `settings.local.json` |
| `flagSettings` | Feature flags |
| `policySettings` | 企业管理策略 |
| `cliArg` | `--allowedTools` / `--deniedTools` |
| `command` | 内联命令 |
| `session` | 会话内临时授权 |
每条规则格式:`{ toolName: "Bash", ruleBehavior: "deny", ruleContent: "npm publish:*" }`。多个来源的规则合并高优先级来源覆盖低优先级从低到高user < project < local < flag < policy加上 cliArg、command、session
### 四、isDestructive() 是什么
CC 中 `isDestructive``Tool.ts:405-406`**纯粹是 UI 展示用的**——在工具列表里显示 `[destructive]` 标签。它不参与权限决策。默认所有工具都返回 `false`。只有 ExitWorktreeremove 时)和 MCP 工具(依赖 `annotations.destructiveHint`)覆写了它。
### 五、YoloClassifier自动审批
CC 的 auto 模式下,不会每次都弹对话框。`classifyYoloAction``utils/permissions/yoloClassifier.ts:1012`)把工具调用 + 对话上下文发给一个分类器 LLM 判断是否安全。先尝试 acceptEdits 模式模拟(`permissions.ts:620-656`,如果 acceptEdits 允许 → 直接批准),再查安全工具白名单(`permissions.ts:658-686`),最后才调分类器。分类器连续拒绝太多次 → 回退到人工审批。
### 六、权限冒泡
子 Agent通过 AgentTool fork 出来的)的 `permissionMode` 设为 `'bubble'``forkSubagent.ts:50`)。意思是权限弹窗**冒泡到父 Agent 的终端**,而不是在子 Agent 里静默拒绝。Bash 分类器在这个过程中继续跑——给权限对话框显示的同时在后台判断是否可以自动批准。
### 教学版的简化是刻意的
- 多阶段管线 → 3 道闸门:理解门槛大幅降低
- 8 个规则来源 → 1 个本地 DENY_LIST概念量可控
- isDestructive → 忽略(教学版没有 UI 层CC 里它也不参与权限决策)
- YoloClassifier → 省略(依赖于额外的 LLM 调用和遥测系统)
- 权限冒泡 → 省略s15 才涉及多 Agent
</details>
<!-- translation-sync: zh@v1, en@v1, ja@v1 -->