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,522 @@
1
+ """工具执行前的权限运行时:规则集合、批准通道、会话记忆与最近判定。
2
+
3
+ 判定本身在 :mod:`braid_coding_agent.permissions.evaluate`,本模块只负责:
4
+
5
+ - 把配置与运行时规则合成一份不可变的 ``RuleSet``;
6
+ - 在工具执行前调用纯判定;
7
+ - 需要询问时等待批准通道,把 ``once`` / ``session`` / ``project`` / ``deny``
8
+ 折成允许或拒绝;
9
+ - 把最近的判定留给 ``/permission`` 展示。
10
+
11
+ ## 批准的作用域
12
+
13
+ ``once`` 只对本次调用有效;``session`` 把请求的 ``fingerprint`` 记在内存里,
14
+ 同一会话内同类操作不再询问;``project`` 把一条精确的 allow 规则写进
15
+ ``.braid/permissions.local.toml``,跨会话有效。子代理没有批准通道,``ask``
16
+ 一律按拒绝处理。
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import asyncio
22
+ import os
23
+ from collections.abc import Mapping
24
+ from dataclasses import replace
25
+ from urllib.parse import urlsplit
26
+
27
+ from braid_ai.cancel import CancelToken
28
+ from braid_ai.types import JsonValue
29
+ from braid_coding_agent.permissions.evaluate import compile_ruleset, evaluate, evaluate_rules
30
+ from braid_coding_agent.permissions.matching import (
31
+ ShellCommand,
32
+ command_fingerprint,
33
+ is_external,
34
+ real_path_variants,
35
+ split_shell_command,
36
+ )
37
+ from braid_coding_agent.permissions.model import (
38
+ APPROVAL_SCOPES,
39
+ BUILTIN_BASH_RULES,
40
+ BUILTIN_PATH_RULES,
41
+ DEFAULT_APPROVAL_TIMEOUT_SECONDS,
42
+ NETWORK_TOOLS,
43
+ PERMISSION_ACTIONS,
44
+ PERMISSION_MODES,
45
+ PLAN_FILE_NAMES,
46
+ PLAN_TOOLS,
47
+ READ_ONLY_TOOLS,
48
+ RULE_SCOPES,
49
+ RULE_TABLES,
50
+ SHELL_TOOLS,
51
+ WRITE_TOOLS,
52
+ ApprovalAnswer,
53
+ ApprovalHandler,
54
+ ApprovalScope,
55
+ PermissionAction,
56
+ PermissionContext,
57
+ PermissionDecision,
58
+ PermissionMode,
59
+ PermissionPrompt,
60
+ PermissionRequest,
61
+ PermissionSettings,
62
+ RuleProposal,
63
+ RuleScope,
64
+ RuleSet,
65
+ ScopedRule,
66
+ )
67
+ from braid_coding_agent.permissions.store import PermissionStore, PermissionStoreError
68
+ from braid_coding_agent.tools.path_utils import relative_posix, resolve_to_cwd, to_posix
69
+
70
+ _RECENT_LIMIT = 50
71
+
72
+
73
+ def build_request(
74
+ tool_name: str,
75
+ tool_call_id: str,
76
+ args: Mapping[str, JsonValue],
77
+ cwd: str,
78
+ ) -> PermissionRequest:
79
+ """从已校验的工具参数里取出路径、命令与目标主机。
80
+
81
+ 路径同时保留词法形式与真实形式;``bash`` 命令预先分段并标记动态求值。真实
82
+ 路径只参与权限判定,工具本身仍使用词法路径。
83
+ """
84
+ root = to_posix(resolve_to_cwd(".", cwd))
85
+ real_root = to_posix(os.path.realpath(root))
86
+
87
+ paths: list[str] = []
88
+ raw_path = args.get("path")
89
+ if isinstance(raw_path, str) and raw_path.strip():
90
+ paths.append(to_posix(resolve_to_cwd(raw_path, cwd)))
91
+ real_paths: list[str] = []
92
+ for path in paths:
93
+ for variant in real_path_variants(path):
94
+ if variant not in real_paths:
95
+ real_paths.append(variant)
96
+ resolved_paths = [to_posix(os.path.realpath(path)) for path in paths]
97
+
98
+ raw_command = args.get("command") if tool_name in SHELL_TOOLS else None
99
+ command = raw_command.strip() if isinstance(raw_command, str) and raw_command.strip() else None
100
+ shell = split_shell_command(command) if command is not None else None
101
+ host = _target_host(tool_name, args)
102
+ external = any(is_external(path, root) for path in paths) or any(
103
+ is_external(path, real_root) for path in resolved_paths
104
+ )
105
+ return PermissionRequest(
106
+ tool_name=tool_name,
107
+ tool_call_id=tool_call_id,
108
+ args=args,
109
+ cwd=root,
110
+ paths=tuple(paths),
111
+ command=command,
112
+ external=external,
113
+ host=host,
114
+ fingerprint=_fingerprint(tool_name, command, tuple(paths), host, shell),
115
+ segments=shell.segments if shell is not None else (),
116
+ dynamic=shell.dynamic if shell is not None else False,
117
+ real_paths=tuple(real_paths),
118
+ )
119
+
120
+
121
+ def proposal_for(request: PermissionRequest) -> RuleProposal | None:
122
+ """批准提示里"写入项目规则"的候选。
123
+
124
+ 复合命令与动态命令没有可保存的单条规则:命令规则按段匹配,整条命令的规则
125
+ 不会命中任何一段。这类调用只提供一次、本会话与拒绝。
126
+ """
127
+ if request.command is not None:
128
+ if len(request.segments) > 1 or request.dynamic:
129
+ return None
130
+ return RuleProposal("bash", " ".join(request.command.split()))
131
+ if request.host is not None:
132
+ return RuleProposal("domains", request.host)
133
+ if request.paths:
134
+ path = request.paths[0]
135
+ relative = relative_posix(path, request.cwd)
136
+ if relative in (".", ""):
137
+ return RuleProposal("paths", path)
138
+ return RuleProposal("paths", relative)
139
+ if request.tool_name:
140
+ return RuleProposal("tools", request.tool_name)
141
+ return None
142
+
143
+
144
+ def _target_host(tool_name: str, args: Mapping[str, JsonValue]) -> str | None:
145
+ """网络工具的目标主机。``websearch`` 没有 URL,主机留空、按工具名记指纹。"""
146
+ if tool_name not in NETWORK_TOOLS:
147
+ return None
148
+ raw_url = args.get("url")
149
+ if not isinstance(raw_url, str) or not raw_url.strip():
150
+ return None
151
+ return urlsplit(raw_url.strip()).hostname
152
+
153
+
154
+ def _fingerprint(
155
+ tool_name: str,
156
+ command: str | None,
157
+ paths: tuple[str, ...],
158
+ host: str | None,
159
+ shell: ShellCommand | None,
160
+ ) -> str:
161
+ """同类操作的键:命令按段数分组,文件工具按目标路径,网络工具按主机。"""
162
+ if command is not None:
163
+ return command_fingerprint(
164
+ command,
165
+ shell.segments if shell is not None else (),
166
+ shell.dynamic if shell is not None else False,
167
+ )
168
+ if host is not None:
169
+ return f"{tool_name}:{host}"
170
+ if paths:
171
+ return f"{tool_name}:{paths[0]}"
172
+ return tool_name
173
+
174
+
175
+ class PermissionEngine:
176
+ """一个会话的权限状态:规则、批准通道、会话内批准记忆与最近决策。"""
177
+
178
+ def __init__(
179
+ self,
180
+ *,
181
+ settings: PermissionSettings,
182
+ cwd: str,
183
+ approval: ApprovalHandler | None = None,
184
+ store: PermissionStore | None = None,
185
+ session_id: str = "",
186
+ ) -> None:
187
+ self._settings = settings
188
+ self._cwd = cwd
189
+ self._approval = approval
190
+ self._store = store
191
+ self._session_id = session_id
192
+ self._approved: set[str] = set()
193
+ self._recent: list[PermissionDecision] = []
194
+ self._approval_lock = asyncio.Lock()
195
+
196
+ compiled = compile_ruleset(settings)
197
+ self._base_rules: list[ScopedRule] = [
198
+ rule for rule in compiled.rules if rule.scope != "builtin"
199
+ ]
200
+ self._session_rules: list[ScopedRule] = []
201
+ self._ruleset = self._compile()
202
+
203
+ @property
204
+ def settings(self) -> PermissionSettings:
205
+ return self._settings
206
+
207
+ @property
208
+ def store(self) -> PermissionStore | None:
209
+ return self._store
210
+
211
+ @property
212
+ def rules(self) -> tuple[ScopedRule, ...]:
213
+ return self._ruleset.rules
214
+
215
+ @property
216
+ def recent(self) -> tuple[PermissionDecision, ...]:
217
+ return tuple(self._recent)
218
+
219
+ @property
220
+ def approved_fingerprints(self) -> frozenset[str]:
221
+ return frozenset(self._approved)
222
+
223
+ @property
224
+ def rule_count(self) -> int:
225
+ return len(self._ruleset)
226
+
227
+ def set_approval_handler(self, handler: ApprovalHandler | None) -> None:
228
+ self._approval = handler
229
+
230
+ def clear_approvals(self) -> None:
231
+ self._approved.clear()
232
+
233
+ def set_mode(self, mode: PermissionMode) -> PermissionMode:
234
+ """原地切换运行模式,返回切换前的模式。"""
235
+ if mode not in PERMISSION_MODES:
236
+ raise ValueError(f"未知权限模式:{mode}")
237
+ previous = self._settings.mode
238
+ self._settings = replace(self._settings, mode=mode)
239
+ return previous
240
+
241
+ def add_rule(self, rule: ScopedRule) -> None:
242
+ """添加一条规则。``session`` 只改内存,其余来源改内存中的基础规则。"""
243
+ if rule.scope == "session":
244
+ self._session_rules = [
245
+ item
246
+ for item in self._session_rules
247
+ if (item.table, item.pattern, item.scope) != (rule.table, rule.pattern, rule.scope)
248
+ ]
249
+ self._session_rules.append(rule)
250
+ else:
251
+ self.add_base_rule(rule)
252
+ self._ruleset = self._compile()
253
+
254
+ def remove_rule(self, rule: ScopedRule) -> bool:
255
+ """删除一条规则。内置规则不能删除,返回 ``False``。"""
256
+ if rule.scope == "builtin":
257
+ return False
258
+ if rule.scope == "session":
259
+ before = len(self._session_rules)
260
+ self._session_rules = [
261
+ item
262
+ for item in self._session_rules
263
+ if (item.table, item.pattern, item.scope) != (rule.table, rule.pattern, rule.scope)
264
+ ]
265
+ self._ruleset = self._compile()
266
+ return len(self._session_rules) != before
267
+ return self.remove_base_rule(rule)
268
+
269
+ def add_base_rule(self, rule: ScopedRule) -> None:
270
+ """把项目或全局来源的规则加入内存,供本次会话立即生效。"""
271
+ self._base_rules = [
272
+ item
273
+ for item in self._base_rules
274
+ if (item.table, item.pattern, item.scope) != (rule.table, rule.pattern, rule.scope)
275
+ ]
276
+ self._base_rules.append(rule)
277
+ self._ruleset = self._compile()
278
+
279
+ def remove_base_rule(self, rule: ScopedRule) -> bool:
280
+ before = len(self._base_rules)
281
+ self._base_rules = [
282
+ item
283
+ for item in self._base_rules
284
+ if (item.table, item.pattern, item.scope) != (rule.table, rule.pattern, rule.scope)
285
+ ]
286
+ self._ruleset = self._compile()
287
+ return len(self._base_rules) != before
288
+
289
+ def reset_session_rules(self) -> int:
290
+ count = len(self._session_rules)
291
+ self._session_rules = []
292
+ self._ruleset = self._compile()
293
+ return count
294
+
295
+ def reset_base_rules(self, scope: RuleScope, *, source: str | None = None) -> int:
296
+ """清空某个来源的内存规则,返回删除的条数。
297
+
298
+ ``source`` 给出时只删除该文件来源的规则;``/permission reset`` 用它区分
299
+ 运行时文件与手写 ``settings.json``,避免把下次启动还会加载的规则一起清掉。
300
+ """
301
+ before = len(self._base_rules)
302
+ self._base_rules = [
303
+ rule
304
+ for rule in self._base_rules
305
+ if rule.scope != scope or (source is not None and rule.source != source)
306
+ ]
307
+ self._ruleset = self._compile()
308
+ return before - len(self._base_rules)
309
+
310
+ def set_project_trusted(self, trusted: bool) -> None:
311
+ """更新本次会话的项目信任状态,影响后续批准提示是否提供 ``project``。"""
312
+ self._settings = replace(self._settings, project_trusted=trusted)
313
+
314
+ async def authorize(
315
+ self,
316
+ tool_name: str,
317
+ tool_call_id: str,
318
+ args: Mapping[str, JsonValue],
319
+ signal: CancelToken | None = None,
320
+ ) -> PermissionDecision:
321
+ """判定一次调用;需要询问时等待批准通道,超时或通道缺失按拒绝处理。"""
322
+ request = build_request(tool_name, tool_call_id, args, self._cwd)
323
+ context = PermissionContext(
324
+ request=request,
325
+ mode=self._settings.mode,
326
+ workspace=self._cwd,
327
+ default=self._settings.default,
328
+ project_trusted=self._settings.project_trusted,
329
+ session_id=self._session_id,
330
+ )
331
+ verdict = evaluate(self._ruleset, context)
332
+ if verdict.action != "ask":
333
+ self._record(verdict)
334
+ return verdict
335
+ if request.fingerprint in self._approved:
336
+ decision = self._session_allow(verdict, request)
337
+ self._record(decision)
338
+ return decision
339
+ if signal is not None and signal.cancelled:
340
+ decision = self._cancel(verdict, signal)
341
+ self._record(decision)
342
+ return decision
343
+
344
+ async with self._approval_lock:
345
+ if request.fingerprint in self._approved:
346
+ decision = self._session_allow(verdict, request)
347
+ self._record(decision)
348
+ return decision
349
+ answer = await self._ask(request, verdict, signal)
350
+ decision = self._from_answer(request, verdict, answer)
351
+ if answer.scope == "session":
352
+ self._approved.add(request.fingerprint)
353
+ self._record(decision)
354
+ return decision
355
+
356
+ def _compile(self) -> RuleSet:
357
+ current = replace(self._settings, rules=tuple((*self._base_rules, *self._session_rules)))
358
+ return compile_ruleset(current)
359
+
360
+ def _approval_options(self, proposal: RuleProposal | None) -> tuple[ApprovalScope, ...]:
361
+ if self._store is not None and self._settings.project_trusted and proposal is not None:
362
+ return ("once", "session", "project", "deny")
363
+ return ("once", "session", "deny")
364
+
365
+ async def _ask(
366
+ self,
367
+ request: PermissionRequest,
368
+ verdict: PermissionDecision,
369
+ signal: CancelToken | None,
370
+ ) -> ApprovalAnswer:
371
+ if self._approval is None:
372
+ return ApprovalAnswer(scope="deny", note="当前运行模式没有批准通道")
373
+ proposal = proposal_for(request)
374
+ prompt = PermissionPrompt(
375
+ request=request,
376
+ reason=verdict.reason,
377
+ rule=verdict.rule,
378
+ mode=self._settings.mode,
379
+ options=self._approval_options(proposal),
380
+ proposal=proposal,
381
+ )
382
+ try:
383
+ return await asyncio.wait_for(
384
+ self._approval(prompt, signal),
385
+ timeout=self._settings.approval_timeout_seconds,
386
+ )
387
+ except TimeoutError:
388
+ return ApprovalAnswer(scope="deny", note="等待批准超时")
389
+
390
+ def _from_answer(
391
+ self,
392
+ request: PermissionRequest,
393
+ verdict: PermissionDecision,
394
+ answer: ApprovalAnswer,
395
+ ) -> PermissionDecision:
396
+ if answer.scope == "project":
397
+ return self._persist_project(request, verdict)
398
+ if answer.scope in ("once", "session"):
399
+ return replace(
400
+ verdict,
401
+ action="allow",
402
+ scope=answer.scope,
403
+ reason=f"权限允许:用户批准({answer.scope});{verdict.reason}",
404
+ rule=f"approval:{verdict.rule}",
405
+ )
406
+ note = answer.note or "用户拒绝这次调用"
407
+ return replace(
408
+ verdict,
409
+ action="deny",
410
+ scope=answer.scope,
411
+ reason=(f"权限拒绝:{note};{verdict.reason}。请改用只读工具,或请用户放宽规则。"),
412
+ rule=f"approval:{verdict.rule}",
413
+ )
414
+
415
+ def _persist_project(
416
+ self, request: PermissionRequest, verdict: PermissionDecision
417
+ ) -> PermissionDecision:
418
+ proposal = proposal_for(request)
419
+ if self._store is None:
420
+ return self._refuse(verdict, "当前会话没有规则存储,不能写入项目规则", scope="deny")
421
+ if not self._settings.project_trusted:
422
+ return self._refuse(
423
+ verdict,
424
+ "项目配置尚未信任;先运行 /permission trust 再写入项目规则",
425
+ scope="deny",
426
+ )
427
+ if proposal is None:
428
+ return self._refuse(verdict, "这次调用没有可保存的规则", scope="deny")
429
+ rule = ScopedRule(
430
+ proposal.table,
431
+ proposal.pattern,
432
+ "allow",
433
+ "project",
434
+ str(self._store.project_path),
435
+ )
436
+ try:
437
+ self._store.append_rule(rule)
438
+ except PermissionStoreError as exc:
439
+ return self._refuse(verdict, f"写入项目规则失败:{exc}", scope="deny")
440
+ self.add_base_rule(rule)
441
+ return replace(
442
+ verdict,
443
+ action="allow",
444
+ scope="project",
445
+ reason=(f"权限允许:用户批准并写入项目规则 {proposal.describe()};{verdict.reason}"),
446
+ rule=f"project:{proposal.table}:{proposal.pattern}",
447
+ )
448
+
449
+ @staticmethod
450
+ def _refuse(
451
+ verdict: PermissionDecision, note: str, *, scope: ApprovalScope
452
+ ) -> PermissionDecision:
453
+ return replace(
454
+ verdict,
455
+ action="deny",
456
+ scope=scope,
457
+ reason=f"权限拒绝:{note};{verdict.reason}。",
458
+ rule=f"approval:{verdict.rule}",
459
+ )
460
+
461
+ @staticmethod
462
+ def _session_allow(
463
+ verdict: PermissionDecision, request: PermissionRequest
464
+ ) -> PermissionDecision:
465
+ reason = f"权限允许:本会话已批准同类操作 {request.fingerprint};{verdict.reason}"
466
+ return replace(
467
+ verdict,
468
+ action="allow",
469
+ scope="session",
470
+ reason=reason,
471
+ rule=f"session:{verdict.rule}",
472
+ )
473
+
474
+ @staticmethod
475
+ def _cancel(verdict: PermissionDecision, signal: CancelToken) -> PermissionDecision:
476
+ return replace(
477
+ verdict,
478
+ action="deny",
479
+ reason=f"权限拒绝:运行已取消({signal.reason});{verdict.reason}",
480
+ rule="cancel",
481
+ )
482
+
483
+ def _record(self, decision: PermissionDecision) -> None:
484
+ self._recent.append(decision)
485
+ if len(self._recent) > _RECENT_LIMIT:
486
+ del self._recent[:-_RECENT_LIMIT]
487
+
488
+
489
+ __all__ = [
490
+ "APPROVAL_SCOPES",
491
+ "BUILTIN_BASH_RULES",
492
+ "BUILTIN_PATH_RULES",
493
+ "DEFAULT_APPROVAL_TIMEOUT_SECONDS",
494
+ "NETWORK_TOOLS",
495
+ "PERMISSION_ACTIONS",
496
+ "PERMISSION_MODES",
497
+ "PLAN_FILE_NAMES",
498
+ "PLAN_TOOLS",
499
+ "READ_ONLY_TOOLS",
500
+ "RULE_SCOPES",
501
+ "RULE_TABLES",
502
+ "SHELL_TOOLS",
503
+ "WRITE_TOOLS",
504
+ "ApprovalAnswer",
505
+ "ApprovalHandler",
506
+ "ApprovalScope",
507
+ "PermissionAction",
508
+ "PermissionContext",
509
+ "PermissionDecision",
510
+ "PermissionEngine",
511
+ "PermissionMode",
512
+ "PermissionPrompt",
513
+ "PermissionRequest",
514
+ "PermissionSettings",
515
+ "RuleProposal",
516
+ "RuleScope",
517
+ "RuleSet",
518
+ "ScopedRule",
519
+ "build_request",
520
+ "evaluate_rules",
521
+ "proposal_for",
522
+ ]