对应源码: permissions.rs:4-9 → PermissionMode 枚举 (5 种策略) sandbox.rs → FilesystemIsolationMode (3 种隔离策略) conversation.rs:170 → run_turn 中根据 permission_outcome 切换行为 策略模式和接口很像, 但侧重点不同: - 接口: "你必须实现这些方法" (关注 what) - 策略: "在运行时选择哪种行为" (关注 when/which) 日常类比:
()
| 725 | # ============================================================ |
| 726 | |
| 727 | def lesson_5_strategy_pattern(): |
| 728 | """ |
| 729 | 对应源码: |
| 730 | permissions.rs:4-9 → PermissionMode 枚举 (5 种策略) |
| 731 | sandbox.rs → FilesystemIsolationMode (3 种隔离策略) |
| 732 | conversation.rs:170 → run_turn 中根据 permission_outcome 切换行为 |
| 733 | |
| 734 | 策略模式和接口很像, 但侧重点不同: |
| 735 | - 接口: "你必须实现这些方法" (关注 what) |
| 736 | - 策略: "在运行时选择哪种行为" (关注 when/which) |
| 737 | |
| 738 | 日常类比: 导航 App 的路线选择 |
| 739 | ───────────────────────────── |
| 740 | 同样从 A 到 B: |
| 741 | - 策略 1: 最短距离 → 走小路 |
| 742 | - 策略 2: 最快时间 → 走高速 |
| 743 | - 策略 3: 避开收费 → 走免费路 |
| 744 | 算法不同, 但 "导航" 的框架完全一样。 |
| 745 | """ |
| 746 | print("=" * 60) |
| 747 | print("第五课: 策略模式 — 换挡: 运行时切换行为") |
| 748 | print("=" * 60) |
| 749 | |
| 750 | # ---- 例 1: 权限策略 (PermissionMode) ---- |
| 751 | print() |
| 752 | print(" 例 1: 权限策略 (对应 permissions.rs)") |
| 753 | print(" ────────────────────────────────────") |
| 754 | |
| 755 | class PermissionMode(IntEnum): |
| 756 | """对应 permissions.rs:4-9 的 5 级权限""" |
| 757 | ReadOnly = 0 # 只能读 |
| 758 | WorkspaceWrite = 1 # 能在工作区写 |
| 759 | DangerFullAccess = 2 # 完全文件系统访问 |
| 760 | Prompt = 3 # 每次询问用户 |
| 761 | Allow = 4 # 全部允许 (YOLO 模式) |
| 762 | |
| 763 | # 策略 1: 只读模式——一切写操作被拦截 |
| 764 | # 策略 2: 工作区写——只能改工作区文件 |
| 765 | # 策略 3: 全权限——随便搞 |
| 766 | |
| 767 | def check_permission( |
| 768 | tool: str, |
| 769 | required: PermissionMode, |
| 770 | current: PermissionMode, |
| 771 | ) -> str: |
| 772 | """ |
| 773 | 对应 permissions.rs:80-120 的 authorize() |
| 774 | 核心逻辑: current >= required → 允许 |
| 775 | """ |
| 776 | if current >= required: |
| 777 | return "允许" |
| 778 | else: |
| 779 | return f"拒绝 (需要 {required.name}, 当前 {current.name})" |
| 780 | |
| 781 | tools = [ |
| 782 | ("read", PermissionMode.ReadOnly), |
| 783 | ("write", PermissionMode.WorkspaceWrite), |
| 784 | ("bash", PermissionMode.DangerFullAccess), |
no test coverage detected