braid-coding-agent 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. braid_coding_agent/__init__.py +13 -0
  2. braid_coding_agent/assembly.py +460 -0
  3. braid_coding_agent/cancellation.py +25 -0
  4. braid_coding_agent/checkpoint/__init__.py +106 -0
  5. braid_coding_agent/checkpoint/git.py +305 -0
  6. braid_coding_agent/checkpoint/settings.py +26 -0
  7. braid_coding_agent/checkpoint/store.py +1261 -0
  8. braid_coding_agent/checkpoint/workspace.py +220 -0
  9. braid_coding_agent/cli.py +2168 -0
  10. braid_coding_agent/commands/__init__.py +50 -0
  11. braid_coding_agent/commands/auth.py +161 -0
  12. braid_coding_agent/commands/config.py +180 -0
  13. braid_coding_agent/commands/doctor.py +511 -0
  14. braid_coding_agent/commands/mcp.py +928 -0
  15. braid_coding_agent/commands/models.py +95 -0
  16. braid_coding_agent/commands/setup.py +89 -0
  17. braid_coding_agent/commands/uninstall.py +277 -0
  18. braid_coding_agent/commands/upgrade.py +381 -0
  19. braid_coding_agent/compaction/__init__.py +174 -0
  20. braid_coding_agent/compaction/prepare.py +430 -0
  21. braid_coding_agent/compaction/summarize.py +542 -0
  22. braid_coding_agent/compaction/tokens.py +204 -0
  23. braid_coding_agent/compaction/tool_results.py +196 -0
  24. braid_coding_agent/compaction/utils.py +181 -0
  25. braid_coding_agent/config.py +2776 -0
  26. braid_coding_agent/config_files.py +191 -0
  27. braid_coding_agent/credentials.py +252 -0
  28. braid_coding_agent/discovery.py +415 -0
  29. braid_coding_agent/extensions/__init__.py +77 -0
  30. braid_coding_agent/extensions/api.py +480 -0
  31. braid_coding_agent/extensions/runner.py +553 -0
  32. braid_coding_agent/formatting/__init__.py +62 -0
  33. braid_coding_agent/formatting/settings.py +87 -0
  34. braid_coding_agent/formatting/tool.py +179 -0
  35. braid_coding_agent/lsp/__init__.py +105 -0
  36. braid_coding_agent/lsp/client.py +546 -0
  37. braid_coding_agent/lsp/manager.py +187 -0
  38. braid_coding_agent/lsp/model.py +316 -0
  39. braid_coding_agent/lsp/protocol.py +105 -0
  40. braid_coding_agent/lsp/settings.py +120 -0
  41. braid_coding_agent/lsp/tool.py +429 -0
  42. braid_coding_agent/mcp/__init__.py +101 -0
  43. braid_coding_agent/mcp/cache.py +230 -0
  44. braid_coding_agent/mcp/catalog.py +108 -0
  45. braid_coding_agent/mcp/config.py +664 -0
  46. braid_coding_agent/mcp/config_store.py +142 -0
  47. braid_coding_agent/mcp/inspector.py +85 -0
  48. braid_coding_agent/mcp/panel.py +254 -0
  49. braid_coding_agent/mcp/runtime.py +1060 -0
  50. braid_coding_agent/mcp/tools.py +579 -0
  51. braid_coding_agent/mcp/trust.py +150 -0
  52. braid_coding_agent/mcp/tui_panel.py +444 -0
  53. braid_coding_agent/messages.py +152 -0
  54. braid_coding_agent/models_view.py +105 -0
  55. braid_coding_agent/modes/__init__.py +64 -0
  56. braid_coding_agent/modes/json_mode.py +480 -0
  57. braid_coding_agent/modes/lifecycle.py +217 -0
  58. braid_coding_agent/modes/print_mode.py +257 -0
  59. braid_coding_agent/modes/repl.py +2687 -0
  60. braid_coding_agent/modes/repl_commands.py +263 -0
  61. braid_coding_agent/modes/rpc.py +953 -0
  62. braid_coding_agent/modes/skill_commands.py +88 -0
  63. braid_coding_agent/modes/tui.py +2226 -0
  64. braid_coding_agent/modes/tui_control.py +90 -0
  65. braid_coding_agent/modes/tui_model.py +1043 -0
  66. braid_coding_agent/modes/tui_render.py +327 -0
  67. braid_coding_agent/modes/tui_rich.py +751 -0
  68. braid_coding_agent/modes/tui_style.py +42 -0
  69. braid_coding_agent/modes/wire.py +81 -0
  70. braid_coding_agent/netsafe.py +82 -0
  71. braid_coding_agent/network/__init__.py +20 -0
  72. braid_coding_agent/network/cache.py +77 -0
  73. braid_coding_agent/network/fetch.py +311 -0
  74. braid_coding_agent/network/html_text.py +160 -0
  75. braid_coding_agent/network/search.py +347 -0
  76. braid_coding_agent/network/settings.py +103 -0
  77. braid_coding_agent/network/urls.py +89 -0
  78. braid_coding_agent/observability/__init__.py +101 -0
  79. braid_coding_agent/observability/audit.py +124 -0
  80. braid_coding_agent/observability/collector.py +314 -0
  81. braid_coding_agent/observability/exporter.py +74 -0
  82. braid_coding_agent/observability/logging_setup.py +149 -0
  83. braid_coding_agent/observability/redaction.py +96 -0
  84. braid_coding_agent/observability/settings.py +29 -0
  85. braid_coding_agent/observability/spans.py +239 -0
  86. braid_coding_agent/permissions/__init__.py +185 -0
  87. braid_coding_agent/permissions/command.py +586 -0
  88. braid_coding_agent/permissions/engine.py +522 -0
  89. braid_coding_agent/permissions/evaluate.py +309 -0
  90. braid_coding_agent/permissions/matching.py +233 -0
  91. braid_coding_agent/permissions/model.py +278 -0
  92. braid_coding_agent/permissions/policy.py +99 -0
  93. braid_coding_agent/permissions/readonly.py +236 -0
  94. braid_coding_agent/permissions/store.py +379 -0
  95. braid_coding_agent/project_init.py +313 -0
  96. braid_coding_agent/prompt/__init__.py +98 -0
  97. braid_coding_agent/prompt/context_files.py +253 -0
  98. braid_coding_agent/prompt/project_context.py +172 -0
  99. braid_coding_agent/prompt/system_prompt.py +378 -0
  100. braid_coding_agent/questions.py +71 -0
  101. braid_coding_agent/render/__init__.py +56 -0
  102. braid_coding_agent/render/batch.py +66 -0
  103. braid_coding_agent/render/history.py +143 -0
  104. braid_coding_agent/render/stream.py +823 -0
  105. braid_coding_agent/render/theme.py +243 -0
  106. braid_coding_agent/sandbox/__init__.py +89 -0
  107. braid_coding_agent/sandbox/backend.py +184 -0
  108. braid_coding_agent/sandbox/bubblewrap.py +96 -0
  109. braid_coding_agent/sandbox/operations.py +301 -0
  110. braid_coding_agent/sandbox/policy.py +221 -0
  111. braid_coding_agent/sandbox/proxy.py +320 -0
  112. braid_coding_agent/sandbox/seatbelt.py +222 -0
  113. braid_coding_agent/sdk/__init__.py +31 -0
  114. braid_coding_agent/sdk/async_client.py +366 -0
  115. braid_coding_agent/sdk/client.py +386 -0
  116. braid_coding_agent/sdk/errors.py +52 -0
  117. braid_coding_agent/sdk/events.py +162 -0
  118. braid_coding_agent/sdk/types.py +63 -0
  119. braid_coding_agent/sdk/wire.py +59 -0
  120. braid_coding_agent/server/__init__.py +54 -0
  121. braid_coding_agent/server/errors.py +52 -0
  122. braid_coding_agent/server/http_server.py +419 -0
  123. braid_coding_agent/server/hub.py +530 -0
  124. braid_coding_agent/server/openapi.py +157 -0
  125. braid_coding_agent/server/registry.py +354 -0
  126. braid_coding_agent/server/router.py +275 -0
  127. braid_coding_agent/server/run.py +148 -0
  128. braid_coding_agent/server/schema.py +194 -0
  129. braid_coding_agent/server/service.py +975 -0
  130. braid_coding_agent/session/__init__.py +293 -0
  131. braid_coding_agent/session/agent_session.py +2706 -0
  132. braid_coding_agent/session/context_breakdown.py +302 -0
  133. braid_coding_agent/session/discovery.py +212 -0
  134. braid_coding_agent/session/entries.py +809 -0
  135. braid_coding_agent/session/evidence.py +295 -0
  136. braid_coding_agent/session/lock.py +176 -0
  137. braid_coding_agent/session/manager.py +1185 -0
  138. braid_coding_agent/session/plan.py +243 -0
  139. braid_coding_agent/session/plan_mode.py +423 -0
  140. braid_coding_agent/session/projection.py +262 -0
  141. braid_coding_agent/session/rewind.py +257 -0
  142. braid_coding_agent/session/status.py +240 -0
  143. braid_coding_agent/settings.py +94 -0
  144. braid_coding_agent/skills/__init__.py +70 -0
  145. braid_coding_agent/skills/loader.py +681 -0
  146. braid_coding_agent/startup/__init__.py +76 -0
  147. braid_coding_agent/startup/cache.py +72 -0
  148. braid_coding_agent/startup/diagnostics.py +37 -0
  149. braid_coding_agent/startup/monitor.py +245 -0
  150. braid_coding_agent/startup/phases.py +79 -0
  151. braid_coding_agent/startup/project.py +165 -0
  152. braid_coding_agent/startup/report.py +560 -0
  153. braid_coding_agent/startup/scheduler.py +347 -0
  154. braid_coding_agent/statusline.py +163 -0
  155. braid_coding_agent/subagents/__init__.py +22 -0
  156. braid_coding_agent/subagents/contract.py +75 -0
  157. braid_coding_agent/subagents/definitions.py +583 -0
  158. braid_coding_agent/subagents/registry.py +277 -0
  159. braid_coding_agent/subagents/runtime.py +610 -0
  160. braid_coding_agent/subagents/settings.py +156 -0
  161. braid_coding_agent/subagents/worktree.py +63 -0
  162. braid_coding_agent/tools/__init__.py +327 -0
  163. braid_coding_agent/tools/args.py +87 -0
  164. braid_coding_agent/tools/bash.py +359 -0
  165. braid_coding_agent/tools/edit.py +298 -0
  166. braid_coding_agent/tools/edit_diff.py +344 -0
  167. braid_coding_agent/tools/find.py +158 -0
  168. braid_coding_agent/tools/grep.py +305 -0
  169. braid_coding_agent/tools/ignore.py +198 -0
  170. braid_coding_agent/tools/ls.py +127 -0
  171. braid_coding_agent/tools/mutation_queue.py +90 -0
  172. braid_coding_agent/tools/operations.py +274 -0
  173. braid_coding_agent/tools/output_accumulator.py +282 -0
  174. braid_coding_agent/tools/output_store.py +244 -0
  175. braid_coding_agent/tools/path_utils.py +91 -0
  176. braid_coding_agent/tools/plan.py +141 -0
  177. braid_coding_agent/tools/prompt_notes.py +52 -0
  178. braid_coding_agent/tools/question.py +180 -0
  179. braid_coding_agent/tools/read.py +223 -0
  180. braid_coding_agent/tools/submit_plan.py +102 -0
  181. braid_coding_agent/tools/truncate.py +423 -0
  182. braid_coding_agent/tools/write.py +100 -0
  183. braid_coding_agent/untrusted.py +50 -0
  184. braid_coding_agent/verify/__init__.py +78 -0
  185. braid_coding_agent/verify/runner.py +260 -0
  186. braid_coding_agent/verify/settings.py +64 -0
  187. braid_coding_agent/verify/tool.py +143 -0
  188. braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
  189. braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
  190. braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
  191. braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
  192. braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,278 @@
