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,156 @@
1
+ """子代理的运行参数与一份代理定义。
2
+
3
+ 四个运行参数都由 ``agents`` 配置节给出,含义是边界而不是偏好:
4
+
5
+ - ``max_depth``:父会话为 0 层,一层子代理为 1 层。默认 1,最多允许调到 2。
6
+ 层数在**装配期**决定是否给子会话装 ``task`` 工具,执行期再判一次,
7
+ 两处都挡住才不会让模型通过提示词把无限嵌套套出来。
8
+ - ``max_background``:同时在跑的后台子代理数量。上限存在的理由是工作树与模型
9
+ 请求都要占资源,没有上限时一句"并行做十件事"就能把仓库切成十份。
10
+ - ``max_concurrent``:同时在跑的子代理总数,同步与后台一起算。``max_background``
11
+ 只约束后台那一类,而一次并行工具批次里的多个同步 ``task`` 调用同样会同时打出
12
+ 多个完整会话——那是最容易撞上端点速率限制的路径。
13
+ - ``timeout_seconds``:单个子代理的墙钟上限。超时后 ``abort()`` 会让它把
14
+ ``aborted`` 消息写进自己的会话文件,父会话收到 ``is_error`` 结果继续跑。
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass, field
20
+ from typing import Final, Literal
21
+
22
+ from braid_ai.types import JsonValue
23
+ from braid_coding_agent.permissions.engine import PERMISSION_MODES, PermissionMode
24
+
25
+ DEFAULT_MAX_DEPTH: Final[int] = 1
26
+ MAX_ALLOWED_DEPTH: Final[int] = 2
27
+ DEFAULT_MAX_BACKGROUND: Final[int] = 2
28
+ DEFAULT_MAX_CONCURRENT: Final[int] = 8
29
+ DEFAULT_TIMEOUT_SECONDS: Final[float] = 300.0
30
+ DEFAULT_MAX_TURNS: Final[int] = 20
31
+
32
+ type TaskStatus = Literal["running", "completed", "failed", "cancelled"]
33
+ type MemoryScope = Literal["none", "user", "project", "session"]
34
+ type IsolationMode = Literal["inherit", "none", "worktree"]
35
+
36
+ #: 权限模式的宽松程度。子代理的模式永远不能超过派生它的那个会话。
37
+ _PERMISSION_RANK: Final[dict[PermissionMode, int]] = {
38
+ "read-only": 0,
39
+ "plan": 1,
40
+ "accept-edits": 2,
41
+ "full": 3,
42
+ }
43
+
44
+
45
+ @dataclass(slots=True, frozen=True)
46
+ class SubagentSettings:
47
+ """一次进程启动时的子代理边界。"""
48
+
49
+ max_depth: int = DEFAULT_MAX_DEPTH
50
+ max_background: int = DEFAULT_MAX_BACKGROUND
51
+ max_concurrent: int = DEFAULT_MAX_CONCURRENT
52
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS
53
+
54
+ def wire(self) -> dict[str, JsonValue]:
55
+ return {
56
+ "maxDepth": self.max_depth,
57
+ "maxBackground": self.max_background,
58
+ "maxConcurrent": self.max_concurrent,
59
+ "timeoutSeconds": self.timeout_seconds,
60
+ }
61
+
62
+
63
+ @dataclass(slots=True, frozen=True)
64
+ class SubagentSpec:
65
+ """一份代理定义。``source`` 记录它来自内置、全局目录还是项目目录。"""
66
+
67
+ name: str
68
+ description: str
69
+ system_prompt: str
70
+ #: ``None`` 表示继承父会话的工具集合;空元组表示这个代理没有任何工具。
71
+ tools: tuple[str, ...] | None = None
72
+ #: 从继承结果或白名单里排除的工具。与 ``tools`` 同时声明同一个名字时从白名单移除。
73
+ disallowed_tools: tuple[str, ...] = ()
74
+ #: ``None`` 表示继承父会话当前的权限模式。
75
+ permission_mode: PermissionMode | None = None
76
+ model: str | None = None
77
+ max_turns: int = DEFAULT_MAX_TURNS
78
+ #: 预加载正文的 Skills。名字在装配期解析,找不到就直接失败。
79
+ skills: tuple[str, ...] = ()
80
+ #: 指定 MCP Server。当前版本只保留接口,不改变子代理可见的工具。
81
+ mcp_servers: tuple[str, ...] = ()
82
+ #: 持久记忆作用域。当前版本只保留接口。
83
+ memory: MemoryScope = "none"
84
+ #: ``inherit`` 跟随后台任务默认策略,``worktree`` 强制独立工作树,
85
+ #: ``none`` 表示与父会话共享工作目录。
86
+ isolation: IsolationMode = "inherit"
87
+ #: 专属生命周期 Hook。当前版本只解析与展示,不执行。
88
+ hooks: dict[str, JsonValue] = field(default_factory=dict[str, JsonValue])
89
+ source: str = "builtin"
90
+
91
+ def wire(self) -> dict[str, JsonValue]:
92
+ wire: dict[str, JsonValue] = {
93
+ "name": self.name,
94
+ "description": self.description,
95
+ "tools": list(self.tools) if self.tools is not None else None,
96
+ "disallowedTools": list(self.disallowed_tools),
97
+ "permissionMode": self.permission_mode or "inherit",
98
+ "maxTurns": self.max_turns,
99
+ "skills": list(self.skills),
100
+ "mcpServers": list(self.mcp_servers),
101
+ "memory": self.memory,
102
+ "isolation": self.isolation,
103
+ "hooks": self.hooks,
104
+ "source": self.source,
105
+ }
106
+ if self.model is not None:
107
+ wire["model"] = self.model
108
+ return wire
109
+
110
+
111
+ def clamp_permission_mode(
112
+ parent: PermissionMode, requested: PermissionMode | None
113
+ ) -> PermissionMode:
114
+ """取两者里更严的那个,堵住"父会话只读、子代理可写"这类越权。"""
115
+ if requested is None:
116
+ return parent
117
+ if _PERMISSION_RANK[parent] < _PERMISSION_RANK[requested]:
118
+ return parent
119
+ return requested
120
+
121
+
122
+ def resolve_tools(spec: SubagentSpec, inherited: tuple[str, ...]) -> tuple[str, ...]:
123
+ """按定义算出子代理最终可用的工具名。
124
+
125
+ ``tools`` 缺失时继承父会话的工具集合;``disallowedTools`` 永远从结果里扣除。
126
+ 解析顺序固定为"先取白名单或继承,再排除",两者同时写了同一个名字时定义层
127
+ 会从 ``tools`` 移除该名字,因此这里不会遇到"既允许又禁止"的输入。
128
+ """
129
+ base = inherited if spec.tools is None else spec.tools
130
+ banned = set(spec.disallowed_tools)
131
+ return tuple(name for name in base if name not in banned)
132
+
133
+
134
+ def as_permission_mode(value: str, *, where: str) -> PermissionMode:
135
+ for mode in PERMISSION_MODES:
136
+ if mode == value:
137
+ return mode
138
+ raise ValueError(f"{where}: 只支持 {', '.join(PERMISSION_MODES)},收到 {value!r}")
139
+
140
+
141
+ __all__ = [
142
+ "DEFAULT_MAX_BACKGROUND",
143
+ "DEFAULT_MAX_CONCURRENT",
144
+ "DEFAULT_MAX_DEPTH",
145
+ "DEFAULT_MAX_TURNS",
146
+ "DEFAULT_TIMEOUT_SECONDS",
147
+ "MAX_ALLOWED_DEPTH",
148
+ "IsolationMode",
149
+ "MemoryScope",
150
+ "SubagentSettings",
151
+ "SubagentSpec",
152
+ "TaskStatus",
153
+ "as_permission_mode",
154
+ "clamp_permission_mode",
155
+ "resolve_tools",
156
+ ]
@@ -0,0 +1,63 @@
1
+ """后台子代理的 Git 工作树隔离。
2
+
3
+ 为什么后台任务要独立工作树:两个子代理同时改文件时,共享工作目录会让后写的覆盖
4
+ 先写的,父会话也很难说清"这份 diff 是谁产生的"。``git worktree add`` 给每个任务
5
+ 一条独立分支与一个独立目录,父工作树保持干净,任务结束后 ``git diff`` 就是它的
6
+ 交付物。目录留在磁盘上,用户可以用 ``/worktree remove <路径>`` 清掉。
7
+
8
+ 工作树建立在运行时根目录下(``<agent_dir>/worktrees/<task_id>``),不放进项目目录:
9
+ 放进项目会让它们出现在父仓库的 ``git status`` 里,等于把隔离产物又混回被隔离的对象。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from dataclasses import dataclass
16
+
17
+ from braid_coding_agent.checkpoint import Git, GitWorkspace
18
+
19
+
20
+ @dataclass(slots=True, frozen=True)
21
+ class WorktreeHandle:
22
+ """一条已建好的工作树。"""
23
+
24
+ path: str
25
+ branch: str
26
+ root: str
27
+
28
+
29
+ def worktree_path(root: str, task_id: str) -> str:
30
+ return os.path.join(root, task_id)
31
+
32
+
33
+ async def create_worktree(*, cwd: str, root: str, task_id: str) -> WorktreeHandle:
34
+ """在 ``root`` 下建一条工作树。不是 Git 仓库、没有提交或 git 不可用都会失败。
35
+
36
+ 失败直接抛 :class:`~braid_coding_agent.checkpoint.git.GitError` 或
37
+ :class:`~braid_coding_agent.checkpoint.workspace.GitWorkspaceError`,由调用方
38
+ 折成 ``is_error`` 工具结果。绝不悄悄退回共享工作目录。
39
+ """
40
+ workspace = GitWorkspace(cwd=cwd)
41
+ await workspace.require_repo()
42
+ path = os.path.abspath(worktree_path(root, task_id))
43
+ branch = f"braid/{task_id}"
44
+ await workspace.add_worktree(path, branch)
45
+ return WorktreeHandle(path=path, branch=branch, root=os.path.abspath(cwd))
46
+
47
+
48
+ async def collect_diff(handle: WorktreeHandle) -> tuple[str, tuple[str, ...]]:
49
+ """取这条工作树相对其基线的完整 diff 与改动文件清单。
50
+
51
+ ``git add -A -N`` 只是把新文件登记成"意图添加",不写入内容也不提交;有了它,
52
+ ``git diff`` 才会把子代理新建的文件一起列出来。只跑 ``git diff`` 会漏掉这类改动,
53
+ 父代理会以为子代理什么都没做。
54
+ """
55
+ git = Git(cwd=handle.path)
56
+ await git.out("add", "-A", "-N")
57
+ diff = await git.out("diff", "--no-color")
58
+ names = await git.out("diff", "--name-only")
59
+ files = tuple(line.strip() for line in names.splitlines() if line.strip())
60
+ return diff, files
61
+
62
+
63
+ __all__ = ["WorktreeHandle", "collect_diff", "create_worktree", "worktree_path"]
@@ -0,0 +1,327 @@
1
+ """编码工具集:``read`` / ``write`` / ``edit`` / ``bash`` / ``grep`` / ``find`` / ``ls``,
2
+ 外加网络工具 ``webfetch`` / ``websearch``、三个会话级工具 ``update_plan`` /
3
+ ``question`` / ``task``,以及三个工程能力工具 ``lsp`` / ``verify`` / ``format``。
4
+
5
+ **工具是工厂函数,不是一个全局单例**。理由有三条:
6
+
7
+ - ``cwd`` 是工具行为的一部分:同一个 ``read`` 在 ``/a`` 与 ``/b`` 下读的是不同文件;
8
+ - ``operations`` 可替换(测试用内存 FS、将来接远端),单例会把这层依赖钉死;
9
+ - 不同会话可以带不同的工具实例(不同的上限、不同的 shell)。
10
+
11
+ ## 模块划分
12
+
13
+ | 模块 | 职责 |
14
+ |---|---|
15
+ | :mod:`.truncate` | 行/字节两条上限、人类可读大小;纯函数 |
16
+ | :mod:`.path_utils` | ``~``/``@``/Unicode 空格归一化、相对路径解析 |
17
+ | :mod:`.operations` | 文件系统与命令执行的协议 + 本地实现 |
18
+ | :mod:`.mutation_queue` | 同一路径的修改串行化 |
19
+ | :mod:`.ignore` | ``.gitignore`` 语义 + 目录遍历 |
20
+ | :mod:`.edit_diff` | 精确替换、展示 diff、unified patch |
21
+ | :mod:`.output_accumulator` | 命令输出的尾部保留与落盘 |
22
+ | :mod:`.output_store` | 完整输出的会话级目录、数量上限与保留期 |
23
+ | :mod:`.args` | schema 校验之后的类型收窄(``assert``,就地失败) |
24
+ | 七个工具模块 | 参数声明、执行流程、结果形态 |
25
+ | :mod:`.plan` | ``update_plan``:多步骤任务的步骤表 |
26
+ | :mod:`.question` | ``question``:向用户发起结构化提问 |
27
+ | :mod:`~braid_coding_agent.subagents` | ``task``:派生独立会话(工厂在 ``subagents/runtime.py``) |
28
+ | :mod:`~braid_coding_agent.network` | ``webfetch`` / ``websearch``:抓网页与搜索 |
29
+ | :mod:`~braid_coding_agent.lsp` | ``lsp``:诊断、定义、引用与符号 |
30
+ | :mod:`~braid_coding_agent.verify` | ``verify``:按配置顺序跑项目检查 |
31
+ | :mod:`~braid_coding_agent.formatting` | ``format``:按扩展名跑项目格式化命令 |
32
+
33
+ ## ``tool_declarations``
34
+
35
+ 模型能调用什么,由转录里的系统消息声明(``declare_tool_changes``);``AgentContext.tools``
36
+ 决定我们真的能执行什么。两者必须一致,因此需要一个"可执行工具 → 模型声明"的折叠函数。
37
+ 折叠函数放在 :mod:`braid_agent.tools`——那是 ``AgentTool`` 的定义处,循环自己也要用它把
38
+ 可执行集合折成声明去做差异计算;留一份在这里会让两张表跟着两份代码走。这里保留导入,
39
+ 是因为示例、测试与提示词组装都按这个路径取用。
40
+
41
+ ## ``PROMPT_SNIPPETS`` 与 ``PROMPT_GUIDELINES``
42
+
43
+ 系统提示词里"能用哪些工具"与"用它们时的规矩"两节,内容来自工具自身而不是提示词模块。
44
+ 理由:工具的作者最清楚这一行该怎么写,而提示词模块只管**排序与去重**。每个工具模块
45
+ 各自导出 ``PROMPT_SNIPPET`` / ``PROMPT_GUIDELINES``,这里是唯一汇总点。
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import importlib
51
+ from typing import TYPE_CHECKING
52
+
53
+ from braid_coding_agent.subagents.contract import TASK_TOOL_NAME
54
+
55
+ if TYPE_CHECKING:
56
+ from braid_agent.tools import AgentTool, tool_declaration, tool_declarations
57
+ from braid_coding_agent.network.fetch import WEBFETCH_PARAMETERS, create_webfetch_tool
58
+ from braid_coding_agent.network.search import WEBSEARCH_PARAMETERS, create_websearch_tool
59
+ from braid_coding_agent.network.settings import WebSettings
60
+ from braid_coding_agent.questions import QuestionHandler
61
+
62
+ # 只为类型标注导入:``sandbox`` 反过来依赖 ``tools.operations``,运行时导入会成环。
63
+ from braid_coding_agent.sandbox.operations import SandboxOperations
64
+ from braid_coding_agent.session.plan import PlanStore
65
+ from braid_coding_agent.tools.bash import BASH_PARAMETERS, create_bash_tool
66
+ from braid_coding_agent.tools.edit import EDIT_PARAMETERS, create_edit_tool
67
+ from braid_coding_agent.tools.find import FIND_PARAMETERS, create_find_tool
68
+ from braid_coding_agent.tools.grep import GREP_PARAMETERS, create_grep_tool
69
+ from braid_coding_agent.tools.ls import LS_PARAMETERS, create_ls_tool
70
+ from braid_coding_agent.tools.output_store import ToolOutputStore
71
+ from braid_coding_agent.tools.plan import UPDATE_PLAN_PARAMETERS, create_update_plan_tool
72
+ from braid_coding_agent.tools.question import QUESTION_PARAMETERS, create_question_tool
73
+ from braid_coding_agent.tools.read import READ_PARAMETERS, create_read_tool
74
+ from braid_coding_agent.tools.write import WRITE_PARAMETERS, create_write_tool
75
+
76
+ PROMPT_SNIPPETS: dict[str, str]
77
+ PROMPT_GUIDELINES: dict[str, tuple[str, ...]]
78
+
79
+ #: 七个文件/命令工具的名字,按"先看再改、最后执行"的顺序排列(提示词里的呈现顺序)。
80
+ ENCODING_TOOL_NAMES: tuple[str, ...] = ("read", "write", "edit", "bash", "grep", "find", "ls")
81
+
82
+ #: 两个会话级工具。它们不碰文件系统,单独成组:``--tools`` 白名单、权限引擎与
83
+ #: 提示词规则都以"是否选中"为准,而不是与编码工具绑在一起。
84
+ PLAN_TOOL_NAMES: tuple[str, ...] = ("update_plan", "question")
85
+
86
+ #: 网络工具。它们会访问外部服务,权限判定走 ``permission.domains``,
87
+ #: 结果一律按不可信内容包裹。
88
+ NETWORK_TOOL_NAMES: tuple[str, ...] = ("webfetch", "websearch")
89
+
90
+ #: 派生子代理的工具。它本身不碰文件系统,但会装配独立会话,单独成组。
91
+ TASK_TOOL_NAMES: tuple[str, ...] = (TASK_TOOL_NAME,)
92
+
93
+ #: 按需加载技能正文的工具。与 ``read`` 分工:``skill`` 按名字查清单并做权限预检。
94
+ SKILL_TOOL_NAMES: tuple[str, ...] = ("skill",)
95
+
96
+ #: 语言服务器。只读(不写工作区、不改文件),权限上按只读工具处理。
97
+ LSP_TOOL_NAMES: tuple[str, ...] = ("lsp",)
98
+
99
+ #: 验证命令。会执行外部程序,权限上按命令执行工具处理。
100
+ VERIFY_TOOL_NAMES: tuple[str, ...] = ("verify",)
101
+
102
+ #: 格式化命令。会改写文件,权限上按写工具处理。
103
+ FORMAT_TOOL_NAMES: tuple[str, ...] = ("format",)
104
+
105
+ #: 全部内建工具。``--tools`` 校验与默认选择都用它。``skill`` 排在 ``task`` 之前,
106
+ #: 保持 "最后一个内建工具是 task" 这一既有断言成立。
107
+ BUILTIN_TOOL_NAMES: tuple[str, ...] = (
108
+ *ENCODING_TOOL_NAMES,
109
+ *NETWORK_TOOL_NAMES,
110
+ *PLAN_TOOL_NAMES,
111
+ *SKILL_TOOL_NAMES,
112
+ *LSP_TOOL_NAMES,
113
+ *VERIFY_TOOL_NAMES,
114
+ *FORMAT_TOOL_NAMES,
115
+ *TASK_TOOL_NAMES,
116
+ )
117
+
118
+ #: 直接转出的参数常量、工厂与轻量类型。工具模块只在第一次取用时加载:
119
+ #: 权限规则匹配只需要 ``tools.path_utils``,不该因此加载 HTTP 客户端与全部工具。
120
+ _LAZY_EXPORTS: dict[str, str] = {
121
+ "AgentTool": "braid_agent.tools",
122
+ "tool_declaration": "braid_agent.tools",
123
+ "tool_declarations": "braid_agent.tools",
124
+ "WebSettings": "braid_coding_agent.network.settings",
125
+ "WEBFETCH_PARAMETERS": "braid_coding_agent.network.fetch",
126
+ "create_webfetch_tool": "braid_coding_agent.network.fetch",
127
+ "WEBSEARCH_PARAMETERS": "braid_coding_agent.network.search",
128
+ "create_websearch_tool": "braid_coding_agent.network.search",
129
+ "BASH_PARAMETERS": "braid_coding_agent.tools.bash",
130
+ "create_bash_tool": "braid_coding_agent.tools.bash",
131
+ "EDIT_PARAMETERS": "braid_coding_agent.tools.edit",
132
+ "create_edit_tool": "braid_coding_agent.tools.edit",
133
+ "FIND_PARAMETERS": "braid_coding_agent.tools.find",
134
+ "create_find_tool": "braid_coding_agent.tools.find",
135
+ "GREP_PARAMETERS": "braid_coding_agent.tools.grep",
136
+ "create_grep_tool": "braid_coding_agent.tools.grep",
137
+ "LS_PARAMETERS": "braid_coding_agent.tools.ls",
138
+ "create_ls_tool": "braid_coding_agent.tools.ls",
139
+ "ToolOutputStore": "braid_coding_agent.tools.output_store",
140
+ "UPDATE_PLAN_PARAMETERS": "braid_coding_agent.tools.plan",
141
+ "create_update_plan_tool": "braid_coding_agent.tools.plan",
142
+ "QUESTION_PARAMETERS": "braid_coding_agent.tools.question",
143
+ "create_question_tool": "braid_coding_agent.tools.question",
144
+ "READ_PARAMETERS": "braid_coding_agent.tools.read",
145
+ "create_read_tool": "braid_coding_agent.tools.read",
146
+ "WRITE_PARAMETERS": "braid_coding_agent.tools.write",
147
+ "create_write_tool": "braid_coding_agent.tools.write",
148
+ }
149
+
150
+
151
+ def _prompt_tables() -> tuple[dict[str, str], dict[str, tuple[str, ...]]]:
152
+ """汇总各工具自己的提示词片段。只在第一次取用时加载全部工具模块。"""
153
+ from braid_coding_agent.network import fetch as webfetch
154
+ from braid_coding_agent.network import search as websearch
155
+ from braid_coding_agent.subagents.contract import (
156
+ TASK_PROMPT_GUIDELINES,
157
+ TASK_PROMPT_SNIPPET,
158
+ )
159
+ from braid_coding_agent.tools import bash, edit, find, grep, ls, plan, question, read, write
160
+ from braid_coding_agent.tools.prompt_notes import (
161
+ FORMAT_GUIDELINES,
162
+ FORMAT_SNIPPET,
163
+ LSP_GUIDELINES,
164
+ LSP_SNIPPET,
165
+ VERIFY_GUIDELINES,
166
+ VERIFY_SNIPPET,
167
+ )
168
+
169
+ snippets: dict[str, str] = {
170
+ "read": read.PROMPT_SNIPPET,
171
+ "write": write.PROMPT_SNIPPET,
172
+ "edit": edit.PROMPT_SNIPPET,
173
+ "bash": bash.PROMPT_SNIPPET,
174
+ "grep": grep.PROMPT_SNIPPET,
175
+ "find": find.PROMPT_SNIPPET,
176
+ "ls": ls.PROMPT_SNIPPET,
177
+ "webfetch": webfetch.PROMPT_SNIPPET,
178
+ "websearch": websearch.PROMPT_SNIPPET,
179
+ "update_plan": plan.PROMPT_SNIPPET,
180
+ "question": question.PROMPT_SNIPPET,
181
+ "skill": "Load a named skill's full instructions into context on demand",
182
+ "lsp": LSP_SNIPPET,
183
+ "verify": VERIFY_SNIPPET,
184
+ "format": FORMAT_SNIPPET,
185
+ TASK_TOOL_NAME: TASK_PROMPT_SNIPPET,
186
+ }
187
+ guidelines: dict[str, tuple[str, ...]] = {
188
+ "read": read.PROMPT_GUIDELINES,
189
+ "write": write.PROMPT_GUIDELINES,
190
+ "edit": edit.PROMPT_GUIDELINES,
191
+ "bash": bash.PROMPT_GUIDELINES,
192
+ "grep": grep.PROMPT_GUIDELINES,
193
+ "find": find.PROMPT_GUIDELINES,
194
+ "ls": ls.PROMPT_GUIDELINES,
195
+ "webfetch": webfetch.PROMPT_GUIDELINES,
196
+ "websearch": websearch.PROMPT_GUIDELINES,
197
+ "update_plan": plan.PROMPT_GUIDELINES,
198
+ "question": question.PROMPT_GUIDELINES,
199
+ "skill": (
200
+ "When a skill's description matches the task, load its full instructions with the "
201
+ "skill tool before proceeding; use /skills to see the list",
202
+ ),
203
+ "lsp": LSP_GUIDELINES,
204
+ "verify": VERIFY_GUIDELINES,
205
+ "format": FORMAT_GUIDELINES,
206
+ TASK_TOOL_NAME: TASK_PROMPT_GUIDELINES,
207
+ }
208
+ return snippets, guidelines
209
+
210
+
211
+ def __getattr__(name: str) -> object:
212
+ """按需导入工具模块与提示词表。"""
213
+ if name in ("PROMPT_SNIPPETS", "PROMPT_GUIDELINES"):
214
+ snippets, guidelines = _prompt_tables()
215
+ globals()["PROMPT_SNIPPETS"] = snippets
216
+ globals()["PROMPT_GUIDELINES"] = guidelines
217
+ return snippets if name == "PROMPT_SNIPPETS" else guidelines
218
+ module_name = _LAZY_EXPORTS.get(name)
219
+ if module_name is None:
220
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
221
+ module = importlib.import_module(module_name)
222
+ value = getattr(module, name)
223
+ globals()[name] = value
224
+ return value
225
+
226
+
227
+ def create_encoding_tools(
228
+ cwd: str,
229
+ *,
230
+ output_store: ToolOutputStore,
231
+ sandbox: SandboxOperations | None = None,
232
+ ) -> list[AgentTool]:
233
+ """一次构造整套编码工具。顺序与 :data:`ENCODING_TOOL_NAMES` 一致。
234
+
235
+ :param output_store: 完整命令输出的落盘目录(会话级):``bash`` 超过展示上限时
236
+ 把原始字节写进去,目录与保留策略见 :mod:`braid_coding_agent.tools.output_store`。
237
+ :param sandbox: 操作系统沙箱。给了就交给 ``bash``——只有命令执行需要它,
238
+ 文件工具走的是权限引擎那条判定链。
239
+ """
240
+ from braid_coding_agent.tools.bash import create_bash_tool
241
+ from braid_coding_agent.tools.edit import create_edit_tool
242
+ from braid_coding_agent.tools.find import create_find_tool
243
+ from braid_coding_agent.tools.grep import create_grep_tool
244
+ from braid_coding_agent.tools.ls import create_ls_tool
245
+ from braid_coding_agent.tools.read import create_read_tool
246
+ from braid_coding_agent.tools.write import create_write_tool
247
+
248
+ return [
249
+ create_read_tool(cwd),
250
+ create_write_tool(cwd),
251
+ create_edit_tool(cwd),
252
+ create_bash_tool(cwd, output_store=output_store, sandbox=sandbox),
253
+ create_grep_tool(cwd),
254
+ create_find_tool(cwd),
255
+ create_ls_tool(cwd),
256
+ ]
257
+
258
+
259
+ def create_network_tools(settings: WebSettings) -> list[AgentTool]:
260
+ """构造两个网络工具,顺序与 :data:`NETWORK_TOOL_NAMES` 一致。
261
+
262
+ 两个工具共享同一份配置;缓存按工具实例存在,也就是按会话存在。
263
+ """
264
+ from braid_coding_agent.network.fetch import create_webfetch_tool
265
+ from braid_coding_agent.network.search import create_websearch_tool
266
+
267
+ return [create_webfetch_tool(settings), create_websearch_tool(settings)]
268
+
269
+
270
+ def create_session_tools(
271
+ *,
272
+ plan: PlanStore,
273
+ question: QuestionHandler | None,
274
+ ) -> list[AgentTool]:
275
+ """构造两个会话级工具,顺序与 :data:`PLAN_TOOL_NAMES` 一致。
276
+
277
+ ``plan`` 是这个会话的计划 store:工具与会话必须拿**同一个实例**,否则
278
+ ``update_plan`` 写的计划对 ``/plan`` 与 ``plan_update`` 事件不可见。
279
+ ``question`` 是提问通道;``None`` 表示这次运行没有交互方,每次提问都按取消收尾。
280
+ """
281
+ from braid_coding_agent.tools.plan import create_update_plan_tool
282
+ from braid_coding_agent.tools.question import create_question_tool
283
+
284
+ return [create_update_plan_tool(plan), create_question_tool(question)]
285
+
286
+
287
+ __all__ = [
288
+ "BASH_PARAMETERS",
289
+ "BUILTIN_TOOL_NAMES",
290
+ "EDIT_PARAMETERS",
291
+ "ENCODING_TOOL_NAMES",
292
+ "FIND_PARAMETERS",
293
+ "FORMAT_TOOL_NAMES",
294
+ "GREP_PARAMETERS",
295
+ "LSP_TOOL_NAMES",
296
+ "LS_PARAMETERS",
297
+ "NETWORK_TOOL_NAMES",
298
+ "PLAN_TOOL_NAMES",
299
+ "PROMPT_GUIDELINES",
300
+ "PROMPT_SNIPPETS",
301
+ "QUESTION_PARAMETERS",
302
+ "READ_PARAMETERS",
303
+ "SKILL_TOOL_NAMES",
304
+ "TASK_TOOL_NAMES",
305
+ "UPDATE_PLAN_PARAMETERS",
306
+ "VERIFY_TOOL_NAMES",
307
+ "WEBFETCH_PARAMETERS",
308
+ "WEBSEARCH_PARAMETERS",
309
+ "WRITE_PARAMETERS",
310
+ "ToolOutputStore",
311
+ "create_bash_tool",
312
+ "create_edit_tool",
313
+ "create_encoding_tools",
314
+ "create_find_tool",
315
+ "create_grep_tool",
316
+ "create_ls_tool",
317
+ "create_network_tools",
318
+ "create_question_tool",
319
+ "create_read_tool",
320
+ "create_session_tools",
321
+ "create_update_plan_tool",
322
+ "create_webfetch_tool",
323
+ "create_websearch_tool",
324
+ "create_write_tool",
325
+ "tool_declaration",
326
+ "tool_declarations",
327
+ ]
@@ -0,0 +1,87 @@
1
+ """工具参数的类型收窄。
2
+
3
+ 工具的 ``execute`` 拿到的是 ``dict[str, JsonValue]``——Agent 循环在校验**之前**已经把
4
+ schema 对过一遍(``braid_ai.validation``),所以这里的每个字段都应该是声明好的类型。
5
+ 类型检查器看不到这层保证,于是需要一次收窄。
6
+
7
+ **用 ``assert`` 收窄类型**:走到 ``execute`` 说明 schema 已经通过,类型不对意味着
8
+ 这层保证失效了(有人绕过循环直接调工具,或者 schema 与读取代码不一致)。这时应当就地失败并
9
+ 暴露 bug;把它伪装成"模型参数错了"会让模型重试一百次也不会成功,还掩盖了真正的问题。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from braid_ai.types import JsonValue
15
+
16
+
17
+ def string_arg(args: dict[str, JsonValue], name: str) -> str:
18
+ value = args.get(name)
19
+ assert isinstance(value, str), f"参数 {name} 应为字符串,实际是 {type(value).__name__}"
20
+ return value
21
+
22
+
23
+ def optional_string_arg(args: dict[str, JsonValue], name: str) -> str | None:
24
+ value = args.get(name)
25
+ if value is None:
26
+ return None
27
+ assert isinstance(value, str), f"参数 {name} 应为字符串,实际是 {type(value).__name__}"
28
+ return value
29
+
30
+
31
+ def integer_arg(args: dict[str, JsonValue], name: str) -> int:
32
+ value = args.get(name)
33
+ assert isinstance(value, int) and not isinstance(value, bool), (
34
+ f"参数 {name} 应为整数,实际是 {type(value).__name__}"
35
+ )
36
+ return value
37
+
38
+
39
+ def optional_integer_arg(args: dict[str, JsonValue], name: str) -> int | None:
40
+ value = args.get(name)
41
+ if value is None:
42
+ return None
43
+ assert isinstance(value, int) and not isinstance(value, bool), (
44
+ f"参数 {name} 应为整数,实际是 {type(value).__name__}"
45
+ )
46
+ return value
47
+
48
+
49
+ def optional_number_arg(args: dict[str, JsonValue], name: str) -> float | None:
50
+ """JSON 里 ``1`` 与 ``1.0`` 都合法;统一收成 ``float``。"""
51
+ value = args.get(name)
52
+ if value is None:
53
+ return None
54
+ assert isinstance(value, (int, float)) and not isinstance(value, bool), (
55
+ f"参数 {name} 应为数字,实际是 {type(value).__name__}"
56
+ )
57
+ return float(value)
58
+
59
+
60
+ def optional_bool_arg(args: dict[str, JsonValue], name: str) -> bool | None:
61
+ value = args.get(name)
62
+ if value is None:
63
+ return None
64
+ assert isinstance(value, bool), f"参数 {name} 应为布尔值,实际是 {type(value).__name__}"
65
+ return value
66
+
67
+
68
+ def object_list_arg(args: dict[str, JsonValue], name: str) -> list[dict[str, JsonValue]]:
69
+ """取一个"对象数组"参数(``edit`` 的 ``edits``)。"""
70
+ value = args.get(name)
71
+ assert isinstance(value, list), f"参数 {name} 应为数组,实际是 {type(value).__name__}"
72
+ items: list[dict[str, JsonValue]] = []
73
+ for item in value:
74
+ assert isinstance(item, dict), f"参数 {name} 的每一项应为对象,实际是 {type(item).__name__}"
75
+ items.append(item)
76
+ return items
77
+
78
+
79
+ __all__ = [
80
+ "integer_arg",
81
+ "object_list_arg",
82
+ "optional_bool_arg",
83
+ "optional_integer_arg",
84
+ "optional_number_arg",
85
+ "optional_string_arg",
86
+ "string_arg",
87
+ ]