1
+ """权限领域模型:规则、请求、判定与运行模式。
2
+
3
+ 这一层不读文件、不弹窗、不做 I/O。规则从配置或运行时命令来,判定函数只读
4
+ :class:`PermissionContext`,结果是一份 :class:`PermissionDecision`。把类型集中
5
+ 在这里,:mod:`braid_coding_agent.permissions.engine` 才能只保留运行时协调。
6
+
7
+ ## 规则胜负
8
+
9
+ 所有命中的规则按具体度排队,具体度是模式里非 ``*``、``?`` 字符的数量。取最具体
10
+ 的一组,组内按 deny > ask > allow 取最严。``default`` 的具体度固定为 -1,只在
11
+ 没有别的规则命中时生效。
12
+
13
+ ## 模式与规则
14
+
15
+ 模式回答"这次运行允许哪一类动作",规则回答"这一类动作具体要不要问"。模式只能
16
+ 放宽 `default` 兜底,不能改写显式规则:``full`` 把兜底的 ``ask`` 变成 ``allow``,
17
+ 用户显式写的 ``ask`` 仍然询问;``accept-edits`` 只放宽写工具的兜底,显式 ``ask``
18
+ 同样保留。
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from collections.abc import Awaitable, Callable, Iterator, Mapping
24
+ from dataclasses import dataclass, field
25
+ from types import MappingProxyType
26
+ from typing import Literal
27
+
28
+ from braid_ai.cancel import CancelToken
29
+ from braid_ai.types import JsonValue
30
+
31
+ type PermissionAction = Literal["allow", "ask", "deny"]
32
+ type PermissionMode = Literal["read-only", "plan", "accept-edits", "full"]
33
+ type ApprovalScope = Literal["once", "session", "project", "deny"]
34
+ type RuleTable = Literal["tools", "bash", "paths", "domains"]
35
+ type RuleScope = Literal["builtin", "global", "project", "session"]
36
+
37
+ PERMISSION_ACTIONS: tuple[PermissionAction, ...] = ("allow", "ask", "deny")
38
+ PERMISSION_MODES: tuple[PermissionMode, ...] = ("read-only", "plan", "accept-edits", "full")
39
+ APPROVAL_SCOPES: tuple[ApprovalScope, ...] = ("once", "session", "project", "deny")
40
+ RULE_TABLES: tuple[RuleTable, ...] = ("tools", "bash", "paths", "domains")
41
+ RULE_SCOPES: tuple[RuleScope, ...] = ("builtin", "global", "project", "session")
42
+
43
+ #: 只读工具:read-only 与 plan 模式只放行这几类。``lsp`` 归在这里——它启动语言服务器
44
+ #: 进程、读文件、算诊断,但不写工作区,规划模式正需要它来判断"这么改会不会错"。
45
+ READ_ONLY_TOOLS = frozenset({"read", "grep", "find", "ls", "lsp"})
46
+ #: 文件写入工具:accept-edits 自动放行兜底询问,read-only 与 plan 拒绝。``format`` 会
47
+ #: 重写文件,按写工具处理;路径规则(``**/.env`` 之类)因此对它同样生效。
48
+ WRITE_TOOLS = frozenset({"write", "edit", "format"})
49
+ #: 命令执行工具:所有模式都按命令规则判定。``verify`` 跑的是项目配置的检查命令,
50
+ #: 与 ``bash`` 同一类:它会执行外部程序、可能写缓存目录,plan 模式不该跑它。
51
+ SHELL_TOOLS = frozenset({"bash", "verify"})
52
+ #: 不改动工作区的计划工具,plan 模式放行。``submit_plan`` 提交实施计划并等用户批准,
53
+ #: 它只写会话树(``plan_mode`` 条目),从不碰工作区。
54
+ PLAN_TOOLS = frozenset({"update_plan", "question", "submit_plan"})
55
+ #: 网络工具:不碰工作区,但会把数据送出去。默认走 ``default``(ask),
56
+ #: 域名规则可以按主机收紧或放宽。
57
+ NETWORK_TOOLS = frozenset({"webfetch", "websearch"})
58
+ #: plan 模式允许写入的计划文件。
59
+ PLAN_FILE_NAMES = frozenset({"plan.md", "PLAN.md"})
60
+
61
+ DEFAULT_APPROVAL_TIMEOUT_SECONDS = 60.0
62
+
63
+ #: 内置命令规则。``*`` 不作为规则出现:没有别的命令规则命中时,由判定层按
64
+ #: ``default`` 给出 ``bash:*`` 兜底(``default = "deny"`` 时为 deny,其余为 ask)。
65
+ #: 这样 ``full`` 可以放宽兜底,而用户显式写的 ``* = ask`` 仍然询问。
66
+ BUILTIN_BASH_RULES: Mapping[str, PermissionAction] = MappingProxyType(
67
+ {
68
+ "git status*": "allow",
69
+ "git diff*": "allow",
70
+ "git log*": "allow",
71
+ "git show*": "allow",
72
+ "git branch*": "allow",
73
+ "git rev-parse*": "allow",
74
+ "ls*": "allow",
75
+ "pwd*": "allow",
76
+ "rm -rf *": "deny",
77
+ "rm -fr *": "deny",
78
+ }
79
+ )
80
+
81
+ #: 内置凭证规则。``.env.example`` 与 ``.env.sample`` 用更具体的 allow 放行。
82
+ BUILTIN_PATH_RULES: Mapping[str, PermissionAction] = MappingProxyType(
83
+ {
84
+ "**/.env": "deny",
85
+ "**/.env.*": "deny",
86
+ "**/.env.example": "allow",
87
+ "**/.env.sample": "allow",
88
+ "**/id_rsa*": "deny",
89
+ "**/id_ed25519*": "deny",
90
+ "**/*.pem": "deny",
91
+ "**/*.key": "deny",
92
+ "**/.npmrc": "deny",
93
+ "**/.pypirc": "deny",
94
+ "**/credentials.json": "deny",
95
+ "~/.ssh/**": "deny",
96
+ "~/.aws/**": "deny",
97
+ "~/.config/gcloud/**": "deny",
98
+ }
99
+ )
100
+
101
+
102
+ @dataclass(slots=True, frozen=True)
103
+ class ScopedRule:
104
+ """一条带来源的规则。``scope`` 用于展示、信任过滤与持久化,不参与胜负。"""
105
+
106
+ table: RuleTable
107
+ pattern: str
108
+ effect: PermissionAction
109
+ scope: RuleScope
110
+ source: str = ""
111
+
112
+
113
+ #: 判定结果里携带的规则引用。字段与 :class:`ScopedRule` 相同,单独命名是为了让
114
+ #: "规则定义"与"命中记录"在类型上分开。
115
+ type RuleRef = ScopedRule
116
+
117
+
118
+ @dataclass(slots=True, frozen=True)
119
+ class RuleSet:
120
+ """一组不可变规则。运行时替换整个对象,避免半更新。"""
121
+
122
+ rules: tuple[ScopedRule, ...] = ()
123
+
124
+ def by_table(self, table: RuleTable) -> tuple[ScopedRule, ...]:
125
+ return tuple(rule for rule in self.rules if rule.table == table)
126
+
127
+ def __len__(self) -> int:
128
+ return len(self.rules)
129
+
130
+ def __iter__(self) -> Iterator[ScopedRule]:
131
+ return iter(self.rules)
132
+
133
+
134
+ @dataclass(slots=True, frozen=True)
135
+ class PermissionSettings:
136
+ """一份合并完成的权限配置。
137
+
138
+ ``rules`` 是带来源的完整规则列表,判定以它为准;四张表保留为配置层的派生
139
+ 视图,供 ``replace_permission``、``/permission show`` 与旧测试使用。``rules``
140
+ 为空时,判定会从四张表现编译一份,来源记为 ``global``。
141
+ """
142
+
143
+ default: PermissionAction = "ask"
144
+ mode: PermissionMode = "full"
145
+ approval_timeout_seconds: float = DEFAULT_APPROVAL_TIMEOUT_SECONDS
146
+ tools: Mapping[str, PermissionAction] = field(default_factory=dict[str, PermissionAction])
147
+ bash: Mapping[str, PermissionAction] = field(default_factory=dict[str, PermissionAction])
148
+ paths: Mapping[str, PermissionAction] = field(default_factory=dict[str, PermissionAction])
149
+ #: 网络工具的目标域名规则(``*.example.com`` / ``example.com``)。
150
+ domains: Mapping[str, PermissionAction] = field(default_factory=dict[str, PermissionAction])
151
+ #: 带来源的规则。为空表示从四张表现编译。
152
+ rules: tuple[ScopedRule, ...] = ()
153
+ #: 当前项目配置是否已信任。未信任时只加载项目来源的 deny 规则。
154
+ project_trusted: bool = False
155
+
156
+
157
+ @dataclass(slots=True, frozen=True)
158
+ class PermissionRequest:
159
+ """一次工具调用里与权限有关的部分。路径已经按 cwd 归一化成 posix 绝对路径。"""
160
+
161
+ tool_name: str
162
+ tool_call_id: str
163
+ args: Mapping[str, JsonValue]
164
+ cwd: str
165
+ paths: tuple[str, ...]
166
+ command: str | None
167
+ external: bool
168
+ fingerprint: str
169
+ #: 网络工具的目标主机;其余工具为 ``None``。
170
+ host: str | None = None
171
+ #: ``bash`` 命令按 shell 运算符切出的段;其余工具为空。
172
+ segments: tuple[str, ...] = ()
173
+ #: 命令包含动态求值(命令替换、反引号、heredoc、``eval``、``bash -c`` 等)。
174
+ dynamic: bool = False
175
+ #: 词法路径对应的真实路径;用于识别符号链接指向。
176
+ real_paths: tuple[str, ...] = ()
177
+
178
+
179
+ @dataclass(slots=True, frozen=True)
180
+ class RuleProposal:
181
+ """批准提示里"写入项目规则"将要保存的规则。"""
182
+
183
+ table: RuleTable
184
+ pattern: str
185
+
186
+ def describe(self) -> str:
187
+ return f'{self.table} "{self.pattern}"'
188
+
189
+
190
+ @dataclass(slots=True, frozen=True)
191
+ class PermissionDecision:
192
+ """一次判定的最终结论。``reason`` 会作为工具结果文本回到模型上下文。"""
193
+
194
+ action: PermissionAction
195
+ reason: str
196
+ rule: str
197
+ tool_name: str
198
+ tool_call_id: str
199
+ fingerprint: str
200
+ scope: ApprovalScope | None = None
201
+ #: 命中规则所在的层级;模式级拒绝与兜底也有来源。
202
+ origin: RuleScope | None = None
203
+ #: 所有命中的规则,按具体度从高到低排列,供展示与审计使用。
204
+ matched: tuple[RuleRef, ...] = ()
205
+
206
+
207
+ @dataclass(slots=True, frozen=True)
208
+ class PermissionPrompt:
209
+ """交给交互通道的一次批准请求。"""
210
+
211
+ request: PermissionRequest
212
+ reason: str
213
+ rule: str
214
+ mode: PermissionMode
215
+ #: 这次请求可用的作用域。默认三档;引擎在可持久化时追加 ``project``。
216
+ options: tuple[ApprovalScope, ...] = ("once", "session", "deny")
217
+ #: 选择 ``project`` 时会写入的规则;不可持久化时为 ``None``。
218
+ proposal: RuleProposal | None = None
219
+
220
+
221
+ @dataclass(slots=True, frozen=True)
222
+ class ApprovalAnswer:
223
+ """用户或 RPC 客户端的选择。``note`` 用于把拒绝原因带回模型。"""
224
+
225
+ scope: ApprovalScope
226
+ note: str = ""
227
+
228
+
229
+ #: 批准通道由运行模式提供:REPL 读一行输入,RPC 配对一次请求与响应。
230
+ type ApprovalHandler = Callable[[PermissionPrompt, CancelToken | None], Awaitable[ApprovalAnswer]]
231
+
232
+
233
+ @dataclass(slots=True, frozen=True)
234
+ class PermissionContext:
235
+ """一次判定需要的全部输入。判定函数只读它。"""
236
+
237
+ request: PermissionRequest
238
+ mode: PermissionMode
239
+ workspace: str
240
+ default: PermissionAction = "ask"
241
+ project_trusted: bool = False
242
+ session_id: str = ""
243
+ agent_depth: int = 0
244
+ now_ms: int = 0
245
+
246
+
247
+ __all__ = [
248
+ "APPROVAL_SCOPES",
249
+ "BUILTIN_BASH_RULES",
250
+ "BUILTIN_PATH_RULES",
251
+ "DEFAULT_APPROVAL_TIMEOUT_SECONDS",
252
+ "NETWORK_TOOLS",
253
+ "PERMISSION_ACTIONS",
254
+ "PERMISSION_MODES",
255
+ "PLAN_FILE_NAMES",
256
+ "PLAN_TOOLS",
257
+ "READ_ONLY_TOOLS",
258
+ "RULE_SCOPES",
259
+ "RULE_TABLES",
260
+ "SHELL_TOOLS",
261
+ "WRITE_TOOLS",
262
+ "ApprovalAnswer",
263
+ "ApprovalHandler",
264
+ "ApprovalScope",
265
+ "PermissionAction",
266
+ "PermissionContext",
267
+ "PermissionDecision",
268
+ "PermissionMode",
269
+ "PermissionPrompt",
270
+ "PermissionRequest",
271
+ "PermissionSettings",
272
+ "RuleProposal",
273
+ "RuleRef",
274
+ "RuleScope",
275
+ "RuleSet",
276
+ "RuleTable",
277
+ "ScopedRule",
278
+ ]
@@ -0,0 +1,99 @@
1
+ """运行模式的策略表。
2
+
3
+ 模式负责"这次运行允许哪一类动作",并决定没有规则命中时的兜底。它不负责改写
4
+ 用户显式写下的规则:``full`` 只把兜底的 ``ask`` 变成 ``allow``,显式 ``ask``
5
+ 仍然询问;``accept-edits`` 只放宽写工具的兜底。
6
+
7
+ ``read-only`` 与 ``plan`` 是两种硬边界,判定顺序是"先看模式、再看规则":模式说不允许,
8
+ 用户点批准也执行不了。两者的差别只有一条——``plan`` 额外放行计划工具(``update_plan``、
9
+ ``submit_plan``、``question``)、把技能正文读进上下文、派生子代理,以及**经过结构判定
10
+ 确认只读**的命令;``read-only`` 拒绝一切命令执行。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from braid_coding_agent.permissions.model import (
16
+ NETWORK_TOOLS,
17
+ PLAN_FILE_NAMES,
18
+ PLAN_TOOLS,
19
+ READ_ONLY_TOOLS,
20
+ WRITE_TOOLS,
21
+ PermissionAction,
22
+ PermissionMode,
23
+ PermissionRequest,
24
+ )
25
+ from braid_coding_agent.permissions.readonly import read_only_command_problem
26
+
27
+ #: ``plan`` 模式在只读工具之外额外放行的工具。
28
+ #:
29
+ #: - ``skill``:只把技能正文读进上下文,不碰工作区;
30
+ #: - ``task``:派生子代理做只读探索。子代理继承父会话当前的权限模式(装配层按
31
+ #: ``clamp_permission_mode`` 取更严的那个),所以它拿不到父会话没有的写权限。
32
+ PLAN_EXTRA_TOOLS: frozenset[str] = frozenset({"submit_plan", "skill", "task"})
33
+
34
+
35
+ def mode_block_reason(mode: PermissionMode, request: PermissionRequest) -> str | None:
36
+ """模式级硬限制。返回拒绝理由;``None`` 表示这个模式不拦它。
37
+
38
+ 只对 ``read-only`` 与 ``plan`` 生效:另外两个模式的边界由规则表给出。
39
+ """
40
+ if mode not in ("read-only", "plan"):
41
+ return None
42
+ name = request.tool_name
43
+ if name in READ_ONLY_TOOLS or name in NETWORK_TOOLS:
44
+ return None
45
+ if mode == "plan":
46
+ if name in PLAN_TOOLS or name in PLAN_EXTRA_TOOLS:
47
+ return None
48
+ if name in WRITE_TOOLS and _all_plan_files(request.paths):
49
+ return None
50
+ if name == "bash":
51
+ problem = read_only_command_problem(request)
52
+ if problem is None:
53
+ return None
54
+ return f"plan 模式只允许只读命令({problem})"
55
+ return f"{mode} 模式拒绝调用 {name},只放行只读操作"
56
+
57
+
58
+ def _all_plan_files(paths: tuple[str, ...]) -> bool:
59
+ """目标是不是全部为计划文件(``plan.md`` / ``PLAN.md``)。"""
60
+ return bool(paths) and all(path.rsplit("/", 1)[-1] in PLAN_FILE_NAMES for path in paths)
61
+
62
+
63
+ def mode_default(
64
+ mode: PermissionMode, tool_name: str, default: PermissionAction
65
+ ) -> PermissionAction:
66
+ """没有规则命中时的兜底动作。
67
+
68
+ ``read-only`` 与 ``plan`` 已经用模式级限制挡住越界工具,放行的只读工具不该因为
69
+ ``default = "ask"`` 再问一次。网络工具例外:它们不写工作区,但会把数据发出去,
70
+ 仍然按 ``default`` 与域名规则判定。
71
+ """
72
+ if mode in ("read-only", "plan"):
73
+ if tool_name in NETWORK_TOOLS:
74
+ return default
75
+ return "allow"
76
+ if mode == "accept-edits" and tool_name in WRITE_TOOLS:
77
+ return "allow" if default == "ask" else default
78
+ if mode == "full":
79
+ return "allow" if default == "ask" else default
80
+ return default
81
+
82
+
83
+ def mode_label(mode: PermissionMode) -> str:
84
+ """一行说明,供 ``/permission mode`` 列出。"""
85
+ labels: dict[PermissionMode, str] = {
86
+ "read-only": "拒绝全部写操作与命令执行",
87
+ "plan": "只读:放行只读工具与只读命令,允许计划工具与 plan.md",
88
+ "accept-edits": "文件修改的兜底询问放行,命令与网络按规则",
89
+ "full": "兜底询问放行;显式 ask 规则仍然询问",
90
+ }
91
+ return labels[mode]
92
+
93
+
94
+ __all__ = [
95
+ "PLAN_EXTRA_TOOLS",
96
+ "mode_block_reason",
97
+ "mode_default",
98
+ "mode_label",
99
+ ]
@@ -0,0 +1,236 @@
1
+ """只读命令的结构判定:``plan`` 模式能不能执行这条命令。
2
+
3
+ ## 为什么按 argv 判而不是查关键词
4
+
5
+ "命令里没有 rm 就是安全的"这类判断会被两条路绕开:``git commit`` 里没有危险词,
6
+ ``python -c "open('f','w')"`` 里也没有。反过来,``grep -r "rm -rf" docs`` 里有关键词,
7
+ 却完全无害。判定必须落在**每个命令段的程序名与参数**上:程序在只读白名单里,
8
+ 参数不触发写入或执行,才算确认安全。
9
+
10
+ ## 默认拒绝
11
+
12
+ 白名单之外的程序、白名单之内但带未知危险参数的命令、包含重定向或动态求值的命令,
13
+ 一律返回拒绝理由。这里的目标是"能确认才放行",不是"看起来不像危险操作就放行":
14
+ 漏掉一种写法的代价是规划模式被绕开,多拒绝一条命令的代价只是模型换用 ``read``。
15
+
16
+ ## 边界
17
+
18
+ 这套判定守着工具层,沙箱守着进程层。它能挡住 ``rm``、``git commit``、
19
+ ``sed -i``、``find -delete``、重定向与命令替换;它挡不住刻意混淆(变量拼接、
20
+ 编码后的命令、脚本文件内部的行为),这类行为需要沙箱给出最终边界。
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import posixpath
26
+ import re
27
+ import shlex
28
+ from collections.abc import Mapping
29
+ from dataclasses import dataclass
30
+ from fnmatch import fnmatchcase
31
+ from types import MappingProxyType
32
+
33
+ from braid_coding_agent.permissions.model import (
34
+ BUILTIN_PATH_RULES,
35
+ PermissionRequest,
36
+ )
37
+
38
+ __all__ = [
39
+ "READ_ONLY_PROGRAMS",
40
+ "ReadOnlyProgram",
41
+ "read_only_command_problem",
42
+ ]
43
+
44
+ #: 重定向与后台运算符。出现在段内说明这条命令会写文件或另起进程。
45
+ _REDIRECT = re.compile(r"[<>]")
46
+
47
+ #: 凭证文件的后缀模式。取自内置路径规则里以 ``**/`` 开头的 deny 条目:路径规则管
48
+ #: ``read`` / ``write`` 的 ``path`` 参数,命令里的路径参数由这里补上。
49
+ _SECRET_PATTERNS: tuple[str, ...] = tuple(
50
+ pattern[3:]
51
+ for pattern, action in BUILTIN_PATH_RULES.items()
52
+ if action == "deny" and pattern.startswith("**/")
53
+ )
54
+
55
+
56
+ @dataclass(slots=True, frozen=True)
57
+ class ReadOnlyProgram:
58
+ """一个允许的只读程序:可选子命令白名单与必须拒绝的参数。
59
+
60
+ ``subcommands`` 为空表示这个程序没有子命令的概念;非空时第一个非选项参数必须
61
+ 落在表里(``git`` 用它区分 ``status`` 与 ``commit``)。
62
+ """
63
+
64
+ subcommands: frozenset[str] = frozenset()
65
+ denied_flags: frozenset[str] = frozenset()
66
+
67
+
68
+ #: 只读白名单。新增条目要能回答"它的哪个参数会写文件或执行程序",答不上来就不加。
69
+ READ_ONLY_PROGRAMS: Mapping[str, ReadOnlyProgram] = MappingProxyType(
70
+ {
71
+ "ls": ReadOnlyProgram(),
72
+ "pwd": ReadOnlyProgram(),
73
+ "cat": ReadOnlyProgram(),
74
+ "head": ReadOnlyProgram(),
75
+ "tail": ReadOnlyProgram(denied_flags=frozenset({"-f", "-F", "--follow", "--retry"})),
76
+ "wc": ReadOnlyProgram(),
77
+ "stat": ReadOnlyProgram(),
78
+ "file": ReadOnlyProgram(denied_flags=frozenset({"-C", "-c", "--compile"})),
79
+ "du": ReadOnlyProgram(),
80
+ "df": ReadOnlyProgram(),
81
+ "tree": ReadOnlyProgram(denied_flags=frozenset({"-o", "--output"})),
82
+ "basename": ReadOnlyProgram(),
83
+ "dirname": ReadOnlyProgram(),
84
+ "realpath": ReadOnlyProgram(),
85
+ "echo": ReadOnlyProgram(),
86
+ "uname": ReadOnlyProgram(),
87
+ "whoami": ReadOnlyProgram(),
88
+ "grep": ReadOnlyProgram(),
89
+ "diff": ReadOnlyProgram(),
90
+ "sort": ReadOnlyProgram(denied_flags=frozenset({"-o", "--output"})),
91
+ "jq": ReadOnlyProgram(),
92
+ "rg": ReadOnlyProgram(denied_flags=frozenset({"--pre", "--pre-glob"})),
93
+ "find": ReadOnlyProgram(
94
+ denied_flags=frozenset(
95
+ {
96
+ "-delete",
97
+ "-exec",
98
+ "-execdir",
99
+ "-ok",
100
+ "-okdir",
101
+ "-fprint",
102
+ "-fprint0",
103
+ "-fprintf",
104
+ "-fls",
105
+ }
106
+ )
107
+ ),
108
+ "git": ReadOnlyProgram(
109
+ subcommands=frozenset(
110
+ {
111
+ "status",
112
+ "diff",
113
+ "log",
114
+ "show",
115
+ "rev-parse",
116
+ "ls-files",
117
+ "ls-tree",
118
+ "cat-file",
119
+ "blame",
120
+ "describe",
121
+ "shortlog",
122
+ "merge-base",
123
+ "name-rev",
124
+ "whatchanged",
125
+ }
126
+ ),
127
+ # ``git diff`` 会调用外部 diff 驱动与 textconv 过滤器,两者都能执行命令。
128
+ denied_flags=frozenset({"--output", "-o", "--ext-diff", "--textconv"}),
129
+ ),
130
+ }
131
+ )
132
+
133
+ #: ``git`` 的子命令之前允许出现的全局选项。``-c`` 能改配置(含 pager),不在其中。
134
+ _GIT_GLOBAL_FLAGS = frozenset({"--no-pager", "--version", "-P"})
135
+
136
+
137
+ def read_only_command_problem(request: PermissionRequest) -> str | None:
138
+ """确认一条命令只读;无法确认时返回拒绝理由。
139
+
140
+ :return: ``None`` 表示每个命令段都落在只读白名单内且参数安全。
141
+ """
142
+ if request.command is None:
143
+ return "这次调用没有命令文本"
144
+ if request.dynamic:
145
+ return "命令包含动态求值(命令替换、heredoc 或脚本包装器),无法确认副作用"
146
+ if not request.segments:
147
+ return "无法把命令拆成可判定的段"
148
+ for segment in request.segments:
149
+ problem = _segment_problem(segment)
150
+ if problem is not None:
151
+ return problem
152
+ return None
153
+
154
+
155
+ def _segment_problem(segment: str) -> str | None:
156
+ try:
157
+ raw = shlex.split(segment, posix=True)
158
+ except ValueError:
159
+ return f"无法解析命令段:{segment}"
160
+ tokens = _drop_safe_redirects(raw)
161
+ if not tokens:
162
+ return f"命令段为空:{segment}"
163
+ if any(_REDIRECT.search(token) for token in tokens):
164
+ return f"命令包含重定向,会写文件:{segment}"
165
+ program = posixpath.basename(tokens[0])
166
+ rule = READ_ONLY_PROGRAMS.get(program)
167
+ if rule is None:
168
+ return f"{program} 不在只读命令白名单里"
169
+ rest = tokens[1:]
170
+ if rule.subcommands:
171
+ head, tail = _split_subcommand(rest)
172
+ if head is None:
173
+ # 只有全局选项(``git --version`` / ``git --no-pager``):不碰仓库。
174
+ return None
175
+ if head not in rule.subcommands:
176
+ return f"git 的 {head} 子命令不在只读白名单里"
177
+ rest = tail
178
+ for token in rest:
179
+ if token.startswith("-"):
180
+ if any(token == flag or token.startswith(flag + "=") for flag in rule.denied_flags):
181
+ return f"{program} 的 {token} 会写文件或执行外部程序"
182
+ continue
183
+ if _looks_like_secret(token):
184
+ return f"命令要读取凭证文件 {token}"
185
+ return None
186
+
187
+
188
+ def _drop_safe_redirects(tokens: list[str]) -> list[str]:
189
+ """去掉不碰工作区的重定向:文件描述符复制与 ``/dev/null``。
190
+
191
+ 分段的切分器把 ``2>&1`` 拆成 ``2`` ``>&`` ``1``,把 ``2>/dev/null`` 拆成
192
+ ``2`` ``>`` ``/dev/null``。这两类只改变输出去处,是模型最常写的形式;
193
+ ``> out.txt``、``&> out.txt`` 仍然留在列表里,由上面的重定向检查拒绝。
194
+ """
195
+ kept: list[str] = []
196
+ index = 0
197
+ while index < len(tokens):
198
+ token = tokens[index]
199
+ digit = token.isdigit()
200
+ if digit and index + 2 < len(tokens):
201
+ operator, target = tokens[index + 1], tokens[index + 2]
202
+ if operator == ">&" and (target.isdigit() or target == "-"):
203
+ index += 3
204
+ continue
205
+ if operator in (">", ">>") and target == "/dev/null":
206
+ index += 3
207
+ continue
208
+ if not digit and index + 1 < len(tokens):
209
+ operator, target = token, tokens[index + 1]
210
+ if operator == ">&" and (target.isdigit() or target == "-"):
211
+ index += 2
212
+ continue
213
+ kept.append(token)
214
+ index += 1
215
+ return kept
216
+
217
+
218
+ def _split_subcommand(tokens: list[str]) -> tuple[str | None, list[str]]:
219
+ """跳过 ``git`` 的全局选项,返回 ``(子命令, 其余参数)``。"""
220
+ index = 0
221
+ while index < len(tokens):
222
+ token = tokens[index]
223
+ if token == "-C":
224
+ index += 2
225
+ continue
226
+ if token in _GIT_GLOBAL_FLAGS:
227
+ index += 1
228
+ continue
229
+ return token, tokens[index + 1 :]
230
+ return None, []
231
+
232
+
233
+ def _looks_like_secret(token: str) -> bool:
234
+ """参数看起来是不是凭证文件。比较文件名,路径前缀不参与。"""
235
+ name = posixpath.basename(token)
236
+ return any(fnmatchcase(name, pattern) for pattern in _SECRET_PATTERNS)